Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ How the specification maps onto Go:
members the specification
does not know. Only if that fails too does the call fail, so a response that
merely holds more than the specification says still reaches the caller.
A response holding a value of an enum the specification does not list, which
decodes, is recorded too: each type holding an enum has an `unknownEnum`
method, which the client calls on what it decoded, in debug mode only.
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.
Expand Down
4 changes: 4 additions & 0 deletions ir/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ func FromDocument(doc *openapi.Document, packageName, userAgent string, producti
return nil, fmt.Errorf("paths: %w", err)
}

if debug {
markUnknownEnums(schemas)
}

hasURL, hasDuration, hasDate, hasDateTimeOrInt := needsSpecialImports(schemas, operations)

encodings, err := markEncodings(schemas)
Expand Down
7 changes: 6 additions & 1 deletion ir/ir.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import (
// Document is the top-level IR type passed to templates.
type Document struct {
// If enabled, debug mode will record responses that failed to unmarshal.
Debug bool `json:"debug,omitzero"`
Debug bool `json:"debug,omitzero"`
// enums tells what each type holds of an enum, see [Document.UnknownEnum].
enums *enums
Title string `json:"title,omitzero"`
Production bool `json:"production,omitzero"`
PackageName string `json:"packageName,omitzero"`
Expand Down Expand Up @@ -253,6 +255,9 @@ type Schema struct {
// response leaves out.
ReadOnly []string `json:"readOnly,omitempty"`
WriteOnly []string `json:"writeOnly,omitempty"`
// UnknownEnum is set in debug mode for a type that holds an enum: the body of its unknownEnum method, an
// expression of its receiver v, true if an enum it holds has a value the specification does not list.
UnknownEnum string `json:"unknownEnum,omitzero"`
}

// AllOfUnion is the union part of an allOf.
Expand Down
258 changes: 258 additions & 0 deletions ir/unknown_enum.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
package ir

import (
"strconv"
"strings"
)

// enums tells what a Go type of the document holds of an enum, so that debug mode can record a response holding a
// value the specification does not list: it decodes, since an enum is a plain string or number, but is news.
type enums struct {
byName map[string]*Schema
zero map[string]string // the zero value of each enum type, which an optional member holds while left out
holds map[string]bool // whether a named type holds an enum, as found so far
}

func newEnums(schemas []Schema) *enums {
e := &enums{byName: make(map[string]*Schema, len(schemas)), zero: map[string]string{}, holds: map[string]bool{}}

for i := range schemas {
s := &schemas[i]
e.byName[s.Name] = s

if s.Kind == SchemaKindEnum {
e.zero[s.Name] = zeroOf(s.Type)
}

if s.Tagged != nil && len(s.Tagged.Enum) > 0 {
e.zero[s.Tagged.Type] = `""`
}
}

return e
}

func zeroOf(typ string) string {
if typ == "string" {
return `""`
}

return "0"
}

// markUnknownEnums gives each schema that holds an enum, if not through a type alias, its UnknownEnum.
func markUnknownEnums(schemas []Schema) {
e := newEnums(schemas)

for i := range schemas {
if s := &schemas[i]; !s.IsTypeAlias && e.holdsEnum(s.Name) {
s.UnknownEnum = e.method(s)
}
}
}

// holdsEnum reports whether a value of the Go type typ may hold an enum.
func (e *enums) holdsEnum(typ string) bool {
if elem, ok := strings.CutPrefix(typ, "*"); ok {
return e.holdsEnum(elem)
}

if elem, ok := strings.CutPrefix(typ, "[]"); ok {
return e.holdsEnum(elem)
}

if key, value, ok := mapTypes(typ); ok {
return e.holdsEnum(key) || e.holdsEnum(value)
}

if _, ok := e.zero[typ]; ok {
return true
}

s := e.byName[typ]
if s == nil {
return false
}

if holds, ok := e.holds[typ]; ok {
return holds
}

e.holds[typ] = false // a type that refers to itself holds an enum only if another of its members does

holds := false

switch s.Kind {
case SchemaKindAlias:
holds = e.holdsEnum(s.Type)
case SchemaKindMap:
holds = e.holdsEnum(s.MapKey) || e.holdsEnum(s.MapValue)
case SchemaKindUnion:
for _, v := range s.UnionVariants {
holds = holds || e.holdsEnum(v.Type)
}
default:
for _, f := range s.Fields {
holds = holds || e.holdsEnum(f.Type)
}
}

e.holds[typ] = holds

return holds
}

// method is the body of the unknownEnum method of the schema s, which holds an enum: an expression of its receiver,
// v, true if any enum v holds has a value the enum does not list.
func (e *enums) method(s *Schema) string {
var checks []string

add := func(expr, typ string, optional bool) {
if c := e.check(expr, typ, optional, 0); c != "" {
checks = append(checks, c)
}
}

switch s.Kind {
case SchemaKindAlias:
if e.byName[s.Type] != nil || e.zero[s.Type] != "" {
add(convert(s.Type, "v"), s.Type, false) // a new type of another, which has its methods
} else {
add("v", s.Type, false)
}
case SchemaKindMap:
add("v", "map["+s.MapKey+"]"+s.MapValue, false)
case SchemaKindUnion:
for _, u := range s.UnionVariants {
if u.Zero != "" {
add("v."+u.FieldName, u.Type, true)
} else {
add("v."+u.FieldName, "*"+u.Type, false)
}
}
case SchemaKindTuple:
for _, f := range s.Fields {
add("v."+f.Name, f.Type, false)
}
default:
for _, f := range s.Fields {
name := f.Name
if f.Embedded {
name = strings.TrimPrefix(f.Type, "*")
}

add("v."+name, f.Type, !f.Required)
}
}

return strings.Join(checks, " ||\n")
}

// convert is expr, a value of a new type of typ, as one of typ, whose methods it then has.
func convert(typ, expr string) string {
if strings.HasPrefix(typ, "*") || strings.HasPrefix(typ, "[]") || strings.HasPrefix(typ, "map[") {
return "(" + typ + ")(" + expr + ")"
}

return typ + "(" + expr + ")"
}

// check is an expression true if expr, of the Go type typ, holds a value of an enum the enum does not list, or ""
// if typ holds no enum. Where optional, the zero value of an enum is one left out, and fine. depth names the
// variables of nested loops.
func (e *enums) check(expr, typ string, optional bool, depth int) string {
if !e.holdsEnum(typ) {
return ""
}

if elem, ok := strings.CutPrefix(typ, "*"); ok {
inner := expr
if strings.HasPrefix(elem, "[]") || strings.HasPrefix(elem, "map[") {
inner = "(*" + expr + ")"
}

return expr + " != nil && " + e.check(inner, elem, false, depth)
}

x := "x"
if depth > 0 {
x += strconv.Itoa(depth + 1)
}

if elem, ok := strings.CutPrefix(typ, "[]"); ok {
return "slices.ContainsFunc(" + expr + ", func(" + x + " " + elem + ") bool { return " +
e.check(x, elem, false, depth+1) + " })"
}

if key, value, ok := mapTypes(typ); ok {
k, v := "_", "_"

var checks []string

if c := e.check("k"+x[1:], key, false, depth+1); c != "" {
k = "k" + x[1:]

checks = append(checks, c)
}

if c := e.check(x, value, false, depth+1); c != "" {
v = x

checks = append(checks, c)
}

vars := k + ", " + v
if v == "_" {
vars = k
}

return "func() bool {\nfor " + vars + " := range " + expr + " {\nif " + strings.Join(checks, " || ") +
" {\nreturn true\n}\n}\n\nreturn false\n}()"
}

if zero, ok := e.zero[typ]; ok {
if optional {
return expr + " != " + zero + " && !" + expr + ".Valid()"
}

return "!" + expr + ".Valid()"
}

if s := e.byName[typ]; s.IsTypeAlias {
return e.check(expr, s.Type, optional, depth)
}

return expr + ".unknownEnum()"
}

// mapTypes is the key and value types of typ, if it is a map type.
func mapTypes(typ string) (key, value string, ok bool) {
rest, ok := strings.CutPrefix(typ, "map[")
if !ok {
return "", "", false
}

depth := 1
for i, r := range rest {
switch r {
case '[':
depth++
case ']':
if depth--; depth == 0 {
return rest[:i], rest[i+1:], true
}
}
}

return "", "", false
}

// UnknownEnum is, for the decoded value expr of the Go type typ, an expression true if it holds a value of an enum
// the enum does not list, or "" if it can hold none: a response debug mode records.
func (d *Document) UnknownEnum(expr, typ string) string {
if d.enums == nil {
d.enums = newEnums(d.Schemas)
}

return d.enums.check(expr, typ, false, 0)
}
38 changes: 38 additions & 0 deletions ir/unknown_enum_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package ir

import "testing"

func TestEnumsCheck(t *testing.T) {
t.Parallel()

e := newEnums([]Schema{
{Name: "Status", Kind: SchemaKindEnum, Type: "string"},
{Name: "Level", Kind: SchemaKindEnum, Type: "int"},
{Name: "Item", Kind: SchemaKindStruct, Fields: []Field{{Name: "Status", Type: "Status"}}},
{Name: "Items", Kind: SchemaKindAlias, Type: "[]Item"},
{Name: "Same", Kind: SchemaKindAlias, Type: "Items", IsTypeAlias: true},
{Name: "Node", Kind: SchemaKindStruct, Fields: []Field{{Name: "Next", Type: "*Node"}, {Name: "Name", Type: "string"}}},
})

for _, tc := range []struct {
typ string
optional bool
want string
}{
{"string", false, ""},
{"Node", false, ""}, // refers to itself, but holds no enum
{"Status", false, "!v.Valid()"},
{"Level", true, "v != 0 && !v.Valid()"},
{"*Item", false, "v != nil && v.unknownEnum()"},
{"*[]Status", false, "v != nil && slices.ContainsFunc((*v), func(x Status) bool { return !x.Valid() })"},
{"[][]Status", false, "slices.ContainsFunc(v, func(x []Status) bool { return " +
"slices.ContainsFunc(x, func(x2 Status) bool { return !x2.Valid() }) })"},
{"map[Status]string", false, "func() bool {\nfor k := range v {\nif !k.Valid() {\nreturn true\n}\n}\n\nreturn false\n}()"},
{"map[string][]Item", false, "func() bool {\nfor _, x := range v {\nif slices.ContainsFunc(x, func(x2 Item) bool { return x2.unknownEnum() }) {\nreturn true\n}\n}\n\nreturn false\n}()"},
{"Same", false, "v.unknownEnum()"},
} {
if got := e.check("v", tc.typ, tc.optional, 0); got != tc.want {
t.Errorf("check(%s) =\n%s\nwant\n%s", tc.typ, got, tc.want)
}
}
}
9 changes: 9 additions & 0 deletions render/templates/client.gen.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,15 @@ func (c *Client) {{.Name}}(ctx context.Context{{range .PathParams}}, {{.GoName}}
{{- end }}
}

{{ if $.Debug }}{{ with $.UnknownEnum "out" (print $out) -}}
// a value of an enum the specification does not list decodes, but is news
if ia != nil && ({{ . }}) {
if err := c.keep(ia); err != nil {
return {{if $op.SuccessReturn}}nil, {{end}}fmt.Errorf("recording the call: %w", err)
}
}

{{ end }}{{ end -}}
{{ if and .IsSuccess $op.SuccessReturn -}}
return {{ if not $op.SuccessReturn.NilByItself }}&{{ end }}out, nil
{{ else if .IsSuccess -}}
Expand Down
8 changes: 8 additions & 0 deletions render/templates/types.gen.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,14 @@ func (a {{$typeName}}) MarshalJSONTo(enc *jsontext.Encoder) error {
{{ else }}
// TODO: unimplemented schema kind {{ .Kind }}
{{- end }}
{{- if .UnknownEnum }}

// unknownEnum reports whether v holds a value of an enum the specification does not list, a response debug mode
// records.
func (v {{ if not (or (eq .Kind 2) (eq .Kind 4)) }}*{{ end }}{{ .Name }}) unknownEnum() bool {
return {{ .UnknownEnum }}
}
{{- end }}
{{end}}
{{- if .NeedsJSONHelpers }}

Expand Down
Loading
Loading