forked from tomnomnom/gron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statements.go
268 lines (227 loc) · 6.2 KB
/
statements.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
package main
import (
"encoding/json"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"github.com/pkg/errors"
)
// A statement is a slice of tokens representing an assignment statement.
// An assignment statement is something like:
//
// json.city = "Leeds";
//
// Where 'json', '.', 'city', '=', '"Leeds"' and ';' are discrete tokens.
// Statements are stored as tokens to make sorting more efficient, and so
// that the same type can easily be used when gronning and ungronning.
type statement []token
// String returns the string form of a statement rather than the
// underlying slice of tokens
func (s statement) String() string {
out := make([]string, 0, len(s)+2)
for _, t := range s {
out = append(out, t.format())
}
return strings.Join(out, "")
}
// colorString returns the string form of a statement with ASCII color codes
func (s statement) colorString() string {
out := make([]string, 0, len(s)+2)
for _, t := range s {
out = append(out, t.formatColor())
}
return strings.Join(out, "")
}
// withBare returns a copy of a statement with a new bare
// word token appended to it
func (s statement) withBare(k string) statement {
new := make(statement, len(s), len(s)+2)
copy(new, s)
return append(
new,
token{".", typDot},
token{k, typBare},
)
}
// withQuotedKey returns a copy of a statement with a new
// quoted key token appended to it
func (s statement) withQuotedKey(k string) statement {
new := make(statement, len(s), len(s)+3)
copy(new, s)
return append(
new,
token{"[", typLBrace},
token{quoteString(k), typQuotedKey},
token{"]", typRBrace},
)
}
// withNumericKey returns a copy of a statement with a new
// numeric key token appended to it
func (s statement) withNumericKey(k int) statement {
new := make(statement, len(s), len(s)+3)
copy(new, s)
return append(
new,
token{"[", typLBrace},
token{strconv.Itoa(k), typNumericKey},
token{"]", typRBrace},
)
}
// statements is a list of assignment statements.
// E.g statement: json.foo = "bar";
type statements []statement
// addWithValue takes a statement representing a path, copies it,
// adds a value token to the end of the statement and appends
// the new statement to the list of statements
func (ss *statements) addWithValue(path statement, value token) {
s := make(statement, len(path), len(path)+3)
copy(s, path)
s = append(s, token{"=", typEquals}, value, token{";", typSemi})
*ss = append(*ss, s)
}
// add appends a new complete statement to list of statements
func (ss *statements) add(s statement) {
*ss = append(*ss, s)
}
// Len returns the number of statements for sort.Sort
func (ss statements) Len() int {
return len(ss)
}
// Swap swaps two statements for sort.Sort
func (ss statements) Swap(i, j int) {
ss[i], ss[j] = ss[j], ss[i]
}
// statementFromString takes statement string, lexes it and returns
// the corresponding statement
func statementFromString(str string) statement {
l := newLexer(str)
s := l.lex()
return s
}
// ungron turns statements into a proper datastructure
func (ss statements) toInterface() (interface{}, error) {
// Get all the individually parsed statements
var parsed []interface{}
for _, s := range ss {
u, err := ungronTokens(s)
switch err.(type) {
case nil:
// no problem :)
case errRecoverable:
continue
default:
return nil, errors.Wrapf(err, "ungron failed for `%s`", s)
}
parsed = append(parsed, u)
}
if len(parsed) == 0 {
return nil, fmt.Errorf("no statements were parsed")
}
merged := parsed[0]
for _, p := range parsed[1:] {
m, err := recursiveMerge(merged, p)
if err != nil {
return nil, errors.Wrap(err, "failed to merge statements")
}
merged = m
}
return merged, nil
}
// Less compares two statements for sort.Sort
// Implements a natural sort to keep array indexes in order
func (ss statements) Less(a, b int) bool {
diffStart := -1
for i := range ss[a] {
if len(ss[b]) < i+1 {
// b must be shorter than a, so it
// should come first
return false
}
// The tokens match, so just carry on
if ss[a][i] == ss[b][i] {
continue
}
// We've found a difference
diffStart = i
break
}
// If diffStart is still -1 then the only difference must be
// that string B is longer than A, so A should come first
if diffStart == -1 {
return true
}
// Get the tokens that differ
ta := ss[a][diffStart]
tb := ss[b][diffStart]
// An equals always comes first
if ta.typ == typEquals {
return true
}
if tb.typ == typEquals {
return false
}
// If both tokens are numeric keys do an integer comparison
if ta.typ == typNumericKey && tb.typ == typNumericKey {
ia, _ := strconv.Atoi(ta.text)
ib, _ := strconv.Atoi(tb.text)
return ia < ib
}
// If neither token is a number, just do a string comparison
if ta.typ != typNumber || tb.typ != typNumber {
return ta.text < tb.text
}
// We have two numbers to compare so turn them into json.Number
// for comparison
na, _ := json.Number(ta.text).Float64()
nb, _ := json.Number(tb.text).Float64()
return na < nb
}
// Contains searches the statements for a given statement
// Mostly to make testing things easier
func (ss statements) Contains(search statement) bool {
for _, i := range ss {
if reflect.DeepEqual(i, search) {
return true
}
}
return false
}
// statementsFromJSON takes an io.Reader containing JSON
// and returns statements or an error on failure
func statementsFromJSON(r io.Reader, prefix statement) (statements, error) {
var top interface{}
d := json.NewDecoder(r)
d.UseNumber()
err := d.Decode(&top)
if err != nil {
return nil, err
}
ss := make(statements, 0, 32)
ss.fill(prefix, top)
return ss, nil
}
// fill takes a prefix statement and some value and recursively fills
// the statement list using that value
func (ss *statements) fill(prefix statement, v interface{}) {
// Add a statement for the current prefix and value
ss.addWithValue(prefix, valueTokenFromInterface(v))
// Recurse into objects and arrays
switch vv := v.(type) {
case map[string]interface{}:
// It's an object
for k, sub := range vv {
if validIdentifier(k) {
ss.fill(prefix.withBare(k), sub)
} else {
ss.fill(prefix.withQuotedKey(k), sub)
}
}
case []interface{}:
// It's an array
for k, sub := range vv {
ss.fill(prefix.withNumericKey(k), sub)
}
}
}