| 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 "maps" |
| 8 | |
| 9 | // An annotations tracks certain properties computed by keywords that are used by validation. |
| 10 | // ("Annotation" is the spec's term.) |
| 11 | // In particular, the unevaluatedItems and unevaluatedProperties keywords need to know which |
| 12 | // items and properties were evaluated (validated successfully). |
| 13 | type annotations struct { |
| 14 | allItems bool // all items were evaluated |
| 15 | endIndex int // 1+largest index evaluated by prefixItems |
| 16 | evaluatedIndexes map[int]bool // set of indexes evaluated by contains |
| 17 | allProperties bool // all properties were evaluated |
| 18 | evaluatedProperties map[string]bool // set of properties evaluated by various keywords |
| 19 | } |
| 20 | |
| 21 | // noteIndex marks i as evaluated. |
| 22 | func (a *annotations) noteIndex(i int) { |
| 23 | if a.evaluatedIndexes == nil { |
| 24 | a.evaluatedIndexes = map[int]bool{} |
| 25 | } |
| 26 | a.evaluatedIndexes[i] = true |
| 27 | } |
| 28 | |
| 29 | // noteEndIndex marks items with index less than end as evaluated. |
| 30 | func (a *annotations) noteEndIndex(end int) { |
| 31 | if end > a.endIndex { |
| 32 | a.endIndex = end |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | // noteProperty marks prop as evaluated. |
| 37 | func (a *annotations) noteProperty(prop string) { |
| 38 | if a.evaluatedProperties == nil { |
| 39 | a.evaluatedProperties = map[string]bool{} |
| 40 | } |
| 41 | a.evaluatedProperties[prop] = true |
| 42 | } |
| 43 | |
| 44 | // noteProperties marks all the properties in props as evaluated. |
| 45 | func (a *annotations) noteProperties(props map[string]bool) { |
| 46 | a.evaluatedProperties = merge(a.evaluatedProperties, props) |
| 47 | } |
| 48 | |
| 49 | // merge adds b's annotations to a. |
| 50 | // a must not be nil. |
| 51 | func (a *annotations) merge(b *annotations) { |
| 52 | if b == nil { |
| 53 | return |
| 54 | } |
| 55 | if b.allItems { |
| 56 | a.allItems = true |
| 57 | } |
| 58 | if b.endIndex > a.endIndex { |
| 59 | a.endIndex = b.endIndex |
| 60 | } |
| 61 | a.evaluatedIndexes = merge(a.evaluatedIndexes, b.evaluatedIndexes) |
| 62 | if b.allProperties { |
| 63 | a.allProperties = true |
| 64 | } |
| 65 | a.evaluatedProperties = merge(a.evaluatedProperties, b.evaluatedProperties) |
| 66 | } |
| 67 | |
| 68 | // merge adds t's keys to s and returns s. |
| 69 | // If s is nil, it returns a copy of t. |
| 70 | func merge[K comparable](s, t map[K]bool) map[K]bool { |
| 71 | if s == nil { |
| 72 | return maps.Clone(t) |
| 73 | } |
| 74 | maps.Copy(s, t) |
| 75 | return s |
| 76 | } |