-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
392 lines (333 loc) · 7.5 KB
/
parser.go
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
package main
import (
"bytes"
"fmt"
"os"
"strconv"
"strings"
)
/*
JSON structure:
root: value
value : object | array | literal
object: '{' [ property [, property]* ] '}'
array: '[' [ value [, value]* ] ']'
literal: string | number | "true" | "false" | "null"
property: literal ':' value
string: '"' [a-zA-Z0-9_] '"" // TODO: fix this expression
number: [0-9]+
*/
type State int
const (
INIT_STATE State = iota
OBJECT_START
OBJECT_OPEN
OBJECT_END
ARRAY_START
ARRAY_END
)
var states = []string{
INIT_STATE: "INIT_STATE",
OBJECT_START: "OBJECT_START",
OBJECT_OPEN: "OBJECT_OPEN",
OBJECT_END: "OBJECT_END",
ARRAY_START: "ARRAY_START",
ARRAY_END: "ARRAY_END",
}
func (s State) String() string {
return states[s]
}
type NodeType int
const (
ROOT NodeType = iota
OBJECT
ARRAY
LITERAL
PROPERTY
)
type Value interface {
GetType() NodeType
}
type Root struct {
Type NodeType
Value Value
}
func (r Root) GetType() NodeType {
return r.Type
}
func NewRoot() *Root {
return &Root{
Type: ROOT,
}
}
type Object struct {
Type NodeType
Properties []Property
}
func (o Object) GetType() NodeType {
return o.Type
}
type Array struct {
Type NodeType
Elements []Value
}
func (a Array) GetType() NodeType {
return a.Type
}
type Property struct {
Type NodeType
Key Literal
Value Value
}
func (p Property) GetType() NodeType {
return p.Type
}
type Literal struct {
Type NodeType
Value string
}
func (l Literal) GetType() NodeType {
return l.Type
}
type Parser struct {
lexer *Lexer
curToken Token
peekToken Token
root *Root
}
func NewParser(l *Lexer) *Parser {
p := &Parser{
lexer: l,
root: NewRoot(),
}
// fill curToken & peekToken
p.nextToken()
p.nextToken()
return p
}
func (p *Parser) readToken() Token {
return p.lexer.Lex()
}
func (p *Parser) nextToken() {
p.curToken = p.peekToken
p.peekToken = p.readToken()
}
func (p *Parser) parseValue() (Value, error) {
if os.Getenv("DEBUG") == "true" {
fmt.Println("parseValue")
}
var value Value
var err error
switch p.curToken.Type {
case L_BRACE:
value, err = p.parseObject()
case L_BRACKET:
value, err = p.parseArray()
case IDENT:
value, err = p.parseLiteral()
case NUMBER:
value, err = p.parseLiteral()
case BOOLEAN:
value, err = p.parseLiteral()
case NULL:
value, err = p.parseLiteral()
default:
err := fmt.Errorf("cannot parse value, got token '%s' at line %s", p.curToken.Literal, p.curToken.Pos)
return nil, err
}
return value, err
}
func (p *Parser) parseObject() (Object, error) {
if p.curToken.Type != L_BRACE {
return Object{}, fmt.Errorf("invalid start of object, expected '{' got '%s' at line %v", p.curToken.Literal, p.curToken.Pos)
}
state := OBJECT_START
object := Object{
Type: OBJECT,
Properties: make([]Property, 0),
}
for {
if p.peekToken.Type == EOF {
if state != OBJECT_OPEN {
return object, nil
}
return Object{}, fmt.Errorf("invalid object, EOF reached before '{' at line %s", p.peekToken.Pos)
}
switch state {
case OBJECT_START:
switch p.peekToken.Type {
case R_BRACE:
p.nextToken()
state = OBJECT_END
case COMMA:
p.nextToken()
p.nextToken()
state = OBJECT_OPEN
case IDENT:
p.nextToken()
state = OBJECT_OPEN
default:
return Object{}, fmt.Errorf("invalid object, invalid token '%s' of type %s at line %s", p.peekToken.Literal, p.peekToken.Type, p.peekToken.Pos)
}
case OBJECT_OPEN:
prop, err := p.parseProperty()
if err != nil {
return Object{}, err
}
object.Properties = append(object.Properties, prop)
state = OBJECT_START
case OBJECT_END:
p.nextToken()
return object, nil
default:
panic("parsing object reached unknown state")
}
}
}
func (p *Parser) parseArray() (Array, error) {
if os.Getenv("DEBUG") == "true" {
fmt.Println("parseArray")
}
if p.curToken.Type != L_BRACKET {
return Array{}, fmt.Errorf("invalid start of array, expected '[' got '%s' at line %s", p.curToken.Literal, p.curToken.Pos)
}
Arr := Array{Type: ARRAY, Elements: make([]Value, 0)}
state := ARRAY_START
for {
if p.peekToken.Type == EOF {
if state == ARRAY_END {
return Arr, nil
}
return Arr, fmt.Errorf("invalid array, EOF reached before '['")
}
switch state {
case ARRAY_START:
p.nextToken()
if p.curToken.Type == R_BRACKET {
p.nextToken()
return Arr, nil
}
v, err := p.parseValue()
handleError(err)
Arr.Elements = append(Arr.Elements, v)
if p.peekToken.Type == R_BRACKET {
p.nextToken()
return Arr, nil
}
if p.peekToken.Type == COMMA {
p.nextToken()
}
case ARRAY_END:
p.nextToken()
return Arr, nil
}
}
}
func (p *Parser) parseLiteral() (Literal, error) {
if os.Getenv("DEBUG") == "true" {
fmt.Println("parseLiteral")
}
if p.curToken.Type == IDENT || p.curToken.Type == BOOLEAN || p.curToken.Type == NULL || p.curToken.Type == NUMBER {
return Literal{Type: LITERAL, Value: p.curToken.Literal}, nil
}
return Literal{}, fmt.Errorf("cannot parse literal from token '%s' of type '%s' at line %s", p.curToken.Literal, p.curToken.Type, p.curToken.Pos)
}
func (p *Parser) parseProperty() (Property, error) {
if os.Getenv("DEBUG") == "true" {
fmt.Println("parseProperty cur:", p.curToken.Literal, " next:", p.peekToken.Literal)
}
lit, err := p.parseLiteral()
if err != nil {
return Property{}, err
}
if p.peekToken.Type != COLON {
return Property{}, fmt.Errorf("invalid property, expected ':' got '%s' at line %s", p.curToken.Literal, p.curToken.Pos)
}
p.nextToken()
p.nextToken()
value, err := p.parseValue()
if err != nil {
return Property{}, err
}
return Property{Type: PROPERTY, Key: lit, Value: value}, nil
}
func (p *Parser) Parse() error {
if os.Getenv("DEBUG") == "true" {
fmt.Println("func Parse()")
}
value, err := p.parseValue()
if err != nil {
return err
}
p.root.Value = value
return nil
}
func (p *Parser) String() string {
if p.root != nil {
return p.printValue(p.root.Value)
}
return ""
}
// Get returns a json value corresponding to the given query
// A query is a string referring to a path in the underlying JSON data
// A query starts with a . (dot) representing the root node, and followed by either attribute names
// or a [i] to access the i-th element of an array
func (p *Parser) Get(query string) (string, error) {
fields := strings.Split(query, ".")
v := p.root.Value
for _, field := range fields {
if field == "" {
continue
}
switch v.GetType() {
case OBJECT:
o := v.(Object)
for _, prop := range o.Properties {
if field == prop.Key.Value[1:len(prop.Key.Value)-1] {
v = prop.Value
}
}
case ARRAY:
a := v.(Array)
if end := strings.Index(field, "]"); end != -1 {
idx, err := strconv.Atoi(field[1:end])
if err != nil {
return "", err
}
v = a.Elements[idx]
}
default:
panic("cannot parse query: " + query)
}
}
return p.printValue(v), nil
}
func (p *Parser) printValue(v Value) string {
res := bytes.Buffer{}
switch v.GetType() {
case OBJECT:
o := v.(Object)
res.WriteString("{")
for idx, prop := range o.Properties {
res.WriteString(fmt.Sprintf("%s: %s", prop.Key.Value, p.printValue(prop.Value)))
if idx != len(o.Properties)-1 {
res.WriteString(",")
}
}
res.WriteString("}")
case LITERAL:
l := v.(Literal)
res.WriteString(l.Value)
case ARRAY:
a := v.(Array)
res.WriteString("[")
for idx, elem := range a.Elements {
res.WriteString(p.printValue(elem))
if idx != len(a.Elements)-1 {
res.WriteString(",")
}
}
res.WriteString("]")
}
return res.String()
}