-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
365 lines (315 loc) · 7.93 KB
/
main.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
package main
import (
"fmt"
"github.com/onflow/cadence/runtime/ast"
"github.com/onflow/cadence/runtime/parser"
"os"
"reflect"
"slices"
"sort"
"strings"
)
type QueryContext map[string]ast.Element
type ElementGroup []ElementWithContext
type ElementWithContext struct {
context QueryContext
element ast.Element
}
func (g ElementGroup) Do(f func(QueryContext)) {
for _, element := range g {
f(element.context)
}
}
func (g ElementGroup) Where(f func(QueryContext) bool) ElementGroup {
var elements ElementGroup
for _, element := range g {
if f(element.context) {
elements = append(elements, element)
}
}
return elements
}
func (g ElementGroup) Each(variable string, elementTypes []ast.ElementType) ElementGroup {
var elements ElementGroup
for _, elementWithContext := range g {
var walker func(ast.Element)
walker = func(e ast.Element) {
if slices.Contains(elementTypes, e.ElementType()) {
ec := ElementWithContext{element: e, context: QueryContext{}}
for k, v := range elementWithContext.context {
ec.context[k] = v
}
ec.context[variable] = e
elements = append(elements, ec)
}
e.Walk(walker)
}
elementWithContext.element.Walk(walker)
}
return elements
}
var elementTypes map[string][]ast.ElementType
var elementTypesHelp map[string]bool
func getElementType(t string) []ast.ElementType {
if elementTypes == nil {
elementTypes = make(map[string][]ast.ElementType)
elementTypesHelp = make(map[string]bool)
expressions := []ast.ElementType{}
statements := []ast.ElementType{}
declarations := []ast.ElementType{}
for i := 1; i < 50; i++ {
elementType := strings.Replace(ast.ElementType(i).String(), "ElementType", "", 1)
elementTypes[strings.ToLower(elementType)] = []ast.ElementType{ast.ElementType(i)}
//try short name
ty := elementType
if strings.HasSuffix(ty, "Declaration") {
declarations = append(declarations, ast.ElementType(i))
ty = strings.Replace(ty, "Declaration", "", 1)
}
if strings.HasSuffix(ty, "Expression") {
expressions = append(expressions, ast.ElementType(i))
ty = strings.Replace(ty, "Expression", "", 1)
}
if strings.HasSuffix(ty, "Statement") {
statements = append(statements, ast.ElementType(i))
ty = strings.Replace(ty, "Statement", "", 1)
}
if _, ok := elementTypes[strings.ToLower(ty)]; !ok {
elementTypes[strings.ToLower(ty)] = []ast.ElementType{ast.ElementType(i)}
//add short to help
elementTypesHelp[ty] = true
} else {
//can't add comparator, add long to help
elementTypesHelp[elementType] = true
}
}
//add groups
elementTypesHelp["Statement"] = true
elementTypes["statement"] = statements
elementTypesHelp["Declaration"] = true
elementTypes["declaration"] = declarations
elementTypesHelp["Expression"] = true
//todo: not sure about this, check
elementTypes["expression"] = append(expressions, ast.ElementTypeExpressionStatement)
}
if v, ok := elementTypes[strings.ToLower(t)]; ok {
return v
}
return nil
}
func reflectGetField(typeName string, value ast.Element, fieldName string, isOptional bool) reflect.Value {
v := reflect.Indirect(reflect.ValueOf(value))
fieldValue := v.FieldByName(fieldName)
if !fieldValue.IsValid() {
if isOptional {
return fieldValue
}
keys := make([]string, v.Type().NumField())
for i := 0; i < v.NumField(); i++ {
keys[i] = v.Type().Field(i).Name
}
sort.Strings(keys)
panic(
fmt.Sprintf("Invalid field `%s` on variable `%s`.\nAvailable fields: %s",
fieldName,
typeName,
strings.Join(keys, ", "),
),
)
}
return fieldValue
}
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
}
}()
if len(os.Args) != 3 {
panic("cdcq <cadence file> <filter>")
}
filePath := os.Args[1]
queryParts := strings.Split(os.Args[2], "|")
if len(queryParts) != 2 {
panic("Query should be in the format of: `<search> | <display>`")
}
query := queryParts[0]
if !strings.Contains(query, ".") {
panic("you need to have at least one selector. Example: .Function")
}
display := queryParts[1]
code, _ := os.ReadFile(filePath)
program, err := parser.ParseProgram(nil, code, parser.Config{})
if err != nil {
return
}
root := ElementGroup{ElementWithContext{QueryContext{}, program}}
c := 0
typeName := ""
//parse query
for c < len(query) {
var op = query[c]
switch op {
case ' ':
c = c + 1
break
case '.': //each
var t strings.Builder
c = c + 1
for {
if query[c] == '[' || query[c] == '.' || query[c] == ' ' {
break
}
t.Write([]byte{query[c]})
c = c + 1
}
typeName = t.String()
elementTypesToFilter := getElementType(typeName)
if elementTypesToFilter == nil {
keys := make([]string, len(elementTypesHelp))
i := 0
for k := range elementTypesHelp {
keys[i] = k
i = i + 1
}
sort.Strings(keys)
panic(
fmt.Sprintf("Invalid element type `%s`.\nAvailable types: %s",
typeName,
strings.Join(keys, ", "),
),
)
}
root = root.Each(typeName, elementTypesToFilter)
break
case '[': //where
var t strings.Builder
c = c + 1
for {
if query[c] == ']' || query[c] == '=' {
break
}
t.Write([]byte{query[c]})
c = c + 1
}
field := t.String()
t.Reset()
c = c + 1
for {
if query[c] == ']' {
c = c + 1
break
}
t.Write([]byte{query[c]})
c = c + 1
}
value := t.String()
root = root.Where(func(context QueryContext) bool {
isNot := false
fieldName := field
lookupValue := value
var comparator = strings.EqualFold
if strings.HasPrefix(value, "~") {
comparator = strings.Contains
lookupValue = lookupValue[1:]
}
if strings.HasPrefix(value, "'") {
lookupValue = lookupValue[1 : len(lookupValue)-1]
}
if strings.HasSuffix(field, "!") {
isNot = true
fieldName = fieldName[:len(fieldName)-1]
}
element, ok := context[typeName]
if !ok {
panic("invalid query")
}
fieldValue := reflectGetField(typeName, element, fieldName, false)
data := fmt.Sprintf("%s", fieldValue)
if fieldValue.Kind() == reflect.Slice {
data = data[1 : len(data)-1]
}
b := comparator(
strings.ToLower(data),
strings.ToLower(lookupValue),
)
if isNot {
return !b
}
return b
})
break
}
}
var variables []string
// extract variables from display
c = 0
for c < len(display) {
var op = display[c]
switch op {
case '{':
c = c + 1
variableName := ""
for {
if display[c] == '}' {
c = c + 1
break
}
variableName = fmt.Sprintf("%s%c", variableName, display[c])
c = c + 1
}
variables = append(variables, variableName)
default:
c = c + 1
break
}
}
root.Do(func(context QueryContext) {
result := display
for _, v := range variables {
parts := strings.Split(v, ".")
object := parts[0]
field := ""
if len(parts) > 1 {
field = parts[1]
}
isOptional := false
if strings.HasSuffix(object, "?") {
isOptional = true
object = object[:len(object)-1]
}
data := ""
if v == "Path" {
data = filePath
} else {
vv, ok := context[object]
if !ok {
keys := make([]string, len(context))
i := 0
for k := range context {
keys[i] = k
i++
}
sort.Strings(keys)
panic(fmt.Sprintf("invalid variable `%s`. Available variables: %s", object, strings.Join(keys, ", ")))
}
t := reflect.Indirect(reflect.ValueOf(vv).Elem())
if len(parts) == 1 {
data = fmt.Sprintf("%s", vv)
} else {
t = reflect.ValueOf(vv)
m := t.MethodByName(field)
if m.IsValid() {
data = m.Call([]reflect.Value{})[0].String()
} else {
v := reflectGetField(object, vv, field, isOptional)
data = fmt.Sprintf("%s", v)
data = strings.ReplaceAll(data, "<invalid reflect.Value>", "<invalid field>")
}
}
}
result = strings.ReplaceAll(result, fmt.Sprintf("{%s}", v), data)
}
fmt.Println(result)
})
}