summaryrefslogtreecommitdiff
path: root/parse.go
blob: 50c8ba3e0f3e60420d64891d556d11b6464b9e47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
// Copyright (C) 2022  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package lowmemjson

import (
	"errors"
	"fmt"
	"io"
	"unicode/utf8"
)

type reencodeState func(rune) error

type ReEncoder struct {
	Out io.Writer

	// Whether to minify the JSON.
	Compact bool
	// String to use to indent; ignored if Compact is true.
	Indent string
	// String to put before indents, for testing-compat with
	// encoding/json only.
	prefix string
	// Returns whether a given character in a string should be
	// "\uXXXX" escaped.  The bool argument is whether it was
	// \u-escaped in the input.  This does not affect characters
	// that must or must-not be \u-escaped to be valid JSON.
	//
	// If not set, then EscapeUnicodeDefault is used.
	UnicodeEscape func(rune, bool) bool

	bailAfterCurrent bool

	// state: .Write's utf8-decoding buffer
	buf    [utf8.UTFMax]byte
	bufLen int

	// state: .WriteRune
	err            error
	inputPos       int64
	written        int
	stack          []reencodeState
	stack0IsNumber bool
	curIndent      int

	// state: reencodeState-specific
	stateBuf []byte
}

// public API //////////////////////////////////////////////////////////////////

func (enc *ReEncoder) Write(p []byte) (int, error) {
	if len(p) == 0 {
		return 0, nil
	}
	var n int
	if enc.bufLen > 0 {
		copy(enc.buf[enc.bufLen:], p)
		c, size := utf8.DecodeRune(enc.buf[:])
		n += size - enc.bufLen
		enc.bufLen = 0
		if _, err := enc.WriteRune(c); err != nil {
			return 0, err
		}
	}
	for utf8.FullRune(p[n:]) {
		c, size := utf8.DecodeRune(p[n:])
		if _, err := enc.WriteRune(c); err != nil {
			return n, err
		}
		n += size
	}
	enc.bufLen = copy(enc.buf[:], p[n:])
	return len(p), nil
}

func (enc *ReEncoder) Flush() error {
	if enc.bufLen > 0 {
		return &SyntaxError{fmt.Sprintf("EOF: unflushed unicode garbage: %q", enc.buf[:enc.bufLen]), enc.inputPos}
	}
	switch len(enc.stack) {
	case 0:
		return nil
	case 1:
		if enc.stack0IsNumber {
			enc.Compact = true
			return enc.state('\n')
		}
		fallthrough
	default:
		return &SyntaxError{fmt.Sprintf("EOF: in the middle of a value"), enc.inputPos}
	}
}

func (enc *ReEncoder) WriteRune(c rune) (n int, err error) {
	if enc.err != nil {
		return 0, enc.err
	}
	if enc.bufLen != 0 {
		enc.err = errors.New("lowmemjson.ReEncoder: cannot .WriteRune() when there is a partial rune that has been .Write()n")
		return 0, enc.err
	}
	enc.written = 0
	enc.err = enc.state(c)
	enc.inputPos += int64(utf8.RuneLen(c))
	return enc.written, enc.err
}

// io helpers //////////////////////////////////////////////////////////////////

func (enc *ReEncoder) emitByte(c byte) error {
	err := writeByte(enc.Out, c)
	if err == nil {
		enc.written++
	}
	return err
}

func (enc *ReEncoder) emit(n int, err error) error {
	enc.written += n
	return err
}

func (enc *ReEncoder) nlIndent() error {
	if enc.Compact || enc.Indent == "" {
		return nil
	}
	if err := enc.emitByte('\n'); err != nil {
		return err
	}
	if enc.prefix != "" {
		if err := enc.emit(io.WriteString(enc.Out, enc.prefix)); err != nil {
			return err
		}
	}
	for i := 0; i < enc.curIndent; i++ {
		if err := enc.emit(io.WriteString(enc.Out, enc.Indent)); err != nil {
			return err
		}
	}
	return nil
}

// state helpers ///////////////////////////////////////////////////////////////

func (enc *ReEncoder) pushState(state reencodeState, isNumber bool) {
	if len(enc.stack) == 0 {
		enc.stack0IsNumber = isNumber
	}
	enc.stack = append(enc.stack, state)
}
func (enc *ReEncoder) replaceState(state reencodeState, isNumber bool) {
	if len(enc.stack) == 1 {
		enc.stack0IsNumber = isNumber
	}
	enc.stack[len(enc.stack)-1] = state
}
func (enc *ReEncoder) popState() {
	if len(enc.stack) == 1 {
		enc.stack0IsNumber = false
	}
	enc.stack = enc.stack[:len(enc.stack)-1]
}

var errBailedAfterCurrent = errors.New("bailed after current")

func (enc *ReEncoder) state(c rune) error {
	if len(enc.stack) == 0 {
		if enc.bailAfterCurrent {
			return errBailedAfterCurrent
		}
		enc.pushState(enc.stateAny, false)
	}
	return enc.stack[len(enc.stack)-1](c)
}

// any /////////////////////////////////////////////////////////////////////////////////////////////

func (enc *ReEncoder) stateAny(c rune) error {
	switch c {
	case 0x0020, 0x000A, 0x000D, 0x0009:
		if enc.Compact || enc.Indent != "" {
			return nil
		}
	case '{':
		enc.replaceState(enc.stateInEmptyObject, false)
		enc.curIndent++
	case '[':
		enc.replaceState(enc.stateInEmptyArray, false)
		enc.curIndent++
	case '"':
		enc.replaceState(enc.stateInString, false)
	case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		enc.replaceState(enc.stateNumberA, true)
		return enc.state(c)
	case 't':
		enc.replaceState(enc.stateInTrue, false)
		enc.stateBuf = append(enc.stateBuf[:0], 't')
	case 'f':
		enc.replaceState(enc.stateInFalse, false)
		enc.stateBuf = append(enc.stateBuf[:0], 'f')
	case 'n':
		enc.replaceState(enc.stateInNull, false)
		enc.stateBuf = append(enc.stateBuf[:0], 'n')
	default:
		return &SyntaxError{fmt.Sprintf("any: unexpected character: %c", c), enc.inputPos}
	}
	return enc.emitByte(byte(c))
}

// object //////////////////////////////////////////////////////////////////////////////////////////

func (enc *ReEncoder) stateInEmptyObject(c rune) error    { return enc._stateInObject(c, false) }
func (enc *ReEncoder) stateInNonEmptyObject(c rune) error { return enc._stateInObject(c, true) }
func (enc *ReEncoder) _stateInObject(c rune, nonempty bool) error {
	switch c {
	case 0x0020, 0x000A, 0x000D, 0x0009:
		if enc.Compact || enc.Indent != "" {
			return nil
		}
	case '"':
		if err := enc.nlIndent(); err != nil {
			return err
		}
		enc.replaceState(enc.stateInKV, false)
		enc.pushState(enc.stateInString, false)
	case '}':
		enc.popState()
		enc.curIndent--
		if nonempty {
			if err := enc.nlIndent(); err != nil {
				return err
			}
		}
	default:
		return &SyntaxError{fmt.Sprintf("object: unexpected character: %c", c), enc.inputPos}
	}
	return enc.emitByte(byte(c))
}
func (enc *ReEncoder) stateInKV(c rune) error {
	switch c {
	case 0x0020, 0x000A, 0x000D, 0x0009:
		if enc.Compact || enc.Indent != "" {
			return nil
		}
		return enc.emitByte(byte(c))
	case ':':
		enc.replaceState(enc.stateAfterV, false)
		enc.pushState(enc.stateAny, false)
		if err := enc.emitByte(byte(c)); err != nil {
			return err
		}
		if !enc.Compact && enc.Indent != "" {
			return enc.emitByte(' ')
		}
		return nil
	default:
		return &SyntaxError{fmt.Sprintf("object member: unexpected character: %c", c), enc.inputPos}
	}
}
func (enc *ReEncoder) stateAfterV(c rune) error {
	switch c {
	case 0x0020, 0x000A, 0x000D, 0x0009:
		if enc.Compact || enc.Indent != "" {
			return nil
		}
	case ',':
		enc.replaceState(enc.stateInNonEmptyObject, false)
	case '}':
		enc.popState()
		enc.curIndent--
		if err := enc.nlIndent(); err != nil {
			return err
		}
	default:
		return &SyntaxError{fmt.Sprintf("object member: unexpected character: %c", c), enc.inputPos}
	}
	return enc.emitByte(byte(c))
}

// array ///////////////////////////////////////////////////////////////////////////////////////////

func (enc *ReEncoder) stateInEmptyArray(c rune) error    { return enc._stateInArray(c, false) }
func (enc *ReEncoder) stateInNonEmptyArray(c rune) error { return enc._stateInArray(c, true) }
func (enc *ReEncoder) _stateInArray(c rune, nonempty bool) error {
	switch c {
	case 0x0020, 0x000A, 0x000D, 0x0009:
		if enc.Compact || enc.Indent != "" {
			return nil
		}
	case ']':
		enc.popState()
		enc.curIndent--
		if nonempty {
			if err := enc.nlIndent(); err != nil {
				return err
			}
		}
	default:
		if err := enc.nlIndent(); err != nil {
			return err
		}
		enc.replaceState(enc.stateAfterItem, false)
		enc.pushState(enc.stateAny, false)
		return enc.state(c)
	}
	return enc.emitByte(byte(c))
}
func (enc *ReEncoder) stateAfterItem(c rune) error {
	switch c {
	case 0x0020, 0x000A, 0x000D, 0x0009:
		if enc.Compact || enc.Indent != "" {
			return nil
		}
	case ',':
		enc.replaceState(enc.stateInNonEmptyArray, false)
	case ']':
		enc.popState()
		enc.curIndent--
		if err := enc.nlIndent(); err != nil {
			return err
		}
	default:
		return &SyntaxError{fmt.Sprintf("array: unexpected character: %c", c), enc.inputPos}
	}
	return enc.emitByte(byte(c))
}

// string //////////////////////////////////////////////////////////////////////////////////////////

func (enc *ReEncoder) stateInString(c rune) error {
	switch {
	case c == '\\':
		enc.replaceState(enc.stateInBackslash, false)
		return nil
	case c == '"':
		enc.popState()
		return enc.emitByte(byte(c))
	case 0x0020 <= c && c <= 0x10FFFF:
		return enc.emit(writeStringChar(enc.Out, c, false, enc.UnicodeEscape))
	default:
		return &SyntaxError{fmt.Sprintf("string: unexpected character: %c", c), enc.inputPos}
	}
}
func (enc *ReEncoder) stateInBackslash(c rune) error {
	switch c {
	case '"':
		enc.replaceState(enc.stateInString, false)
		return enc.emit(writeStringChar(enc.Out, '"', false, enc.UnicodeEscape))
	case '\\':
		enc.replaceState(enc.stateInString, false)
		return enc.emit(writeStringChar(enc.Out, '\\', false, enc.UnicodeEscape))
	case '/':
		enc.replaceState(enc.stateInString, false)
		return enc.emit(writeStringChar(enc.Out, '/', false, enc.UnicodeEscape))
	case 'b':
		enc.replaceState(enc.stateInString, false)
		return enc.emit(writeStringChar(enc.Out, '\b', false, enc.UnicodeEscape))
	case 'f':
		enc.replaceState(enc.stateInString, false)
		return enc.emit(writeStringChar(enc.Out, '\f', false, enc.UnicodeEscape))
	case 'n':
		enc.replaceState(enc.stateInString, false)
		return enc.emit(writeStringChar(enc.Out, '\n', false, enc.UnicodeEscape))
	case 'r':
		enc.replaceState(enc.stateInString, false)
		return enc.emit(writeStringChar(enc.Out, '\r', false, enc.UnicodeEscape))
	case 't':
		enc.replaceState(enc.stateInString, false)
		return enc.emit(writeStringChar(enc.Out, '\t', false, enc.UnicodeEscape))
	case 'u':
		enc.replaceState(enc.stateInUnicode, false)
		return nil
	default:
		return &SyntaxError{fmt.Sprintf("string backslash sequence: unexpected character: %c", c), enc.inputPos}
	}
}
func (enc *ReEncoder) stateInUnicode(c rune) error {
	switch {
	case '0' <= c && c <= '9':
		enc.stateBuf = append(enc.stateBuf, byte(c)-'0')
	case 'a' <= c && c <= 'f':
		enc.stateBuf = append(enc.stateBuf, byte(c)-'a'+10)
	case 'A' <= c && c <= 'F':
		enc.stateBuf = append(enc.stateBuf, byte(c)-'A'+10)
	default:
		return &SyntaxError{fmt.Sprintf("string unicode sequence: unexpected character: %c", c), enc.inputPos}
	}
	if len(enc.stateBuf) == 4 {
		enc.replaceState(enc.stateInString, false)
		c := 0 |
			rune(enc.stateBuf[0])<<12 |
			rune(enc.stateBuf[1])<<8 |
			rune(enc.stateBuf[2])<<4 |
			rune(enc.stateBuf[3])<<0
		enc.stateBuf = enc.stateBuf[:0]
		return enc.emit(writeStringChar(enc.Out, c, true, enc.UnicodeEscape))
	}
	return nil
}

// number //////////////////////////////////////////////////////////////////////////////////////////

// Here's a flattened drawing of the syntax diagram from www.json.org :
//
//      [------------ integer ----------][-- fraction ---][-------- exponent -------]
//     >─╮─────╭─╮─"0"───────╭─────────╭──╮─────────────╭──╮───────────────────────╭─>
//       │     │ │           │         │  │             │  │                       │
//       ╰─"-"─╯ ╰─digit 1-9─╯─╭digit╮─╯  ╰─"."─╭digit╮─╯  ╰─"e"─╭─╮─────╭─╭digit╮─╯
//                             ╰──<──╯          ╰──<──╯    │     │ │     │ ╰──<──╯
//                                                         ╰─"E"─╯ ╰─"-"─╯
//                                                                 │     │
//                                                                 ╰─"+"─╯
//
// Now here it is slightly redrawn, and with each distinct state our
// decoder can be in marked with a single-capital-letter:
//
//        [-------------- integer ------------][--------- fraction --------][--------- exponent ---------]
//     >─A─╮───────╭──╮─"0"─────────C─╭─────────╮──────────────────╭─────────╮──────────────────────────╭─>
//         │       │  │               │         │                  │         │                          │
//         ╰─"-"─B─╯  ╰─digit 1-9─╭─D─╯─digit╮  ╰─"."─E─digit──╭─F─╯─digit╮  ╰─"e"─╭─G─╮─────╭─╭digit─H─╯
//                                ╰────<─────╯                 ╰────<─────╯  │     │   │     │ ╰────<───╯
//                                                                           ╰─"E"─╯   ╰─"-"─╯
//                                                                                     │     │
//                                                                                     ╰─"+"─╯
//
// Which state we're at is the 'X' in 'stateNumberX'.
//
// Besides just traversing that, there are a few compressions we want to make:
//
//  - trim trailing 0s from fraction the (but don't remove the
//    fraction if it's all 0s); do this by making the F state a little
//    special.  This requires a little more state, because when we
//    encounter the 0 we don't yet know if it's trailing.  So, store
//    the number of maybe-trailing zeros in enc.stateBuf[0]; if that
//    reaches 255, then bleed over to enc.stateBuf[1] and so on.
//
//  - trim leading 0s from the exponent (but don't remove the exponent
//    if it's all 0s); do this by making the H state a little special.
//    Record whether we've seen a non-zero digit in enc.stateBuf[0]
//    (0=false, 1=true).

// integer-part ////////////////////////////////////////////////////////////////
func (enc *ReEncoder) stateNumberA(c rune) error { // start
	switch c {
	case '-':
		enc.replaceState(enc.stateNumberB, true)
	case '0':
		enc.replaceState(enc.stateNumberC, true)
	case '1', '2', '3', '4', '5', '6', '7', '8', '9':
		enc.replaceState(enc.stateNumberD, true)
	default:
		return &SyntaxError{fmt.Sprintf("number: unexpected character: %c", c), enc.inputPos}
	}
	return enc.emitByte(byte(c))
}
func (enc *ReEncoder) stateNumberB(c rune) error { // got a leading "-"
	switch c {
	case '0':
		enc.replaceState(enc.stateNumberC, true)
	case '1', '2', '3', '4', '5', '6', '7', '8', '9':
		enc.replaceState(enc.stateNumberD, true)
	default:
		return &SyntaxError{fmt.Sprintf("number: unexpected character: %c", c), enc.inputPos}
	}
	return enc.emitByte(byte(c))
}
func (enc *ReEncoder) stateNumberC(c rune) error { // ready for the fraction or exponent part to start
	switch c {
	case '.':
		enc.replaceState(enc.stateNumberE, true)
		return enc.emitByte('.')
	case 'e', 'E':
		enc.replaceState(enc.stateNumberG, true)
		enc.stateBuf = append(enc.stateBuf[:0], 0)
		return enc.emitByte('e')
	default:
		enc.popState()
		return enc.state(c)
	}
}
func (enc *ReEncoder) stateNumberD(c rune) error { // in the integer part
	switch c {
	case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		return enc.emitByte(byte(c))
	case '.':
		enc.replaceState(enc.stateNumberE, true)
		return enc.emitByte('.')
	case 'e', 'E':
		enc.replaceState(enc.stateNumberG, true)
		enc.stateBuf = append(enc.stateBuf[:0], 0)
		return enc.emitByte('e')
	default:
		enc.popState()
		return enc.state(c)
	}
}

// fraction-part ///////////////////////////////////////////////////////////////
func (enc *ReEncoder) stateNumberE(c rune) error { // got a ".", ready to read a number for the fraction part
	switch c {
	case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		enc.replaceState(enc.stateNumberF, true)
		return enc.emitByte(byte(c))
	default:
		return &SyntaxError{fmt.Sprintf("number: unexpected character: %c", c), enc.inputPos}
	}
}
func (enc *ReEncoder) stateNumberF(c rune) error { // in the fraction part
	switch c {
	case '0':
		if len(enc.stateBuf) > 0 && enc.stateBuf[len(enc.stateBuf)-1] < 255 {
			enc.stateBuf[len(enc.stateBuf)-1]++
		} else {
			enc.stateBuf = append(enc.stateBuf, 1)
		}
		return nil
	case '1', '2', '3', '4', '5', '6', '7', '8', '9':
		for len(enc.stateBuf) > 0 {
			if err := enc.emitByte('0'); err != nil {
				return err
			}
			if enc.stateBuf[len(enc.stateBuf)-1] == 1 {
				enc.stateBuf = enc.stateBuf[:len(enc.stateBuf)-1]
			} else {
				enc.stateBuf[len(enc.stateBuf)-1]--
			}
		}
		return enc.emitByte(byte(c))
	case 'e', 'E':
		enc.replaceState(enc.stateNumberG, true)
		enc.stateBuf = append(enc.stateBuf[:0], 0)
		return enc.emitByte('e')
	default:
		enc.stateBuf = enc.stateBuf[:0]
		enc.popState()
		return enc.state(c)
	}
}

// exponent-part ///////////////////////////////////////////////////////////////
func (enc *ReEncoder) stateNumberG(c rune) error { // got a leading "e"
	switch c {
	case '-', '+':
		enc.replaceState(enc.stateNumberH, true)
		return enc.emitByte(byte(c))
	case '0':
		enc.replaceState(enc.stateNumberH, true)
		return nil
	case '1', '2', '3', '4', '5', '6', '7', '8', '9':
		enc.replaceState(enc.stateNumberH, true)
		enc.stateBuf[0] = 1
		return enc.emitByte(byte(c))
	default:
		enc.stateBuf = enc.stateBuf[:0]
		return &SyntaxError{fmt.Sprintf("number: unexpected character: %c", c), enc.inputPos}
	}
}
func (enc *ReEncoder) stateNumberH(c rune) error { // in the exponent's number part
	switch c {
	case '0':
		if enc.stateBuf[0] == 0 {
			return nil
		}
		return enc.emitByte('0')
	case '1', '2', '3', '4', '5', '6', '7', '8', '9':
		enc.stateBuf[0] = 1
		return enc.emitByte(byte(c))
	default:
		if enc.stateBuf[0] == 0 {
			if err := enc.emitByte('0'); err != nil {
				return err
			}
		}
		enc.stateBuf = enc.stateBuf[:0]
		enc.popState()
		return enc.state(c)
	}
}

// literals ////////////////////////////////////////////////////////////////////////////////////////

func (enc *ReEncoder) stateInTrue(c rune) error  { return enc._stateInLiteral(c, "true") }
func (enc *ReEncoder) stateInFalse(c rune) error { return enc._stateInLiteral(c, "false") }
func (enc *ReEncoder) stateInNull(c rune) error  { return enc._stateInLiteral(c, "null") }
func (enc *ReEncoder) _stateInLiteral(c rune, full string) error {
	if c != rune(full[len(enc.stateBuf)]) {
		return &SyntaxError{fmt.Sprintf("%s: unexpected character: %c", full, c), enc.inputPos}
	}
	enc.stateBuf = append(enc.stateBuf, byte(c))
	if len(enc.stateBuf) == len(full) {
		enc.stateBuf = enc.stateBuf[:0]
		enc.popState()
	}
	return enc.emitByte(byte(c))
}