gunk-dev/the-valley

json.go

source32bd55de0d87main's published tip history
7.6 KiB
1package review
2
3import (
4 "errors"
5 "fmt"
6 "strconv"
7 "unicode/utf16"
8 "unicode/utf8"
9)
10
11// This file is a JSON reader stricter than encoding/json, which accepts a
12// duplicate key, matches a key to a field whatever its case, and silently
13// replaces bytes that are not UTF-8. A review in which one key appears
14// twice reads differently to two readers that keep different copies, so
15// the reader here refuses it, at any depth. It is the change record's
16// reader (../change/json.go), read the same way.
17//
18// It reads the JSON a review is written in and nothing more. Every value
19// is an object, an array, a string or a number, and true, false and null
20// are read as values of their own kind, so the schema can refuse them by
21// name. A number is kept as its text, and the schema decides whether it
22// is an integer in range.
23
24// maxDepth is how deeply values may nest. A review nests four deep: the
25// review, its notes, one note, and the note's lines.
26const maxDepth = 8
27
28// kind is the kind of a JSON value.
29type kind int
30
31const (
32 kindObject kind = iota
33 kindArray
34 kindString
35 kindNumber
36 kindLiteral // true, false or null
37)
38
39func (k kind) String() string {
40 return [...]string{"an object", "an array", "a string", "a number", "a literal"}[k]
41}
42
43// value is one JSON value as read.
44type value struct {
45 kind kind
46 text string // a string's content, a number's or a literal's text
47 keys []string // an object's keys, in the order they appear
48 fields map[string]*value // an object's values
49 items []*value // an array's values
50}
51
52// readJSON reads data as exactly one JSON value, with only white space
53// around it.
54func readJSON(data []byte) (*value, error) {
55 if !utf8.Valid(data) {
56 return nil, errors.New("it is not valid UTF-8")
57 }
58 r := reader{data: data}
59 r.space()
60 v, err := r.value(1)
61 if err != nil {
62 return nil, err
63 }
64 r.space()
65 if r.pos != len(r.data) {
66 return nil, fmt.Errorf("it holds more after the value it opens with, at byte %d", r.pos)
67 }
68 return v, nil
69}
70
71type reader struct {
72 data []byte
73 pos int
74}
75
76func (r *reader) space() {
77 for r.pos < len(r.data) {
78 switch r.data[r.pos] {
79 case ' ', '\t', '\n', '\r':
80 r.pos++
81 default:
82 return
83 }
84 }
85}
86
87func (r *reader) fail(what string) error {
88 if r.pos >= len(r.data) {
89 return fmt.Errorf("it ends where %s was expected", what)
90 }
91 return fmt.Errorf("it holds %q at byte %d, where %s was expected", r.data[r.pos], r.pos, what)
92}
93
94func (r *reader) value(depth int) (*value, error) {
95 if depth > maxDepth {
96 return nil, fmt.Errorf("it nests values more than %d deep", maxDepth)
97 }
98 if r.pos >= len(r.data) {
99 return nil, r.fail("a value")
100 }
101 switch c := r.data[r.pos]; {
102 case c == '{':
103 return r.object(depth)
104 case c == '[':
105 return r.array(depth)
106 case c == '"':
107 s, err := r.string()
108 if err != nil {
109 return nil, err
110 }
111 return &value{kind: kindString, text: s}, nil
112 case c == '-' || (c >= '0' && c <= '9'):
113 return r.number()
114 default:
115 for _, lit := range []string{"true", "false", "null"} {
116 if len(r.data)-r.pos >= len(lit) && string(r.data[r.pos:r.pos+len(lit)]) == lit {
117 r.pos += len(lit)
118 return &value{kind: kindLiteral, text: lit}, nil
119 }
120 }
121 return nil, r.fail("a value")
122 }
123}
124
125func (r *reader) object(depth int) (*value, error) {
126 v := &value{kind: kindObject, fields: map[string]*value{}}
127 r.pos++ // {
128 r.space()
129 if r.pos < len(r.data) && r.data[r.pos] == '}' {
130 r.pos++
131 return v, nil
132 }
133 for {
134 r.space()
135 if r.pos >= len(r.data) || r.data[r.pos] != '"' {
136 return nil, r.fail("a key")
137 }
138 key, err := r.string()
139 if err != nil {
140 return nil, err
141 }
142 if _, seen := v.fields[key]; seen {
143 return nil, fmt.Errorf("it names the key %q twice in one object", key)
144 }
145 r.space()
146 if r.pos >= len(r.data) || r.data[r.pos] != ':' {
147 return nil, r.fail("a colon")
148 }
149 r.pos++
150 r.space()
151 field, err := r.value(depth + 1)
152 if err != nil {
153 return nil, err
154 }
155 v.keys = append(v.keys, key)
156 v.fields[key] = field
157 r.space()
158 if r.pos >= len(r.data) {
159 return nil, r.fail("a comma or a closing brace")
160 }
161 switch r.data[r.pos] {
162 case ',':
163 r.pos++
164 case '}':
165 r.pos++
166 return v, nil
167 default:
168 return nil, r.fail("a comma or a closing brace")
169 }
170 }
171}
172
173func (r *reader) array(depth int) (*value, error) {
174 v := &value{kind: kindArray}
175 r.pos++ // [
176 r.space()
177 if r.pos < len(r.data) && r.data[r.pos] == ']' {
178 r.pos++
179 return v, nil
180 }
181 for {
182 r.space()
183 item, err := r.value(depth + 1)
184 if err != nil {
185 return nil, err
186 }
187 v.items = append(v.items, item)
188 r.space()
189 if r.pos >= len(r.data) {
190 return nil, r.fail("a comma or a closing bracket")
191 }
192 switch r.data[r.pos] {
193 case ',':
194 r.pos++
195 case ']':
196 r.pos++
197 return v, nil
198 default:
199 return nil, r.fail("a comma or a closing bracket")
200 }
201 }
202}
203
204// string reads one JSON string. An escape that names half of a UTF-16
205// surrogate pair alone names no character, so it is refused rather than
206// read as U+FFFD, the way encoding/json reads it.
207func (r *reader) string() (string, error) {
208 r.pos++ // "
209 var out []byte
210 for {
211 if r.pos >= len(r.data) {
212 return "", r.fail("the end of a string")
213 }
214 c := r.data[r.pos]
215 switch {
216 case c == '"':
217 r.pos++
218 return string(out), nil
219 case c < 0x20:
220 return "", fmt.Errorf("it holds the control character %q unescaped in a string, at byte %d", c, r.pos)
221 case c != '\\':
222 out = append(out, c)
223 r.pos++
224 continue
225 }
226 r.pos++ // the backslash
227 if r.pos >= len(r.data) {
228 return "", r.fail("an escape")
229 }
230 e := r.data[r.pos]
231 r.pos++
232 switch e {
233 case '"', '\\', '/':
234 out = append(out, e)
235 case 'b':
236 out = append(out, '\b')
237 case 'f':
238 out = append(out, '\f')
239 case 'n':
240 out = append(out, '\n')
241 case 'r':
242 out = append(out, '\r')
243 case 't':
244 out = append(out, '\t')
245 case 'u':
246 rn, err := r.hex4()
247 if err != nil {
248 return "", err
249 }
250 if utf16.IsSurrogate(rn) {
251 if rn >= 0xdc00 || len(r.data)-r.pos < 2 || r.data[r.pos] != '\\' || r.data[r.pos+1] != 'u' {
252 return "", fmt.Errorf("it escapes half of a surrogate pair alone, at byte %d", r.pos)
253 }
254 r.pos += 2
255 low, err := r.hex4()
256 if err != nil {
257 return "", err
258 }
259 rn = utf16.DecodeRune(rn, low)
260 if rn == utf8.RuneError {
261 return "", fmt.Errorf("it escapes half of a surrogate pair alone, at byte %d", r.pos)
262 }
263 }
264 out = utf8.AppendRune(out, rn)
265 default:
266 return "", fmt.Errorf("it holds the escape \\%c, which JSON does not have, at byte %d", e, r.pos-1)
267 }
268 }
269}
270
271func (r *reader) hex4() (rune, error) {
272 if len(r.data)-r.pos < 4 {
273 return 0, r.fail("four hex digits")
274 }
275 n, err := strconv.ParseUint(string(r.data[r.pos:r.pos+4]), 16, 32)
276 if err != nil {
277 return 0, r.fail("four hex digits")
278 }
279 r.pos += 4
280 return rune(n), nil
281}
282
283// number reads one JSON number, keeping its text.
284func (r *reader) number() (*value, error) {
285 start := r.pos
286 if r.data[r.pos] == '-' {
287 r.pos++
288 }
289 switch {
290 case r.pos < len(r.data) && r.data[r.pos] == '0':
291 r.pos++
292 case r.pos < len(r.data) && r.data[r.pos] >= '1' && r.data[r.pos] <= '9':
293 r.digits()
294 default:
295 return nil, r.fail("a digit")
296 }
297 if r.pos < len(r.data) && r.data[r.pos] == '.' {
298 r.pos++
299 if !r.digits() {
300 return nil, r.fail("a digit")
301 }
302 }
303 if r.pos < len(r.data) && (r.data[r.pos] == 'e' || r.data[r.pos] == 'E') {
304 r.pos++
305 if r.pos < len(r.data) && (r.data[r.pos] == '+' || r.data[r.pos] == '-') {
306 r.pos++
307 }
308 if !r.digits() {
309 return nil, r.fail("a digit")
310 }
311 }
312 return &value{kind: kindNumber, text: string(r.data[start:r.pos])}, nil
313}
314
315func (r *reader) digits() bool {
316 start := r.pos
317 for r.pos < len(r.data) && r.data[r.pos] >= '0' && r.data[r.pos] <= '9' {
318 r.pos++
319 }
320 return r.pos > start
321}