Skip to content

Commit

Permalink
Merge pull request #1111 from tdakkota/fix/set-proper-alias-nil-semantic
Browse files Browse the repository at this point in the history
fix(gen): set proper nil semantic for aliased arrays
  • Loading branch information
ernado authored Nov 17, 2023
2 parents 64bf6f4 + 88780a9 commit 36ebf3a
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 113 deletions.
15 changes: 10 additions & 5 deletions examples/ex_github/oas_json_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

85 changes: 0 additions & 85 deletions examples/ex_github/oas_validators_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 21 additions & 17 deletions examples/ex_openapi/output.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 13 additions & 6 deletions gen/_template/json/encoders_alias.tmpl
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
{{- /*gotype: github.com/ogen-go/ogen/gen/ir.Type*/ -}}
{{- define "json/encoders_alias" }}
{{- $a := $.AliasTo }}
// Encode encodes {{ $.Name }} as json.
func (s {{ $.ReadOnlyReceiver }}) Encode(e *jx.Encoder) {
{{- if $.AliasTo.DoPassByPointer }}
unwrapped := (*{{ $.AliasTo.Go }})(s)
{{- if $a.DoPassByPointer }}
unwrapped := (*{{ $a.Go }})(s)
{{- else }}
unwrapped := {{ $.AliasTo.Go }}(s)
unwrapped := {{ $a.Go }}(s)
{{- end }}
{{ template "json/enc" elem $.AliasTo "unwrapped" -}}
{{- if and $a.IsArray $a.NilSemantic.Optional }}{{/* Prevents empty value encoding */}}
if unwrapped == nil {
e.ArrEmpty()
return
}
{{- end }}
{{ template "json/enc" elem $a "unwrapped" -}}
}

// Decode decodes {{ $.Name }} from json.
func (s *{{ $.Name }}) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New({{ printf "invalid: unable to decode %s to nil" $.Name | quote }})
}
var unwrapped {{ $.AliasTo.Go }}
var unwrapped {{ $a.Go }}
if err := func() error {
{{- template "json/dec" elem $.AliasTo "unwrapped" }}
{{- template "json/dec" elem $a "unwrapped" }}
return nil
}(); err != nil {
return errors.Wrap(err, "alias")
Expand Down
2 changes: 2 additions & 0 deletions gen/generics.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func boxType(t *ir.Type, v ir.GenericVariant) (*ir.Type, error) {
if dealiased.IsAlias() {
dealiased = dealiased.AliasTo
}

// Do not wrap if
// * type is Any
// * type is Stream
Expand Down Expand Up @@ -93,6 +94,7 @@ func boxType(t *ir.Type, v ir.GenericVariant) (*ir.Type, error) {
}
return ir.Generic(postfix, t, v), nil
}
dealiased.NilSemantic = t.NilSemantic

return t, nil
}
Expand Down

0 comments on commit 36ebf3a

Please sign in to comment.