Skip to content

Commit 570c5ec

Browse files
fredbiclaude
andcommitted
fix(schema): support bare swagger:enum on a type decl (F4b, part C)
Quirk F4b (doc-site-quirks.md): a bare `swagger:enum` (no name argument) on a type declaration parse-errored (missing-required-arg) and dropped the enum entirely — even though the name is redundant on a type decl (it IS the type). Bare `swagger:enum` is now valid and equivalent to `swagger:enum <TypeName>`: * grammar: the AnnEnum arm no longer raises missing-required-arg for the bare form — it is structurally valid; "does a type with consts exist?" is a builder-level question. * builder: classifierNamedBasic takes the declared type name and, when swagger:enum is present without an explicit name, infers the enum name from the declaration (new `enumName` helper) and collects its consts. With this, a bare `swagger:enum` + `swagger:model` type publishes the same first-class enum definition as the named form (F4): the definition carries the enum values + x-go-enum-desc and referencing fields $ref it. * TestParser_EnumDecl_Empty → TestParser_EnumDecl_Bare (bare form is valid, no diagnostic); the F1/F2/F4 witness flipped (Priority now carries its enum and the bare form raises no error); golden regenerated. * annotations.md swagger:enum: document the optional/bare name and the swagger:model ⇒ first-class enum definition behaviour. This completes the F1/F2/F4 reconciliation. * contributes go-swagger/go-swagger doc-site quirk F4 (bare enum) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
1 parent 78f915e commit 570c5ec

7 files changed

Lines changed: 67 additions & 29 deletions

File tree

‎docs/doc-site/maintainers/annotations.md‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -260,12 +260,18 @@ itself; the format name is the entire surface.
260260
## `swagger:enum`
261261

262262
**What it does.** Marks a string-typed (or integer-typed) named type
263-
as an enum and collects the type's `const` declarations. The values
264-
are applied **inline on each model field that references the type**:
265-
the property gets an `enum` array plus an `x-go-enum-desc` extension
266-
carrying the per-value godoc descriptions in `<value> <doc-text>`
267-
shape. The enum type itself is **not** emitted as a standalone
268-
definition — the values travel with each referencing property.
263+
as an enum and collects the type's `const` declarations.
264+
265+
- **Without `swagger:model`** (the default): the values are applied
266+
**inline on each model field that references the type** — the
267+
property gets an `enum` array plus an `x-go-enum-desc` extension
268+
carrying the per-value godoc descriptions in `<value> <doc-text>`
269+
shape. The enum type itself is not a standalone definition; the
270+
values travel with each referencing property.
271+
- **With `swagger:model`**: the enum becomes a **first-class
272+
definition** carrying the `enum` array (+ `x-go-enum-desc`), and
273+
referencing fields point at it via `$ref` — the general
274+
`swagger:model ⇒ definition + $ref` rule applied to enums.
269275

270276
(Edge case: if `swagger:enum` names a type for which no matching
271277
`const` values are found, the enum semantics are dropped and the type
@@ -277,8 +283,11 @@ values are discovered via Go's type-system traversal; they do not
277283
need to live in the same file. The values surface only when a model
278284
reaches the enum type through a field.
279285

280-
**Argument shape.** IDENT naming the type whose `const` values to
281-
collect (its own name).
286+
**Argument shape.** Optional IDENT naming the type whose `const`
287+
values to collect. On a type declaration the name is redundant, so the
288+
**bare `swagger:enum`** form is accepted and infers the name from the
289+
declared type. `swagger:enum Priority` and a bare `swagger:enum` on
290+
`type Priority …` are equivalent.
282291

283292
**Sample.**
284293

‎fixtures/integration/golden/quirk_model_override_matrix.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@
2626
"type": "integer",
2727
"format": "int64",
2828
"title": "Priority is an enum declared with the BARE swagger:enum (no name arg) (F4b):",
29+
"enum": [
30+
1,
31+
9
32+
],
33+
"x-go-enum-desc": "1 PriorityLow is low.\n9 PriorityHigh is high.",
2934
"x-go-package": "github.com/go-openapi/codescan/fixtures/quirks/model-override-matrix"
3035
},
3136
"RawID": {

‎internal/builders/schema/schema.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ func (s *Builder) buildFromDecl(schema *oaispec.Schema) error {
159159
return nil
160160
}
161161
case *types.Basic:
162-
if s.classifierNamedBasic(s.Decl.Comments, s.Decl.Pkg, ut, defTgt) {
162+
if s.classifierNamedBasic(s.Decl.Comments, s.Decl.Pkg, ut, defTgt, tpe.Obj().Name()) {
163163
return nil
164164
}
165165
}
@@ -459,7 +459,7 @@ func (s *Builder) buildNamedType(titpe *types.Named, target ifaces.SwaggerTypabl
459459
s.Warn("skipped unsupported builtin", slog.Any("type", tio))
460460
return nil
461461
}
462-
if !isModel && s.classifierNamedBasic(cmt, pkg, utitpe, target) {
462+
if !isModel && s.classifierNamedBasic(cmt, pkg, utitpe, target, tio.Name()) {
463463
return nil
464464
}
465465
return s.resolveRefOr(tio, target, func() error {

‎internal/builders/schema/walker_classifiers.go‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,21 @@ func (s *Builder) classifierNamedTypeOverride(cg *ast.CommentGroup, tgt ifaces.S
106106
return true, true
107107
}
108108

109+
// enumName resolves the enum type name for a swagger:enum annotation: the
110+
// explicit `swagger:enum <Name>` argument, or — for the BARE `swagger:enum`
111+
// form on a type declaration — the declared type's own name (F4b, the name is
112+
// redundant on a type decl). Returns ("", false) when no swagger:enum is
113+
// present, or when the bare form has no declared type to infer from.
114+
func (s *Builder) enumName(cg *ast.CommentGroup, declTypeName string) (string, bool) {
115+
if name, ok := s.findAnnotationArg(cg, grammar.AnnEnum); ok {
116+
return name, true
117+
}
118+
if declTypeName != "" && s.findAnnotation(cg, grammar.AnnEnum) != nil {
119+
return declTypeName, true
120+
}
121+
return "", false
122+
}
123+
109124
// classifierNamedBasic is the named-type walker for
110125
// `buildNamedBasic`. Consumes a cascade of classifier
111126
// annotations in source-priority order:
@@ -124,13 +139,13 @@ func (s *Builder) classifierNamedTypeOverride(cg *ast.CommentGroup, tgt ifaces.S
124139
// - handled=true → caller returns nil (target written, terminal)
125140
// - handled=false → no classifier matched; caller continues to
126141
// FindModel / SwaggerSchemaForType fallback
127-
func (s *Builder) classifierNamedBasic(cg *ast.CommentGroup, pkg *packages.Package, utitpe *types.Basic, tgt ifaces.SwaggerTypable) (resolved bool) {
142+
func (s *Builder) classifierNamedBasic(cg *ast.CommentGroup, pkg *packages.Package, utitpe *types.Basic, tgt ifaces.SwaggerTypable, declTypeName string) (resolved bool) {
128143
if name, ok := s.findAnnotationArg(cg, grammar.AnnStrfmt); ok {
129144
tgt.Typed("string", name)
130145
return true
131146
}
132147

133-
if enumName, ok := s.findAnnotationArg(cg, grammar.AnnEnum); ok {
148+
if enumName, ok := s.enumName(cg, declTypeName); ok {
134149
enumValues, enumDesces, _ := s.Ctx.FindEnumValues(pkg, enumName)
135150
if len(enumValues) > 0 {
136151
tgt.WithEnum(enumValues...)

‎internal/integration/coverage_quirk_model_override_test.go‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,21 +55,18 @@ func TestQuirk_ModelOverrideMatrix(t *testing.T) {
5555
assert.Equal(t, "#/definitions/Status", state.Ref.String())
5656
assert.Equal(t, []any{"active", "closed"}, doc.Definitions["Status"].Enum)
5757

58-
// F4b (TODO Part C): bare swagger:enum (no name) still does not collect the
59-
// decl's consts — Priority is a plain integer model with no enum, and the
60-
// bare form still raises a parse error. Part C will infer the name from the
61-
// decl and collect the consts.
58+
// F4b: bare swagger:enum (no name) on a type decl now infers the enum name
59+
// from the declaration and collects its consts; the definition carries the
60+
// enum and the field $refs it.
6261
priority := h["priority"]
6362
assert.Equal(t, "#/definitions/Priority", priority.Ref.String())
64-
assert.Empty(t, doc.Definitions["Priority"].Enum, "TODO Part C: bare swagger:enum collects no values yet")
63+
require.Len(t, doc.Definitions["Priority"].Enum, 2, "bare swagger:enum collects the decl's consts")
6564

66-
var bareEnumErr bool
65+
// The bare form no longer raises a missing-required-arg parse error.
6766
for _, d := range diags {
68-
if d.Code == grammar.CodeMissingRequiredArg {
69-
bareEnumErr = true
70-
}
67+
assert.NotEqualf(t, grammar.CodeMissingRequiredArg, d.Code,
68+
"bare swagger:enum must not error: %s", d)
7169
}
72-
assert.True(t, bareEnumErr, "TODO Part C: bare swagger:enum still errors (name/value-list required)")
7370

7471
scantest.CompareOrDumpJSON(t, doc, "quirk_model_override_matrix.json")
7572
}

‎internal/parsers/grammar/parser.go‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -551,11 +551,13 @@ func (s *parseState) parseClassifierBlock(annIdx int, annTok Token, kind Annotat
551551
// reach the returned Block.
552552
switch kind {
553553
case AnnEnum:
554+
// A bare `swagger:enum` (no name, no inline values, no body) is valid
555+
// on a type declaration: the builder infers the enum name from the
556+
// declared type and collects its consts (F4b). Only the grammar's
557+
// structural shape is checked here, and the bare form is structurally
558+
// fine — semantic resolution (does a type with consts exist?) is the
559+
// builder's job.
554560
form, name, _, valuesArgs := splitEnumArgs(annTok)
555-
if name == "" && len(valuesArgs) == 0 && enumBody == "" {
556-
s.emit(Errorf(annTok.Pos, CodeMissingRequiredArg,
557-
"swagger:enum requires a name and/or a value list"))
558-
}
559561
s.finaliseBase(base)
560562
return &EnumDeclBlock{
561563
baseBlock: base,

‎internal/parsers/grammar/parser_test.go‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -320,10 +320,20 @@ func TestParser_EnumDecl_PlainList(t *testing.T) {
320320
assert.Equal(t, enumFormPlainOnly, eb.InlineForm)
321321
}
322322

323-
func TestParser_EnumDecl_Empty(t *testing.T) {
323+
// TestParser_EnumDecl_Bare pins the relaxed bare-swagger:enum contract (F4b):
324+
// a bare `swagger:enum` (no name, no inline values, no body) is structurally
325+
// valid — it produces an EnumDeclBlock with an empty Name and raises NO parse
326+
// diagnostic. The builder infers the enum name from the declared type and
327+
// collects its consts; "no consts found" is a builder-level concern, not a
328+
// grammar error.
329+
func TestParser_EnumDecl_Bare(t *testing.T) {
324330
b := parseString(t, "swagger:enum")
325-
require.NotEmpty(t, b.Diagnostics())
326-
assert.Equal(t, CodeMissingRequiredArg, b.Diagnostics()[0].Code)
331+
eb, ok := b.(*EnumDeclBlock)
332+
require.True(t, ok, "expected *EnumDeclBlock, got %T", b)
333+
assert.Empty(t, eb.Name)
334+
for _, d := range b.Diagnostics() {
335+
assert.NotEqual(t, CodeMissingRequiredArg, d.Code, "bare swagger:enum must not error")
336+
}
327337
}
328338

329339
func TestParser_UnboundBlock(t *testing.T) {

0 commit comments

Comments
 (0)
⌂ 换网址