Debian Codegraph @

debian/go/src/github.com/google/jsonschema-go/jsonschema/schema.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/json"
11 "errors"
12 "fmt"
13 "iter"
14 "maps"
15 "math"
16 "reflect"
17 "slices"
18 )
19
20 // A Schema is a JSON schema object.
21 // It corresponds to the 2020-12 draft, as described in https://json-schema.org/draft/2020-12,
22 // specifically:
23 // - https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-01
24 // - https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01
25 //
26 // A Schema value may have non-zero values for more than one field:
27 // all relevant non-zero fields are used for validation.
28 // There is one exception to provide more Go type-safety: the Type and Types fields
29 // are mutually exclusive.
30 //
31 // Since this struct is a Go representation of a JSON value, it inherits JSON's
32 // distinction between nil and empty. Nil slices and maps are considered absent,
33 // but empty ones are present and affect validation. For example,
34 //
35 // Schema{Enum: nil}
36 //
37 // is equivalent to an empty schema, so it validates every instance. But
38 //
39 // Schema{Enum: []any{}}
40 //
41 // requires equality to some slice element, so it vacuously rejects every instance.
42 type Schema struct {
43 // core
44 ID string `json:"$id,omitempty"`
45 Schema string `json:"$schema,omitempty"`
46 Ref string `json:"$ref,omitempty"`
47 Comment string `json:"$comment,omitempty"`
48 Defs map[string]*Schema `json:"$defs,omitempty"`
49 // definitions is deprecated but still allowed. It is a synonym for $defs.
50 Definitions map[string]*Schema `json:"definitions,omitempty"`
51
52 Anchor string `json:"$anchor,omitempty"`
53 DynamicAnchor string `json:"$dynamicAnchor,omitempty"`
54 DynamicRef string `json:"$dynamicRef,omitempty"`
55 Vocabulary map[string]bool `json:"$vocabulary,omitempty"`
56
57 // metadata
58 Title string `json:"title,omitempty"`
59 Description string `json:"description,omitempty"`
60 Default json.RawMessage `json:"default,omitempty"`
61 Deprecated bool `json:"deprecated,omitempty"`
62 ReadOnly bool `json:"readOnly,omitempty"`
63 WriteOnly bool `json:"writeOnly,omitempty"`
64 Examples []any `json:"examples,omitempty"`
65
66 // validation
67 // Use Type for a single type, or Types for multiple types; never both.
68 Type string `json:"-"`
69 Types []string `json:"-"`
70 Enum []any `json:"enum,omitempty"`
71 // Const is *any because a JSON null (Go nil) is a valid value.
72 Const *any `json:"const,omitempty"`
73 MultipleOf *float64 `json:"multipleOf,omitempty"`
74 Minimum *float64 `json:"minimum,omitempty"`
75 Maximum *float64 `json:"maximum,omitempty"`
76 ExclusiveMinimum *float64 `json:"exclusiveMinimum,omitempty"`
77 ExclusiveMaximum *float64 `json:"exclusiveMaximum,omitempty"`
78 MinLength *int `json:"minLength,omitempty"`
79 MaxLength *int `json:"maxLength,omitempty"`
80 Pattern string `json:"pattern,omitempty"`
81
82 // arrays
83 PrefixItems []*Schema `json:"prefixItems,omitempty"`
84 Items *Schema `json:"items,omitempty"`
85 MinItems *int `json:"minItems,omitempty"`
86 MaxItems *int `json:"maxItems,omitempty"`
87 AdditionalItems *Schema `json:"additionalItems,omitempty"`
88 UniqueItems bool `json:"uniqueItems,omitempty"`
89 Contains *Schema `json:"contains,omitempty"`
90 MinContains *int `json:"minContains,omitempty"` // *int, not int: default is 1, not 0
91 MaxContains *int `json:"maxContains,omitempty"`
92 UnevaluatedItems *Schema `json:"unevaluatedItems,omitempty"`
93
94 // objects
95 MinProperties *int `json:"minProperties,omitempty"`
96 MaxProperties *int `json:"maxProperties,omitempty"`
97 Required []string `json:"required,omitempty"`
98 DependentRequired map[string][]string `json:"dependentRequired,omitempty"`
99 Properties map[string]*Schema `json:"properties,omitempty"`
100 PatternProperties map[string]*Schema `json:"patternProperties,omitempty"`
101 AdditionalProperties *Schema `json:"additionalProperties,omitempty"`
102 PropertyNames *Schema `json:"propertyNames,omitempty"`
103 UnevaluatedProperties *Schema `json:"unevaluatedProperties,omitempty"`
104
105 // logic
106 AllOf []*Schema `json:"allOf,omitempty"`
107 AnyOf []*Schema `json:"anyOf,omitempty"`
108 OneOf []*Schema `json:"oneOf,omitempty"`
109 Not *Schema `json:"not,omitempty"`
110
111 // conditional
112 If *Schema `json:"if,omitempty"`
113 Then *Schema `json:"then,omitempty"`
114 Else *Schema `json:"else,omitempty"`
115 DependentSchemas map[string]*Schema `json:"dependentSchemas,omitempty"`
116
117 // other
118 // https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.8
119 ContentEncoding string `json:"contentEncoding,omitempty"`
120 ContentMediaType string `json:"contentMediaType,omitempty"`
121 ContentSchema *Schema `json:"contentSchema,omitempty"`
122
123 // https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7
124 Format string `json:"format,omitempty"`
125
126 // Extra allows for additional keywords beyond those specified.
127 Extra map[string]any `json:"-"`
128 }
129
130 // falseSchema returns a new Schema tree that fails to validate any value.
131 func falseSchema() *Schema {
132 return &Schema{Not: &Schema{}}
133 }
134
135 // anchorInfo records the subschema to which an anchor refers, and whether
136 // the anchor keyword is $anchor or $dynamicAnchor.
137 type anchorInfo struct {
138 schema *Schema
139 dynamic bool
140 }
141
142 // String returns a short description of the schema.
143 func (s *Schema) String() string {
144 if s.ID != "" {
145 return s.ID
146 }
147 if a := cmp.Or(s.Anchor, s.DynamicAnchor); a != "" {
148 return fmt.Sprintf("anchor %s", a)
149 }
150 return "<anonymous schema>"
151 }
152
153 // CloneSchemas returns a copy of s.
154 // The copy is shallow except for sub-schemas, which are themelves copied with CloneSchemas.
155 // This allows both s and s.CloneSchemas() to appear as sub-schemas of the same parent.
156 func (s *Schema) CloneSchemas() *Schema {
157 if s == nil {
158 return nil
159 }
160 s2 := *s
161 v := reflect.ValueOf(&s2)
162 for _, info := range schemaFieldInfos {
163 fv := v.Elem().FieldByIndex(info.sf.Index)
164 switch info.sf.Type {
165 case schemaType:
166 sscss := fv.Interface().(*Schema)
167 fv.Set(reflect.ValueOf(sscss.CloneSchemas()))
168
169 case schemaSliceType:
170 slice := fv.Interface().([]*Schema)
171 slice = slices.Clone(slice)
172 for i, ss := range slice {
173 slice[i] = ss.CloneSchemas()
174 }
175 fv.Set(reflect.ValueOf(slice))
176
177 case schemaMapType:
178 m := fv.Interface().(map[string]*Schema)
179 m = maps.Clone(m)
180 for k, ss := range m {
181 m[k] = ss.CloneSchemas()
182 }
183 fv.Set(reflect.ValueOf(m))
184 }
185 }
186 return &s2
187 }
188
189 func (s *Schema) basicChecks() error {
190 if s.Type != "" && s.Types != nil {
191 return errors.New("both Type and Types are set; at most one should be")
192 }
193 if s.Defs != nil && s.Definitions != nil {
194 return errors.New("both Defs and Definitions are set; at most one should be")
195 }
196 return nil
197 }
198
199 type schemaWithoutMethods Schema // doesn't implement json.{Unm,M}arshaler
200
201 func (s *Schema) MarshalJSON() ([]byte, error) {
202 if err := s.basicChecks(); err != nil {
203 return nil, err
204 }
205
206 // Marshal either Type or Types as "type".
207 var typ any
208 switch {
209 case s.Type != "":
210 typ = s.Type
211 case s.Types != nil:
212 typ = s.Types
213 }
214 ms := struct {
215 Type any `json:"type,omitempty"`
216 *schemaWithoutMethods
217 }{
218 Type: typ,
219 schemaWithoutMethods: (*schemaWithoutMethods)(s),
220 }
221 bs, err := marshalStructWithMap(&ms, "Extra")
222 if err != nil {
223 return nil, err
224 }
225 // Marshal {} as true and {"not": {}} as false.
226 // It is wasteful to do this here instead of earlier, but much easier.
227 switch {
228 case bytes.Equal(bs, []byte(`{}`)):
229 bs = []byte("true")
230 case bytes.Equal(bs, []byte(`{"not":true}`)):
231 bs = []byte("false")
232 }
233 return bs, nil
234 }
235
236 func (s *Schema) UnmarshalJSON(data []byte) error {
237 // A JSON boolean is a valid schema.
238 var b bool
239 if err := json.Unmarshal(data, &b); err == nil {
240 if b {
241 // true is the empty schema, which validates everything.
242 *s = Schema{}
243 } else {
244 // false is the schema that validates nothing.
245 *s = *falseSchema()
246 }
247 return nil
248 }
249
250 ms := struct {
251 Type json.RawMessage `json:"type,omitempty"`
252 Const json.RawMessage `json:"const,omitempty"`
253 MinLength *integer `json:"minLength,omitempty"`
254 MaxLength *integer `json:"maxLength,omitempty"`
255 MinItems *integer `json:"minItems,omitempty"`
256 MaxItems *integer `json:"maxItems,omitempty"`
257 MinProperties *integer `json:"minProperties,omitempty"`
258 MaxProperties *integer `json:"maxProperties,omitempty"`
259 MinContains *integer `json:"minContains,omitempty"`
260 MaxContains *integer `json:"maxContains,omitempty"`
261
262 *schemaWithoutMethods
263 }{
264 schemaWithoutMethods: (*schemaWithoutMethods)(s),
265 }
266 if err := unmarshalStructWithMap(data, &ms, "Extra"); err != nil {
267 return err
268 }
269 // Unmarshal "type" as either Type or Types.
270 var err error
271 if len(ms.Type) > 0 {
272 switch ms.Type[0] {
273 case '"':
274 err = json.Unmarshal(ms.Type, &s.Type)
275 case '[':
276 err = json.Unmarshal(ms.Type, &s.Types)
277 default:
278 err = fmt.Errorf(`invalid value for "type": %q`, ms.Type)
279 }
280 }
281 if err != nil {
282 return err
283 }
284
285 unmarshalAnyPtr := func(p **any, raw json.RawMessage) error {
286 if len(raw) == 0 {
287 return nil
288 }
289 if bytes.Equal(raw, []byte("null")) {
290 *p = new(any)
291 return nil
292 }
293 return json.Unmarshal(raw, p)
294 }
295
296 // Setting Const to a pointer to null will marshal properly, but won't
297 // unmarshal: the *any is set to nil, not a pointer to nil.
298 if err := unmarshalAnyPtr(&s.Const, ms.Const); err != nil {
299 return err
300 }
301
302 set := func(dst **int, src *integer) {
303 if src != nil {
304 *dst = Ptr(int(*src))
305 }
306 }
307
308 set(&s.MinLength, ms.MinLength)
309 set(&s.MaxLength, ms.MaxLength)
310 set(&s.MinItems, ms.MinItems)
311 set(&s.MaxItems, ms.MaxItems)
312 set(&s.MinProperties, ms.MinProperties)
313 set(&s.MaxProperties, ms.MaxProperties)
314 set(&s.MinContains, ms.MinContains)
315 set(&s.MaxContains, ms.MaxContains)
316
317 return nil
318 }
319
320 type integer int32 // for the integer-valued fields of Schema
321
322 func (ip *integer) UnmarshalJSON(data []byte) error {
323 if len(data) == 0 {
324 // nothing to do
325 return nil
326 }
327 // If there is a decimal point, src is a floating-point number.
328 var i int64
329 if bytes.ContainsRune(data, '.') {
330 var f float64
331 if err := json.Unmarshal(data, &f); err != nil {
332 return errors.New("not a number")
333 }
334 i = int64(f)
335 if float64(i) != f {
336 return errors.New("not an integer value")
337 }
338 } else {
339 if err := json.Unmarshal(data, &i); err != nil {
340 return errors.New("cannot be unmarshaled into an int")
341 }
342 }
343 // Ensure behavior is the same on both 32-bit and 64-bit systems.
344 if i < math.MinInt32 || i > math.MaxInt32 {
345 return errors.New("integer is out of range")
346 }
347 *ip = integer(i)
348 return nil
349 }
350
351 // Ptr returns a pointer to a new variable whose value is x.
352 func Ptr[T any](x T) *T { return &x }
353
354 // every applies f preorder to every schema under s including s.
355 // The second argument to f is the path to the schema appended to the argument path.
356 // It stops when f returns false.
357 func (s *Schema) every(f func(*Schema) bool) bool {
358 return f(s) && s.everyChild(func(s *Schema) bool { return s.every(f) })
359 }
360
361 // everyChild reports whether f is true for every immediate child schema of s.
362 func (s *Schema) everyChild(f func(*Schema) bool) bool {
363 v := reflect.ValueOf(s)
364 for _, info := range schemaFieldInfos {
365 fv := v.Elem().FieldByIndex(info.sf.Index)
366 switch info.sf.Type {
367 case schemaType:
368 // A field that contains an individual schema. A nil is valid: it just means the field isn't present.
369 c := fv.Interface().(*Schema)
370 if c != nil && !f(c) {
371 return false
372 }
373
374 case schemaSliceType:
375 slice := fv.Interface().([]*Schema)
376 for _, c := range slice {
377 if !f(c) {
378 return false
379 }
380 }
381
382 case schemaMapType:
383 // Sort keys for determinism.
384 m := fv.Interface().(map[string]*Schema)
385 for _, k := range slices.Sorted(maps.Keys(m)) {
386 if !f(m[k]) {
387 return false
388 }
389 }
390 }
391 }
392 return true
393 }
394
395 // all wraps every in an iterator.
396 func (s *Schema) all() iter.Seq[*Schema] {
397 return func(yield func(*Schema) bool) { s.every(yield) }
398 }
399
400 // children wraps everyChild in an iterator.
401 func (s *Schema) children() iter.Seq[*Schema] {
402 return func(yield func(*Schema) bool) { s.everyChild(yield) }
403 }
404
405 var (
406 schemaType = reflect.TypeFor[*Schema]()
407 schemaSliceType = reflect.TypeFor[[]*Schema]()
408 schemaMapType = reflect.TypeFor[map[string]*Schema]()
409 )
410
411 type structFieldInfo struct {
412 sf reflect.StructField
413 jsonName string
414 }
415
416 var (
417 // the visible fields of Schema that have a JSON name, sorted by that name
418 schemaFieldInfos []structFieldInfo
419 // map from JSON name to field
420 schemaFieldMap = map[string]reflect.StructField{}
421 )
422
423 func init() {
424 for _, sf := range reflect.VisibleFields(reflect.TypeFor[Schema]()) {
425 info := fieldJSONInfo(sf)
426 if !info.omit {
427 schemaFieldInfos = append(schemaFieldInfos, structFieldInfo{sf, info.name})
428 }
429 }
430 slices.SortFunc(schemaFieldInfos, func(i1, i2 structFieldInfo) int {
431 return cmp.Compare(i1.jsonName, i2.jsonName)
432 })
433 for _, info := range schemaFieldInfos {
434 schemaFieldMap[info.jsonName] = info.sf
435 }
436 }