Skip to content

Commit c37d503

Browse files
authored
Merge pull request #76 from fredbi/fix/3412-enum-negative
Fix/3412 enum negative
2 parents 354fe10 + 7afe0e3 commit c37d503

36 files changed

Lines changed: 2815 additions & 68 deletions

‎.claude/CLAUDE.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,18 @@ malformed input, the petstore, aliased schemas, go123-specific forms, and cross-
220220
(`types.LookupFieldOrMethod`), never against the emitted names. Placed on the embed (plain field
221221
names) or on the declaration (dotted embed paths); embeds only. Unresolved / behind-`$ref`
222222
targets raise Hints. See `internal/builders/schema/README.md#omit`.
223+
- A `swagger:enum` schema takes its `type`/`format` from the **declared** Go type (`int8` →
224+
`integer/int8`, `float32` → `number/float`), never from the parsed const values, and each member is
225+
normalised to that type — typing from the first value let the const block's declaration order
226+
decide the schema type. Member *values* come from the type-checker
227+
(`TypesInfo.Defs[name].(*types.Const).Val()`), never from the literal syntax, and membership is
228+
decided per name from the constant's own type — which is what makes `iota` blocks (where only the
229+
first spec carries a type and a value) visible at all. So `iota`, expressions (`1 << 3`),
230+
references to earlier members, rune literals (`'a'` → 97), `true`/`false` (identifiers, not
231+
literals), raw/escaped strings, every integer base and above-`MaxInt64` members all resolve
232+
(go-swagger#3412). A literal reader survives only as the degraded-load fallback. See
233+
`internal/scanner/README.md#enum-values`, `internal/builders/schema/README.md#enum-typing` and
234+
`internal/builders/validations/README.md#enum-const-values`.
223235
- The scanner works at the AST / `go/types` level — it never executes or compiles scanned code.
224236
- Parsers never import builders; they write through the interfaces in `internal/ifaces`.
225237
When adding a new annotation, extend the relevant builder's `taggers.go` rather than reaching

‎docs/doc-site/annotation-index/_index.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ tutorial that shows the annotation as runnable Go next to the spec it produces;
1717
| `swagger:allOf` | embedded field / struct | an `allOf` composition | [example]({{% relref "/tutorials/model-definitions#swaggerallof" %}}) | [reference]({{% relref "/maintainers/annotations/swagger-allof" %}}) |
1818
| `swagger:default` | value / field doc | a default-value anchor | [example]({{% relref "/tutorials/examples-and-defaults#swaggerdefault" %}}) | [reference]({{% relref "/maintainers/annotations/swagger-default" %}}) |
1919
| `swagger:description` | type / field / response doc | overrides the `description` (verbatim body with `\|`) | [how-to]({{% relref "overriding-titles-and-descriptions" %}}) | [reference]({{% relref "/maintainers/annotations/swagger-description" %}}) |
20-
| `swagger:enum` | named type | an `enum` array (+ `x-go-enum-desc`) | [example]({{% relref "/tutorials/model-definitions#swaggerenum" %}}) | [reference]({{% relref "/maintainers/annotations/swagger-enum" %}}) |
20+
| `swagger:enum` | named type | an `enum` array (+ `x-go-enum-desc`) | [example]({{% relref "/tutorials/enumerations" %}}) | [reference]({{% relref "/maintainers/annotations/swagger-enum" %}}) |
2121
| `swagger:file` | param / response field | `{type: file}` | [example]({{% relref "/tutorials/routes-and-operations#swaggerfile" %}}) | [reference]({{% relref "/maintainers/annotations/swagger-file" %}}) |
2222
| `swagger:ignore` | type / field doc | excludes the declaration | [example]({{% relref "/tutorials/model-definitions#swaggerignore" %}}) | [reference]({{% relref "/maintainers/annotations/swagger-ignore" %}}) |
2323
| `swagger:meta` | package doc | top-level `info`, `host`, `basePath`, `schemes`, … | [example]({{% relref "/tutorials/document-metadata#swaggermeta" %}}) | [reference]({{% relref "/maintainers/annotations/swagger-meta" %}}) |

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

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,24 @@ description: "Marks a named type as an enum and collects its const values."
1212

1313
## What it does
1414

15-
Marks a string-typed (or integer-typed) named type as an enum and
16-
collects the type's `const` declarations.
15+
Marks a named type over a string, integer, number or boolean as an enum
16+
and collects the type's `const` declarations.
17+
18+
Values come from the Go type-checker, so any constant expression is
19+
collected — `iota` (including the implicit specs, which carry neither a
20+
type nor a value), computed members (`1 << 3`), references to earlier
21+
members, negative values, every integer base, values above `MaxInt64` in
22+
an unsigned enum, rune literals (as code points), `true` / `false`, and
23+
both string forms. The emitted `type` / `format` come from the **declared
24+
Go type**, never from the members, so an `int8` enum is
25+
`{integer, int8}` and reordering the const block cannot change the type.
26+
A type declared over another named type keeps that type's format
27+
(`type Kind strfmt.UUID` stays `format: uuid`).
28+
29+
Two shapes do not work: an alias to a basic type cannot host an enum (the
30+
type-checker erases the alias, leaving nothing to collect), and a `rune`
31+
or `byte` enum emits integers, which is what those types are on the wire.
32+
See [Enumerations]({{% relref "/tutorials/enumerations" %}}).
1733

1834
- **Without `swagger:model`** (the default): the values are applied
1935
**inline on each model field that references the type** — the property
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
---
2+
title: Enumerations
3+
weight: 12
4+
description: |
5+
Publish a Go const block as a spec enum — any constant expression, the type
6+
and format taken from the declaration, and the same members inline on
7+
parameters and headers.
8+
---
9+
10+
An enum in Go is a named type plus a block of constants. `swagger:enum` turns
11+
that pair into an `enum` array on every schema, parameter and header the type
12+
reaches. This page covers what the scanner accepts on the value side, what
13+
decides the emitted `type` / `format`, and the two shapes that do not work.
14+
15+
Every Go snippet below comes from the test-covered
16+
[`docs/examples/concepts/enums`](https://github.com/go-openapi/codescan/tree/master/docs/examples/concepts/enums)
17+
package, and every JSON pane is a golden file a test regenerates.
18+
19+
## swagger:enum
20+
21+
`swagger:enum <name>` collects the `const` values declared with that type. A
22+
bare `swagger:enum` on the type declaration works too — the name is inferred
23+
from the declaration it sits on.
24+
25+
The enum type is emitted **because something points at it**: a model field, a
26+
parameter, a header. On its own it is unreachable, and unreachable types are not
27+
published. Add `swagger:model` to the enum type to make it a first-class
28+
definition (carrying the `enum` array) that fields `$ref` instead — the general
29+
`swagger:model ⇒ definition + $ref` rule.
30+
31+
Each member's doc comment becomes a line of the `x-go-enum-desc` extension, and
32+
is appended to the property description. Set
33+
[`SkipEnumDescriptions`]({{% relref "/maintainers/options" %}}) to keep the
34+
mapping on the extension only.
35+
36+
## Any constant expression, not just literals
37+
38+
The values come from the Go **type-checker**, which has already evaluated the
39+
const block. So the members do not have to be written as literals — anything the
40+
compiler can fold is collected.
41+
42+
`iota` is the case that matters most, because after the first line there is
43+
nothing left in the source to read: the following specs carry neither a type nor
44+
a value, and inherit both implicitly.
45+
46+
{{< example go="concepts/enums/enums.go" goregion="iota"
47+
json="concepts/enums/testdata/iota.json" jsonlabel="#/definitions/Schedule" >}}
48+
49+
Constant expressions and references to earlier members are collected the same
50+
way.
51+
52+
{{< example go="concepts/enums/enums.go" goregion="expressions"
53+
json="concepts/enums/testdata/expressions.json" jsonlabel="#/definitions/Threshold" >}}
54+
55+
The same goes for every other constant form Go offers: negative values, the
56+
non-decimal bases (`0x2a`, `0b101010`, `0o52`) and digit separators, values
57+
above `MaxInt64` in an unsigned enum, `true` / `false`, rune literals, and both
58+
the raw and the escaped string forms.
59+
60+
Negative members are worth a pane of their own, since a signed constant is not a
61+
literal in the Go grammar — it is an expression wrapping one:
62+
63+
{{< example go="concepts/enums/enums.go" goregion="signed"
64+
json="concepts/enums/testdata/signed.json" jsonlabel="#/definitions/Camera" >}}
65+
66+
## The type comes from the declaration
67+
68+
`type` and `format` are read from the Go type you declared, never from the
69+
members. `PanDirection` above is an `int8`, so the property is
70+
`{integer, int8}` — even though every member would fit in a smaller or larger
71+
box.
72+
73+
This is also what makes the const block **safe to reorder**. `Zoom` is a
74+
`float32` whose first member is written `0`, an integer literal; the schema is a
75+
number enum regardless of which member comes first:
76+
77+
{{< example go="concepts/enums/enums.go" goregion="width"
78+
json="concepts/enums/testdata/width.json" jsonlabel="#/definitions/Lens" >}}
79+
80+
A type declared over another **named** type keeps what that type contributed. An
81+
enum written over a string format is still that format:
82+
83+
{{< example go="concepts/enums/enums.go" goregion="strfmt"
84+
json="concepts/enums/testdata/strfmt.json" jsonlabel="#/definitions/Label" >}}
85+
86+
## Parameters and headers
87+
88+
OpenAPI 2.0 forbids a `$ref` on a non-body parameter or a response header, so
89+
there the members and the format are written **inline**. Nothing changes on the
90+
annotation side — the same enum type reaches `in: query`, `path`, `header` and
91+
`formData`, and the `items` of an array-typed one:
92+
93+
{{< example go="concepts/enums/enums.go" goregion="params"
94+
json="concepts/enums/testdata/params.json" jsonlabel="GET /cameras/search — parameters"
95+
full="concepts/enums/testdata/full.json" >}}
96+
97+
## Two shapes that do not work
98+
99+
**A `rune` or `byte` enum emits integers.** It is collected like any other, and
100+
`'a'` reaches the spec as `97`:
101+
102+
{{< example go="concepts/enums/enums.go" goregion="runes"
103+
json="concepts/enums/testdata/runes.json" jsonlabel="#/definitions/Glyph" >}}
104+
105+
That is unlikely to be what you pictured, and it is the only faithful answer: a
106+
scalar `rune` is an `int32` on the wire as much as in Go, so `json.Marshal`
107+
writes `97`, and `encoding/json` **refuses** to unmarshal `"a"` back into the
108+
field. A string-typed schema would describe a payload your own server rejects.
109+
If you meant characters, declare the type over `string`
110+
(`type Letter string`, `LetterA Letter = "a"`) — that changes the wire, and the
111+
schema follows.
112+
113+
**An alias to a basic type cannot host an enum.**
114+
115+
```go
116+
type Unsigned = uint64 // an alias, not a new type
117+
118+
// swagger:enum Unsigned // ← collects nothing
119+
const Zero Unsigned = 0
120+
```
121+
122+
The Go type-checker erases the alias, so `Zero` is indistinguishable from any
123+
other `uint64` constant and there is no set of members to collect. Declare a
124+
real type instead (`type Unsigned uint64`). An alias to a *named* enum type is
125+
fine — the named type survives.
126+
127+
## Where to go next
128+
129+
- [Validations]({{% relref "/tutorials/validations" %}}) — the other constraints
130+
a property can carry, and the reduced surface parameters accept.
131+
- [Model definitions]({{% relref "/tutorials/model-definitions" %}}) — the rest
132+
of the per-type annotations.
133+
- [`swagger:enum` reference]({{% relref "/maintainers/annotations/swagger-enum" %}})
134+
— the exhaustive rule.

‎docs/doc-site/tutorials/model-definitions.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,11 @@ Here the values inline on the referencing field. Add `swagger:model` to the enum
5959
type to make it a first-class definition (carrying the `enum` array) that fields
6060
`$ref` — again the `swagger:model ⇒ definition + $ref` rule.
6161

62+
Enums have more to them than a string const block: `iota` and computed members,
63+
what decides the emitted `type` / `format`, and the inline form parameters and
64+
headers take. They get their own page —
65+
[Enumerations]({{% relref "/tutorials/enumerations" %}}).
66+
6267
## swagger:allOf
6368

6469
Embedding base types under `swagger:allOf` composes a schema. Each embedded base

0 commit comments

Comments
 (0)
⌂ 换网址