-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
353 lines (315 loc) · 6.67 KB
/
node.go
File metadata and controls
353 lines (315 loc) · 6.67 KB
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
package fracturedjson
import (
"encoding/json"
"errors"
"fmt"
"io"
"strings"
)
// Kind is the kind of JSON node.
type Kind int
const (
KindNull Kind = iota
KindBool
KindNumber
KindString
KindArray
KindObject
)
// Member is one object property in input order.
type Member struct {
Name string
Value *Node
}
// Node is an ordered JSON AST used by the formatter.
type Node struct {
Kind Kind
Bool bool
Number string
String string
Array []*Node
Object []Member
Complexity int
}
type parseMeta struct {
Comments []string
LeadingBlanks int
TrailingBlanks int
}
func parseJSON(input string, opts Options) (*Node, parseMeta, error) {
clean, meta, err := preprocessJSONInput(input, opts)
if err != nil {
return nil, parseMeta{}, err
}
dec := json.NewDecoder(strings.NewReader(clean))
dec.UseNumber()
n, err := parseValue(dec)
if err != nil {
return nil, parseMeta{}, err
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
if err == nil {
return nil, parseMeta{}, fmt.Errorf("extra content after top-level JSON value")
}
return nil, parseMeta{}, err
}
computeComplexity(n)
return n, meta, nil
}
func preprocessJSONInput(input string, opts Options) (string, parseMeta, error) {
meta := parseMeta{}
meta.LeadingBlanks = countLeadingBlankLines(input)
meta.TrailingBlanks = countTrailingBlankLines(input)
var out strings.Builder
out.Grow(len(input))
inString := false
escaped := false
for i := 0; i < len(input); i++ {
ch := input[i]
if inString {
out.WriteByte(ch)
if escaped {
escaped = false
continue
}
if ch == '\\' {
escaped = true
continue
}
if ch == '"' {
inString = false
}
continue
}
if ch == '"' {
inString = true
out.WriteByte(ch)
continue
}
if ch == '/' && i+1 < len(input) {
next := input[i+1]
if next == '/' {
if opts.CommentPolicy == CommentTreatAsError {
return "", parseMeta{}, fmt.Errorf("comments are not allowed by current CommentPolicy")
}
j := i
for j < len(input) && input[j] != '\n' {
j++
}
comment := input[i:j]
if opts.CommentPolicy == CommentPreserve {
meta.Comments = append(meta.Comments, comment)
}
for k := i; k < j; k++ {
out.WriteByte(' ')
}
i = j - 1
continue
}
if next == '*' {
if opts.CommentPolicy == CommentTreatAsError {
return "", parseMeta{}, fmt.Errorf("comments are not allowed by current CommentPolicy")
}
j := i + 2
for j+1 < len(input) && !(input[j] == '*' && input[j+1] == '/') {
j++
}
if j+1 >= len(input) {
return "", parseMeta{}, fmt.Errorf("unterminated block comment")
}
j += 2
comment := input[i:j]
if opts.CommentPolicy == CommentPreserve {
meta.Comments = append(meta.Comments, comment)
}
for k := i; k < j; k++ {
if input[k] == '\n' {
out.WriteByte('\n')
} else {
out.WriteByte(' ')
}
}
i = j - 1
continue
}
}
out.WriteByte(ch)
}
clean := out.String()
var err error
clean, err = applyTrailingCommaPolicy(clean, opts.AllowTrailingCommas)
if err != nil {
return "", parseMeta{}, err
}
return clean, meta, nil
}
func applyTrailingCommaPolicy(input string, allow bool) (string, error) {
b := []byte(input)
inString := false
escaped := false
for i := 0; i < len(b); i++ {
ch := b[i]
if inString {
if escaped {
escaped = false
continue
}
if ch == '\\' {
escaped = true
continue
}
if ch == '"' {
inString = false
}
continue
}
if ch == '"' {
inString = true
continue
}
if ch != ',' {
continue
}
j := i + 1
for j < len(b) && (b[j] == ' ' || b[j] == '\t' || b[j] == '\r' || b[j] == '\n') {
j++
}
if j < len(b) && (b[j] == ']' || b[j] == '}') {
if !allow {
return "", fmt.Errorf("trailing commas are not allowed by current AllowTrailingCommas setting")
}
b[i] = ' '
}
}
return string(b), nil
}
func countLeadingBlankLines(s string) int {
lines := strings.Split(s, "\n")
count := 0
for _, line := range lines {
if strings.TrimSpace(line) == "" {
count++
continue
}
break
}
return count
}
func countTrailingBlankLines(s string) int {
lines := strings.Split(s, "\n")
count := 0
for i := len(lines) - 1; i >= 0; i-- {
if strings.TrimSpace(lines[i]) == "" {
count++
continue
}
break
}
return count
}
func parseValue(dec *json.Decoder) (*Node, error) {
tok, err := dec.Token()
if err != nil {
return nil, err
}
switch t := tok.(type) {
case nil:
return &Node{Kind: KindNull}, nil
case bool:
return &Node{Kind: KindBool, Bool: t}, nil
case string:
return &Node{Kind: KindString, String: t}, nil
case json.Number:
return &Node{Kind: KindNumber, Number: t.String()}, nil
case json.Delim:
switch t {
case '{':
return parseObject(dec)
case '[':
return parseArray(dec)
default:
return nil, fmt.Errorf("unexpected delimiter %q", t)
}
default:
return nil, fmt.Errorf("unexpected token type %T", t)
}
}
func parseObject(dec *json.Decoder) (*Node, error) {
obj := &Node{Kind: KindObject}
for dec.More() {
kTok, err := dec.Token()
if err != nil {
return nil, err
}
key, ok := kTok.(string)
if !ok {
return nil, fmt.Errorf("expected object key string, got %T", kTok)
}
value, err := parseValue(dec)
if err != nil {
return nil, err
}
obj.Object = append(obj.Object, Member{Name: key, Value: value})
}
endTok, err := dec.Token()
if err != nil {
return nil, err
}
if d, ok := endTok.(json.Delim); !ok || d != '}' {
return nil, fmt.Errorf("expected object close delimiter, got %v", endTok)
}
return obj, nil
}
func parseArray(dec *json.Decoder) (*Node, error) {
arr := &Node{Kind: KindArray}
for dec.More() {
v, err := parseValue(dec)
if err != nil {
return nil, err
}
arr.Array = append(arr.Array, v)
}
endTok, err := dec.Token()
if err != nil {
return nil, err
}
if d, ok := endTok.(json.Delim); !ok || d != ']' {
return nil, fmt.Errorf("expected array close delimiter, got %v", endTok)
}
return arr, nil
}
func computeComplexity(n *Node) int {
switch n.Kind {
case KindArray:
if len(n.Array) == 0 {
n.Complexity = 0
return 0
}
maxComplexity := 0
for _, child := range n.Array {
c := computeComplexity(child)
if c > maxComplexity {
maxComplexity = c
}
}
n.Complexity = maxComplexity + 1
return n.Complexity
case KindObject:
if len(n.Object) == 0 {
n.Complexity = 0
return 0
}
maxComplexity := 0
for _, member := range n.Object {
c := computeComplexity(member.Value)
if c > maxComplexity {
maxComplexity = c
}
}
n.Complexity = maxComplexity + 1
return n.Complexity
default:
n.Complexity = 0
return 0
}
}