This repository has been archived by the owner on Apr 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnode.go
509 lines (445 loc) · 13.1 KB
/
node.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
package el
import (
"fmt"
"reflect"
"strconv"
"strings"
)
const (
varTypeInt = iota
varTypeIdent
)
type IEvaluator interface {
GetPositionToken() *Token
Evaluate(target interface{}) (*Value, *Error)
}
type intResolver struct {
locationToken *Token
val int
}
func (i *intResolver) Evaluate(target interface{}) (*Value, *Error) {
return AsValue(i.val), nil
}
func (i *intResolver) GetPositionToken() *Token {
return i.locationToken
}
type stringResolver struct {
locationToken *Token
val string
}
func (s *stringResolver) Evaluate(target interface{}) (*Value, *Error) {
return AsValue(s.val), nil
}
func (s *stringResolver) GetPositionToken() *Token {
return s.locationToken
}
type boolResolver struct {
locationToken *Token
val bool
}
func (b *boolResolver) Evaluate(target interface{}) (*Value, *Error) {
return AsValue(b.val), nil
}
func (b *boolResolver) GetPositionToken() *Token {
return b.locationToken
}
type variableResolver struct {
locationToken *Token
parts []*variablePart
}
type functionCallArgument interface {
Evaluate(target interface{}) (*Value, *Error)
}
func (vr *variableResolver) Evaluate(target interface{}) (*Value, *Error) {
value, err := vr.resolve(target)
if err != nil {
return AsValue(nil), NewError(err.Error(), vr.locationToken)
}
return value, nil
}
func (vr *variableResolver) String() string {
parts := make([]string, 0, len(vr.parts))
for _, p := range vr.parts {
switch p.typ {
case varTypeInt:
parts = append(parts, strconv.Itoa(p.i))
case varTypeIdent:
parts = append(parts, p.s)
default:
panic("unimplemented")
}
}
return strings.Join(parts, ".")
}
func (vr *variableResolver) resolve(target interface{}) (*Value, error) {
var keySetter *KeySetter
current := reflect.ValueOf(target)
for _, part := range vr.parts {
// Before resolving the pointer, let's see if we have a method to call
// Problem with resolving the pointer is we're changing the receiver
isFunc := false
keySetter = nil
if part.typ == varTypeIdent {
funcValue := current.MethodByName(part.s)
if funcValue.IsValid() {
current = funcValue
isFunc = true
}
}
if !isFunc {
// If current a pointer, resolve it
if current.Kind() == reflect.Ptr {
current = current.Elem()
if !current.IsValid() {
// Value is not valid (anymore)
return AsValue(nil), nil
}
}
// Look up which part must be called now
switch part.typ {
case varTypeInt:
// Calling an index is only possible for:
// * slices/arrays/strings
switch current.Kind() {
case reflect.String, reflect.Array, reflect.Slice:
if current.Len() > part.i {
current = current.Index(part.i)
} else {
return nil, fmt.Errorf("Index out of range: %d (variable %s)", part.i, vr.String())
}
default:
return nil, fmt.Errorf("Can't access an index on type %s (variable %s)",
current.Kind().String(), vr.String())
}
case varTypeIdent:
// debugging:
// fmt.Printf("now = %s (kind: %s)\n", part.s, current.Kind().String())
// Calling a field or key
switch current.Kind() {
case reflect.Struct:
current = current.FieldByName(part.s)
case reflect.Map:
current = current.MapIndex(reflect.ValueOf(part.s))
default:
return nil, fmt.Errorf("Can't access a field by name on type %s (variable %s)",
current.Kind().String(), vr.String())
}
default:
panic("unimplemented")
}
}
if !current.IsValid() {
// Value is not valid (anymore)
return AsValue(nil), nil
}
// If current is a reflect.ValueOf(Value), then unpack it
// Happens in function calls (as a return value) or by injecting
// into the execution context (e.g. in a for-loop)
if current.Type() == reflect.TypeOf(&Value{}) {
tmpValue := current.Interface().(*Value)
current = tmpValue.val
}
// Check whether this is an interface and resolve it where required
if current.Kind() == reflect.Interface {
current = reflect.ValueOf(current.Interface())
}
// Handle index call
if part.isIndexCall {
if current.Kind() != reflect.String && current.Kind() != reflect.Array && current.Kind() != reflect.Slice && current.Kind() != reflect.Map {
return nil, fmt.Errorf("'%s' can not be index access (it is %s)", vr.String(), current.Kind().String())
}
idxVal, err := part.indexArg.Evaluate(target)
if err != nil {
return nil, err
}
switch current.Kind() {
case reflect.String, reflect.Array, reflect.Slice:
currentLen := current.Len()
resolveKey := idxVal.getResolvedValue()
if currentLen > idxVal.Integer() {
current = current.Index(idxVal.Integer())
keySetter = &KeySetter{
prev: &Value{val: current},
key: resolveKey,
}
} else {
if current.Kind() != reflect.Slice {
return nil, fmt.Errorf("Index out of range: %d (variable %s)", idxVal.Integer(), vr.String())
}
idxInt := int(idxVal.Integer())
wantLen := idxInt + 1
if wantLen > current.Cap() {
nav := reflect.MakeSlice(current.Type(), wantLen, wantLen*2)
reflect.Copy(nav, current)
current.Set(nav)
current.SetLen(wantLen)
} else {
current.SetLen(wantLen)
}
current = current.Index(idxInt)
keySetter = &KeySetter{
prev: &Value{val: current},
key: resolveKey,
}
}
case reflect.Map:
resolveKey := idxVal.getResolvedValue()
if idxVal.IsInteger() {
resolveKey = reflect.ValueOf(idxVal.String())
}
keySetter = &KeySetter{
prev: &Value{val: current},
key: resolveKey,
}
current = current.MapIndex(resolveKey)
default:
return nil, fmt.Errorf("Can't access an index on type %s (variable %s)",
current.Kind().String(), vr.String())
}
}
// Check if the part is a function call
if part.isFunctionCall || current.Kind() == reflect.Func {
// Check for callable
if current.Kind() != reflect.Func {
return nil, fmt.Errorf("'%s' is not a function (it is %s)", vr.String(), current.Kind().String())
}
// Check for correct function syntax and types
// func(*Value, ...) *Value
t := current.Type()
// Input arguments
if len(part.callingArgs) != t.NumIn() && !(len(part.callingArgs) >= t.NumIn()-1 && t.IsVariadic()) {
return nil,
fmt.Errorf("Function input argument count (%d) of '%s' must be equal to the calling argument count (%d).",
t.NumIn(), vr.String(), len(part.callingArgs))
}
// Output arguments
if t.NumOut() != 1 {
return nil, fmt.Errorf("'%s' must have exactly 1 output argument", vr.String())
}
// Evaluate all parameters
var parameters []reflect.Value
numArgs := t.NumIn()
isVariadic := t.IsVariadic()
var fnArg reflect.Type
for idx, arg := range part.callingArgs {
pv, err := arg.Evaluate(target)
if err != nil {
return nil, err
}
if isVariadic {
if idx >= t.NumIn()-1 {
fnArg = t.In(numArgs - 1).Elem()
} else {
fnArg = t.In(idx)
}
} else {
fnArg = t.In(idx)
}
if fnArg != reflect.TypeOf(new(Value)) {
// Function's argument is not a *Value, then we have to check whether input argument is of the same type as the function's argument
if !isVariadic {
if fnArg != reflect.TypeOf(pv.Interface()) && fnArg.Kind() != reflect.Interface {
return nil, fmt.Errorf("Function input argument %d of '%s' must be of type %s or *Value (not %T).",
idx, vr.String(), fnArg.String(), pv.Interface())
}
// Function's argument has another type, using the interface-value
parameters = append(parameters, reflect.ValueOf(pv.Interface()))
} else {
if fnArg != reflect.TypeOf(pv.Interface()) && fnArg.Kind() != reflect.Interface {
return nil, fmt.Errorf("Function variadic input argument of '%s' must be of type %s or *Value (not %T).",
vr.String(), fnArg.String(), pv.Interface())
}
// Function's argument has another type, using the interface-value
parameters = append(parameters, reflect.ValueOf(pv.Interface()))
}
} else {
// Function's argument is a *Value
parameters = append(parameters, reflect.ValueOf(pv))
}
}
// Check if any of the values are invalid
for _, p := range parameters {
if p.Kind() == reflect.Invalid {
return nil, fmt.Errorf("Calling a function using an invalid parameter")
}
}
// Call it and get first return parameter back
rv := current.Call(parameters)[0]
if rv.Type() != reflect.TypeOf(new(Value)) {
current = reflect.ValueOf(rv.Interface())
} else {
// Return the function call value
current = rv.Interface().(*Value).val
}
}
}
if !current.IsValid() {
// Value is not valid (e. g. NIL value)
return AsValueWithSetter(nil, keySetter), nil
}
return &Value{val: current, keySetter: keySetter}, nil
}
func (vr *variableResolver) GetPositionToken() *Token {
return vr.locationToken
}
type variablePart struct {
typ int
s string
i int
isIndexCall bool
isFunctionCall bool
indexArg functionCallArgument
callingArgs []functionCallArgument // needed for a function call, represents all argument nodes (INode supports nested function calls)
}
func (p *Parser) ParseExp() (IEvaluator, *Error) {
if p.Match(TokenSymbol, "(") != nil {
expr, err := p.ParseExp()
if err != nil {
return nil, err
}
if p.Match(TokenSymbol, ")") == nil {
return nil, p.Error("Closing bracket expected after expression", nil)
}
return expr, nil
}
t := p.Current()
if t == nil {
return nil, p.Error("Unexpect EOF, expected an identifier", p.lastToken)
}
switch t.Typ {
case TokenNumber:
p.Consume()
i, err := strconv.Atoi(t.Val)
if err != nil {
return nil, p.Error(err.Error(), t)
}
nr := &intResolver{
locationToken: t,
val: i,
}
return nr, nil
case TokenString:
p.Consume()
sr := &stringResolver{
locationToken: t,
val: t.Val,
}
return sr, nil
case TokenKeyword:
p.Consume()
switch t.Val {
case "true":
br := &boolResolver{
locationToken: t,
val: true,
}
return br, nil
case "false":
br := &boolResolver{
locationToken: t,
val: false,
}
return br, nil
default:
return nil, p.Error("This keyword is not allowed here.", nil)
}
}
if t.Typ != TokenIdentifier {
return nil, p.Error("Expected either a number, string, keyword or identifier.", t)
}
resolver := &variableResolver{
locationToken: t,
}
resolver.parts = append(resolver.parts, &variablePart{
typ: varTypeIdent,
s: t.Val,
})
p.Consume()
variableLoop:
for p.Remaining() > 0 {
t = p.Current()
if p.Match(TokenSymbol, ".") != nil {
t2 := p.Current()
if t2 != nil {
switch t2.Typ {
case TokenIdentifier:
resolver.parts = append(resolver.parts, &variablePart{
typ: varTypeIdent,
s: t2.Val,
})
p.Consume()
continue variableLoop
case TokenNumber:
i, err := strconv.Atoi(t2.Val)
if err != nil {
return nil, p.Error(err.Error(), t2)
}
resolver.parts = append(resolver.parts, &variablePart{
typ: varTypeInt,
i: i,
})
p.Consume()
continue variableLoop
default:
return nil, p.Error("This token is not allowed within a variable name", t2)
}
} else {
return nil, p.Error("Unexpected EOF", p.lastToken)
}
} else if p.Match(TokenSymbol, "(") != nil {
// Function call
// FunctionName '(' Comma-separated list of expressions ')'
part := resolver.parts[len(resolver.parts)-1]
part.isFunctionCall = true
argumentLoop:
for {
if p.Remaining() == 0 {
return nil, p.Error("Unexpected EOF, expected function call argument list.", p.lastToken)
}
if p.Peek(TokenSymbol, ")") == nil {
// No closing bracket, so we're parsing an expression
exprArg, err := p.ParseExp()
if err != nil {
return nil, err
}
part.callingArgs = append(part.callingArgs, exprArg)
if p.Match(TokenSymbol, ")") != nil {
// If there's a closing bracket after an expression, we will stop parsing the arguments
break argumentLoop
} else {
// If there's NO closing bracket, there MUST be an comma
if p.Match(TokenSymbol, ",") == nil {
return nil, p.Error("Missing comma or closing bracket after argument.", nil)
}
}
} else {
// We got a closing bracket, so stop parsing arguments
p.Consume()
break argumentLoop
}
}
// We're done parsing the function call, next variable part
continue variableLoop
} else if p.Match(TokenSymbol, "[") != nil {
part := resolver.parts[len(resolver.parts)-1]
part.isIndexCall = true
if p.Remaining() == 0 {
return nil, p.Error("Unexpected EOF, expected index call expression.", p.lastToken)
}
if p.Peek(TokenSymbol, "]") != nil {
return nil, p.Error("Unexpected ], expected index argument.", p.lastToken)
}
exprArg, err := p.ParseExp()
if err != nil {
return nil, err
}
part.indexArg = exprArg
if p.Match(TokenSymbol, "]") == nil {
return nil, p.Error("Miss [ for index argument call.", p.lastToken)
}
continue variableLoop
}
break
}
return resolver, nil
}