Debian Codegraph @

debian/go/src/github.com/google/jsonschema-go/jsonschema/json_pointer.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 // This file implements JSON Pointers.
6 // A JSON Pointer is a path that refers to one JSON value within another.
7 // If the path is empty, it refers to the root value.
8 // Otherwise, it is a sequence of slash-prefixed strings, like "/points/1/x",
9 // selecting successive properties (for JSON objects) or items (for JSON arrays).
10 // For example, when applied to this JSON value:
11 // {
12 // "points": [
13 // {"x": 1, "y": 2},
14 // {"x": 3, "y": 4}
15 // ]
16 // }
17 //
18 // the JSON Pointer "/points/1/x" refers to the number 3.
19 // See the spec at https://datatracker.ietf.org/doc/html/rfc6901.
20
21 package jsonschema
22
23 import (
24 "errors"
25 "fmt"
26 "reflect"
27 "strconv"
28 "strings"
29 )
30
31 var (
32 jsonPointerEscaper = strings.NewReplacer("~", "~0", "/", "~1")
33 jsonPointerUnescaper = strings.NewReplacer("~0", "~", "~1", "/")
34 )
35
36 func escapeJSONPointerSegment(s string) string {
37 return jsonPointerEscaper.Replace(s)
38 }
39
40 func unescapeJSONPointerSegment(s string) string {
41 return jsonPointerUnescaper.Replace(s)
42 }
43
44 // parseJSONPointer splits a JSON Pointer into a sequence of segments. It doesn't
45 // convert strings to numbers, because that depends on the traversal: a segment
46 // is treated as a number when applied to an array, but a string when applied to
47 // an object. See section 4 of the spec.
48 func parseJSONPointer(ptr string) (segments []string, err error) {
49 if ptr == "" {
50 return nil, nil
51 }
52 if ptr[0] != '/' {
53 return nil, fmt.Errorf("JSON Pointer %q does not begin with '/'", ptr)
54 }
55 // Unlike file paths, consecutive slashes are not coalesced.
56 // Split is nicer than Cut here, because it gets a final "/" right.
57 segments = strings.Split(ptr[1:], "/")
58 if strings.Contains(ptr, "~") {
59 // Undo the simple escaping rules that allow one to include a slash in a segment.
60 for i := range segments {
61 segments[i] = unescapeJSONPointerSegment(segments[i])
62 }
63 }
64 return segments, nil
65 }
66
67 // dereferenceJSONPointer returns the Schema that sptr points to within s,
68 // or an error if none.
69 // This implementation suffices for JSON Schema: pointers are applied only to Schemas,
70 // and refer only to Schemas.
71 func dereferenceJSONPointer(s *Schema, sptr string) (_ *Schema, err error) {
72 defer wrapf(&err, "JSON Pointer %q", sptr)
73
74 segments, err := parseJSONPointer(sptr)
75 if err != nil {
76 return nil, err
77 }
78 v := reflect.ValueOf(s)
79 for _, seg := range segments {
80 switch v.Kind() {
81 case reflect.Pointer:
82 v = v.Elem()
83 if !v.IsValid() {
84 return nil, errors.New("navigated to nil reference")
85 }
86 fallthrough // if valid, can only be a pointer to a Schema
87
88 case reflect.Struct:
89 // The segment must refer to a field in a Schema.
90 if v.Type() != reflect.TypeFor[Schema]() {
91 return nil, fmt.Errorf("navigated to non-Schema %s", v.Type())
92 }
93 v = lookupSchemaField(v, seg)
94 if !v.IsValid() {
95 return nil, fmt.Errorf("no schema field %q", seg)
96 }
97 case reflect.Slice, reflect.Array:
98 // The segment must be an integer without leading zeroes that refers to an item in the
99 // slice or array.
100 if seg == "-" {
101 return nil, errors.New("the JSON Pointer array segment '-' is not supported")
102 }
103 if len(seg) > 1 && seg[0] == '0' {
104 return nil, fmt.Errorf("segment %q has leading zeroes", seg)
105 }
106 n, err := strconv.Atoi(seg)
107 if err != nil {
108 return nil, fmt.Errorf("invalid int: %q", seg)
109 }
110 if n < 0 || n >= v.Len() {
111 return nil, fmt.Errorf("index %d is out of bounds for array of length %d", n, v.Len())
112 }
113 v = v.Index(n)
114 // Cannot be invalid.
115 case reflect.Map:
116 // The segment must be a key in the map.
117 v = v.MapIndex(reflect.ValueOf(seg))
118 if !v.IsValid() {
119 return nil, fmt.Errorf("no key %q in map", seg)
120 }
121 default:
122 return nil, fmt.Errorf("value %s (%s) is not a schema, slice or map", v, v.Type())
123 }
124 }
125 if s, ok := v.Interface().(*Schema); ok {
126 return s, nil
127 }
128 return nil, fmt.Errorf("does not refer to a schema, but to a %s", v.Type())
129 }
130
131 // lookupSchemaField returns the value of the field with the given name in v,
132 // or the zero value if there is no such field or it is not of type Schema or *Schema.
133 func lookupSchemaField(v reflect.Value, name string) reflect.Value {
134 if name == "type" {
135 // The "type" keyword may refer to Type or Types.
136 // At most one will be non-zero.
137 if t := v.FieldByName("Type"); !t.IsZero() {
138 return t
139 }
140 return v.FieldByName("Types")
141 }
142 if sf, ok := schemaFieldMap[name]; ok {
143 return v.FieldByIndex(sf.Index)
144 }
145 return reflect.Value{}
146 }