-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.go
More file actions
357 lines (327 loc) · 10.8 KB
/
Copy pathschema.go
File metadata and controls
357 lines (327 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package gobspect
import (
"encoding/json"
"fmt"
"io"
"slices"
"strings"
)
// Schema represents a complete parsed Gob schema comprising multiple type declarations.
type Schema struct {
Types []TypeDecl
Indent string
}
// TypeDecl represents a top-level type declaration in the schema.
type TypeDecl struct {
Name string
Kind TypeKind
Fields []FieldDecl // Populated if Kind is KindStruct
TargetType string // Target expression for slices, maps, arrays
Annotation string // Opaque type annotations (GobEncoder, etc.)
}
// FieldDecl represents a field within a struct declaration.
type FieldDecl struct {
Name string
Type string
Annotation string
}
// SchemaFormatOption configures the rendering of a [Schema].
// Unlike [FormatOption], which applies to value trees, SchemaFormatOption
// covers only the subset of formatting options meaningful for type-declaration output.
type SchemaFormatOption func(*formatConfig)
// SchemaWithColor sets the [ColorScheme] used when rendering a Schema.
// A zero-valued ColorScheme (the default) produces plain text identical to [Schema.String].
func SchemaWithColor(scheme ColorScheme) SchemaFormatOption {
return func(c *formatConfig) { c.color = scheme }
}
// SchemaWithIndent sets the indentation string used inside struct bodies.
// The default is two spaces.
func SchemaWithIndent(indent string) SchemaFormatOption {
return func(c *formatConfig) { c.indent = indent }
}
// FormatSchema converts a []TypeInfo slice into an AST-based *Schema, covering
// all top-level named types. Named types with mechanically generated names
// (containing brackets, e.g. "[]int") are safely excluded from the top-level
// schema output. Anonymous (unnamed) types appear only inline within other
// declarations.
//
// To control rendering, pass [SchemaFormatOption] values to [Schema.Format] or
// [Schema.FormatTo] after calling FormatSchema.
func FormatSchema(types []TypeInfo) *Schema {
// Build a lookup map keyed by type ID for resolving references.
byID := make(map[int]TypeInfo, len(types))
for _, ti := range types {
byID[ti.ID] = ti
}
// Collect only named types; anonymous types appear inline only.
// We also skip mechanically-generated names: anonymous slices ([]T), arrays
// ([N]T), maps (map[K]V), and pointers (*T) all begin with one of those
// prefixes. User-defined generic instantiations like "Pair[int,string]" do
// NOT start with those prefixes, so they are kept.
var named []TypeInfo
for _, ti := range types {
if ti.Name != "" && !isMechanicalTypeName(ti.Name) {
named = append(named, ti)
}
}
// Sort alphabetically for deterministic, readable output.
slices.SortFunc(named, func(a, b TypeInfo) int {
return strings.Compare(a.Name, b.Name)
})
schema := &Schema{Indent: " "}
for _, ti := range named {
schema.Types = append(schema.Types, buildTypeDecl(ti, byID))
}
return schema
}
// String renders the Schema as a human-readable Go-style type declaration block,
// matching the original plain-text formatting exactly.
func (s *Schema) String() string {
return s.Format()
}
// Format renders the Schema as a string, applying any provided SchemaFormatOptions.
// A zero-valued [ColorScheme] (the default) produces plain text identical to [Schema.String].
func (s *Schema) Format(opts ...SchemaFormatOption) string {
var sb strings.Builder
_ = s.FormatTo(&sb, opts...)
return sb.String()
}
// FormatTo renders the Schema to w, applying any provided SchemaFormatOptions.
// The first write error aborts rendering and is returned.
func (s *Schema) FormatTo(w io.Writer, opts ...SchemaFormatOption) error {
cfg := &formatConfig{indent: s.Indent}
if cfg.indent == "" {
cfg.indent = " "
}
for _, o := range opts {
o(cfg)
}
return schemaFormatTo(w, s, cfg)
}
// JSON returns a compact machine-readable representation of the schema. The
// output is an array of type declarations with stable keys; downstream tools
// (code generators, documentation, compatibility checkers) can consume it
// without parsing Go-style syntax.
func (s *Schema) JSON() ([]byte, error) {
return json.Marshal(schemaJSONPayload(s))
}
// JSONIndent is like [Schema.JSON] but formats the output with the given
// indentation (see [encoding/json.MarshalIndent]).
func (s *Schema) JSONIndent(prefix, indent string) ([]byte, error) {
return json.MarshalIndent(schemaJSONPayload(s), prefix, indent)
}
// schemaJSONPayload builds the ordered map shape we serialize. Each type
// appears as {name, kind, fields?, target?, annotation?}.
func schemaJSONPayload(s *Schema) []map[string]any {
out := make([]map[string]any, 0, len(s.Types))
for _, t := range s.Types {
entry := map[string]any{
"name": t.Name,
"kind": t.Kind.String(),
}
switch t.Kind {
case KindStruct:
fields := make([]map[string]any, 0, len(t.Fields))
for _, f := range t.Fields {
m := map[string]any{"name": f.Name, "type": f.Type}
if f.Annotation != "" {
m["annotation"] = f.Annotation
}
fields = append(fields, m)
}
entry["fields"] = fields
case KindSlice, KindArray, KindMap:
entry["target"] = t.TargetType
case KindGobEncoder, KindBinaryMarshaler, KindTextMarshaler:
entry["annotation"] = t.Annotation
}
out = append(out, entry)
}
return out
}
// TypeByName locates a top-level type declaration by its name.
func (s *Schema) TypeByName(name string) (*TypeDecl, bool) {
for i := range s.Types {
if s.Types[i].Name == name {
return &s.Types[i], true
}
}
return nil, false
}
// schemaFormatTo writes the Schema to w using the given formatConfig for indent
// and color options.
func schemaFormatTo(w io.Writer, s *Schema, cfg *formatConfig) error {
indent := cfg.indent
clr := cfg.color
// keyword wraps a keyword token (e.g. "type") in the TypeHeader style.
// In the schema, we use TypeHeader for the "type" keyword and for the
// type name. We reuse OpaquePrefix (dim) for comments/annotations.
for i, t := range s.Types {
if i > 0 {
if _, err := io.WriteString(w, "\n\n"); err != nil {
return err
}
}
switch t.Kind {
case KindStruct:
if len(t.Fields) == 0 {
_, err := io.WriteString(w,
clr.Number.Apply("type")+" "+clr.TypeHeader.Apply(t.Name)+" struct{}")
if err != nil {
return err
}
continue
}
// Determine max len to align all field types.
maxLen := 0
for _, f := range t.Fields {
if len(f.Name) > maxLen {
maxLen = len(f.Name)
}
}
line := clr.Number.Apply("type") + " " + clr.TypeHeader.Apply(t.Name) + " struct {\n"
if _, err := io.WriteString(w, line); err != nil {
return err
}
for _, f := range t.Fields {
fieldLine := indent +
clr.FieldName.Apply(f.Name) +
strings.Repeat(" ", maxLen-len(f.Name)+2) +
f.Type
if f.Annotation != "" {
fieldLine += " " + clr.OpaquePrefix.Apply("// "+f.Annotation)
}
fieldLine += "\n"
if _, err := io.WriteString(w, fieldLine); err != nil {
return err
}
}
if _, err := io.WriteString(w, cfg.color.CloseBrace.Apply("}")); err != nil {
return err
}
case KindMap, KindSlice, KindArray:
line := clr.Number.Apply("type") + " " + clr.TypeHeader.Apply(t.Name) + " " + t.TargetType
if _, err := io.WriteString(w, line); err != nil {
return err
}
case KindGobEncoder, KindBinaryMarshaler, KindTextMarshaler:
line := clr.Number.Apply("type") + " " + clr.TypeHeader.Apply(t.Name) +
" " + clr.OpaquePrefix.Apply("// "+t.Annotation)
if _, err := io.WriteString(w, line); err != nil {
return err
}
default:
line := clr.OpaquePrefix.Apply("// type " + t.Name)
if _, err := io.WriteString(w, line); err != nil {
return err
}
}
}
return nil
}
func buildTypeDecl(ti TypeInfo, byID map[int]TypeInfo) TypeDecl {
decl := TypeDecl{
Name: ti.Name,
Kind: ti.Kind,
}
switch ti.Kind {
case KindStruct:
for _, f := range ti.Fields {
expr, annotation := schemaFieldTypeExpr(f.TypeID, byID)
decl.Fields = append(decl.Fields, FieldDecl{
Name: f.Name,
Type: expr,
Annotation: annotation,
})
}
case KindMap:
decl.TargetType = fmt.Sprintf("map[%s]%s", schemaTypeExpr(ti.Key, byID), schemaTypeExpr(ti.Elem, byID))
case KindSlice:
decl.TargetType = fmt.Sprintf("[]%s", schemaTypeExpr(ti.Elem, byID))
case KindArray:
decl.TargetType = fmt.Sprintf("[%d]%s", ti.Len, schemaTypeExpr(ti.Elem, byID))
case KindGobEncoder:
decl.Annotation = "GobEncoder"
case KindBinaryMarshaler:
decl.Annotation = "BinaryMarshaler"
case KindTextMarshaler:
decl.Annotation = "TextMarshaler"
}
return decl
}
// schemaTypeExpr returns the Go type expression for the type identified by ref.
// For named types it returns the name. For anonymous composite types it
// constructs an inline expression (e.g. "[]string", "map[string]int").
func schemaTypeExpr(ref *TypeRef, byID map[int]TypeInfo) string {
if ref == nil {
return "?"
}
if name, ok := builtinTypeName(ref.ID); ok {
return name
}
ti, ok := byID[ref.ID]
if !ok {
if ref.Name != "" {
return ref.Name
}
return "?"
}
if ti.Name != "" {
return ti.Name
}
// Anonymous composite: build inline expression.
switch ti.Kind {
case KindSlice:
return "[]" + schemaTypeExpr(ti.Elem, byID)
case KindArray:
return fmt.Sprintf("[%d]%s", ti.Len, schemaTypeExpr(ti.Elem, byID))
case KindMap:
return "map[" + schemaTypeExpr(ti.Key, byID) + "]" + schemaTypeExpr(ti.Elem, byID)
default:
if ref.Name != "" {
return ref.Name
}
return "?"
}
}
// schemaFieldTypeExpr returns the type expression and optional opaque-kind
// annotation for a struct field whose type ID is typeID.
// The annotation is non-empty only for opaque kinds (GobEncoder, BinaryMarshaler,
// TextMarshaler) and names the encoding interface.
func schemaFieldTypeExpr(typeID int, byID map[int]TypeInfo) (expr, annotation string) {
if name, ok := builtinTypeName(typeID); ok {
return name, ""
}
ti, ok := byID[typeID]
if !ok {
return "?", ""
}
name := ti.Name
if name == "" {
name = "?"
}
switch ti.Kind {
case KindGobEncoder:
return name, "GobEncoder"
case KindBinaryMarshaler:
return name, "BinaryMarshaler"
case KindTextMarshaler:
return name, "TextMarshaler"
default:
return schemaTypeExpr(&TypeRef{ID: typeID, Name: ti.Name}, byID), ""
}
}
// isMechanicalTypeName reports whether name is an anonymous composite type
// generated by the reflect package (slice, array, map, or pointer). These names
// start with "[", "map[", or "*". User-defined generic instantiations such as
// "Pair[int,string]" do not start with any of these prefixes and therefore
// return false, so they are preserved in schema output.
//
// Names containing a space (e.g. "struct { X int }") are also treated as
// mechanical to guard against anonymous struct literals.
func isMechanicalTypeName(name string) bool {
return strings.HasPrefix(name, "[") ||
strings.HasPrefix(name, "map[") ||
strings.HasPrefix(name, "*") ||
strings.Contains(name, " ")
}