-
Notifications
You must be signed in to change notification settings - Fork 10
/
eval.go
676 lines (566 loc) · 11.6 KB
/
eval.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
// Copyright 2012-2018, Rolf Veen and contributors.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ogdl
// import "fmt"
// Eval takes a parsed expression and evaluates it
// in the context of the current graph.
func (g *Graph) Eval(e *Graph) (interface{}, error) {
switch e.ThisString() {
case TypePath:
return g.evalPath(e, true)
case TypeExpression:
return g.evalExpression(e, true)
}
// A complex object that is not a path or expression: return as is.
if e.Len() != 0 {
return e, nil
}
// A constant: return in its normalizad native form
// either: int64, float64, string, bool or []byte
return e.ThisScalar(), nil
}
// EvalBool takes a parsed expression and evaluates it in the context of the
// current graph, and converts the result to a boolean.
func (g *Graph) evalBool(e *Graph) bool {
i, err := g.Eval(e)
if err != nil {
return false
}
b, _ := _boolf(i)
return b
}
// GetPath <-> EvalPath
func (g *Graph) getPath(p *Graph) (*Graph, error) {
if p.Len() == 0 || g == nil {
return nil, ErrInvalidArgs
}
// fmt.Printf("%s\n", p.Show())
ctx := g // Current context node
var ctxPrev *Graph // Previous context node
var elemPrev string // Previous path element searched in the context node
for i := 0; i < len(p.Out); i++ {
if ctx == nil {
break
}
pathNode := p.Out[i]
pathElement := pathNode.ThisString()
switch pathElement {
case TypeIndex:
// must evaluate to an integer
ix := pathNode.index(g)
if ix < 0 {
return nil, ErrInvalidIndex
}
r := New("[")
r.Add(ctx.GetAt(ix))
ctxPrev = ctx
ctx = r
case TypeSelector:
if ctxPrev == nil || len(elemPrev) == 0 {
return nil, ErrInvalidIndex
}
r := New("{")
ix := pathNode.index(g) + 1 // 0 is {}, {n} becomes ix = n+1
if ix < 0 {
return nil, ErrInvalidIndex
} else if ix == 0 {
// This case is {}, thus return all ocurrences of the token just before
r.addEqualNodes(ctxPrev, elemPrev, false)
} else {
// of all the nodes with name elemPrev, select the ix_th.
for _, nn := range ctxPrev.Out {
if nn.ThisString() == elemPrev {
ix--
if ix == 0 {
r.AddNodes(nn)
break
}
}
}
}
ctxPrev = ctx
ctx = r
case TypeArguments:
// We have hit an argument list of a function
if ctx.Len() > 0 {
itf, err := g.function(p, ctx.GetAt(0).This)
if err != nil {
return nil, err
}
var ok bool
ctxPrev = ctx
ctx, ok = itf.(*Graph)
if !ok {
return nil, ErrFunctionNoGraph
}
} else {
return nil, ErrNotFound
}
case TypeGroup:
// The expression is evaluated and used as path element
itf, err := g.Eval(pathNode.Out[0])
if err != nil {
return nil, err
}
str := _string(itf)
if len(str) == 0 {
return nil, nil // expr does not evaluate to a string
}
pathElement = str
// [!] .().
fallthrough
default:
ctxPrev = ctx
ctx = ctx.Node(pathElement)
elemPrev = pathElement
if ctx == nil {
if ctxPrev.Len() > 0 {
itf, err := g.function(p, ctxPrev.GetAt(0).This)
if err != nil {
return nil, err
}
var ok bool
ctx, ok = itf.(*Graph)
if !ok {
return nil, ErrFunctionNoGraph
}
}
}
}
}
return ctx, nil
}
// evalPath traverses g following a path p. The path needs to be previously converted
// to a Graph with NewPath().
//
func (g *Graph) evalPath(p *Graph, simpl bool) (interface{}, error) {
// fmt.Printf("evalPath\n%s\n%s\n", p.Show(), g.Show())
if p.Len() == 0 || g == nil {
return nil, ErrInvalidArgs
}
ctx := g // Current context
var ctxPrev *Graph // Previous context
var elemPrev string // Previous path element
var addRoot bool
for i := 0; i < len(p.Out); i++ {
if ctx == nil {
break
}
pathNode := p.Out[i]
pathElement := pathNode.ThisString()
addRoot = false
switch pathElement {
case TypeIndex:
// must evaluate to an integer
ix := pathNode.index(g)
if ix < 0 {
return nil, ErrInvalidIndex
}
ctxPrev = ctx
ctx = ctx.GetAt(ix)
addRoot = true
case TypeSelector:
if ctxPrev == nil || len(elemPrev) == 0 {
return nil, ErrInvalidIndex
}
r := New("{")
ix := pathNode.index(g) + 1 // 0 is {}, {n} becomes ix = n+1
if ix < 0 {
return nil, ErrInvalidIndex
} else if ix == 0 {
// This case is {}, thus return all ocurrences of the token just before
r.addEqualNodes(ctxPrev, elemPrev, false)
} else {
// of all the nodes with name elemPrev, select the ix_th.
for _, nn := range ctxPrev.Out {
if nn.ThisString() == elemPrev {
ix--
if ix == 0 {
r.AddNodes(nn)
break
}
}
}
}
ctxPrev = ctx
ctx = r
case "_len":
return ctx.Len(), nil
case "_this":
return ctx, nil
case "_thisString":
return ctx.ThisString(), nil
case "_string":
return ctx.String(), nil
case "_json":
return ctx.JSON(), nil
case TypeArguments:
// We have hit an argument list of a function
if ctx.Len() > 0 {
itf, err := g.function(p, ctx.GetAt(0).This)
if err != nil {
return nil, err
}
var ok bool
ctxPrev = ctx
ctx, ok = itf.(*Graph)
if !ok {
return itf, nil
}
} else {
return nil, nil
}
case TypeGroup:
// The expression is evaluated and used as path element
itf, err := g.Eval(pathNode.Out[0])
if err != nil {
return nil, err
}
str := _string(itf)
if len(str) == 0 {
return nil, nil // expr does not evaluate to a string
}
pathElement = str
// [!] .().
fallthrough
default:
ctxPrev = ctx
ctx = ctx.Node(pathElement)
elemPrev = pathElement
if ctx == nil {
if ctxPrev.Len() > 0 {
itf, err := g.function(p, ctxPrev.GetAt(0).This)
if err != nil {
return nil, err
}
var ok bool
ctx, ok = itf.(*Graph)
if !ok {
return itf, nil
}
// fmt.Printf("evalPath function %s %d %d %d\n", pathElement, i, p.Len(), len(p.Out))
return itf, nil
}
}
}
}
if addRoot {
r := New("[")
r.Add(ctx)
ctx = r
}
if simpl {
return _simplify(ctx), nil
} else {
return ctx, nil
}
}
// evalExpression evaluates expressions (!e)
// g can have native types (other things than strings), but
// p only []byte or string
//
func (g *Graph) evalExpression(p *Graph, simpl bool) (interface{}, error) {
// Return nil and empty strings as is
if p.This == nil {
return nil, ErrNilReceiver
}
s := p.ThisString()
if len(s) == 0 {
return "", nil
}
// first check if it is a number because it can have an operatorChar
// in front: the minus sign
if isNumber(s) {
return p.ThisNumber(), nil
}
switch s {
case "!":
// Unary expression !expr
return !g.evalBool(p.Out[0]), nil
case TypeExpression:
return g.evalExpression(p.GetAt(0), simpl)
case TypePath:
return g.evalPath(p, simpl)
case TypeGroup:
// TODO expression list (could also be OGDL flow!)
r := New(TypeGroup)
for _, expr := range p.Out {
itf, err := g.evalExpression(expr, simpl)
if err == nil {
r.Add(itf)
}
}
return r, nil
case TypeString:
if p.Len() == 0 {
return "", nil
}
return p.GetAt(0).ThisString(), nil
}
c := s[0]
// [!] Operator should be identified. Operators written as strings are
// missinterpreted.
if isOperatorChar(c) {
if len(s) <= 2 {
if len(s) == 1 || isOperatorChar(s[1]) {
return g.evalBinary(p), nil
}
}
}
if c == '"' || c == '\'' {
return s, nil
}
if IsLetter(rune(c)) {
if s == "false" {
return false, nil
}
if s == "true" {
return true, nil
}
return s, nil
}
return p, nil
}
func (g *Graph) evalBinary(p *Graph) interface{} {
n1 := p.Out[0]
i2, err := g.evalExpression(p.Out[1], true)
if err != nil {
return err // ?
}
switch p.ThisString() {
case "=":
return g.assign(n1, i2, '=')
case "+=":
return g.assign(n1, i2, '+')
case "-=":
return g.assign(n1, i2, '-')
case "*=":
return g.assign(n1, i2, '*')
case "/=":
return g.assign(n1, i2, '/')
case "%=":
return g.assign(n1, i2, '%')
}
i1, err := g.evalExpression(n1, true)
if err != nil {
return err // ?
}
switch p.ThisString() {
case "+":
return calc(i1, i2, '+')
case "-":
return calc(i1, i2, '-')
case "*":
return calc(i1, i2, '*')
case "/":
return calc(i1, i2, '/')
case "%":
return calc(i1, i2, '%')
case "==":
return compare(i1, i2, '=')
case ">=":
return compare(i1, i2, '+')
case "<=":
return compare(i1, i2, '-')
case "!=":
return compare(i1, i2, '!')
case ">":
return compare(i1, i2, '>')
case "<":
return compare(i1, i2, '<')
case "&&":
return logic(i1, i2, '&')
case "||":
return logic(i1, i2, '|')
}
return nil
}
// int* | float* | string
// first element determines type
func compare(v1, v2 interface{}, op int) bool {
var i1, i2 int64
var ok bool
i1, ok = _int64(v1)
if ok {
i2, ok = _int64f(v2)
if !ok {
return false
}
switch op {
case '=':
return i1 == i2
case '+':
return i1 >= i2
case '-':
return i1 <= i2
case '>':
return i1 > i2
case '<':
return i1 < i2
case '!':
return i1 != i2
}
return false
}
var f1, f2 float64
f1, ok = _float64(v1)
if ok {
f2, ok = _float64f(v2)
if !ok {
return false
}
switch op {
case '=':
return f1 == f2
case '+':
return f1 >= f2
case '-':
return f1 <= f2
case '>':
return f1 > f2
case '<':
return f1 < f2
case '!':
return f1 != f2
}
return false
}
s1 := _string(v1)
s2 := _string(v2)
switch op {
case '=':
return s1 == s2
case '!':
return s1 != s2
}
return false
}
// logic: and / or
func logic(i1, i2 interface{}, op int) bool {
b1, ok1 := _boolf(i1)
b2, ok2 := _boolf(i2)
if !ok1 || !ok2 {
return false
}
switch op {
case '&':
return b1 && b2
case '|':
return b1 || b2
}
return false
}
// assign modifies the context graph
func (g *Graph) assign(p *Graph, v interface{}, op int) interface{} {
if op == '=' {
return g.set(p, v)
}
// if p doesn't exist, just set it to the value given
left, _ := g.getPath(p)
if left != nil {
return g.set(p, calc(left.Out[0].This, v, op))
}
switch op {
case '+':
return g.set(p, v)
case '-':
return g.set(p, calc(0, v, '-'))
case '*':
return g.set(p, 0)
case '/':
return g.set(p, "infinity")
case '%':
return g.set(p, "undefined")
}
return nil
}
// calc: int64 | float64 | string
func calc(v1, v2 interface{}, op int) interface{} {
i1, ok := _int64(v1)
i2, ok2 := _int64(v2)
var ok3, ok4 bool
var i3, i4 float64
if !ok {
i3, ok3 = _float64(v1)
}
if !ok2 {
i4, ok4 = _float64(v2)
}
if ok && ok2 {
switch op {
case '+':
return i1 + i2
case '-':
return i1 - i2
case '*':
return i1 * i2
case '/':
return i1 / i2
case '%':
return i1 % i2
}
}
if ok3 && ok4 {
switch op {
case '+':
return i3 + i4
case '-':
return i3 - i4
case '*':
return i3 * i4
case '/':
return i3 / i4
case '%':
return int(i3) % int(i4)
}
}
if ok && ok4 {
i3 = float64(i1)
switch op {
case '+':
return i3 + i4
case '-':
return i3 - i4
case '*':
return i3 * i4
case '/':
return i3 / i4
case '%':
return i1 % int64(i4)
}
}
if ok3 && ok2 {
i4 = float64(i2)
switch op {
case '+':
return i3 + i4
case '-':
return i3 - i4
case '*':
return i3 * i4
case '/':
return i3 / i4
case '%':
return int64(i3) % i2
}
}
if op != '+' {
return nil
}
return _string(v1) + _string(v2)
}
func (g *Graph) index(c *Graph) int {
if g.Len() == 0 {
return -1
}
itf, err := c.evalExpression(g.Out[0], true)
if err != nil {
return -2
}
ix, ok := _int64(itf)
if !ok || ix < 0 {
return -3
}
return int(ix)
}