Skip to content

cmd/cue: gengotypes should be able to generate Go code for disjunctions #3887

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
rogpeppe opened this issue Apr 9, 2025 · 1 comment
Open
Labels
encoding FeatureRequest New feature or request

Comments

@rogpeppe
Copy link
Member

rogpeppe commented Apr 9, 2025

Currently, if cue exp gengotypes is run on the following code:

package x

#T: #Foo | #Bar

#Foo: {
	type!: "foo"
	x?: bool
}

#Bar: {
	type!: "bar"
	x?: int
}

It will produce Go code like this:

package x

type T map[string]any

type Foo struct {
	Type string `json:"type"`

	X bool `json:"x,omitempty"`
}

type Bar struct {
	Type string `json:"type"`

	X int64 `json:"x,omitempty"`
}

Although the type T should be linked closely with the Foo and Bar types, it
is not.

It would be better if gengotypes could look at the schemas,
see that they're discriminated with the type field and generate Go code
that looks for the field at json umarshal time and creates the correct
struct type.

The cuediscrim package is a step in that direction.

@rogpeppe rogpeppe added encoding FeatureRequest New feature or request labels Apr 9, 2025
@rogpeppe
Copy link
Member Author

rogpeppe commented Apr 9, 2025

As one example of how a reasonably modern Go API does this, see the OpenAI Go API, for example the responses package. This appears to have been generated by https://www.stainless.com/.

See https://github.com/openai/openai-go?tab=readme-ov-file#response-unions for some general docs on how they deal with unions/disjunctions. Here's an example: http://pkg.go.dev/github.com/openai/openai-go/responses#ResponseCodeInterpreterToolCallResultUnion

Note the way that they use (generated) types to represent constant discriminator fields, such as https://pkg.go.dev/github.com/openai/openai-go/responses#FileSearch using https://pkg.go.dev/github.com/openai/[email protected]/shared/constant#FileSearch

As an aside, they also make extensive use of a generic Opt[T] type to represent optional fields, something which we could also choose to do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
encoding FeatureRequest New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant