forked from ricardolonga/jsongo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.go
241 lines (210 loc) · 6.11 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
/*
Copyright 2020 Libu Jacob Varghese
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package jsone
import (
"log"
"strconv"
"bramp.net/antlr4/json" // The parser
"github.com/antlr/antlr4/runtime/Go/antlr" // The antlr library
)
// jsonListener is an event-driven callback for the parser.
type jsonListener struct {
*json.BaseJSONListener // https://godoc.org/bramp.net/antlr4/json#BaseJSONListener
jsonObject O
jsonArray *A
jsonEntryStack *Stack
}
func (l *jsonListener) EnterJson(ctx *json.JsonContext) {
l.jsonEntryStack = NewStack()
}
func (l *jsonListener) ExitJson(ctx *json.JsonContext) {
}
func (l *jsonListener) EnterObj(ctx *json.ObjContext) {
if l.jsonEntryStack.length == 0 {
l.jsonObject = Object()
l.jsonEntryStack.Push(l.jsonObject)
} else {
l.jsonEntryStack.Push(Object())
}
}
func (l *jsonListener) ExitObj(ctx *json.ObjContext) {
// Object can be placed in a pair or on an array itself, so here we handle
// both the cases
value := l.jsonEntryStack.Pop()
// Popping the out the key from the Stack to fill the object
key := getKeyFromStack(l)
insertIntoStackTopValue(l, key, value)
}
func (l *jsonListener) EnterPair(ctx *json.PairContext) {
key := ctx.STRING().GetText()
l.jsonEntryStack.Push(key[1 : len(key)-1])
}
func (l *jsonListener) ExitPair(ctx *json.PairContext) {
}
func (l *jsonListener) EnterArray(ctx *json.ArrayContext) {
if l.jsonEntryStack.length == 0 {
l.jsonArray = Array()
l.jsonEntryStack.Push(l.jsonArray)
} else {
l.jsonEntryStack.Push(Array())
}
}
func (l *jsonListener) ExitArray(ctx *json.ArrayContext) {
// Arrays can be in a pair on on another array itself. So here we handle
// both cases.
value := l.jsonEntryStack.Pop()
// Popping the out the key from the Stack to fill the object
key := getKeyFromStack(l)
insertIntoStackTopValue(l, key, value)
}
func (l *jsonListener) EnterValue(ctx *json.ValueContext) {
}
func (l *jsonListener) ExitValue(ctx *json.ValueContext) {
// Popping the out the key from the Stack to fill the object
key := getKeyFromStack(l)
if ctx.Array() != nil || ctx.Obj() != nil {
return
}
// Handle only terminal values here
if nil != ctx.STRING() {
value := ctx.STRING().GetText()
value = value[1 : len(value)-1]
insertIntoStackTopValue(l, key, value)
} else if nil != ctx.NUMBER() {
value := ctx.NUMBER().GetText()
if !isNumericValue(value) {
log.Panicf("Invalid numeric value [%s]!", value)
}
if isFloatValue(value) {
numValue, err := strconv.ParseFloat(value, 64)
if err != nil {
log.Panicf("Invalid numeric value [%s], parsing failed!", value)
}
insertIntoStackTopValue(l, key, numValue)
} else {
if len(value) > 1 && value[0:1] == "0" {
log.Panicf("Invalid numeric value [%s], only decimal is supported!", value)
}
numValue, err := strconv.ParseInt(value, 0, 64)
if err != nil {
log.Panicf("Invalid numeric value [%s], parsing failed!", value)
}
insertIntoStackTopValue(l, key, numValue)
}
} else {
switch ctx.GetText() {
case "true":
{
insertIntoStackTopValue(l, key, true)
break
}
case "false":
{
insertIntoStackTopValue(l, key, false)
break
}
case "null":
{
insertIntoStackTopValue(l, key, nil)
break
}
default:
log.Panic("Invalid json string!")
}
return
}
}
// Get next key from the Stack
func getKeyFromStack(l *jsonListener) string {
key := ""
// Popping the out the key from the Stack to fill the object
switch l.jsonEntryStack.Top().(type) {
case string:
last := l.jsonEntryStack.Pop()
if last == nil {
log.Panic("No data in Stack!")
}
key = last.(string)
}
return key
}
// Insert the value in to the next object into the Stack
func insertIntoStackTopValue(l *jsonListener, key string, value interface{}) {
switch l.jsonEntryStack.Top().(type) {
case O:
if key != "" {
l.jsonEntryStack.Top().(O).Put(key, value)
} else {
log.Panic("No key string in Stack to insert the array value!")
}
case *A:
l.jsonEntryStack.Top().(*A).Put(value)
default:
// log.Print("Not a proper data type expected here")
}
}
// ParseJsonObject parse the json object to generate the json map structure
func ParseJsonObject(inData []byte) O {
// Setup the input
is := antlr.NewInputStream(string(inData))
// Create the Lexer
lexer := json.NewJSONLexer(is)
stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
// Create the Parser
p := json.NewJSONParser(stream)
p.BuildParseTrees = true
p.AddErrorListener(antlr.NewDiagnosticErrorListener(true))
// Finally walk the tree
tree := p.Json()
listener := jsonListener{}
antlr.ParseTreeWalkerDefault.Walk(&listener, tree)
return listener.jsonObject
}
// ParseJsonArray parse an array to generate the json map structure
func ParseJsonArray(inData []byte) *A {
// Setup the input
is := antlr.NewInputStream(string(inData))
// Create the Lexer
lexer := json.NewJSONLexer(is)
stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
// Create the Parser
p := json.NewJSONParser(stream)
p.BuildParseTrees = true
p.AddErrorListener(antlr.NewDiagnosticErrorListener(true))
// Finally walk the tree
tree := p.Json()
listener := jsonListener{}
antlr.ParseTreeWalkerDefault.Walk(&listener, tree)
return listener.jsonArray
}
// Check the number value is correct
func isNumericValue(s string) bool {
containsDot := 0
for _, ch := range s {
if ch == '.' {
containsDot++
} else if ch < '0' || ch > '9' {
return false
}
}
return containsDot == 0 || containsDot == 1
}
// Check whether the number is float or not
func isFloatValue(s string) bool {
for _, ch := range s {
if ch == '.' {
return true
}
}
return false
}