forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
889 lines (822 loc) · 17 KB
/
helpers.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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
package gno
import (
"fmt"
"regexp"
"strconv"
"strings"
)
//----------------------------------------
// AST Construction (Expr)
// These are copied over from go-amino-x, but produces Gno ASTs.
func N(n interface{}) Name {
switch n := n.(type) {
case string:
return Name(n)
case Name:
return n
default:
panic("unexpected name arg")
}
}
func Nx(n interface{}) *NameExpr {
return &NameExpr{Name: N(n)}
}
func ArrayT(l, elt interface{}) *ArrayTypeExpr {
return &ArrayTypeExpr{
Len: X(l),
Elt: X(elt),
}
}
func SliceT(elt interface{}) *SliceTypeExpr {
return &SliceTypeExpr{
Elt: X(elt),
Vrd: false,
}
}
func MapT(key, value interface{}) *MapTypeExpr {
return &MapTypeExpr{
Key: X(key),
Value: X(value),
}
}
func Vrd(elt interface{}) *SliceTypeExpr {
return &SliceTypeExpr{
Elt: X(elt),
Vrd: true,
}
}
func InterfaceT(methods FieldTypeExprs) *InterfaceTypeExpr {
return &InterfaceTypeExpr{
Methods: methods,
}
}
func AnyT() *InterfaceTypeExpr {
return InterfaceT(nil)
}
func GenT(generic Name, methods FieldTypeExprs) *InterfaceTypeExpr {
return &InterfaceTypeExpr{
Generic: generic,
Methods: methods,
}
}
func FuncT(params, results FieldTypeExprs) *FuncTypeExpr {
return &FuncTypeExpr{
Params: params,
Results: results,
}
}
func Flds(args ...interface{}) FieldTypeExprs {
list := FieldTypeExprs{}
for i := 0; i < len(args); i += 2 {
list = append(list, FieldTypeExpr{
Name: N(args[i]),
Type: X(args[i+1]),
})
}
return list
}
func Recv(n, t interface{}) FieldTypeExpr {
if n == "" {
n = "_"
}
return FieldTypeExpr{
Name: N(n),
Type: X(t),
}
}
func MaybeNativeT(tx interface{}) *MaybeNativeTypeExpr {
return &MaybeNativeTypeExpr{
Type: X(tx),
}
}
func FuncD(name interface{}, params, results FieldTypeExprs, body []Stmt) *FuncDecl {
return &FuncDecl{
NameExpr: *Nx(name),
Type: FuncTypeExpr{
Params: params,
Results: results,
},
Body: body,
}
}
func MthdD(name interface{}, recv FieldTypeExpr, params, results FieldTypeExprs, body []Stmt) *FuncDecl {
return &FuncDecl{
NameExpr: *Nx(name),
Recv: recv,
Type: FuncTypeExpr{
Params: params,
Results: results,
},
Body: body,
IsMethod: true,
}
}
func Fn(params, results FieldTypeExprs, body []Stmt) *FuncLitExpr {
return &FuncLitExpr{
Type: *FuncT(params, results),
Body: body,
}
}
func Kv(n, v interface{}) KeyValueExpr {
var kx, vx Expr
if ns, ok := n.(string); ok {
kx = X(ns) // key expr
} else {
kx = n.(Expr)
}
if vs, ok := v.(string); ok {
vx = X(vs) // type expr
} else {
vx = v.(Expr)
}
return KeyValueExpr{
Key: kx,
Value: vx,
}
}
// Tries to infer statement from args.
func S(args ...interface{}) Stmt {
if len(args) == 1 {
switch arg0 := args[0].(type) {
case Expr:
return &ExprStmt{X: arg0}
case Stmt:
return arg0
default:
panic("dunno how to construct statement from argument")
}
}
panic("dunno how to construct statement from arguments")
}
// Parses simple expressions (but not all).
// Useful for parsing strings to ast nodes, like foo.bar["qwe"](),
// new(bytes.Buffer), *bytes.Buffer, package.MyStruct{FieldA:1}, numeric
//
// * num/char (e.g. e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f')
// * strings (e.g. "foo" or `\m\n\o`), nil, function calls
// * square bracket indexing
// * dot notation
// * star expression for pointers
// * composite expressions
// * nil
// * type assertions, for EXPR.(EXPR) and also EXPR.(type)
// * []type slice types
// * [n]type array types
// * &something referencing
// * unary operations, namely
// "+" | "-" | "!" | "^" | "*" | "&" | "<-" .
// * binary operations, namely
// "||", "&&",
// "==" | "!=" | "<" | "<=" | ">" | ">="
// "+" | "-" | "|" | "^"
// "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" .
//
// If the first argument is an expression, returns it.
// TODO replace this with rewrite of Joeson parser.
func X(x interface{}, args ...interface{}) Expr {
switch cx := x.(type) {
case Expr:
return cx
case int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64:
return X(fmt.Sprintf("%v", x))
case string:
if cx == "" {
panic("input cannot be blank for X()")
}
case Name:
if cx == "" {
panic("input cannot be blank for X()")
}
x = string(cx)
default:
panic("unexpected input type for X()")
}
expr := x.(string)
expr = fmt.Sprintf(expr, args...)
expr = strings.TrimSpace(expr)
first := expr[0]
// 1: Binary operators have a lower predecence than unary operators (or
// monoids).
left, op, right, ok := chopBinary(expr)
if ok {
return Bx(X(left), op, X(right))
}
// 2: Unary operators that depend on the first letter.
switch first {
case '*':
return &StarExpr{
X: X(expr[1:]),
}
case '&':
return &RefExpr{
X: X(expr[1:]),
}
case '+', '-', '!', '^':
return &UnaryExpr{
Op: Op2Word(expr[:1]),
X: X(expr[1:]),
}
case '<':
second := expr[1] // is required.
if second != '-' {
panic("unparseable expression " + expr)
}
return &UnaryExpr{
Op: Op2Word("<-"),
X: X(expr[2:]),
}
}
// 3: Unary operators or literals that don't depend on the first letter,
// and have some distinct suffix.
if len(expr) > 1 {
last := expr[len(expr)-1]
switch last {
case 'l':
if expr == "nil" {
return Nx("nil")
}
case 'i':
if '0' <= expr[0] && expr[0] <= '9' {
num := X(expr[:len(expr)-1]).(*BasicLitExpr)
if num.Kind != INT && num.Kind != FLOAT {
panic("expected int or float before 'i'")
}
num.Kind = IMAG
return num
}
case '\'':
if first != last {
panic("unmatched quote")
}
return &BasicLitExpr{
Kind: CHAR,
Value: string(expr[1 : len(expr)-1]),
}
case '"', '`':
if first != last {
panic("unmatched quote")
}
return &BasicLitExpr{
Kind: STRING,
Value: string(expr),
}
case ')':
left, _, right := chopRight(expr)
if left == "" {
// Special case, not a function call.
return X(right)
} else if left[len(left)-1] == '.' {
// Special case, a type assert.
var x, t Expr = X(left[:len(left)-1]), nil
if right == "type" {
t = nil
} else {
t = X(right)
}
return &TypeAssertExpr{
X: x,
Type: t,
}
}
fn := X(left)
args := []Expr{}
parts := strings.Split(right, ",")
for _, part := range parts {
// NOTE: repeated commas have no effect,
// nor do trailing commas.
if len(part) > 0 {
args = append(args, X(part))
}
}
return &CallExpr{
Func: fn,
Args: args,
}
case '}':
left, _, right := chopRight(expr)
switch left {
case "interface":
panic("interface type expressions not supported, use InterfaceT(Flds(...)) instead")
case "struct":
panic("struct type expressions not supported")
default:
// composite type
typ := X(left)
kvs := []KeyValueExpr{}
parts := strings.Split(right, ",")
for _, part := range parts {
if strings.TrimSpace(part) != "" {
parts := strings.Split(part, ":")
if len(parts) != 2 {
panic("key:value requires 1 colon")
}
kvs = append(kvs, Kv(parts[0], parts[1]))
}
}
return &CompositeLitExpr{
Type: typ,
Elts: kvs,
}
}
case ']':
left, _, right := chopRight(expr)
return Idx(left, right)
}
}
// 4. Monoids of array or slice type.
// NOTE: []foo.bar requires this to have lower predence than dots.
switch first {
case '.': // variadic ... prefix.
if expr[1] == '.' && expr[2] == '.' {
return Vrd(expr[3:])
} else {
// nothing else should start with a dot.
panic(fmt.Sprintf(
"illegal expression %s",
expr))
}
case '[': // array or slice prefix.
if expr[1] == ']' {
return SliceT(expr[2:])
} else {
idx := strings.Index(expr, "]")
if idx == -1 {
panic(fmt.Sprintf(
"mismatched '[' in slice expr %v",
expr))
}
return ArrayT(expr[1:idx], expr[idx+1:])
}
}
// Numeric int? We do these before dots, because dots are legal in numbers.
const (
DGTS = `(?:[0-9]+)`
HExX = `(?:0[xX][0-9a-fA-F]+)`
PSCI = `(?:[eE]+?[0-9]+)`
NSCI = `(?:[eE]-[1-9][0-9]+)`
ASCI = `(?:[eE][-+]?[0-9]+)`
)
isInt, err := regexp.Match(
`^-?(?:`+
DGTS+`|`+
HExX+`)`+PSCI+`?$`,
[]byte(expr),
)
if err != nil {
panic("should not happen")
}
if isInt {
return &BasicLitExpr{
Kind: INT,
Value: string(expr),
}
}
// Numeric float? We do these before dots, because dots are legal in floats.
isFloat, err := regexp.Match(
`^-?(?:`+
DGTS+`\.`+DGTS+ASCI+`?|`+
DGTS+NSCI+`)$`,
[]byte(expr),
)
if err != nil {
panic("should not happen")
}
if isFloat {
return &BasicLitExpr{
Kind: FLOAT,
Value: string(expr),
}
}
// Last case, handle dots.
// It's last, meaning it's got the highest precedence.
if idx := strings.LastIndex(expr, "."); idx != -1 {
return &SelectorExpr{
X: X(expr[:idx]),
Sel: N(expr[idx+1:]),
}
}
return Nx(expr)
}
// Returns idx=-1 if not a binary operator.
// Precedence Operator
// 5 * / % << >> & &^
// 4 + - | ^
// 3 == != < <= > >=
// 2 &&
// 1 ||
var sp = " "
var (
prec5 = strings.Split("* / % << >> & &^", sp)
prec4 = strings.Split("+ - | ^", sp)
prec3 = strings.Split("== != < <= > >=", sp)
prec2 = strings.Split("&&", sp)
prec1 = strings.Split("||", sp)
precs = [][]string{prec1, prec2, prec3, prec4, prec5}
)
// 0 for prec1... -1 if no match.
func lowestMatch(op string) int {
for i, prec := range precs {
for _, op2 := range prec {
if op == op2 {
return i
}
}
}
return -1
}
func Ss(b ...Stmt) []Stmt {
return b
}
func Xs(exprs ...Expr) []Expr {
return exprs
}
// Usage: A(lhs1, lhs2, ..., ":=", rhs1, rhs2, ...)
// Operation can be like ":=", "=", "+=", etc.
// Other strings are automatically parsed as X(arg).
func A(args ...interface{}) *AssignStmt {
lhs := []Expr(nil)
op := ILLEGAL
rhs := []Expr(nil)
setOp := func(w Word) {
if op != ILLEGAL {
panic("too many assignment operators")
}
op = w
}
for _, arg := range args {
if s, ok := arg.(string); ok {
switch s {
case "=", ":=", "+=", "-=", "*=", "/=", "%=",
"&=", "|=", "^=", "<<=", ">>=", "&^=":
setOp(Op2Word(s))
continue
default:
arg = X(s)
}
}
// append to lhs or rhs depending on op.
if op == ILLEGAL {
lhs = append(lhs, arg.(Expr))
} else {
rhs = append(rhs, arg.(Expr))
}
}
return &AssignStmt{
Op: op,
Lhs: lhs,
Rhs: rhs,
}
}
func Not(x Expr) *UnaryExpr {
return &UnaryExpr{
Op: Op2Word("!"),
X: x,
}
}
// Binary expression. x, y can be Expr or string.
func Bx(lx interface{}, op string, rx interface{}) Expr {
return &BinaryExpr{
Left: X(lx),
Op: Op2Word(op),
Right: X(rx),
}
}
func Call(fn interface{}, args ...interface{}) *CallExpr {
argz := make([]Expr, len(args))
for i := 0; i < len(args); i++ {
argz[i] = X(args[i])
}
return &CallExpr{
Func: X(fn),
Args: argz,
}
}
func TypeAssert(x interface{}, t interface{}) *TypeAssertExpr {
return &TypeAssertExpr{
X: X(x),
Type: X(t),
}
}
func Sel(x interface{}, sel interface{}) *SelectorExpr {
return &SelectorExpr{
X: X(x),
Sel: N(sel),
}
}
func Idx(x interface{}, idx interface{}) *IndexExpr {
return &IndexExpr{
X: X(x),
Index: X(idx),
}
}
func Str(s string) *BasicLitExpr {
return &BasicLitExpr{
Kind: STRING,
Value: strconv.Quote(s),
}
}
func Num(s string) *BasicLitExpr {
return &BasicLitExpr{
Kind: INT,
Value: s,
}
}
func Ref(x interface{}) *RefExpr {
return &RefExpr{
X: X(x),
}
}
func Deref(x interface{}) *StarExpr {
return &StarExpr{
X: X(x),
}
}
// NOTE: Same as DEREF, but different context.
func Ptr(x interface{}) *StarExpr {
return &StarExpr{
X: X(x),
}
}
//----------------------------------------
// AST Construction (Stmt)
func If(cond Expr, b ...Stmt) *IfStmt {
return &IfStmt{
Cond: cond,
Then: IfCaseStmt{Body: b},
}
}
func IfElse(cond Expr, bdy, els Stmt) *IfStmt {
var body []Stmt
if bdy, ok := bdy.(*BlockStmt); !ok {
body = bdy.Body
} else {
body = []Stmt{bdy}
}
var els_ []Stmt
if els, ok := els.(*BlockStmt); !ok {
els_ = els.Body
} else {
els_ = []Stmt{els}
}
return &IfStmt{
Cond: cond,
Then: IfCaseStmt{Body: body},
Else: IfCaseStmt{Body: els_},
}
}
func Return(results ...Expr) *ReturnStmt {
return &ReturnStmt{
Results: results,
}
}
func Continue(label interface{}) *BranchStmt {
return &BranchStmt{
Op: CONTINUE,
Label: N(label),
}
}
func Break(label interface{}) *BranchStmt {
return &BranchStmt{
Op: BREAK,
Label: N(label),
}
}
func Goto(label interface{}) *BranchStmt {
return &BranchStmt{
Op: GOTO,
Label: N(label),
}
}
func Fallthrough(label interface{}) *BranchStmt {
return &BranchStmt{
Op: FALLTHROUGH,
Label: N(label),
}
}
func ImportD(name interface{}, path string) *ImportDecl {
return &ImportDecl{
NameExpr: *Nx(name),
PkgPath: path,
}
}
func For(init, cond, post interface{}, b ...Stmt) *ForStmt {
return &ForStmt{
Init: S(init).(SimpleStmt),
Cond: X(cond),
Post: S(post).(SimpleStmt),
Body: b,
}
}
func Loop(b ...Stmt) *ForStmt {
return For(nil, nil, nil, b...)
}
func Once(b ...Stmt) *ForStmt {
b = append(b, Break(""))
return For(nil, nil, nil, b...)
}
func Len(x Expr) *CallExpr {
return Call(Nx("len"), x)
}
func Var(name interface{}, typ Expr, value Expr) *DeclStmt {
return &DeclStmt{
Body: []Stmt{&ValueDecl{
NameExprs: []NameExpr{*Nx(name)},
Type: typ,
Values: []Expr{value},
Const: false,
}},
}
}
func Inc(x interface{}) *IncDecStmt {
var xx Expr
if xs, ok := x.(string); ok {
xx = X(xs)
}
return &IncDecStmt{
X: xx,
Op: INC,
}
}
func Dec(x interface{}) *IncDecStmt {
var xx Expr
if xs, ok := x.(string); ok {
xx = X(xs)
}
return &IncDecStmt{
X: xx,
Op: DEC,
}
}
func Op2Word(op string) Word {
switch op {
case "+":
return ADD
case "-":
return SUB
case "*":
return MUL
case "/":
return QUO
case "%":
return REM
case "&":
return BAND
case "|":
return BOR
case "^":
return XOR
case "<<":
return SHL
case ">>":
return SHR
case "&^":
return BAND_NOT
case "&&":
return LAND
case "||":
return LOR
case "<-":
return ARROW
case "++":
return INC
case "--":
return DEC
case "==":
return EQL
case "<":
return LSS
case ">":
return GTR
case "!":
return NOT
case "!=":
return NEQ
case "<=":
return LEQ
case ">=":
return GEQ
// Assignment
case "=":
return ASSIGN
case ":=":
return DEFINE
case "+=":
return ADD_ASSIGN
case "-=":
return SUB_ASSIGN
case "*=":
return MUL_ASSIGN
case "/=":
return QUO_ASSIGN
case "%=":
return REM_ASSIGN
case "&=":
return BAND_ASSIGN
case "|=":
return BOR_ASSIGN
case "^=":
return XOR_ASSIGN
case "<<=":
return SHL_ASSIGN
case ">>=":
return SHR_ASSIGN
case "&^=":
return BAND_NOT_ASSIGN
default:
panic("unrecognized binary/unary/assignment operator " + op)
}
}
//----------------------------------------
// AST Static (compile time)
func SIf(cond bool, then_, else_ Stmt) Stmt {
if cond {
return then_
} else if else_ != nil {
return else_
} else {
return &EmptyStmt{}
}
}
//----------------------------------------
// chop functions
//----------------------------------------
func chopBinary(expr string) (left, op, right string, ok bool) {
// 0 for prec1... -1 if no match.
matchOp := func(op string) int {
for i, prec := range precs {
for _, op2 := range prec {
if op == op2 {
return i
}
}
}
return -1
}
ss := newScanner(expr)
lowestMatch := 0xff
for !ss.advance() {
if ss.out() {
// find match starting with longer operators.
for ln := 2; ln > 0; ln-- {
op2 := ss.peek(ln)
match := matchOp(op2)
if match != -1 {
if match <= lowestMatch {
ok = true
lowestMatch = match
left = string(ss.rnz[:ss.idx])
op = op2
// NOTE: `op2` may be shorter than ln.
// NOTE: assumes operators are ascii chars.
right = string(ss.rnz[ss.idx+len(op2):])
}
// advance, so we don't match a substring
// operator.
for i := 0; i < len(op2); i++ {
ss.advance()
}
break
// Do not return here, we want to find the last
// match. But don't consider shorter operators.
}
if len(op2) == 1 {
// nothing more to read.
break
}
}
}
}
if !ss.out() {
return "", "", "", false
}
return
}
// Given that 'in' ends with ')', '}', or ']',
// find the matching opener, while processing escape
// sequences of strings and rune literals.
// `tok` is the corresponding opening rune.
// `right` excludes the last character (closer).
func chopRight(in string) (left string, tok rune, right string) {
switch in[len(in)-1] {
case '}', ')', ']':
// good
default:
panic("input doesn't start with brace: " + in)
}
ss := newScanner(in)
lastOut := 0 // last position where out.
for !ss.advance() {
if ss.out() {
lastOut = ss.idx
}
}
if !ss.out() {
panic("mismatched braces/brackets")
} else {
left = string(ss.rnz[:lastOut+1])
tok = ss.rnz[lastOut+1]
right = string(ss.rnz[lastOut+2 : len(in)-2])
return
}
}