Debian Codegraph @

lib/json/json.go

raw
1 // Copyright 2020 The Bazel Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package json defines utilities for converting Starlark values
6 // to/from JSON strings. The most recent IETF standard for JSON is
7 // https://www.ietf.org/rfc/rfc7159.txt.
8 package json // import "go.starlark.net/lib/json"
9
10 import (
11 "bytes"
12 "encoding/json"
13 "fmt"
14 "math"
15 "math/big"
16 "reflect"
17 "slices"
18 "sort"
19 "strconv"
20 "strings"
21 "unicode/utf8"
22 "unsafe"
23
24 "go.starlark.net/starlark"
25 "go.starlark.net/starlarkstruct"
26 )
27
28 // Module json is a Starlark module of JSON-related functions.
29 //
30 // json = module(
31 // encode,
32 // encode_indent,
33 // decode,
34 // indent,
35 // )
36 //
37 // def encode(x):
38 //
39 // The encode function accepts one required positional argument,
40 // which it converts to JSON by cases:
41 // - A Starlark value that implements Go's standard json.Marshal
42 // interface defines its own JSON encoding.
43 // - None, True, and False are converted to null, true, and false, respectively.
44 // - Starlark int values, no matter how large, are encoded as decimal integers.
45 // Some decoders may not be able to decode very large integers.
46 // - Starlark float values are encoded using decimal point notation,
47 // even if the value is an integer.
48 // It is an error to encode a non-finite floating-point value.
49 // - Starlark strings are encoded as JSON strings, using UTF-16 escapes.
50 // - a Starlark IterableMapping (e.g. dict) is encoded as a JSON object.
51 // It is an error if any key is not a string.
52 // - any other Starlark Iterable (e.g. list, tuple) is encoded as a JSON array.
53 // - a Starlark HasAttrs (e.g. struct) is encoded as a JSON object.
54 //
55 // It an application-defined type matches more than one the cases describe above,
56 // (e.g. it implements both Iterable and HasFields), the first case takes precedence.
57 // Encoding any other value yields an error.
58 //
59 // def encode_indent(x, *, prefix="", indent="\t"):
60 //
61 // Equivalent to json.indent(json.encode(x), prefix=prefix, indent=indent).
62 //
63 // def decode(x[, default]):
64 //
65 // The decode function has one required positional parameter, a JSON string.
66 // It returns the Starlark value that the string denotes.
67 // - Numbers are parsed as int or float, depending on whether they
68 // contain a decimal point.
69 // - JSON objects are parsed as new unfrozen Starlark dicts.
70 // - JSON arrays are parsed as new unfrozen Starlark lists.
71 //
72 // If x is not a valid JSON string, the behavior depends on the "default"
73 // parameter: if present, Decode returns its value; otherwise, Decode fails.
74 //
75 // def indent(str, *, prefix="", indent="\t"):
76 //
77 // The indent function pretty-prints a valid JSON encoding,
78 // and returns a string containing the indented form.
79 // It accepts one required positional parameter, the JSON string,
80 // and two optional keyword-only string parameters, prefix and indent,
81 // that specify a prefix of each new line, and the unit of indentation.
82 var Module = &starlarkstruct.Module{
83 Name: "json",
84 Members: starlark.StringDict{
85 "encode": starlark.NewBuiltin("json.encode", encode),
86 "encode_indent": starlark.NewBuiltin("json.encode_indent", encodeIndent),
87 "decode": starlark.NewBuiltin("json.decode", decode),
88 "indent": starlark.NewBuiltin("json.indent", indent),
89 },
90 }
91
92 func encode(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
93 var x starlark.Value
94 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &x); err != nil {
95 return nil, err
96 }
97
98 buf := new(bytes.Buffer)
99
100 var quoteSpace [128]byte
101 quote := func(s string) {
102 // Non-trivial escaping is handled by Go's encoding/json.
103 if isPrintableASCII(s) {
104 buf.Write(strconv.AppendQuote(quoteSpace[:0], s))
105 } else {
106 // TODO(adonovan): opt: RFC 8259 mandates UTF-8 for JSON.
107 // Can we avoid this call?
108 data, _ := json.Marshal(s)
109 buf.Write(data)
110 }
111 }
112
113 path := make([]unsafe.Pointer, 0, 8)
114
115 var emit func(x starlark.Value) error
116 emit = func(x starlark.Value) error {
117
118 // It is only necessary to push/pop the item when it might contain
119 // itself (i.e. the last three switch cases), but omitting it in the other
120 // cases did not show significant improvement on the benchmarks.
121 if ptr := pointer(x); ptr != nil {
122 if pathContains(path, ptr) {
123 return fmt.Errorf("cycle in JSON structure")
124 }
125
126 path = append(path, ptr)
127 defer func() { path = path[0 : len(path)-1] }()
128 }
129
130 switch x := x.(type) {
131 case json.Marshaler:
132 // Application-defined starlark.Value types
133 // may define their own JSON encoding.
134 data, err := x.MarshalJSON()
135 if err != nil {
136 return err
137 }
138 buf.Write(data)
139
140 case starlark.NoneType:
141 buf.WriteString("null")
142
143 case starlark.Bool:
144 if x {
145 buf.WriteString("true")
146 } else {
147 buf.WriteString("false")
148 }
149
150 case starlark.Int:
151 fmt.Fprint(buf, x)
152
153 case starlark.Float:
154 if !isFinite(float64(x)) {
155 return fmt.Errorf("cannot encode non-finite float %v", x)
156 }
157 // Float.String always contains a decimal point. (%g does not!)
158 buf.WriteString(x.String())
159
160 case starlark.String:
161 quote(string(x))
162
163 case starlark.IterableMapping:
164 // e.g. dict (must have string keys)
165 buf.WriteByte('{')
166 items := x.Items()
167 for _, item := range items {
168 if _, ok := item[0].(starlark.String); !ok {
169 return fmt.Errorf("%s has %s key, want string", x.Type(), item[0].Type())
170 }
171 }
172 sort.Slice(items, func(i, j int) bool {
173 return items[i][0].(starlark.String) < items[j][0].(starlark.String)
174 })
175 for i, item := range items {
176 if i > 0 {
177 buf.WriteByte(',')
178 }
179 k, _ := starlark.AsString(item[0])
180 quote(k)
181 buf.WriteByte(':')
182 if err := emit(item[1]); err != nil {
183 return fmt.Errorf("in %s key %s: %v", x.Type(), item[0], err)
184 }
185 }
186 buf.WriteByte('}')
187
188 case starlark.Iterable:
189 // e.g. tuple, list
190 buf.WriteByte('[')
191 iter := x.Iterate()
192 defer iter.Done()
193 var elem starlark.Value
194 for i := 0; iter.Next(&elem); i++ {
195 if i > 0 {
196 buf.WriteByte(',')
197 }
198 if err := emit(elem); err != nil {
199 return fmt.Errorf("at %s index %d: %v", x.Type(), i, err)
200 }
201 }
202 buf.WriteByte(']')
203
204 case starlark.HasAttrs:
205 // e.g. struct
206 buf.WriteByte('{')
207 var names []string
208 names = append(names, x.AttrNames()...)
209 sort.Strings(names)
210 for i, name := range names {
211 v, err := x.Attr(name)
212 if err != nil {
213 return fmt.Errorf("cannot access attribute %s.%s: %w", x.Type(), name, err)
214 }
215 if v == nil {
216 // x.AttrNames() returned name, but x.Attr(name) returned nil, stating
217 // that the field doesn't exist.
218 return fmt.Errorf("missing attribute %s.%s (despite %q appearing in dir()", x.Type(), name, name)
219 }
220 if i > 0 {
221 buf.WriteByte(',')
222 }
223 quote(name)
224 buf.WriteByte(':')
225 if err := emit(v); err != nil {
226 return fmt.Errorf("in field .%s: %v", name, err)
227 }
228 }
229 buf.WriteByte('}')
230
231 default:
232 return fmt.Errorf("cannot encode %s as JSON", x.Type())
233 }
234 return nil
235 }
236
237 if err := emit(x); err != nil {
238 return nil, fmt.Errorf("%s: %v", b.Name(), err)
239 }
240 return starlark.String(buf.String()), nil
241 }
242
243 func encodeIndent(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
244 prefix, indent := "", "\t" // keyword-only
245 if err := starlark.UnpackArgs(b.Name(), nil, kwargs,
246 "prefix?", &prefix,
247 "indent?", &indent,
248 ); err != nil {
249 return nil, err
250 }
251 // Rely on encode() to parse the positional parameter (since the signature matches); use our b so
252 // error messages are attributed to json.encode_indent.
253 str, err := encode(thread, b, args, nil)
254 if err != nil {
255 return nil, err
256 }
257 var buf bytes.Buffer
258 if err := json.Indent(&buf, []byte(str.(starlark.String)), prefix, indent); err != nil {
259 return nil, fmt.Errorf("%s: %v", b.Name(), err)
260 }
261 return starlark.String(buf.String()), nil
262 }
263
264 func pointer(i any) unsafe.Pointer {
265 v := reflect.ValueOf(i)
266 switch v.Kind() {
267 case reflect.Pointer, reflect.Chan, reflect.Map, reflect.UnsafePointer, reflect.Slice:
268 // TODO(adonovan): use v.Pointer() when we drop go1.17.
269 return unsafe.Pointer(v.Pointer())
270 default:
271 return nil
272 }
273 }
274
275 func pathContains(path []unsafe.Pointer, item unsafe.Pointer) bool {
276 return slices.Contains(path, item)
277 }
278
279 // isPrintableASCII reports whether s contains only printable ASCII.
280 func isPrintableASCII(s string) bool {
281 for i := 0; i < len(s); i++ {
282 b := s[i]
283 if b < 0x20 || b >= 0x80 {
284 return false
285 }
286 }
287 return true
288 }
289
290 // isFinite reports whether f represents a finite rational value.
291 // It is equivalent to !math.IsNan(f) && !math.IsInf(f, 0).
292 func isFinite(f float64) bool {
293 return math.Abs(f) <= math.MaxFloat64
294 }
295
296 func indent(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
297 prefix, indent := "", "\t" // keyword-only
298 if err := starlark.UnpackArgs(b.Name(), nil, kwargs,
299 "prefix?", &prefix,
300 "indent?", &indent,
301 ); err != nil {
302 return nil, err
303 }
304 var str string // positional-only
305 if err := starlark.UnpackPositionalArgs(b.Name(), args, nil, 1, &str); err != nil {
306 return nil, err
307 }
308
309 buf := new(bytes.Buffer)
310 if err := json.Indent(buf, []byte(str), prefix, indent); err != nil {
311 return nil, fmt.Errorf("%s: %v", b.Name(), err)
312 }
313 return starlark.String(buf.String()), nil
314 }
315
316 func decode(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (v starlark.Value, err error) {
317 var s string
318 var d starlark.Value
319 if err := starlark.UnpackArgs(b.Name(), args, kwargs, "x", &s, "default?", &d); err != nil {
320 return nil, err
321 }
322 if len(args) < 1 {
323 // "x" parameter is positional only; UnpackArgs does not allow us to
324 // directly express "def decode(x, *, default)"
325 return nil, fmt.Errorf("%s: unexpected keyword argument x", b.Name())
326 }
327
328 // The decoder necessarily makes certain representation choices
329 // such as list vs tuple, struct vs dict, int vs float.
330 // In principle, we could parameterize it to allow the caller to
331 // control the returned types, but there's no compelling need yet.
332
333 // Use panic/recover with a distinguished type (failure) for error handling.
334 // If "default" is set, we only want to return it when encountering invalid
335 // json - not for any other possible causes of panic.
336 // In particular, if we ever extend the json.decode API to take a callback,
337 // a distinguished, private failure type prevents the possibility of
338 // json.decode with "default" becoming abused as a try-catch mechanism.
339 type failure string
340 fail := func(format string, args ...any) {
341 panic(failure(fmt.Sprintf(format, args...)))
342 }
343
344 i := 0
345
346 // skipSpace consumes leading spaces, and reports whether there is more input.
347 skipSpace := func() bool {
348 for ; i < len(s); i++ {
349 b := s[i]
350 if b != ' ' && b != '\t' && b != '\n' && b != '\r' {
351 return true
352 }
353 }
354 return false
355 }
356
357 // next consumes leading spaces and returns the first non-space.
358 // It panics if at EOF.
359 next := func() byte {
360 if skipSpace() {
361 return s[i]
362 }
363 fail("unexpected end of file")
364 panic("unreachable")
365 }
366
367 // parse returns the next JSON value from the input.
368 // It consumes leading but not trailing whitespace.
369 // It panics on error.
370 var parse func() starlark.Value
371 parse = func() starlark.Value {
372 b := next()
373 switch b {
374 case '"':
375 // string
376
377 // Find end of quotation.
378 // Also, record whether trivial unquoting is safe.
379 // Non-trivial unquoting is handled by Go's encoding/json.
380 safe := true
381 closed := false
382 j := i + 1
383 for ; j < len(s); j++ {
384 b := s[j]
385 if b == '\\' {
386 safe = false
387 j++ // skip x in \x
388 } else if b == '"' {
389 closed = true
390 j++ // skip '"'
391 break
392 } else if b >= utf8.RuneSelf {
393 safe = false
394 }
395 }
396 if !closed {
397 fail("unclosed string literal")
398 }
399
400 r := s[i:j]
401 i = j
402
403 // unquote
404 if safe {
405 r = r[1 : len(r)-1]
406 } else if err := json.Unmarshal([]byte(r), &r); err != nil {
407 fail("%s", err)
408 }
409 return starlark.String(r)
410
411 case 'n':
412 if strings.HasPrefix(s[i:], "null") {
413 i += len("null")
414 return starlark.None
415 }
416
417 case 't':
418 if strings.HasPrefix(s[i:], "true") {
419 i += len("true")
420 return starlark.True
421 }
422
423 case 'f':
424 if strings.HasPrefix(s[i:], "false") {
425 i += len("false")
426 return starlark.False
427 }
428
429 case '[':
430 // array
431 var elems []starlark.Value
432
433 i++ // '['
434 b = next()
435 if b != ']' {
436 for {
437 elem := parse()
438 elems = append(elems, elem)
439 b = next()
440 if b != ',' {
441 if b != ']' {
442 fail("got %q, want ',' or ']'", b)
443 }
444 break
445 }
446 i++ // ','
447 }
448 }
449 i++ // ']'
450 return starlark.NewList(elems)
451
452 case '{':
453 // object
454 dict := new(starlark.Dict)
455
456 i++ // '{'
457 b = next()
458 if b != '}' {
459 for {
460 key := parse()
461 if _, ok := key.(starlark.String); !ok {
462 fail("got %s for object key, want string", key.Type())
463 }
464 b = next()
465 if b != ':' {
466 fail("after object key, got %q, want ':' ", b)
467 }
468 i++ // ':'
469 value := parse()
470 dict.SetKey(key, value) // can't fail
471 b = next()
472 if b != ',' {
473 if b != '}' {
474 fail("in object, got %q, want ',' or '}'", b)
475 }
476 break
477 }
478 i++ // ','
479 }
480 }
481 i++ // '}'
482 return dict
483
484 default:
485 // number?
486 if isdigit(b) || b == '-' {
487 // scan literal. Allow [0-9+-eE.] for now.
488 float := false
489 var j int
490 for j = i + 1; j < len(s); j++ {
491 b = s[j]
492 if isdigit(b) {
493 // ok
494 } else if b == '.' ||
495 b == 'e' ||
496 b == 'E' ||
497 b == '+' ||
498 b == '-' {
499 float = true
500 } else {
501 break
502 }
503 }
504 num := s[i:j]
505 i = j
506
507 // Unlike most C-like languages,
508 // JSON disallows a leading zero before a digit.
509 digits := num
510 if num[0] == '-' {
511 digits = num[1:]
512 }
513 if digits == "" || digits[0] == '0' && len(digits) > 1 && isdigit(digits[1]) {
514 fail("invalid number: %s", num)
515 }
516
517 // parse literal
518 if float {
519 x, err := strconv.ParseFloat(num, 64)
520 if err != nil {
521 fail("invalid number: %s", num)
522 }
523 return starlark.Float(x)
524 } else {
525 x, ok := new(big.Int).SetString(num, 10)
526 if !ok {
527 fail("invalid number: %s", num)
528 }
529 return starlark.MakeBigInt(x)
530 }
531 }
532 }
533 fail("unexpected character %q", b)
534 panic("unreachable")
535 }
536 defer func() {
537 x := recover()
538 switch x := x.(type) {
539 case failure:
540 if d != nil {
541 v = d
542 } else {
543 err = fmt.Errorf("json.decode: at offset %d, %s", i, x)
544 }
545 case nil:
546 // nop
547 default:
548 panic(x) // unexpected panic
549 }
550 }()
551 v = parse()
552 if skipSpace() {
553 fail("unexpected character %q after value", s[i])
554 }
555 return v, nil
556 }
557
558 func isdigit(b byte) bool {
559 return b >= '0' && b <= '9'
560 }