Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328// Command genwireencode emits hand-written per-type JSON encoders for the// translation package's wire types (wire_encode_gen.go). The encoders replace// the engine's reflection-based struct marshal and the nested// custom-marshaler dispatch with direct field emission in struct order;// extras merging stays in mergeExtras and any value form the generated code// does not encode exactly (complex string escapes, whitespace-bearing or// HTML-bearing raw values, extreme floats) routes through the engine// helpers in wire_encode.go, so output stays byte-identical to// encodeWithExtras on the plain alias.//// Run from the repository root://// mise exec -- go run ./hack/genwireencode > internal/translation/wire_encode_gen.gopackage main
import ( "encoding/json" "fmt" "go/format" "os" "reflect" "strings"
"go.daevix.com/daevix/internal/translation")
var rawMessageType = reflect.TypeFor[json.RawMessage]()
var jsonMarshalerType = reflect.TypeFor[json.Marshaler]()
// wireTypeNames mirrors hack/genwiredecode: every wire type participating in// generated arshalers. Types whose pointer implements json.Marshaler also get// the full encoder (extras branch); the others (OpenAIResponsesInDetail,// OpenAIResponsesTool) have no marshaler today and drop their extras slot on// encode, exactly as the engine did.var wireTypes = []any{ translation.OpenAIChatRequest{}, translation.OpenAIChatMessage{}, translation.OpenAIChatToolCall{}, translation.OpenAIChatFunctionCall{}, translation.OpenAIChatTool{}, translation.OpenAIChatFunctionDef{}, translation.OpenAIChatResponse{}, translation.OpenAIChatChoice{}, translation.OpenAIChatUsage{}, translation.OpenAIChatPromptTokensDetails{}, translation.OpenAIChatCompletionTokDetails{}, translation.AnthropicRequest{}, translation.AnthropicMessage{}, translation.AnthropicBlock{}, translation.AnthropicImageSource{}, translation.AnthropicTool{}, translation.AnthropicResponse{}, translation.AnthropicUsage{}, translation.OpenAIResponsesRequest{}, translation.OpenAIResponsesItem{}, translation.OpenAIResponsesResponse{}, translation.OpenAIResponsesUsage{}, translation.OpenAIResponsesInDetail{}, translation.OpenAIResponsesOutDetail{}, translation.OpenAIResponsesTool{}, translation.OpenAIChatChunk{}, translation.OpenAIChatDelta{}, translation.OpenAIChatChunkChoice{}, translation.OpenAIChatDeltaToolCall{},}
type field struct { name string // JSON name goName string kind string // string|int|int64|bool|floatptr|raw|struct|ptrstruct|slicestring|slicestruct elemType string // nested Go type for slices and structs extras bool // nested type has its own full encoder (extras branch) omitempty bool // encoding/json omitempty option}
func main() { var out strings.Builder out.WriteString("// Code generated by hack/genwireencode; DO NOT EDIT.\n\n") out.WriteString("package translation\n\n") out.WriteString("import (\n\t\"strconv\"\n)\n\n")
types := map[string]reflect.Type{} for _, v := range wireTypes { t := reflect.TypeOf(v) if t.Kind() != reflect.Struct { fail("not a struct: %s", t.Name()) } types[t.Name()] = t }
for _, name := range typeOrder(types) { t := types[name] fields := classify(t) hasMarshal := reflect.PointerTo(t).Implements(jsonMarshalerType) writeFieldsEncoder(&out, name, fields, hasMarshal) }
formatted, err := format.Source([]byte(out.String())) if err != nil { _, _ = os.Stderr.WriteString(out.String()) fmt.Fprintf(os.Stderr, "format: %v\n", err) os.Exit(1) } _, _ = os.Stdout.Write(formatted)}
// typeOrder returns the type names in the generator's declaration order.func typeOrder(types map[string]reflect.Type) []string { order := make([]string, 0, len(types)) for _, v := range wireTypes { order = append(order, reflect.TypeOf(v).Name()) } return order}
func classify(t reflect.Type) []field { var fields []field for i := 0; i < t.NumField(); i++ { f := t.Field(i) if f.PkgPath != "" || f.Anonymous { continue } tag := f.Tag.Get("json") if tag == "-" { continue } name, opts, _ := strings.Cut(tag, ",") if name == "" { name = f.Name } ft := f.Type var k field k.name = name k.goName = f.Name k.omitempty = strings.Contains(opts, "omitempty") switch ft { case rawMessageType: k.kind = "raw" default: switch ft.Kind() { //nolint:staticcheck // struct field analysis reads clearer on Kind case reflect.String: k.kind = "string" case reflect.Int, reflect.Int64: if ft.Kind() == reflect.Int { k.kind = "int" } else { k.kind = "int64" } case reflect.Bool: k.kind = "bool" case reflect.Pointer: switch ft.Elem().Kind() { case reflect.Float64: k.kind = "floatptr" case reflect.Int: k.kind = "intptr" case reflect.Struct: k.kind = "ptrstruct" default: fail("unsupported pointer field %s.%s", t.Name(), f.Name) } case reflect.Slice: switch ft.Elem().Kind() { case reflect.String: k.kind = "slicestring" case reflect.Struct: k.kind = "slicestruct" default: fail("unsupported slice field %s.%s", t.Name(), f.Name) } case reflect.Struct: k.kind = "struct" default: fail("unsupported field %s.%s (%s)", t.Name(), f.Name, ft.Kind()) } } switch k.kind { case "struct", "ptrstruct", "slicestruct": et := ft if k.kind != "struct" { et = ft.Elem() } k.elemType = et.Name() k.extras = reflect.PointerTo(et).Implements(jsonMarshalerType) } fields = append(fields, k) } return fields}
func writeFieldsEncoder(out *strings.Builder, name string, fields []field, hasMarshal bool) { fmt.Fprintf(out, "// wireEncode%sFields appends the typed fields of %s in struct\n", name, name) fmt.Fprintf(out, "// order with encoding/json's omitempty semantics, byte-identical to the\n// engine's encoding of the plain alias.\n") fmt.Fprintf(out, "func wireEncode%sFields(out []byte, w *%s) ([]byte, error) {\n", name, name) fmt.Fprintf(out, "\tout = append(out, '{')\n\tfirst := true\n") for _, f := range fields { if f.omitempty { fmt.Fprintf(out, "\tif %s {\n\t} else {\n\t\tif !first {\n\t\t\tout = append(out, ',')\n\t\t}\n\t\tfirst = false\n\t\tout = append(out, %q...)\n\t\t%s\n\t}\n", omitCond(f), `"`+f.name+`":`, fieldValue(f)) } else { fmt.Fprintf(out, "\t{\n\t\tif !first {\n\t\t\tout = append(out, ',')\n\t\t}\n\t\tfirst = false\n\t\tout = append(out, %q...)\n\t\t%s\n\t}\n", `"`+f.name+`":`, fieldValue(f)) } } fmt.Fprintf(out, "\tout = append(out, '}')\n\treturn out, nil\n}\n\n") if hasMarshal { fmt.Fprintf(out, "// wireEncode%s encodes %s including the extras merge: extras override\n// same-name typed keys, and the merged output is alphabetized, exactly as\n// the previous encodeWithExtras engine path produced it.\n", name, name) fmt.Fprintf(out, "func wireEncode%s(out []byte, w *%s) ([]byte, error) {\n", name, name) fmt.Fprintf(out, "\tif len(w.Extras) != 0 {\n\t\tb, err := wireEncode%sFields(nil, w)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm, err := mergeExtras(b, w.Extras)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn append(out, m...), nil\n\t}\n\treturn wireEncode%sFields(out, w)\n}\n\n", name, name) }}
// omitCond is the encoding/json omitempty test for the field's kind,// mirroring jsonOmitted in extras.go.func omitCond(f field) string { switch f.kind { case "string": return fmt.Sprintf("w.%s == \"\"", f.goName) case "int", "int64": return fmt.Sprintf("w.%s == 0", f.goName) case "bool": return fmt.Sprintf("!w.%s", f.goName) case "floatptr", "intptr", "ptrstruct": // encoding/json pointer omitempty is nil-only. return fmt.Sprintf("w.%s == nil", f.goName) case "raw", "slicestring", "slicestruct": // json.RawMessage and slices omit zero-length values too // (encoding/json's isEmptyValue uses Len == 0). return fmt.Sprintf("len(w.%s) == 0", f.goName) default: // struct: never omitted return "false" }}
// fieldValue emits the field's value into out. Nilable non-omitempty fields// encode null when nil, as the engine does.func fieldValue(f field) string { switch f.kind { case "string": return "out = appendJSONString(out, w." + f.goName + ")" case "int": return "out = strconv.AppendInt(out, int64(w." + f.goName + "), 10)" case "int64": return "out = strconv.AppendInt(out, w." + f.goName + ", 10)" case "bool": return "out = strconv.AppendBool(out, w." + f.goName + ")" case "floatptr": return fmt.Sprintf(`if w.%s == nil { out = append(out, `+"`null`"+`...) } else { var err error out, err = wireAppendFloat(out, *w.%s) if err != nil { return nil, err } }`, f.goName, f.goName) case "intptr": return fmt.Sprintf(`if w.%[1]s == nil { out = append(out, `+"`null`"+`...) } else { out = strconv.AppendInt(out, int64(*w.%[1]s), 10) }`, f.goName) case "raw": return fmt.Sprintf(`if len(w.%[1]s) == 0 { out = append(out, `+"`null`"+`...) } else { var err error out, err = wireAppendRaw(out, w.%[1]s) if err != nil { return nil, err } }`, f.goName) case "slicestring": return fmt.Sprintf(`if w.%s == nil { out = append(out, `+"`null`"+`...) } else { out = append(out, '[') for j := range w.%s { if j > 0 { out = append(out, ',') } out = appendJSONString(out, w.%s[j]) } out = append(out, ']') }`, f.goName, f.goName, f.goName) case "slicestruct": return fmt.Sprintf(`if w.%s == nil { out = append(out, `+"`null`"+`...) } else { out = append(out, '[') for j := range w.%s { if j > 0 { out = append(out, ',') } var err error out, err = %s(out, &w.%s[j]) if err != nil { return nil, err } } out = append(out, ']') }`, f.goName, f.goName, nestedEncoder(f), f.goName) case "struct": return fmt.Sprintf(`{ var err error out, err = %s(out, &w.%s) if err != nil { return nil, err } }`, nestedEncoder(f), f.goName) case "ptrstruct": return fmt.Sprintf(`if w.%s == nil { out = append(out, `+"`null`"+`...) } else { var err error out, err = %s(out, w.%s) if err != nil { return nil, err } }`, f.goName, nestedEncoder(f), f.goName) default: fail("unhandled kind %s", f.kind) return "" }}
// nestedEncoder picks the nested encode entry: full (extras branch) for// marshaler-carrying types, fields-only otherwise.func nestedEncoder(f field) string { if f.extras { return "wireEncode" + f.elemType } return "wireEncode" + f.elemType + "Fields"}
func fail(format string, args ...any) { fmt.Fprintf(os.Stderr, "genwireencode: "+format+"\n", args...) os.Exit(1)}