~mna/zerojson

ref: 780b8ea647d6b91e344b6dd20401a7f05b7f6317 zerojson/zerojson.go -rw-r--r-- 6.4 KiB View raw
780b8ea6Martin Angers scan strings, start escapes 1 year, 2 months ago
                                                                                
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
package zerojson

import (
	"io"
)

// errorString allows a string constant to be an error.
type errorString string

func (e errorString) Error() string {
	return string(e)
}

const (
	// ErrIncompleteToken is the error representing an incomplete true, false or
	// null token.
	ErrIncompleteToken errorString = "incomplete token"

	// ErrUnclosedString is the error representing an unclosed string value, i.e.
	// when the opening quote was encountered, but EOF was reached before the closing
	// quote, or an unescaped code point that must be escaped is found.
	ErrUnclosedString errorString = "unclosed string"

	// ErrInvalidCodePoint is the error representing an invalid code point. This is
	// any code point disallowed in the JSON grammar (e.g. "!" outside a string value),
	// as well as an unescaped code point that is only allowed in escaped form within
	// a string (quotation mark U+0022, reverse solidus U+005C, and the control characters
	// U+0000 to U+001F).
	ErrInvalidCodePoint errorString = "invalid code point"
)

// JSON supports 7 different values:
//
// - Object, starting with '{'
// - Array, starting with '['
// - String, starting with '"'
// - Number, starting with '-' or [0-9]
// - True, starting with 't'
// - False, starting with 'f'
// - Null, starting with 'n'
//
// Of those, Object and Array can nest and as such require a stack.
// However, since String and Number can be arbitrarily long, when tokenizing
// with a limited buffer, those values may be broken down in multiple chunks
// too.
//
// Also, when processing an Object, the parser must keep track of whether
// it is processing a key or a value (both may be strings).

const (
	staticStackSize = 4

	trueTrail  = "rue"
	falseTrail = "alse"
	nullTrail  = "ull"
)

type stack struct {
	depth int
	cur   byte

	// each uint64 can store 64 levels deep (1 bit is sufficient per level)
	static [staticStackSize]uint64
	// for very deeply-nested JSON, resort to allocation
	dynamic []uint64
}

// It is expected that v is either '{' or '['. Behaviour is undefined
// if a different value is provided.
func (s *stack) push(v byte) {
	// depth 0 means nothing pushed on the stack, so to find the bit
	// index we need to get depth *before* incrementing it, and then
	// module 64 as each uint64 has 64 bits.
	wordIndex := s.depth / 64
	bitIndex := s.depth % 64
	s.depth++
	s.cur = v

	// set bit to 1 for Object, 0 for Array, by dividing the byte
	// by '{'. That is:
	// '{' / '{' == 1 ==> Object
	// '[' / '{' == 0 ==> Array
	bit := uint64(v / '{')

	if wordIndex < staticStackSize {
		s.static[wordIndex] |= bit << uint(bitIndex)
		return
	}

	wordIndex -= staticStackSize
	if wordIndex >= len(s.dynamic) {
		s.dynamic = append(s.dynamic, 0)
	}
	s.dynamic[wordIndex] |= bit << uint(bitIndex)
}

func (s *stack) peek() byte {
	if s.cur > 0 || s.depth == 0 {
		return s.cur
	}

	ix := s.depth - 1
	wordIndex := ix / 64
	bitIndex := ix % 64

	var word uint64
	if wordIndex < staticStackSize {
		word = s.static[wordIndex]
	} else {
		wordIndex -= staticStackSize
		word = s.dynamic[wordIndex]
	}
	if word&(1<<uint(bitIndex)) == 0 {
		s.cur = '['
	} else {
		s.cur = '{'
	}
	return s.cur
}

func (s *stack) pop() byte {
	b := s.peek()
	s.depth--
	s.cur = 0 // unset, will need to be read on peek
	return b
}

type parser struct {
	// immutable fields
	// input is the data to parse
	input []byte
	// emit is called for each parsed tokens with the type of token, the
	// value and an error if the token is an invalid token. If the function returns
	// an error, the parsing stops, otherwise it continues with the next
	// token.
	//
	// The type may be:
	// '{' : start of an object (v is '{')
	// '[' : start of an array (v is '[')
	// '"' : a string (v is the full string, with quotes)
	// '1' : a number (v is the full number)
	// 't' : true (v is the full literal)
	// 'f' : false (v is the full literal)
	// 'n' : null (v is the full literal)
	// other : unknown or eof, only provided with a non-nil err
	//
	// The value v is a slice into the original input, it should not be
	// modified. If err is not nil, typ represents the type that it should
	// have been had it been valid.
	emit func(offset int, typ byte, v []byte, err error) error

	// parser state
	cur   byte
	pos   int
	stack stack
}

func (p *parser) parse() error {
	// bootstrap execution
	p.pos = -1
	p.advance()

loop:
	for {
		p.skipWhitespace()

		var (
			typ byte
			err error
		)

		start := p.pos
		typ = p.cur
		p.advance()

		switch typ {
		case '{':
			p.stack.push(typ)
		case '[':
			p.stack.push(typ)
		case '"':
			err = p.scanString()
		case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
			//first := typ
			typ = '1'
			//err = p.scanNumber(first)
		case 't':
			err = p.scanToken(trueTrail)
		case 'f':
			err = p.scanToken(falseTrail)
		case 'n':
			err = p.scanToken(nullTrail)

		default:
			if p.eof() {
				// TODO: if a token was required, error
				break loop
			}
			err = ErrInvalidCodePoint
		}

		if e := p.emit(start, typ, p.input[start:p.pos], err); e != nil {
			return e
		}
	}
	return p.emit(p.pos, p.cur, nil, io.EOF)
}

func (p *parser) scanString() error {
	for p.cur != '"' {
		switch cur := p.cur; {
		case cur == '\\':
			// TODO: parse escape
			p.advance()
			if err := p.scanEscape(); err != nil {
				return err
			}
		case p.eof():
			return ErrUnclosedString
		case cur <= 0x1F:
			// do not advance, the control character will be considered outside
			// the string and will generate a distinct ErrInvalidCodePoint.
			return ErrUnclosedString
		}
		p.advance()
	}
	return nil
}

func (p *parser) scanEscape() error {
	switch p.cur {
	case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
		p.advance()
		return nil
	case 'u', 'U':
		// TODO: scan 4 hex digits
		return nil
	default:
		// invalid escape, move back to previous byte and report unclosed
		// string, then treat the single backslash as an invalid code point.
		p.back()
		return ErrUnclosedString
	}
}

func (p *parser) scanToken(trail string) error {
	for _, b := range []byte(trail) {
		if p.cur != b {
			return ErrIncompleteToken
		}
		p.advance()
	}
	return nil
}

func (p *parser) eof() bool {
	return p.cur == 0 && p.pos >= len(p.input)
}

func (p *parser) advance() {
	if p.pos >= len(p.input)-1 {
		p.pos++
		p.cur = 0
		return
	}
	p.pos++
	p.cur = p.input[p.pos]
}

func (p *parser) back() {
	p.pos--
	p.cur = p.input[p.pos]
}

func (p *parser) skipWhitespace() {
	for p.cur == '\t' || p.cur == '\r' || p.cur == '\n' || p.cur == ' ' {
		p.advance()
	}
}