From 46d5b5a83b97ad0d97e2ed39e527ba649b69880a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 14:03:25 +0000 Subject: [PATCH 1/3] feat: a nullable field is no pointer Null reads as the zero value, and a required nullable field sends its zero value where it would have sent null. An optional nullable field is a pointer only where the field would be without null, and a default on the nullable schema itself, as {"anyOf": [integer, null], "default": 0}, now counts. A union, which refuses null, and a type whose zero value cannot be encoded keep their pointers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- README.md | 27 +++++++------ README/features.md | 27 +++++++------ ir/pointer.go | 10 +++-- ir/pointer_internal_test.go | 8 ++-- ir/query_test.go | 6 +-- ir/schema.go | 20 ++-------- ir/schema_test.go | 51 ++++++++++++++----------- testdata/golden/pkg/golden/ir.json | 2 +- testdata/golden/pkg/golden/types.gen.go | 2 +- 9 files changed, 73 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index 517b6cb8..bc124db9 100644 --- a/README.md +++ b/README.md @@ -139,16 +139,14 @@ How the specification maps onto Go: Nothing the specification leaves open decodes into `any` then: the empty schema, an array without `items`, a free-form object and `not` alone become `struct{}`, so any value in them is recorded, and any but an object fails. -- **Fields** — a field is a pointer only where its zero value must be told apart - from something else: from leaving the field out, if it is optional, or from - null, if it is nullable. That is a boolean, a number that may be 0, or an object - that requires nothing, so `{}` says something; nil then leaves the field out, - and a pointer to the zero value sends it. A zero value the specification makes - the default, or rules out with a bound or an enum, needs no pointer. A string, - a slice, a map or a union is never a pointer: its zero value leaves it out. A - time or a date is a pointer only if it is nullable, since its zero value is - written as a time, not as null. A struct that would contain itself refers to - itself through a pointer. +- **Fields** — a field is a pointer only where it is optional and its zero value + must be told apart from leaving it out. That is a boolean, a number that may + be 0, or an object that requires nothing, so `{}` says something; nil then + leaves the field out, and a pointer to the zero value sends it. A zero value + the specification makes the default, or rules out with a bound or an enum, + needs no pointer. A string, a time, a date, a slice, a map or a union is never + a pointer: its zero value leaves it out. A struct that would contain itself + refers to itself through a pointer. - **Omitting** — an optional field is tagged `omitzero`, so it is left out while it holds its zero value: nil for a pointer, a slice or a map, so an empty one is still sent. A required field is always sent, `""`, `0` and `false` @@ -160,10 +158,11 @@ How the specification maps onto Go: write-only members out of a response, as their fields hold them or not, through unions and embedded parts alike; any other encoding keeps them. - **Null** — a schema that is only ever `null` is `*struct{}`, and "X or null", - a `type` of `[X, "null"]` or a `oneOf` or `anyOf` of `X` and `null`, is `X`, a - pointer to `X` only by the rule for fields above, so that null and - the zero value can differ, or where `X` decodes itself, such as a union or a - tuple, which would refuse null. + a `type` of `[X, "null"]` or a `oneOf` or `anyOf` of `X` and `null`, is `X`: + null reads as its zero value, and a required field sends the zero value where + it would have sent null. It is a pointer to `X` only by the rule for fields + above, or where `X` decodes itself, such as a union or a tuple, which would + refuse null. - **Fixed parameters** — a required parameter that can take only one value, its `const` or the only value of its `enum`, is sent by the client itself: in the path, the query or the headers, such as Notion's `Notion-Version`. The caller diff --git a/README/features.md b/README/features.md index 1c1b3007..ed3c437a 100644 --- a/README/features.md +++ b/README/features.md @@ -94,16 +94,14 @@ How the specification maps onto Go: Nothing the specification leaves open decodes into `any` then: the empty schema, an array without `items`, a free-form object and `not` alone become `struct{}`, so any value in them is recorded, and any but an object fails. -- **Fields** — a field is a pointer only where its zero value must be told apart - from something else: from leaving the field out, if it is optional, or from - null, if it is nullable. That is a boolean, a number that may be 0, or an object - that requires nothing, so `{}` says something; nil then leaves the field out, - and a pointer to the zero value sends it. A zero value the specification makes - the default, or rules out with a bound or an enum, needs no pointer. A string, - a slice, a map or a union is never a pointer: its zero value leaves it out. A - time or a date is a pointer only if it is nullable, since its zero value is - written as a time, not as null. A struct that would contain itself refers to - itself through a pointer. +- **Fields** — a field is a pointer only where it is optional and its zero value + must be told apart from leaving it out. That is a boolean, a number that may + be 0, or an object that requires nothing, so `{}` says something; nil then + leaves the field out, and a pointer to the zero value sends it. A zero value + the specification makes the default, or rules out with a bound or an enum, + needs no pointer. A string, a time, a date, a slice, a map or a union is never + a pointer: its zero value leaves it out. A struct that would contain itself + refers to itself through a pointer. - **Omitting** — an optional field is tagged `omitzero`, so it is left out while it holds its zero value: nil for a pointer, a slice or a map, so an empty one is still sent. A required field is always sent, `""`, `0` and `false` @@ -115,10 +113,11 @@ How the specification maps onto Go: write-only members out of a response, as their fields hold them or not, through unions and embedded parts alike; any other encoding keeps them. - **Null** — a schema that is only ever `null` is `*struct{}`, and "X or null", - a `type` of `[X, "null"]` or a `oneOf` or `anyOf` of `X` and `null`, is `X`, a - pointer to `X` only by the rule for fields above, so that null and - the zero value can differ, or where `X` decodes itself, such as a union or a - tuple, which would refuse null. + a `type` of `[X, "null"]` or a `oneOf` or `anyOf` of `X` and `null`, is `X`: + null reads as its zero value, and a required field sends the zero value where + it would have sent null. It is a pointer to `X` only by the rule for fields + above, or where `X` decodes itself, such as a union or a tuple, which would + refuse null. - **Fixed parameters** — a required parameter that can take only one value, its `const` or the only value of its `enum`, is sent by the client itself: in the path, the query or the headers, such as Notion's `Notion-Version`. The caller diff --git a/ir/pointer.go b/ir/pointer.go index d754eb34..00c1770b 100644 --- a/ir/pointer.go +++ b/ir/pointer.go @@ -22,14 +22,16 @@ func zeroIsAValue(s *openapi.Schema, tp *GoType) bool { } s = deref(s) - if v := nullableVariant(s); v != nil { - s = deref(v) - } - if s == nil || len(s.Default) > 0 && isZeroJSON(s.Default) { // leaving it out already means the zero value return false } + if v := nullableVariant(s); v != nil { + if s = deref(v); s == nil || len(s.Default) > 0 && isZeroJSON(s.Default) { + return false + } + } + switch s.Type { case openapi.TypeBoolean, openapi.TypeInteger, openapi.TypeNumber: switch { diff --git a/ir/pointer_internal_test.go b/ir/pointer_internal_test.go index cf73a3b1..60a6f9a9 100644 --- a/ir/pointer_internal_test.go +++ b/ir/pointer_internal_test.go @@ -114,7 +114,7 @@ func TestNullableGoType(t *testing.T) { s *openapi.Schema pointer bool }{ - // null and the zero value mean the same: no pointer + // null reads as the zero value: no pointer {"a string", &openapi.Schema{Type: openapi.TypeString}, false}, {"a time", &openapi.Schema{Type: openapi.TypeString, Format: openapi.FormatDateTime}, false}, {"a date", &openapi.Schema{Type: openapi.TypeString, Format: openapi.FormatDate}, false}, @@ -122,9 +122,9 @@ func TestNullableGoType(t *testing.T) { {"an object requiring nothing", &openapi.Schema{Type: openapi.TypeObject, Properties: openapi.Schemas{ "name": {Type: openapi.TypeString}, }}, false}, - // they differ: a pointer - {"a number", &openapi.Schema{Type: openapi.TypeInteger}, true}, - {"a boolean", &openapi.Schema{Type: openapi.TypeBoolean}, true}, + {"a number", &openapi.Schema{Type: openapi.TypeInteger}, false}, + {"a boolean", &openapi.Schema{Type: openapi.TypeBoolean}, false}, + // it cannot: a pointer {"a union, which refuses null", union, true}, } { tp, err := nullableGoType(tc.s) diff --git a/ir/query_test.go b/ir/query_test.go index 78d9dacf..7a679101 100644 --- a/ir/query_test.go +++ b/ir/query_test.go @@ -177,9 +177,9 @@ func TestQueryParams(t *testing.T) { t.Errorf("the client guards the required member x of the required object point:\n%s", encode) } - // a null cannot be sent, so a required member that may be null is left out while it is - if want := "if params.Point.Z != nil {\nparts = append(parts, \"z\", strconv.Itoa(*params.Point.Z))"; !strings.Contains(encode, want) { - t.Errorf("the client sends the nullable member z when nil:\n%s", encode) + // a required member that may be null is sent like any other required member, null being its zero value + if want := "parts = append(parts, \"z\", strconv.Itoa(params.Point.Z))"; !strings.Contains(encode, want) { + t.Errorf("the client does not send the nullable member z:\n%s", encode) } // a server whose parameters are all split from the raw query declares no query values it would not use diff --git a/ir/schema.go b/ir/schema.go index 92fc01e8..6ec72016 100644 --- a/ir/schema.go +++ b/ir/schema.go @@ -214,10 +214,9 @@ func nullableVariant(s *openapi.Schema) *openapi.Schema { } } -// nullableGoType is the Go type of X or null: X itself, null reading as its zero value, unless null and the zero value -// mean different things. They do for a number or a boolean whose zero value is a value of its own, such as a count -// that may be 0, but not for a string, a time, a date or an object: an empty one says what null does. A required -// field of X sends its zero value where it would have sent null, which a client sending such a field can live with. +// nullableGoType is the Go type of X or null: X itself, null reading as its zero value. A required field of X sends +// its zero value where it would have sent null, which a client sending such a field can live with, and an optional one +// is a pointer only where X's would be (see [zeroIsAValue]). func nullableGoType(v *openapi.Schema) (*GoType, error) { tp, err := SchemaGoType(v) if err != nil { @@ -226,24 +225,13 @@ func nullableGoType(v *openapi.Schema) (*GoType, error) { // a type that decodes itself, such as a union, would refuse null, and one whose zero value cannot be encoded could // not write it back - if zeroIsAScalarValue(v, tp) || hasJSONMethods(v) || zeroUnencodable(v) { + if hasJSONMethods(v) || zeroUnencodable(v) { tp.IsPointer = true } return tp, nil } -// zeroIsAScalarValue reports whether s is a number or a boolean whose zero value, that of tp, is a value s can hold -// (see [zeroIsAValue]). -func zeroIsAScalarValue(s *openapi.Schema, tp *GoType) bool { - switch deref(s).Type { - case openapi.TypeBoolean, openapi.TypeInteger, openapi.TypeNumber: - return zeroIsAValue(s, tp) - default: - return false - } -} - // isOneOfOnly reports whether s is an untagged union expressed purely via // oneOf (no type, allOf, or anyOf of its own), and is not the // date-time-or-integer pattern that collapses to time.Time. diff --git a/ir/schema_test.go b/ir/schema_test.go index 1ff3afda..49209fea 100644 --- a/ir/schema_test.go +++ b/ir/schema_test.go @@ -257,6 +257,8 @@ func TestFromDocument_FieldTypesAndTags(t *testing.T) { "tags": {"type": "array", "items": {"type": "string"}}, "nullCount": {"oneOf": [{"type": "integer"}, {"type": "null"}]}, "nullName": {"oneOf": [{"type": "string"}, {"type": "null"}]}, + "seed": {"anyOf": [{"type": "integer"}, {"type": "null"}], "default": 0}, + "nullArchived": {"anyOf": [{"type": "boolean"}, {"type": "null"}], "default": false}, "limit": {"type": "integer"}, "pageSize": {"type": "integer", "minimum": 1}, "offset": {"type": "integer", "default": 0}, @@ -284,30 +286,33 @@ func TestFromDocument_FieldTypesAndTags(t *testing.T) { } // An optional field is omitted when unset, and a required one is always sent. A pointer is there only where its - // zero value is a value of its own, or to keep a struct from containing itself. + // zero value is a value of its own, or to keep a struct from containing itself. Null reads as the zero value, so + // that a field may be null makes it no pointer. for name, want := range map[string]string{ - "count": `int json:"count"`, - "on": `bool json:"on"`, - "id": `string json:"id"`, - "when": `time.Time json:"when"`, - "tags": `[]string json:"tags"`, - "nullCount": `*int json:"nullCount"`, - "nullName": `string json:"nullName"`, - "limit": `*int json:"limit,omitzero"`, - "pageSize": `int json:"pageSize,omitzero"`, - "offset": `int json:"offset,omitzero"`, - "archived": `*bool json:"archived,omitzero"`, - "name": `string json:"name,omitzero"`, - "site": `url.URL json:"site,omitzero"`, - "before": `time.Time json:"before,omitzero"`, - "ids": `[]string json:"ids,omitzero"`, - "labels": `map[string]string json:"labels,omitzero"`, - "ratio": `*float64 json:"ratio,omitzero"`, - "extra": `any json:"extra,omitzero"`, - "empty": `*struct{} json:"empty,omitzero"`, - "owner": `Owner json:"owner,omitzero"`, - "options": `*Options json:"options,omitzero"`, - "next": `*Filter json:"next,omitzero"`, + "count": `int json:"count"`, + "on": `bool json:"on"`, + "id": `string json:"id"`, + "when": `time.Time json:"when"`, + "tags": `[]string json:"tags"`, + "nullCount": `int json:"nullCount"`, + "seed": `int json:"seed,omitzero"`, + "nullArchived": `bool json:"nullArchived,omitzero"`, + "nullName": `string json:"nullName"`, + "limit": `*int json:"limit,omitzero"`, + "pageSize": `int json:"pageSize,omitzero"`, + "offset": `int json:"offset,omitzero"`, + "archived": `*bool json:"archived,omitzero"`, + "name": `string json:"name,omitzero"`, + "site": `url.URL json:"site,omitzero"`, + "before": `time.Time json:"before,omitzero"`, + "ids": `[]string json:"ids,omitzero"`, + "labels": `map[string]string json:"labels,omitzero"`, + "ratio": `*float64 json:"ratio,omitzero"`, + "extra": `any json:"extra,omitzero"`, + "empty": `*struct{} json:"empty,omitzero"`, + "owner": `Owner json:"owner,omitzero"`, + "options": `*Options json:"options,omitzero"`, + "next": `*Filter json:"next,omitzero"`, } { if got[name] != want { t.Errorf("%s: got %s, want %s", name, got[name], want) diff --git a/testdata/golden/pkg/golden/ir.json b/testdata/golden/pkg/golden/ir.json index ae9c37ee..614a49d4 100644 --- a/testdata/golden/pkg/golden/ir.json +++ b/testdata/golden/pkg/golden/ir.json @@ -4572,7 +4572,7 @@ { "name": "Plan", "jsonName": "plan", - "type": "*int", + "type": "int", "jsonTag": "json:\"plan\"", "required": true } diff --git a/testdata/golden/pkg/golden/types.gen.go b/testdata/golden/pkg/golden/types.gen.go index 2394ceb6..08d3fc43 100644 --- a/testdata/golden/pkg/golden/types.gen.go +++ b/testdata/golden/pkg/golden/types.gen.go @@ -2613,7 +2613,7 @@ func (v *Tags) MarshalJSONTo(enc *jsontext.Encoder) error { // A date that may be null is no pointer, since the zero date says what null does; a number that may be null is, since its zero is a number of its own. type Trial struct { Ends civil.Date `json:"ends"` - Plan *int `json:"plan"` + Plan int `json:"plan"` } // User defines a model From 2fbb8451f323b8858f38c314542d1e5a6683a275 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 14:14:18 +0000 Subject: [PATCH 2/3] feat: a union reads null as no alternative and writes it back A nullable union, plain or tagged, is now the union itself rather than a pointer to it: decoding null leaves every alternative unset, and encoding a union with none set writes null, as a nil pointer would. A tagged union's member that may be null is also recognised as such where it is written as type [X, "null"] or is a string, now that neither is a pointer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- README.md | 7 +- README/features.md | 7 +- ir/pointer.go | 4 +- ir/pointer_internal_test.go | 3 +- ir/schema.go | 6 +- ir/tagged.go | 2 +- render/templates/types.gen.go.tmpl | 33 +- testdata/debug/pkg/debug/types.gen.go | 25 +- testdata/golden/pkg/golden/decoding_test.go | 9 +- testdata/golden/pkg/golden/ir.json | 7 +- testdata/golden/pkg/golden/types.gen.go | 348 +++++++++++++++----- testdata/golden/pkg/golden/union_test.go | 6 +- 12 files changed, 343 insertions(+), 114 deletions(-) diff --git a/README.md b/README.md index bc124db9..48f52097 100644 --- a/README.md +++ b/README.md @@ -160,9 +160,10 @@ How the specification maps onto Go: - **Null** — a schema that is only ever `null` is `*struct{}`, and "X or null", a `type` of `[X, "null"]` or a `oneOf` or `anyOf` of `X` and `null`, is `X`: null reads as its zero value, and a required field sends the zero value where - it would have sent null. It is a pointer to `X` only by the rule for fields - above, or where `X` decodes itself, such as a union or a tuple, which would - refuse null. + it would have sent null. A union reads null as no alternative and writes an + unset union as null. `X` is a pointer only by the rule for fields above, + where it is a tuple, which would refuse null, or where it is an object that + requires a union, whose zero value would write that member as null. - **Fixed parameters** — a required parameter that can take only one value, its `const` or the only value of its `enum`, is sent by the client itself: in the path, the query or the headers, such as Notion's `Notion-Version`. The caller diff --git a/README/features.md b/README/features.md index ed3c437a..9f55b8db 100644 --- a/README/features.md +++ b/README/features.md @@ -115,9 +115,10 @@ How the specification maps onto Go: - **Null** — a schema that is only ever `null` is `*struct{}`, and "X or null", a `type` of `[X, "null"]` or a `oneOf` or `anyOf` of `X` and `null`, is `X`: null reads as its zero value, and a required field sends the zero value where - it would have sent null. It is a pointer to `X` only by the rule for fields - above, or where `X` decodes itself, such as a union or a tuple, which would - refuse null. + it would have sent null. A union reads null as no alternative and writes an + unset union as null. `X` is a pointer only by the rule for fields above, + where it is a tuple, which would refuse null, or where it is an object that + requires a union, whose zero value would write that member as null. - **Fixed parameters** — a required parameter that can take only one value, its `const` or the only value of its `enum`, is sent by the client itself: in the path, the query or the headers, such as Notion's `Notion-Version`. The caller diff --git a/ir/pointer.go b/ir/pointer.go index 00c1770b..6f42c46e 100644 --- a/ir/pointer.go +++ b/ir/pointer.go @@ -137,8 +137,8 @@ func pointRecursiveFields(schemas []Schema) { } } -// zeroUnencodable reports whether the zero value of s's Go type cannot be encoded: an object that requires a member, -// directly or through an object it requires, that is a union, which refuses to encode with no alternative set. Null +// zeroUnencodable reports whether the zero value of s's Go type encodes as nothing s allows: an object that requires a +// member, directly or through an object it requires, that is a union, which writes null with no alternative set. Null // reads as that zero value, so only a pointer can hold null and write it back. func zeroUnencodable(s *openapi.Schema) bool { return zeroUnencodableSeen(s, map[*openapi.Schema]bool{}) diff --git a/ir/pointer_internal_test.go b/ir/pointer_internal_test.go index 60a6f9a9..745e8a78 100644 --- a/ir/pointer_internal_test.go +++ b/ir/pointer_internal_test.go @@ -124,8 +124,9 @@ func TestNullableGoType(t *testing.T) { }}, false}, {"a number", &openapi.Schema{Type: openapi.TypeInteger}, false}, {"a boolean", &openapi.Schema{Type: openapi.TypeBoolean}, false}, + {"a union, which reads null as no alternative", union, false}, // it cannot: a pointer - {"a union, which refuses null", union, true}, + {"a tuple, which refuses null", &openapi.Schema{Type: openapi.TypeArray, PrefixItems: openapi.SchemaList{{Type: openapi.TypeString}}}, true}, } { tp, err := nullableGoType(tc.s) if err != nil { diff --git a/ir/schema.go b/ir/schema.go index 6ec72016..3729d7a0 100644 --- a/ir/schema.go +++ b/ir/schema.go @@ -223,9 +223,9 @@ func nullableGoType(v *openapi.Schema) (*GoType, error) { return nil, err } - // a type that decodes itself, such as a union, would refuse null, and one whose zero value cannot be encoded could - // not write it back - if hasJSONMethods(v) || zeroUnencodable(v) { + // a union reads null as no alternative and writes it back, but another type that decodes itself, such as a tuple, + // would refuse null, and an object requiring a union would write it back as an object of a null member + if hasJSONMethods(v) && !isUnion(v) && !isTaggedUnion(v) || zeroUnencodable(v) { tp.IsPointer = true } diff --git a/ir/tagged.go b/ir/tagged.go index 4430cec1..606eef2f 100644 --- a/ir/tagged.go +++ b/ir/tagged.go @@ -397,7 +397,7 @@ func taggedFields(shape *taggedShape, existing []Field) ([]Field, *Tagged, bool, return nil, nil, false, fmt.Errorf("property %q: %w", p.name, err) } - nullable := tp.IsPointer || nullableVariant(deref(own)) != nil + nullable := tp.IsPointer || allowsNull(own) tv.Members = append(tv.Members, TaggedOwn{Name: p.name, Required: shape.ownRequired[i][p.name], Nullable: nullable}) if declared[p.name] { diff --git a/render/templates/types.gen.go.tmpl b/render/templates/types.gen.go.tmpl index de429bc0..e2b1642b 100644 --- a/render/templates/types.gen.go.tmpl +++ b/render/templates/types.gen.go.tmpl @@ -342,10 +342,15 @@ type {{.Name}} struct { {{- if .Streamed }} // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Its member {{$disc}} names the alternative, which then -// decodes each further member as it is read. With {{$disc}} first, nothing is read twice. +// decodes each further member as it is read. With {{$disc}} first, nothing is read twice. Null sets no alternative. func (v *{{$typeName}}) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = {{$typeName}}{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + tag, first, dec, err := union.FirstMember(dec, {{ printf "%q" $disc }}) if err != nil { return err @@ -368,10 +373,15 @@ func (v *{{$typeName}}) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } {{- else }} -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *{{$typeName}}) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = {{$typeName}}{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) {{- if or (and $isOneOf (not .Discriminator)) .HasEnums }} strict := union.Strict(dec) @@ -463,7 +473,8 @@ func (v *{{$typeName}}) UnmarshalJSONFrom(dec *jsontext.Decoder) error { {{- end }} // MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant -{{- if .Streamed }}, with {{ $disc }} first, as decoding wants it, and set to the variant's value{{ end }}. +{{- if .Streamed }}, with {{ $disc }} first, as decoding wants it, and set to the variant's value{{ end }}, or null +// where none is set. func (v *{{$typeName}}) MarshalJSONTo(enc *jsontext.Encoder) error { {{- if .Streamed }} var ( @@ -477,7 +488,7 @@ func (v *{{$typeName}}) MarshalJSONTo(enc *jsontext.Encoder) error { variant, tag = v.{{.FieldName}}, {{ printf "%q" .Value }} {{- end}} default: - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } out, err := json.Marshal(variant, jsonOptsTo(enc)) @@ -498,7 +509,7 @@ func (v *{{$typeName}}) MarshalJSONTo(enc *jsontext.Encoder) error { {{- end}} } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) {{- end }} } {{- else if eq .Kind 6}}{{/* SchemaKindTuple */}} @@ -629,12 +640,17 @@ func (v *{{$s.Name}}) taggedMembers() []string { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. It decodes the members, then checks that of those of an -// alternative's own, only those of the one {{.Tag}} names are set. +// alternative's own, only those of the one {{.Tag}} names are set. Null sets no alternative. func (v *{{$s.Name}}) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type plain {{$s.Name}} *v = {{$s.Name}}{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + raw, err := dec.ReadValue() if err != nil { return err @@ -661,11 +677,14 @@ func (v *{{$s.Name}}) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } // MarshalJSONTo implements [json.MarshalerTo]. It checks the members as decoding does; with {{.Tag}} left empty, it sends -// the value whose member is set. +// the value whose member is set, or null where none is. func (v *{{$s.Name}}) MarshalJSONTo(enc *jsontext.Encoder) error { type plain {{$s.Name}} out, set := *v, v.taggedMembers() + if out.{{.Field}} == "" && len(set) == 0 { + return enc.WriteToken(jsontext.Null) + } if tag, ok := union.InferTag(tagsOf{{$s.Name}}, set); ok && out.{{.Field}} == "" { out.{{.Field}} = {{.Type}}(tag) } diff --git a/testdata/debug/pkg/debug/types.gen.go b/testdata/debug/pkg/debug/types.gen.go index bdae77af..d9286f89 100644 --- a/testdata/debug/pkg/debug/types.gen.go +++ b/testdata/debug/pkg/debug/types.gen.go @@ -7,7 +7,6 @@ package debug import ( "encoding/json/jsontext" "encoding/json/v2" - "errors" "fmt" "cloud.google.com/go/civil" @@ -66,12 +65,17 @@ func (v *Block) taggedMembers() []string { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. It decodes the members, then checks that of those of an -// alternative's own, only those of the one type names are set. +// alternative's own, only those of the one type names are set. Null sets no alternative. func (v *Block) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type plain Block *v = Block{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + raw, err := dec.ReadValue() if err != nil { return err @@ -91,11 +95,14 @@ func (v *Block) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } // MarshalJSONTo implements [json.MarshalerTo]. It checks the members as decoding does; with type left empty, it sends -// the value whose member is set. +// the value whose member is set, or null where none is. func (v *Block) MarshalJSONTo(enc *jsontext.Encoder) error { type plain Block out, set := *v, v.taggedMembers() + if out.Type == "" && len(set) == 0 { + return enc.WriteToken(jsontext.Null) + } if tag, ok := union.InferTag(tagsOfBlock, set); ok && out.Type == "" { out.Type = BlockType(tag) } @@ -131,10 +138,15 @@ type Pet struct { Dog *Dog } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *Pet) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Pet{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -178,7 +190,8 @@ func (v *Pet) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *Pet) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.Cat != nil: @@ -187,7 +200,7 @@ func (v *Pet) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.Dog, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // Problem defines a model diff --git a/testdata/golden/pkg/golden/decoding_test.go b/testdata/golden/pkg/golden/decoding_test.go index ec6dafea..ed00fccd 100644 --- a/testdata/golden/pkg/golden/decoding_test.go +++ b/testdata/golden/pkg/golden/decoding_test.go @@ -65,17 +65,22 @@ func TestDecoding_NullableUnion(t *testing.T) { t.Fatal(err) } - if p.Cover != nil || p.Icon != nil { + if p.Cover != (CoverResponse{}) || p.Icon != (IconResponse{}) { t.Errorf("got %+v, want no cover and no icon", p) } + // a union with no alternative writes the null it read + if out, err := json.Marshal(p, jsonOpts); err != nil || string(out) != page { + t.Errorf("got %s, %v, want %s", out, err, page) + } + p, err = client(t, `{"object":"page","id":"p","cover":{"type":"external","external":{"url":"u"}},"icon":{"emoji":"x"},"position":["a",1]}`). GetPage(t.Context(), "p") if err != nil { t.Fatal(err) } - if p.Cover == nil || p.Cover.External == nil || p.Icon == nil || p.Icon.Emoji == nil || p.Position.Pair == nil { + if p.Cover.External == nil || p.Icon.Emoji == nil || p.Position.Pair == nil { t.Errorf("got %+v, want the cover, the icon and the pair", p) } diff --git a/testdata/golden/pkg/golden/ir.json b/testdata/golden/pkg/golden/ir.json index 614a49d4..f7aca135 100644 --- a/testdata/golden/pkg/golden/ir.json +++ b/testdata/golden/pkg/golden/ir.json @@ -3126,7 +3126,8 @@ }, { "name": "url", - "required": true + "required": true, + "nullable": true } ] }, @@ -3506,14 +3507,14 @@ { "name": "Cover", "jsonName": "cover", - "type": "*CoverResponse", + "type": "CoverResponse", "jsonTag": "json:\"cover\"", "required": true }, { "name": "Icon", "jsonName": "icon", - "type": "*IconResponse", + "type": "IconResponse", "jsonTag": "json:\"icon\"", "required": true }, diff --git a/testdata/golden/pkg/golden/types.gen.go b/testdata/golden/pkg/golden/types.gen.go index 08d3fc43..58f42e9b 100644 --- a/testdata/golden/pkg/golden/types.gen.go +++ b/testdata/golden/pkg/golden/types.gen.go @@ -191,10 +191,15 @@ type AgentModel struct { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Its member mode names the alternative, which then -// decodes each further member as it is read. With mode first, nothing is read twice. +// decodes each further member as it is read. With mode first, nothing is read twice. Null sets no alternative. func (v *AgentModel) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = AgentModel{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + tag, first, dec, err := union.FirstMember(dec, "mode") if err != nil { return err @@ -222,7 +227,8 @@ func (v *AgentModel) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, with mode first, as decoding wants it, and set to the variant's value. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, with mode first, as decoding wants it, and set to the variant's value, or null +// where none is set. func (v *AgentModel) MarshalJSONTo(enc *jsontext.Encoder) error { var ( variant any @@ -235,7 +241,7 @@ func (v *AgentModel) MarshalJSONTo(enc *jsontext.Encoder) error { case v.AgentModelOneOf2 != nil: variant, tag = v.AgentModelOneOf2, "pinned" default: - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } out, err := json.Marshal(variant, jsonOptsTo(enc)) @@ -355,12 +361,17 @@ func (v *Block) taggedMembers() []string { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. It decodes the members, then checks that of those of an -// alternative's own, only those of the one type names are set. +// alternative's own, only those of the one type names are set. Null sets no alternative. func (v *Block) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type plain Block *v = Block{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + raw, err := dec.ReadValue() if err != nil { return err @@ -380,11 +391,14 @@ func (v *Block) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } // MarshalJSONTo implements [json.MarshalerTo]. It checks the members as decoding does; with type left empty, it sends -// the value whose member is set. +// the value whose member is set, or null where none is. func (v *Block) MarshalJSONTo(enc *jsontext.Encoder) error { type plain Block out, set := *v, v.taggedMembers() + if out.Type == "" && len(set) == 0 { + return enc.WriteToken(jsontext.Null) + } if tag, ok := union.InferTag(tagsOfBlock, set); ok && out.Type == "" { out.Type = BlockType(tag) } @@ -403,10 +417,15 @@ type Bot struct { BotAnyOf1 *BotAnyOf1 } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *Bot) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Bot{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) raw, err := dec.ReadValue() @@ -443,7 +462,8 @@ func (v *Bot) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *Bot) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.Object != nil: @@ -452,7 +472,7 @@ func (v *Bot) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.BotAnyOf1, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // BotAnyOf1 defines a model @@ -548,12 +568,17 @@ func (v *CoverResponse) taggedMembers() []string { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. It decodes the members, then checks that of those of an -// alternative's own, only those of the one type names are set. +// alternative's own, only those of the one type names are set. Null sets no alternative. func (v *CoverResponse) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type plain CoverResponse *v = CoverResponse{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + raw, err := dec.ReadValue() if err != nil { return err @@ -573,11 +598,14 @@ func (v *CoverResponse) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } // MarshalJSONTo implements [json.MarshalerTo]. It checks the members as decoding does; with type left empty, it sends -// the value whose member is set. +// the value whose member is set, or null where none is. func (v *CoverResponse) MarshalJSONTo(enc *jsontext.Encoder) error { type plain CoverResponse out, set := *v, v.taggedMembers() + if out.Type == "" && len(set) == 0 { + return enc.WriteToken(jsontext.Null) + } if tag, ok := union.InferTag(tagsOfCoverResponse, set); ok && out.Type == "" { out.Type = CoverResponseType(tag) } @@ -618,12 +646,17 @@ func (v *CreateDatabaseParent) taggedMembers() []string { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. It decodes the members, then checks that of those of an -// alternative's own, only those of the one type names are set. +// alternative's own, only those of the one type names are set. Null sets no alternative. func (v *CreateDatabaseParent) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type plain CreateDatabaseParent *v = CreateDatabaseParent{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + raw, err := dec.ReadValue() if err != nil { return err @@ -648,11 +681,14 @@ func (v *CreateDatabaseParent) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } // MarshalJSONTo implements [json.MarshalerTo]. It checks the members as decoding does; with type left empty, it sends -// the value whose member is set. +// the value whose member is set, or null where none is. func (v *CreateDatabaseParent) MarshalJSONTo(enc *jsontext.Encoder) error { type plain CreateDatabaseParent out, set := *v, v.taggedMembers() + if out.Type == "" && len(set) == 0 { + return enc.WriteToken(jsontext.Null) + } if tag, ok := union.InferTag(tagsOfCreateDatabaseParent, set); ok && out.Type == "" { out.Type = CreateDatabaseParentAllOfType(tag) } @@ -723,10 +759,15 @@ type Entry struct { Note *Note } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *Entry) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Entry{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -770,7 +811,8 @@ func (v *Entry) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *Entry) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.Record != nil: @@ -779,7 +821,7 @@ func (v *Entry) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.Note, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // FileDetails defines a model @@ -801,10 +843,15 @@ type Filter struct { FilterAnyOf1 *FilterAnyOf1 } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *Filter) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Filter{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) raw, err := dec.ReadValue() @@ -845,7 +892,8 @@ func (v *Filter) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *Filter) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.FilterAnyOf0 != nil: @@ -854,7 +902,7 @@ func (v *Filter) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.FilterAnyOf1, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // FilterAnyOf0 defines a model @@ -887,10 +935,15 @@ type GroupBy struct { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Its member type names the alternative, which then -// decodes each further member as it is read. With type first, nothing is read twice. +// decodes each further member as it is read. With type first, nothing is read twice. Null sets no alternative. func (v *GroupBy) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = GroupBy{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + tag, first, dec, err := union.FirstMember(dec, "type") if err != nil { return err @@ -918,7 +971,8 @@ func (v *GroupBy) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, with type first, as decoding wants it, and set to the variant's value. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, with type first, as decoding wants it, and set to the variant's value, or null +// where none is set. func (v *GroupBy) MarshalJSONTo(enc *jsontext.Encoder) error { var ( variant any @@ -931,7 +985,7 @@ func (v *GroupBy) MarshalJSONTo(enc *jsontext.Encoder) error { case v.GroupByAnyOf1 != nil: variant, tag = v.GroupByAnyOf1, "date" default: - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } out, err := json.Marshal(variant, jsonOptsTo(enc)) @@ -1014,10 +1068,15 @@ type IconResponse struct { Link *Link } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *IconResponse) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = IconResponse{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -1061,7 +1120,8 @@ func (v *IconResponse) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *IconResponse) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.Emoji != nil: @@ -1070,7 +1130,7 @@ func (v *IconResponse) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.Link, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // A map of its own. @@ -1117,10 +1177,15 @@ type MaybeMember struct { GroupObjectResponse *GroupObjectResponse } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *MaybeMember) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = MaybeMember{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -1164,7 +1229,8 @@ func (v *MaybeMember) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *MaybeMember) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.NestedValue != nil: @@ -1173,7 +1239,7 @@ func (v *MaybeMember) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.GroupObjectResponse, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // Its alternatives each have members of their own beside the tag, so they stay a union beside the members all share. @@ -1318,10 +1384,15 @@ type MemberAllOf1 struct { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Its member type names the alternative, which then -// decodes each further member as it is read. With type first, nothing is read twice. +// decodes each further member as it is read. With type first, nothing is read twice. Null sets no alternative. func (v *MemberAllOf1) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = MemberAllOf1{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + tag, first, dec, err := union.FirstMember(dec, "type") if err != nil { return err @@ -1349,7 +1420,8 @@ func (v *MemberAllOf1) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, with type first, as decoding wants it, and set to the variant's value. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, with type first, as decoding wants it, and set to the variant's value, or null +// where none is set. func (v *MemberAllOf1) MarshalJSONTo(enc *jsontext.Encoder) error { var ( variant any @@ -1362,7 +1434,7 @@ func (v *MemberAllOf1) MarshalJSONTo(enc *jsontext.Encoder) error { case v.BotUserObjectResponse != nil: variant, tag = v.BotUserObjectResponse, "bot" default: - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } out, err := json.Marshal(variant, jsonOptsTo(enc)) @@ -1494,7 +1566,7 @@ func (e NestedValueType) Valid() bool { // tagsOfNestedValue holds, for each value of type, the members of its alternative's own, each with how it is needed. var tagsOfNestedValue = map[string]map[string]union.TagNeed{ "number": {"number": union.TagRequired}, - "url": {"label": union.TagOptional, "url": union.TagRequired}, + "url": {"label": union.TagOptional, "url": union.TagRequiredOrNull}, "title": {"label": union.TagOptional, "title": union.TagRequired}, } @@ -1518,12 +1590,17 @@ func (v *NestedValue) taggedMembers() []string { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. It decodes the members, then checks that of those of an -// alternative's own, only those of the one type names are set. +// alternative's own, only those of the one type names are set. Null sets no alternative. func (v *NestedValue) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type plain NestedValue *v = NestedValue{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + raw, err := dec.ReadValue() if err != nil { return err @@ -1543,11 +1620,14 @@ func (v *NestedValue) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } // MarshalJSONTo implements [json.MarshalerTo]. It checks the members as decoding does; with type left empty, it sends -// the value whose member is set. +// the value whose member is set, or null where none is. func (v *NestedValue) MarshalJSONTo(enc *jsontext.Encoder) error { type plain NestedValue out, set := *v, v.taggedMembers() + if out.Type == "" && len(set) == 0 { + return enc.WriteToken(jsontext.Null) + } if tag, ok := union.InferTag(tagsOfNestedValue, set); ok && out.Type == "" { out.Type = NestedValueType(tag) } @@ -1566,10 +1646,15 @@ type Node struct { FolderDetails *FolderDetails } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *Node) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Node{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -1613,7 +1698,8 @@ func (v *Node) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *Node) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.FileDetails != nil: @@ -1622,7 +1708,7 @@ func (v *Node) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.FolderDetails, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // Note defines a model @@ -1648,10 +1734,15 @@ type Order struct { OrderOneOf1 OrderOneOf1 } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *Order) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Order{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -1687,7 +1778,8 @@ func (v *Order) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *Order) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.OrderOneOf0 != "": @@ -1696,7 +1788,7 @@ func (v *Order) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.OrderOneOf1, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // OrderOneOf0 defines a model @@ -1746,10 +1838,15 @@ type Owner struct { GroupObjectResponse *GroupObjectResponse } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *Owner) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Owner{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -1793,7 +1890,8 @@ func (v *Owner) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *Owner) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.PartialUserObjectResponse != nil: @@ -1802,16 +1900,16 @@ func (v *Owner) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.GroupObjectResponse, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // Page defines a model type Page struct { - Object string `json:"object"` - ID string `json:"id"` - Cover *CoverResponse `json:"cover"` - Icon *IconResponse `json:"icon"` - Position Position `json:"position"` + Object string `json:"object"` + ID string `json:"id"` + Cover CoverResponse `json:"cover"` + Icon IconResponse `json:"icon"` + Position Position `json:"position"` } // PageOrPartial defines a model @@ -1821,10 +1919,15 @@ type PageOrPartial struct { PartialPage *PartialPage } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *PageOrPartial) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = PageOrPartial{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) raw, err := dec.ReadValue() @@ -1865,7 +1968,8 @@ func (v *PageOrPartial) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *PageOrPartial) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.Page != nil: @@ -1874,7 +1978,7 @@ func (v *PageOrPartial) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.PartialPage, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // Pair defines a model @@ -1945,10 +2049,15 @@ type Pairs struct { Int []int } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *Pairs) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Pairs{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -1984,7 +2093,8 @@ func (v *Pairs) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *Pairs) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.String != nil: @@ -1993,7 +2103,7 @@ func (v *Pairs) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.Int, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // PartialPage defines a model @@ -2016,10 +2126,15 @@ type PeopleArrayBasedPropertyValueResponsePeopleItem struct { GroupObjectResponse *GroupObjectResponse } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *PeopleArrayBasedPropertyValueResponsePeopleItem) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = PeopleArrayBasedPropertyValueResponsePeopleItem{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -2059,7 +2174,8 @@ func (v *PeopleArrayBasedPropertyValueResponsePeopleItem) UnmarshalJSONFrom(dec return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *PeopleArrayBasedPropertyValueResponsePeopleItem) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.UserValueResponse != nil: @@ -2068,7 +2184,7 @@ func (v *PeopleArrayBasedPropertyValueResponsePeopleItem) MarshalJSONTo(enc *jso return json.MarshalEncode(enc, v.GroupObjectResponse, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // PersonGroup defines a model @@ -2103,10 +2219,15 @@ type Position struct { Pair *Pair } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *Position) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Position{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -2142,7 +2263,8 @@ func (v *Position) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *Position) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.String != nil: @@ -2151,7 +2273,7 @@ func (v *Position) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.Pair, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // A failure the server describes. @@ -2201,12 +2323,17 @@ func (v *PropertyFilter) taggedMembers() []string { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. It decodes the members, then checks that of those of an -// alternative's own, only those of the one type names are set. +// alternative's own, only those of the one type names are set. Null sets no alternative. func (v *PropertyFilter) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type plain PropertyFilter *v = PropertyFilter{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + raw, err := dec.ReadValue() if err != nil { return err @@ -2231,11 +2358,14 @@ func (v *PropertyFilter) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } // MarshalJSONTo implements [json.MarshalerTo]. It checks the members as decoding does; with type left empty, it sends -// the value whose member is set. +// the value whose member is set, or null where none is. func (v *PropertyFilter) MarshalJSONTo(enc *jsontext.Encoder) error { type plain PropertyFilter out, set := *v, v.taggedMembers() + if out.Type == "" && len(set) == 0 { + return enc.WriteToken(jsontext.Null) + } if tag, ok := union.InferTag(tagsOfPropertyFilter, set); ok && out.Type == "" { out.Type = PropertyFilterType(tag) } @@ -2288,12 +2418,17 @@ func (v *PropertyValue) taggedMembers() []string { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. It decodes the members, then checks that of those of an -// alternative's own, only those of the one type names are set. +// alternative's own, only those of the one type names are set. Null sets no alternative. func (v *PropertyValue) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type plain PropertyValue *v = PropertyValue{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + raw, err := dec.ReadValue() if err != nil { return err @@ -2313,11 +2448,14 @@ func (v *PropertyValue) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } // MarshalJSONTo implements [json.MarshalerTo]. It checks the members as decoding does; with type left empty, it sends -// the value whose member is set. +// the value whose member is set, or null where none is. func (v *PropertyValue) MarshalJSONTo(enc *jsontext.Encoder) error { type plain PropertyValue out, set := *v, v.taggedMembers() + if out.Type == "" && len(set) == 0 { + return enc.WriteToken(jsontext.Null) + } if tag, ok := union.InferTag(tagsOfPropertyValue, set); ok && out.Type == "" { out.Type = PropertyValueType(tag) } @@ -2511,12 +2649,17 @@ func (v *SimpleOrArray) taggedMembers() []string { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. It decodes the members, then checks that of those of an -// alternative's own, only those of the one type names are set. +// alternative's own, only those of the one type names are set. Null sets no alternative. func (v *SimpleOrArray) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type plain SimpleOrArray *v = SimpleOrArray{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + raw, err := dec.ReadValue() if err != nil { return err @@ -2536,11 +2679,14 @@ func (v *SimpleOrArray) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } // MarshalJSONTo implements [json.MarshalerTo]. It checks the members as decoding does; with type left empty, it sends -// the value whose member is set. +// the value whose member is set, or null where none is. func (v *SimpleOrArray) MarshalJSONTo(enc *jsontext.Encoder) error { type plain SimpleOrArray out, set := *v, v.taggedMembers() + if out.Type == "" && len(set) == 0 { + return enc.WriteToken(jsontext.Null) + } if tag, ok := union.InferTag(tagsOfSimpleOrArray, set); ok && out.Type == "" { out.Type = SimpleOrArrayType(tag) } @@ -2559,10 +2705,15 @@ type Tags struct { String2 []string } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *Tags) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Tags{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -2598,7 +2749,8 @@ func (v *Tags) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *Tags) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.String != "": @@ -2607,7 +2759,7 @@ func (v *Tags) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.String2, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // A date that may be null is no pointer, since the zero date says what null does; a number that may be null is, since its zero is a number of its own. @@ -2668,12 +2820,17 @@ func (v *UserObjectResponse) taggedMembers() []string { } // UnmarshalJSONFrom implements [json.UnmarshalerFrom]. It decodes the members, then checks that of those of an -// alternative's own, only those of the one type names are set. +// alternative's own, only those of the one type names are set. Null sets no alternative. func (v *UserObjectResponse) UnmarshalJSONFrom(dec *jsontext.Decoder) error { type plain UserObjectResponse *v = UserObjectResponse{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + raw, err := dec.ReadValue() if err != nil { return err @@ -2693,11 +2850,14 @@ func (v *UserObjectResponse) UnmarshalJSONFrom(dec *jsontext.Decoder) error { } // MarshalJSONTo implements [json.MarshalerTo]. It checks the members as decoding does; with type left empty, it sends -// the value whose member is set. +// the value whose member is set, or null where none is. func (v *UserObjectResponse) MarshalJSONTo(enc *jsontext.Encoder) error { type plain UserObjectResponse out, set := *v, v.taggedMembers() + if out.Type == "" && len(set) == 0 { + return enc.WriteToken(jsontext.Null) + } if tag, ok := union.InferTag(tagsOfUserObjectResponse, set); ok && out.Type == "" { out.Type = UserObjectResponseType(tag) } @@ -2752,10 +2912,15 @@ type UserValueResponse struct { UserObjectResponse *UserObjectResponse } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *UserValueResponse) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = UserValueResponse{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -2799,7 +2964,8 @@ func (v *UserValueResponse) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *UserValueResponse) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.PartialUserObjectResponse != nil: @@ -2808,7 +2974,7 @@ func (v *UserValueResponse) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.UserObjectResponse, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // Value defines a model @@ -2944,10 +3110,15 @@ type ValueAllOf1 struct { Rollup *Rollup } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *ValueAllOf1) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = ValueAllOf1{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -2991,7 +3162,8 @@ func (v *ValueAllOf1) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *ValueAllOf1) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.SimpleOrArray != nil: @@ -3000,7 +3172,7 @@ func (v *ValueAllOf1) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.Rollup, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // A property filter or a compound one. No property filter requires its type, so neither does PropertyFilter: a filter without one is still a property filter. @@ -3010,10 +3182,15 @@ type ViewFilter struct { CompoundFilter *CompoundFilter } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *ViewFilter) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = ViewFilter{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -3057,7 +3234,8 @@ func (v *ViewFilter) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *ViewFilter) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.PropertyFilter != nil: @@ -3066,7 +3244,7 @@ func (v *ViewFilter) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.CompoundFilter, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // Alternatives told apart by the enums of their type alone: a value outside one rules it out, but leniently only while another fits. @@ -3076,10 +3254,15 @@ type ViewGroupBy struct { PersonGroup *PersonGroup } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. func (v *ViewGroupBy) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = ViewGroupBy{} + if dec.PeekKind() == 'n' { + _, err := dec.ReadToken() + return err + } + opts := jsonOptsOf(dec) strict := union.Strict(dec) @@ -3131,7 +3314,8 @@ func (v *ViewGroupBy) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant. +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// where none is set. func (v *ViewGroupBy) MarshalJSONTo(enc *jsontext.Encoder) error { switch { case v.SelectGroup != nil: @@ -3140,7 +3324,7 @@ func (v *ViewGroupBy) MarshalJSONTo(enc *jsontext.Encoder) error { return json.MarshalEncode(enc, v.PersonGroup, jsonOptsTo(enc)) } - return &json.SemanticError{Err: errors.New("no alternative set")} + return enc.WriteToken(jsontext.Null) } // jsonOptsOf is jsonOpts, or jsonOptsLenient where dec accepts members the specification does not know. diff --git a/testdata/golden/pkg/golden/union_test.go b/testdata/golden/pkg/golden/union_test.go index e63e6858..67f6c391 100644 --- a/testdata/golden/pkg/golden/union_test.go +++ b/testdata/golden/pkg/golden/union_test.go @@ -117,12 +117,16 @@ func TestTagged_Encode(t *testing.T) { for _, p := range []CreateDatabaseParent{ {Type: "page_id", PageID: "59833787-2cf9-4fdf-8782-e53db20768a5", Workspace: new(true)}, {Type: "workspace"}, - {}, } { if _, err := json.Marshal(&p, jsonOpts); err == nil { t.Errorf("%+v: encoded, want an error", p) } } + + // with no alternative, it is null, as decoding reads null + if out, err := json.Marshal(&CreateDatabaseParent{}, jsonOpts); err != nil || string(out) != "null" { + t.Errorf("got %s, %v, want null", out, err) + } } func TestTagged_Nested(t *testing.T) { From eee9564bf4eaf00b1618519b4ec23367f2788644 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 14:18:54 +0000 Subject: [PATCH 3/3] feat: a union that may be null is told apart by its discriminator too Null is read before the discriminator is looked for, so a union such as anyOf [Mask, Oval, Rectangle, null] whose alternatives each pin "type" now decodes by switching on it, member by member, rather than by trying each alternative. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- ir/allof.go | 15 +--- testdata/golden/pkg/golden/ir.json | 14 +++- testdata/golden/pkg/golden/types.gen.go | 97 ++++++++++++++++--------- 3 files changed, 75 insertions(+), 51 deletions(-) diff --git a/ir/allof.go b/ir/allof.go index d78a4098..6b5118c6 100644 --- a/ir/allof.go +++ b/ir/allof.go @@ -348,9 +348,9 @@ func unionVariants(u *openapi.Schema, variants openapi.SchemaList) (fields, choi decider = &openapi.Schema{} } - // a union that can be null cannot have a discriminator come first + // null, where the union may be it, is read before the discriminator is looked for member, values, ok := discriminate(decider, leaves) - if !ok || countNull(variants) > 0 { + if !ok { return fields, choices, "", nil } @@ -367,17 +367,6 @@ func unionVariants(u *openapi.Schema, variants openapi.SchemaList) (fields, choi return fields, choices, member, nil } -func countNull(l openapi.SchemaList) int { - n := 0 - for _, s := range l { - if isNull(s) { - n++ - } - } - - return n -} - // fromAllOfSchema builds the struct of an allOf. A part that only this schema uses is folded into its fields, any // other is embedded, and a union among the parts is held as a field of its own, decoded by the struct's own methods. func fromAllOfSchema(name string, s *openapi.Schema, uses map[string]int, folded map[string]bool) (*Schema, error) { diff --git a/testdata/golden/pkg/golden/ir.json b/testdata/golden/pkg/golden/ir.json index f7aca135..c35024a4 100644 --- a/testdata/golden/pkg/golden/ir.json +++ b/testdata/golden/pkg/golden/ir.json @@ -2442,7 +2442,8 @@ "description": "The name of the group.", "required": true } - ] + ], + "memberDecoder": true }, { "name": "IDRequest", @@ -3397,6 +3398,7 @@ { "fieldName": "PartialUserObjectResponse", "type": "PartialUserObjectResponse", + "value": "user", "members": [ "id", "object" @@ -3416,6 +3418,7 @@ { "fieldName": "GroupObjectResponse", "type": "GroupObjectResponse", + "value": "group", "members": [ "id", "name", @@ -3442,6 +3445,7 @@ { "fieldName": "PartialUserObjectResponse", "type": "PartialUserObjectResponse", + "value": "user", "members": [ "id", "object" @@ -3461,6 +3465,7 @@ { "fieldName": "GroupObjectResponse", "type": "GroupObjectResponse", + "value": "group", "members": [ "id", "name", @@ -3483,7 +3488,9 @@ ] } ], - "isOneOf": true + "isOneOf": true, + "discriminator": "object", + "streamed": true }, { "name": "Page", @@ -3718,7 +3725,8 @@ "required": true, "fixed": "\"user\"" } - ] + ], + "memberDecoder": true }, { "name": "PeopleArrayBasedPropertyValueResponsePeopleItem", diff --git a/testdata/golden/pkg/golden/types.gen.go b/testdata/golden/pkg/golden/types.gen.go index 58f42e9b..c5365444 100644 --- a/testdata/golden/pkg/golden/types.gen.go +++ b/testdata/golden/pkg/golden/types.gen.go @@ -1055,6 +1055,20 @@ type GroupObjectResponse struct { Name string `json:"name"` } +// unmarshalJSONMember decodes the value of the member name into its field, reporting whether GroupObjectResponse declares it. +func (v *GroupObjectResponse) unmarshalJSONMember(dec *jsontext.Decoder, name string) (bool, error) { + switch name { + case "id": + return true, json.UnmarshalDecode(dec, &v.ID, jsonOptsOf(dec)) + case "object": + return true, json.UnmarshalDecode(dec, &v.Object, jsonOptsOf(dec)) + case "name": + return true, json.UnmarshalDecode(dec, &v.Name, jsonOptsOf(dec)) + } + + return false, nil +} + // IDRequest defines a model type IDRequest string @@ -1838,7 +1852,8 @@ type Owner struct { GroupObjectResponse *GroupObjectResponse } -// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Null sets no alternative. +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]. Its member object names the alternative, which then +// decodes each further member as it is read. With object first, nothing is read twice. Null sets no alternative. func (v *Owner) UnmarshalJSONFrom(dec *jsontext.Decoder) error { *v = Owner{} @@ -1847,60 +1862,60 @@ func (v *Owner) UnmarshalJSONFrom(dec *jsontext.Decoder) error { return err } - opts := jsonOptsOf(dec) - strict := union.Strict(dec) - - raw, err := dec.ReadValue() + tag, first, dec, err := union.FirstMember(dec, "object") if err != nil { return err } - var matched int - - // leniently, more than one may match, and the first does - if strict || matched == 0 { - // decoding checks neither the members the alternative requires nor those it pins to one value - required, nullable, pinned := []string{"id", "object"}, map[string]bool{}, map[string]string{"object": "\"user\""} - if union.Fits(raw, required, nullable, pinned) { - var vv PartialUserObjectResponse - if err := json.Unmarshal(raw, &vv, opts); err == nil { - v.PartialUserObjectResponse = &vv - matched++ - } + switch tag { + case "user": + var vv PartialUserObjectResponse + if err := union.MembersFrom(dec, "object", first, vv.unmarshalJSONMember); err != nil { + return err } - } - // leniently, more than one may match, and the first does - if strict || matched == 0 { - // decoding checks neither the members the alternative requires nor those it pins to one value - required, nullable, pinned := []string{"id", "name", "object"}, map[string]bool{"name": true}, map[string]string{"object": "\"group\""} - if union.Fits(raw, required, nullable, pinned) { - var vv GroupObjectResponse - if err := json.Unmarshal(raw, &vv, opts); err == nil { - v.GroupObjectResponse = &vv - matched++ - } + v.PartialUserObjectResponse = &vv + case "group": + var vv GroupObjectResponse + if err := union.MembersFrom(dec, "object", first, vv.unmarshalJSONMember); err != nil { + return err } - } - if matched != 1 { - return &json.SemanticError{Err: fmt.Errorf("matches %d of its alternatives, want exactly one", matched)} + v.GroupObjectResponse = &vv + default: + return union.UnknownValue("object", tag) } return nil } -// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, or null +// MarshalJSONTo implements [json.MarshalerTo]. It emits the first non-nil variant, with object first, as decoding wants it, and set to the variant's value, or null // where none is set. func (v *Owner) MarshalJSONTo(enc *jsontext.Encoder) error { + var ( + variant any + tag string + ) + switch { case v.PartialUserObjectResponse != nil: - return json.MarshalEncode(enc, v.PartialUserObjectResponse, jsonOptsTo(enc)) + variant, tag = v.PartialUserObjectResponse, "user" case v.GroupObjectResponse != nil: - return json.MarshalEncode(enc, v.GroupObjectResponse, jsonOptsTo(enc)) + variant, tag = v.GroupObjectResponse, "group" + default: + return enc.WriteToken(jsontext.Null) } - return enc.WriteToken(jsontext.Null) + out, err := json.Marshal(variant, jsonOptsTo(enc)) + if err != nil { + return err + } + + if out, err = union.First(out, "object", tag); err != nil { + return err + } + + return enc.WriteValue(out) } // Page defines a model @@ -2119,6 +2134,18 @@ type PartialUserObjectResponse struct { Object string `json:"object"` } +// unmarshalJSONMember decodes the value of the member name into its field, reporting whether PartialUserObjectResponse declares it. +func (v *PartialUserObjectResponse) unmarshalJSONMember(dec *jsontext.Decoder, name string) (bool, error) { + switch name { + case "id": + return true, json.UnmarshalDecode(dec, &v.ID, jsonOptsOf(dec)) + case "object": + return true, json.UnmarshalDecode(dec, &v.Object, jsonOptsOf(dec)) + } + + return false, nil +} + // PeopleArrayBasedPropertyValueResponsePeopleItem defines a model // PeopleArrayBasedPropertyValueResponsePeopleItem is an untagged oneOf union: exactly one field is set after unmarshaling. type PeopleArrayBasedPropertyValueResponsePeopleItem struct {