Debian Codegraph @

debian/go/src/github.com/google/jsonschema-go/jsonschema/util.go

raw symbols SCIP
1 // Copyright 2025 The JSON Schema Go Project Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package jsonschema
6
7 import (
8 "bytes"
9 "cmp"
10 "encoding/binary"
11 "encoding/json"
12 "fmt"
13 "hash/maphash"
14 "math"
15 "math/big"
16 "reflect"
17 "slices"
18 "strings"
19 "sync"
20 )
21
22 // Equal reports whether two Go values representing JSON values are equal according
23 // to the JSON Schema spec.
24 // The values must not contain cycles.
25 // See https://json-schema.org/draft/2020-12/json-schema-core#section-4.2.2.
26 // It behaves like reflect.DeepEqual, except that numbers are compared according
27 // to mathematical equality.
28 func Equal(x, y any) bool {
29 return equalValue(reflect.ValueOf(x), reflect.ValueOf(y))
30 }
31
32 func equalValue(x, y reflect.Value) bool {
33 // Copied from src/reflect/deepequal.go, omitting the visited check (because JSON
34 // values are trees).
35 if !x.IsValid() || !y.IsValid() {
36 return x.IsValid() == y.IsValid()
37 }
38
39 // Treat numbers specially.
40 rx, ok1 := jsonNumber(x)
41 ry, ok2 := jsonNumber(y)
42 if ok1 && ok2 {
43 return rx.Cmp(ry) == 0
44 }
45 if x.Kind() != y.Kind() {
46 return false
47 }
48 switch x.Kind() {
49 case reflect.Array:
50 if x.Len() != y.Len() {
51 return false
52 }
53 for i := range x.Len() {
54 if !equalValue(x.Index(i), y.Index(i)) {
55 return false
56 }
57 }
58 return true
59 case reflect.Slice:
60 if x.IsNil() != y.IsNil() {
61 return false
62 }
63 if x.Len() != y.Len() {
64 return false
65 }
66 if x.UnsafePointer() == y.UnsafePointer() {
67 return true
68 }
69 // Special case for []byte, which is common.
70 if x.Type().Elem().Kind() == reflect.Uint8 && x.Type() == y.Type() {
71 return bytes.Equal(x.Bytes(), y.Bytes())
72 }
73 for i := range x.Len() {
74 if !equalValue(x.Index(i), y.Index(i)) {
75 return false
76 }
77 }
78 return true
79 case reflect.Interface:
80 if x.IsNil() || y.IsNil() {
81 return x.IsNil() == y.IsNil()
82 }
83 return equalValue(x.Elem(), y.Elem())
84 case reflect.Pointer:
85 if x.UnsafePointer() == y.UnsafePointer() {
86 return true
87 }
88 return equalValue(x.Elem(), y.Elem())
89 case reflect.Struct:
90 t := x.Type()
91 if t != y.Type() {
92 return false
93 }
94 for i := range t.NumField() {
95 sf := t.Field(i)
96 if !sf.IsExported() {
97 continue
98 }
99 if !equalValue(x.FieldByIndex(sf.Index), y.FieldByIndex(sf.Index)) {
100 return false
101 }
102 }
103 return true
104 case reflect.Map:
105 if x.IsNil() != y.IsNil() {
106 return false
107 }
108 if x.Len() != y.Len() {
109 return false
110 }
111 if x.UnsafePointer() == y.UnsafePointer() {
112 return true
113 }
114 iter := x.MapRange()
115 for iter.Next() {
116 vx := iter.Value()
117 vy := y.MapIndex(iter.Key())
118 if !vy.IsValid() || !equalValue(vx, vy) {
119 return false
120 }
121 }
122 return true
123 case reflect.Func:
124 if x.Type() != y.Type() {
125 return false
126 }
127 if x.IsNil() && y.IsNil() {
128 return true
129 }
130 panic("cannot compare functions")
131 case reflect.String:
132 return x.String() == y.String()
133 case reflect.Bool:
134 return x.Bool() == y.Bool()
135 // Ints, uints and floats handled in jsonNumber, at top of function.
136 default:
137 panic(fmt.Sprintf("unsupported kind: %s", x.Kind()))
138 }
139 }
140
141 // hashValue adds v to the data hashed by h. v must not have cycles.
142 // hashValue panics if the value contains functions or channels, or maps whose
143 // key type is not string.
144 // It ignores unexported fields of structs.
145 // Calls to hashValue with the equal values (in the sense
146 // of [Equal]) result in the same sequence of values written to the hash.
147 func hashValue(h *maphash.Hash, v reflect.Value) {
148 // TODO: replace writes of basic types with WriteComparable in 1.24.
149
150 writeUint := func(u uint64) {
151 var buf [8]byte
152 binary.BigEndian.PutUint64(buf[:], u)
153 h.Write(buf[:])
154 }
155
156 var write func(reflect.Value)
157 write = func(v reflect.Value) {
158 if r, ok := jsonNumber(v); ok {
159 // We want 1.0 and 1 to hash the same.
160 // big.Rats are always normalized, so they will be.
161 // We could do this more efficiently by handling the int and float cases
162 // separately, but that's premature.
163 writeUint(uint64(r.Sign() + 1))
164 h.Write(r.Num().Bytes())
165 h.Write(r.Denom().Bytes())
166 return
167 }
168 switch v.Kind() {
169 case reflect.Invalid:
170 h.WriteByte(0)
171 case reflect.String:
172 h.WriteString(v.String())
173 case reflect.Bool:
174 if v.Bool() {
175 h.WriteByte(1)
176 } else {
177 h.WriteByte(0)
178 }
179 case reflect.Complex64, reflect.Complex128:
180 c := v.Complex()
181 writeUint(math.Float64bits(real(c)))
182 writeUint(math.Float64bits(imag(c)))
183 case reflect.Array, reflect.Slice:
184 // Although we could treat []byte more efficiently,
185 // JSON values are unlikely to contain them.
186 writeUint(uint64(v.Len()))
187 for i := range v.Len() {
188 write(v.Index(i))
189 }
190 case reflect.Interface, reflect.Pointer:
191 write(v.Elem())
192 case reflect.Struct:
193 t := v.Type()
194 for i := range t.NumField() {
195 if sf := t.Field(i); sf.IsExported() {
196 write(v.FieldByIndex(sf.Index))
197 }
198 }
199 case reflect.Map:
200 if v.Type().Key().Kind() != reflect.String {
201 panic("map with non-string key")
202 }
203 // Sort the keys so the hash is deterministic.
204 keys := v.MapKeys()
205 // Write the length. That distinguishes between, say, two consecutive
206 // maps with disjoint keys from one map that has the items of both.
207 writeUint(uint64(len(keys)))
208 slices.SortFunc(keys, func(x, y reflect.Value) int { return cmp.Compare(x.String(), y.String()) })
209 for _, k := range keys {
210 write(k)
211 write(v.MapIndex(k))
212 }
213 // Ints, uints and floats handled in jsonNumber, at top of function.
214 default:
215 panic(fmt.Sprintf("unsupported kind: %s", v.Kind()))
216 }
217 }
218
219 write(v)
220 }
221
222 // jsonNumber converts a numeric value or a json.Number to a [big.Rat].
223 // If v is not a number, it returns nil, false.
224 func jsonNumber(v reflect.Value) (*big.Rat, bool) {
225 r := new(big.Rat)
226 switch {
227 case !v.IsValid():
228 return nil, false
229 case v.CanInt():
230 r.SetInt64(v.Int())
231 case v.CanUint():
232 r.SetUint64(v.Uint())
233 case v.CanFloat():
234 r.SetFloat64(v.Float())
235 default:
236 jn, ok := v.Interface().(json.Number)
237 if !ok {
238 return nil, false
239 }
240 if _, ok := r.SetString(jn.String()); !ok {
241 // This can fail in rare cases; for example, "1e9999999".
242 // That is a valid JSON number, since the spec puts no limit on the size
243 // of the exponent.
244 return nil, false
245 }
246 }
247 return r, true
248 }
249
250 // jsonType returns a string describing the type of the JSON value,
251 // as described in the JSON Schema specification:
252 // https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01#section-6.1.1.
253 // It returns "", false if the value is not valid JSON.
254 func jsonType(v reflect.Value) (string, bool) {
255 if !v.IsValid() {
256 // Not v.IsNil(): a nil []any is still a JSON array.
257 return "null", true
258 }
259 if v.CanInt() || v.CanUint() {
260 return "integer", true
261 }
262 if v.CanFloat() {
263 if _, f := math.Modf(v.Float()); f == 0 {
264 return "integer", true
265 }
266 return "number", true
267 }
268 switch v.Kind() {
269 case reflect.Bool:
270 return "boolean", true
271 case reflect.String:
272 return "string", true
273 case reflect.Slice, reflect.Array:
274 return "array", true
275 case reflect.Map, reflect.Struct:
276 return "object", true
277 default:
278 return "", false
279 }
280 }
281
282 func assert(cond bool, msg string) {
283 if !cond {
284 panic("assertion failed: " + msg)
285 }
286 }
287
288 // marshalStructWithMap marshals its first argument to JSON, treating the field named
289 // mapField as an embedded map. The first argument must be a pointer to
290 // a struct. The underlying type of mapField must be a map[string]any, and it must have
291 // a "-" json tag, meaning it will not be marshaled.
292 //
293 // For example, given this struct:
294 //
295 // type S struct {
296 // A int
297 // Extra map[string] any `json:"-"`
298 // }
299 //
300 // and this value:
301 //
302 // s := S{A: 1, Extra: map[string]any{"B": 2}}
303 //
304 // the call marshalJSONWithMap(s, "Extra") would return
305 //
306 // {"A": 1, "B": 2}
307 //
308 // It is an error if the map contains the same key as another struct field's
309 // JSON name.
310 //
311 // marshalStructWithMap calls json.Marshal on a value of type T, so T must not
312 // have a MarshalJSON method that calls this function, on pain of infinite regress.
313 //
314 // Note that there is a similar function in mcp/util.go, but they are not the same.
315 // Here the function requires `-` json tag, does not clear the mapField map,
316 // and handles embedded struct due to the implementation of jsonNames in this package.
317 //
318 // TODO: avoid this restriction on T by forcing it to marshal in a default way.
319 // See https://go.dev/play/p/EgXKJHxEx_R.
320 func marshalStructWithMap[T any](s *T, mapField string) ([]byte, error) {
321 // Marshal the struct and the map separately, and concatenate the bytes.
322 // This strategy is dramatically less complicated than
323 // constructing a synthetic struct or map with the combined keys.
324 if s == nil {
325 return []byte("null"), nil
326 }
327 s2 := *s
328 vMapField := reflect.ValueOf(&s2).Elem().FieldByName(mapField)
329 mapVal := vMapField.Interface().(map[string]any)
330
331 // Check for duplicates.
332 names := jsonNames(reflect.TypeFor[T]())
333 for key := range mapVal {
334 if names[key] {
335 return nil, fmt.Errorf("map key %q duplicates struct field", key)
336 }
337 }
338
339 structBytes, err := json.Marshal(s2)
340 if err != nil {
341 return nil, fmt.Errorf("marshalStructWithMap(%+v): %w", s, err)
342 }
343 if len(mapVal) == 0 {
344 return structBytes, nil
345 }
346 mapBytes, err := json.Marshal(mapVal)
347 if err != nil {
348 return nil, err
349 }
350 if len(structBytes) == 2 { // must be "{}"
351 return mapBytes, nil
352 }
353 // "{X}" + "{Y}" => "{X,Y}"
354 res := append(structBytes[:len(structBytes)-1], ',')
355 res = append(res, mapBytes[1:]...)
356 return res, nil
357 }
358
359 // unmarshalStructWithMap is the inverse of marshalStructWithMap.
360 // T has the same restrictions as in that function.
361 //
362 // Note that there is a similar function in mcp/util.go, but they are not the same.
363 // Here jsonNames also returns fields from embedded structs, hence this function
364 // handles embedded structs as well.
365 func unmarshalStructWithMap[T any](data []byte, v *T, mapField string) error {
366 // Unmarshal into the struct, ignoring unknown fields.
367 if err := json.Unmarshal(data, v); err != nil {
368 return err
369 }
370 // Unmarshal into the map.
371 m := map[string]any{}
372 if err := json.Unmarshal(data, &m); err != nil {
373 return err
374 }
375 // Delete from the map the fields of the struct.
376 for n := range jsonNames(reflect.TypeFor[T]()) {
377 delete(m, n)
378 }
379 if len(m) != 0 {
380 reflect.ValueOf(v).Elem().FieldByName(mapField).Set(reflect.ValueOf(m))
381 }
382 return nil
383 }
384
385 var jsonNamesMap sync.Map // from reflect.Type to map[string]bool
386
387 // jsonNames returns the set of JSON object keys that t will marshal into,
388 // including fields from embedded structs in t.
389 // t must be a struct type.
390 //
391 // Note that there is a similar function in mcp/util.go, but they are not the same
392 // Here the function recurses over embedded structs and includes fields from them.
393 func jsonNames(t reflect.Type) map[string]bool {
394 // Lock not necessary: at worst we'll duplicate work.
395 if val, ok := jsonNamesMap.Load(t); ok {
396 return val.(map[string]bool)
397 }
398 m := map[string]bool{}
399 for i := range t.NumField() {
400 field := t.Field(i)
401 // handle embedded structs
402 if field.Anonymous {
403 fieldType := field.Type
404 if fieldType.Kind() == reflect.Ptr {
405 fieldType = fieldType.Elem()
406 }
407 for n := range jsonNames(fieldType) {
408 m[n] = true
409 }
410 continue
411 }
412 info := fieldJSONInfo(field)
413 if !info.omit {
414 m[info.name] = true
415 }
416 }
417 jsonNamesMap.Store(t, m)
418 return m
419 }
420
421 type jsonInfo struct {
422 omit bool // unexported or first tag element is "-"
423 name string // Go field name or first tag element. Empty if omit is true.
424 settings map[string]bool // "omitempty", "omitzero", etc.
425 }
426
427 // fieldJSONInfo reports information about how encoding/json
428 // handles the given struct field.
429 // If the field is unexported, jsonInfo.omit is true and no other jsonInfo field
430 // is populated.
431 // If the field is exported and has no tag, then name is the field's name and all
432 // other fields are false.
433 // Otherwise, the information is obtained from the tag.
434 func fieldJSONInfo(f reflect.StructField) jsonInfo {
435 if !f.IsExported() {
436 return jsonInfo{omit: true}
437 }
438 info := jsonInfo{name: f.Name}
439 if tag, ok := f.Tag.Lookup("json"); ok {
440 name, rest, found := strings.Cut(tag, ",")
441 // "-" means omit, but "-," means the name is "-"
442 if name == "-" && !found {
443 return jsonInfo{omit: true}
444 }
445 if name != "" {
446 info.name = name
447 }
448 if len(rest) > 0 {
449 info.settings = map[string]bool{}
450 for _, s := range strings.Split(rest, ",") {
451 info.settings[s] = true
452 }
453 }
454 }
455 return info
456 }
457
458 // wrapf wraps *errp with the given formatted message if *errp is not nil.
459 func wrapf(errp *error, format string, args ...any) {
460 if *errp != nil {
461 *errp = fmt.Errorf("%s: %w", fmt.Sprintf(format, args...), *errp)
462 }
463 }