forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocess.go
3524 lines (3391 loc) · 97.9 KB
/
preprocess.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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gno
import (
"fmt"
"math/big"
"reflect"
"github.com/gnolang/gno/pkgs/errors"
)
// In the case of a *FileSet, some declaration steps have to happen
// in a restricted parallel way across all the files.
// Anything predefined or preprocessed here get skipped during the Preprocess
// phase.
func PredefineFileSet(store Store, pn *PackageNode, fset *FileSet) {
// First, initialize all file nodes and connect to package node.
for _, fn := range fset.Files {
SetNodeLocations(pn.PkgPath, string(fn.Name), fn)
fn.InitStaticBlock(fn, pn)
}
// NOTE: much of what follows is duplicated for a single *FileNode
// in the main Preprocess translation function. Keep synced.
// Predefine all import decls first.
// This must be done before TypeDecls, as it may recursively
// depend on names (even in other files) that depend on imports.
for _, fn := range fset.Files {
for i := 0; i < len(fn.Decls); i++ {
d := fn.Decls[i]
switch d.(type) {
case *ImportDecl:
if d.GetAttribute(ATTR_PREDEFINED) == true {
// skip declarations already predefined
// (e.g. through recursion for a
// dependent)
} else {
// recursively predefine dependencies.
d2, _ := predefineNow(store, fn, d)
fn.Decls[i] = d2
}
}
}
}
// Predefine all type decls decls.
for _, fn := range fset.Files {
for i := 0; i < len(fn.Decls); i++ {
d := fn.Decls[i]
switch d.(type) {
case *TypeDecl:
if d.GetAttribute(ATTR_PREDEFINED) == true {
// skip declarations already predefined
// (e.g. through recursion for a
// dependent)
} else {
// recursively predefine dependencies.
d2, _ := predefineNow(store, fn, d)
fn.Decls[i] = d2
}
}
}
}
// Then, predefine all func/method decls.
for _, fn := range fset.Files {
for i := 0; i < len(fn.Decls); i++ {
d := fn.Decls[i]
switch d.(type) {
case *FuncDecl:
if d.GetAttribute(ATTR_PREDEFINED) == true {
// skip declarations already predefined
// (e.g. through recursion for a
// dependent)
} else {
// recursively predefine dependencies.
d2, _ := predefineNow(store, fn, d)
fn.Decls[i] = d2
}
}
}
}
// Finally, predefine other decls and
// preprocess ValueDecls..
for _, fn := range fset.Files {
for i := 0; i < len(fn.Decls); i++ {
d := fn.Decls[i]
if d.GetAttribute(ATTR_PREDEFINED) == true {
// skip declarations already predefined (e.g.
// through recursion for a dependent)
} else {
// recursively predefine dependencies.
d2, _ := predefineNow(store, fn, d)
fn.Decls[i] = d2
}
}
}
}
// This counter ensures (during testing) that certain functions
// (like ConvertUntypedTo() for bigints and strings)
// are only called during the preprocessing stage.
// It is a counter because Preprocess() is recursive.
var preprocessing int
// Preprocess n whose parent block node is ctx. If any names
// are defined in another file, generally you must call
// PredefineFileSet() on the whole fileset first before calling
// Preprocess.
//
// The ctx passed in may be mutated if there are any statements
// or declarations. The file or package which contains ctx may
// be mutated if there are any file-level declarations.
//
// Store is used to load external package values, but otherwise
// the package and newly created blocks/values are expected
// to be non-RefValues -- in some cases, nil is passed for store
// to enforce this.
//
// List of what Preprocess() does:
// * Assigns BlockValuePath to NameExprs.
// * TODO document what it does.
func Preprocess(store Store, ctx BlockNode, n Node) Node {
// Increment preprocessing counter while preprocessing.
{
preprocessing += 1
defer func() {
preprocessing -= 1
}()
}
if ctx == nil {
// Generally a ctx is required, but if not, it's ok to pass in nil.
// panic("Preprocess requires context")
}
// if n is file node, set node locations recursively.
if fn, ok := n.(*FileNode); ok {
pkgPath := ctx.(*PackageNode).PkgPath
fileName := string(fn.Name)
SetNodeLocations(pkgPath, fileName, fn)
}
// create stack of BlockNodes.
var stack []BlockNode = make([]BlockNode, 0, 32)
var last BlockNode = ctx
var lastpn = packageOf(last)
stack = append(stack, last)
// iterate over all nodes recursively and calculate
// BlockValuePath for each NameExpr.
nn := Transcribe(n, func(ns []Node, ftype TransField, index int, n Node, stage TransStage) (Node, TransCtrl) {
// if already preprocessed, skip it.
if n.GetAttribute(ATTR_PREPROCESSED) == true {
return n, TRANS_SKIP
}
defer func() {
if r := recover(); r != nil {
fmt.Println("--- preprocess stack ---")
for i := len(stack) - 1; i >= 0; i-- {
sbn := stack[i]
fmt.Printf("stack %d: %s\n", i, sbn.String())
}
fmt.Println("------------------------")
// before re-throwing the error, append location information to message.
loc := last.GetLocation()
if nline := n.GetLine(); nline > 0 {
loc.Line = nline
}
if rerr, ok := r.(error); ok {
// NOTE: gotuna/gorilla expects error exceptions.
panic(errors.Wrap(rerr, loc.String()))
} else {
// NOTE: gotuna/gorilla expects error exceptions.
panic(errors.New(fmt.Sprintf("%s: %v", loc.String(), r)))
}
}
}()
if debug {
debug.Printf("Preprocess %s (%v) stage:%v\n", n.String(), reflect.TypeOf(n), stage)
}
switch stage {
//----------------------------------------
case TRANS_ENTER:
switch n := n.(type) {
// TRANS_ENTER -----------------------
case *AssignStmt:
if n.Op == DEFINE {
var defined bool
for _, lx := range n.Lhs {
ln := lx.(*NameExpr).Name
if ln == "_" {
// ignore.
} else {
_, ok := last.GetLocalIndex(ln)
if !ok {
// initial declaration to be re-defined.
last.Define(ln, anyValue(nil))
defined = true
} else {
// do not redeclare.
}
}
}
if !defined {
panic(fmt.Sprintf("nothing defined in asssignment %s", n.String()))
}
} else {
// nothing defined.
}
// TRANS_ENTER -----------------------
case *ImportDecl, *ValueDecl, *TypeDecl, *FuncDecl:
// NOTE func decl usually must happen with a
// file, and so last is usually a *FileNode,
// but for testing convenience we allow
// importing directly onto the package.
// Uverse requires this.
if n.GetAttribute(ATTR_PREDEFINED) == true {
// skip declarations already predefined
// (e.g. through recursion for a dependent)
} else {
// recursively predefine dependencies.
d2, ppd := predefineNow(store, last, n.(Decl))
if ppd {
return d2, TRANS_SKIP
} else {
return d2, TRANS_CONTINUE
}
}
// TRANS_ENTER -----------------------
case *FuncTypeExpr:
for i, _ := range n.Params {
p := &n.Params[i]
if p.Name == "" || p.Name == "_" {
// create a hidden var with leading dot.
// NOTE: document somewhere.
pn := fmt.Sprintf(".arg_%d", i)
p.Name = Name(pn)
}
}
for i, _ := range n.Results {
r := &n.Results[i]
if r.Name == "_" {
// create a hidden var with leading dot.
// NOTE: document somewhere.
rn := fmt.Sprintf(".res_%d", i)
r.Name = Name(rn)
}
}
}
// TRANS_ENTER -----------------------
return n, TRANS_CONTINUE
//----------------------------------------
case TRANS_BLOCK:
switch n := n.(type) {
// TRANS_BLOCK -----------------------
case *BlockStmt:
pushInitBlock(n, &last, &stack)
// TRANS_BLOCK -----------------------
case *ForStmt:
pushInitBlock(n, &last, &stack)
// TRANS_BLOCK -----------------------
case *IfStmt:
// create faux block to store .Init.
// the contents are copied onto the case block
// in the if case below for .Body and .Else.
// NOTE: similar to *SwitchStmt.
pushInitBlock(n, &last, &stack)
// TRANS_BLOCK -----------------------
case *IfCaseStmt:
pushRealBlock(n, &last, &stack)
// parent if statement.
ifs := ns[len(ns)-1].(*IfStmt)
// anything declared in ifs are copied.
for _, n := range ifs.GetBlockNames() {
tv := ifs.GetValueRef(nil, n)
last.Define(n, *tv)
}
// TRANS_BLOCK -----------------------
case *RangeStmt:
pushInitBlock(n, &last, &stack)
// NOTE: preprocess it here, so type can
// be used to set n.IsMap/IsString and
// define key/value.
n.X = Preprocess(store, last, n.X).(Expr)
xt := evalStaticTypeOf(store, last, n.X)
switch xt.Kind() {
case MapKind:
n.IsMap = true
case StringKind:
n.IsString = true
case PointerKind:
if xt.Elem().Kind() != ArrayKind {
panic("range iteration over pointer requires array elem type")
}
xt = xt.Elem()
n.IsArrayPtr = true
}
// key value if define.
if n.Op == DEFINE {
if xt.Kind() == MapKind {
if n.Key != nil {
kt := baseOf(xt).(*MapType).Key
kn := n.Key.(*NameExpr).Name
last.Define(kn, anyValue(kt))
}
if n.Value != nil {
vt := baseOf(xt).(*MapType).Value
vn := n.Value.(*NameExpr).Name
last.Define(vn, anyValue(vt))
}
} else if xt.Kind() == StringKind {
if n.Key != nil {
it := IntType
kn := n.Key.(*NameExpr).Name
last.Define(kn, anyValue(it))
}
if n.Value != nil {
et := Int32Type
vn := n.Value.(*NameExpr).Name
last.Define(vn, anyValue(et))
}
} else {
if n.Key != nil {
it := IntType
kn := n.Key.(*NameExpr).Name
last.Define(kn, anyValue(it))
}
if n.Value != nil {
et := xt.Elem()
vn := n.Value.(*NameExpr).Name
last.Define(vn, anyValue(et))
}
}
}
// TRANS_BLOCK -----------------------
case *FuncLitExpr:
// retrieve cached function type.
ft := evalStaticType(store, last, &n.Type).(*FuncType)
// push func body block.
pushInitBlock(n, &last, &stack)
// define parameters in new block.
for _, p := range ft.Params {
last.Define(p.Name, anyValue(p.Type))
}
// define results in new block.
for i, rf := range ft.Results {
if 0 < len(rf.Name) {
last.Define(rf.Name, anyValue(rf.Type))
} else {
// create a hidden var with leading dot.
// NOTE: document somewhere.
rn := fmt.Sprintf(".res_%d", i)
last.Define(Name(rn), anyValue(rf.Type))
}
}
// TRANS_BLOCK -----------------------
case *SelectCaseStmt:
pushInitBlock(n, &last, &stack)
// TRANS_BLOCK -----------------------
case *SwitchStmt:
// create faux block to store .Init/.Varname.
// the contents are copied onto the case block
// in the switch case below for switch cases.
// NOTE: similar to *IfStmt, but with the major
// difference that each clause block may have
// different number of values.
// To support the .Init statement and for
// conceptual simplicity, we create a block in
// OpExec.SwitchStmt, but since we don't initially
// know which clause will match, we expand the
// block once a clause has matched.
pushInitBlock(n, &last, &stack)
if n.VarName != "" {
// NOTE: this defines for default clauses too,
// see comment on block copying @
// SwitchClauseStmt:TRANS_BLOCK.
last.Define(n.VarName, anyValue(nil))
}
// Preprocess and convert tag if const.
if n.X != nil {
n.X = Preprocess(store, last, n.X).(Expr)
convertIfConst(store, last, n.X)
}
// TRANS_BLOCK -----------------------
case *SwitchClauseStmt:
pushRealBlock(n, &last, &stack)
// parent switch statement.
ss := ns[len(ns)-1].(*SwitchStmt)
// anything declared in ss are copied,
// namely ss.VarName if defined.
for _, n := range ss.GetBlockNames() {
tv := ss.GetValueRef(nil, n)
last.Define(n, *tv)
}
if ss.IsTypeSwitch {
if len(n.Cases) == 0 {
// evaulate default case.
if 0 < len(ss.VarName) {
// The type is the tag type.
tt := evalStaticTypeOf(store, last, ss.X)
last.Define(
ss.VarName, anyValue(tt))
}
} else {
// evaluate case types.
for i, cx := range n.Cases {
cx = Preprocess(
store, last, cx).(Expr)
var ct Type
if cxx, ok := cx.(*ConstExpr); ok {
if !cxx.IsUndefined() {
panic("should not happen")
}
// only in type switch cases, nil type allowed.
ct = nil
} else {
ct = evalStaticType(store, last, cx)
}
n.Cases[i] = constType(cx, ct)
// maybe type-switch def.
if 0 < len(ss.VarName) {
if len(n.Cases) == 1 {
// If there is only 1 case, the
// define applies with type.
// (re-definition).
last.Define(
ss.VarName, anyValue(ct))
} else {
// If there are 2 or more
// cases, the type is the tag type.
tt := evalStaticTypeOf(store, last, ss.X)
last.Define(
ss.VarName, anyValue(tt))
}
}
}
}
} else {
// evalualte tag type
tt := evalStaticTypeOf(store, last, ss.X)
// check or convert case types to tt.
for i, cx := range n.Cases {
cx = Preprocess(
store, last, cx).(Expr)
checkOrConvertType(store, last, &cx, tt, false)
n.Cases[i] = cx
}
}
// TRANS_BLOCK -----------------------
case *FuncDecl:
// retrieve cached function type.
ft := getType(&n.Type).(*FuncType)
if n.IsMethod {
// recv/type set @ predefineNow().
} else {
// type set @ predefineNow().
}
// push func body block.
pushInitBlock(n, &last, &stack)
// define receiver in new block, if method.
if n.IsMethod {
if 0 < len(n.Recv.Name) {
rft := getType(&n.Recv).(FieldType)
rt := rft.Type
last.Define(n.Recv.Name, anyValue(rt))
}
}
// define parameters in new block.
for _, p := range ft.Params {
last.Define(p.Name, anyValue(p.Type))
}
// define results in new block.
for i, rf := range ft.Results {
if 0 < len(rf.Name) {
last.Define(rf.Name, anyValue(rf.Type))
} else {
// create a hidden var with leading dot.
rn := fmt.Sprintf(".res_%d", i)
last.Define(Name(rn), anyValue(rf.Type))
}
}
// TRANS_BLOCK -----------------------
case *FileNode:
// only for imports.
pushInitBlock(n, &last, &stack)
{
// This logic supports out-of-order
// declarations. (this must happen
// after pushInitBlock above, otherwise
// it would happen @ *FileNode:ENTER)
// Predefine all import decls.
for i := 0; i < len(n.Decls); i++ {
d := n.Decls[i]
switch d.(type) {
case *ImportDecl:
if d.GetAttribute(ATTR_PREDEFINED) == true {
// skip declarations already
// predefined (e.g. through
// recursion for a dependent)
} else {
// recursively predefine
// dependencies.
d2, _ := predefineNow(store, n, d)
n.Decls[i] = d2
}
}
}
// Predefine all type decls.
for i := 0; i < len(n.Decls); i++ {
d := n.Decls[i]
switch d.(type) {
case *TypeDecl:
if d.GetAttribute(ATTR_PREDEFINED) == true {
// skip declarations already
// predefined (e.g. through
// recursion for a dependent)
} else {
// recursively predefine
// dependencies.
d2, _ := predefineNow(store, n, d)
n.Decls[i] = d2
}
}
}
// Then, predefine all func/method decls.
for i := 0; i < len(n.Decls); i++ {
d := n.Decls[i]
switch d.(type) {
case *FuncDecl:
if d.GetAttribute(ATTR_PREDEFINED) == true {
// skip declarations already
// predefined (e.g. through
// recursion for a dependent)
} else {
// recursively predefine
// dependencies.
d2, _ := predefineNow(store, n, d)
n.Decls[i] = d2
}
}
}
// Finally, predefine other decls and
// preprocess ValueDecls..
for i := 0; i < len(n.Decls); i++ {
d := n.Decls[i]
if d.GetAttribute(ATTR_PREDEFINED) == true {
// skip declarations already
// predefined (e.g. through
// recursion for a dependent)
} else {
// recursively predefine
// dependencies.
d2, _ := predefineNow(store, n, d)
n.Decls[i] = d2
}
}
}
// TRANS_BLOCK -----------------------
default:
panic("should not happen")
}
return n, TRANS_CONTINUE
//----------------------------------------
case TRANS_LEAVE:
// mark as preprocessed so that it can be used
// in evalStaticType(store,).
n.SetAttribute(ATTR_PREPROCESSED, true)
//-There is still work to be done while leaving, but
//once the logic of that is done, we will have to
//perform additionally deferred logic that is best
//handled with orthogonal switch conditions.
//-For example, while leaving nodes w/
//TRANS_COMPOSITE_TYPE, (regardless of whether name or
//literal), any elided type names are inserted. (This
//works because the transcriber leaves the composite
//type before entering the kv elements.)
defer func() {
switch ftype {
// TRANS_LEAVE (deferred)---------
case TRANS_COMPOSITE_TYPE:
// fill elided element composite lit type exprs
clx := ns[len(ns)-1].(*CompositeLitExpr)
// get or evaluate composite type.
clt := evalStaticType(store, last, n.(Expr))
// elide composite lit element (nested) composite types.
elideCompositeElements(clx, clt)
}
}()
// The main TRANS_LEAVE switch.
switch n := n.(type) {
// TRANS_LEAVE -----------------------
case *NameExpr:
// Validity: check that name isn't reserved.
if isReservedName(n.Name) {
panic(fmt.Sprintf(
"should not happen: name %q is reserved", n.Name))
}
// special case if struct composite key.
if ftype == TRANS_COMPOSITE_KEY {
clx := ns[len(ns)-1].(*CompositeLitExpr)
clt := evalStaticType(store, last, clx.Type)
switch bt := baseOf(clt).(type) {
case *StructType:
n.Path = bt.GetPathForName(n.Name)
return n, TRANS_CONTINUE
case *ArrayType, *SliceType:
fillNameExprPath(last, n, false)
if last.GetIsConst(store, n.Name) {
cx := evalConst(store, last, n)
return cx, TRANS_CONTINUE
}
// If name refers to a package, and this is not in
// the context of a selector, fail. Packages cannot
// be used as a value, for go compatibility but also
// to preserve the security expectation regarding imports.
nt := evalStaticTypeOf(store, last, n)
if nt.Kind() == PackageKind {
panic(fmt.Sprintf(
"package %s cannot only be referred to in a selector expression",
n.Name))
}
return n, TRANS_CONTINUE
case *NativeType:
switch bt.Type.Kind() {
case reflect.Struct:
// NOTE: For simplicity and some degree of
// flexibility, do not use path indices for Go
// native types, but use the name.
n.Path = NewValuePathNative(n.Name)
return n, TRANS_CONTINUE
case reflect.Array, reflect.Slice:
// Replace n with *ConstExpr.
fillNameExprPath(last, n, false)
cx := evalConst(store, last, n)
return cx, TRANS_CONTINUE
default:
panic("should not happen")
}
}
}
// specific and general cases
switch n.Name {
case "_":
n.Path = NewValuePathBlock(0, 0, "_")
return n, TRANS_CONTINUE
case "iota":
pd := lastDecl(ns)
io := pd.GetAttribute(ATTR_IOTA).(int)
cx := constUntypedBigint(n, int64(io))
return cx, TRANS_CONTINUE
case "nil":
// nil will be converted to
// typed-nils when appropriate upon
// leaving the expression nodes that
// contain nil nodes.
fallthrough
default:
if ftype == TRANS_ASSIGN_LHS {
as := ns[len(ns)-1].(*AssignStmt)
fillNameExprPath(last, n, as.Op == DEFINE)
} else {
fillNameExprPath(last, n, false)
}
// If uverse, return a *ConstExpr.
if n.Path.Depth == 0 { // uverse
cx := evalConst(store, last, n)
// built-in functions must be called.
if !cx.IsUndefined() &&
cx.T.Kind() == FuncKind &&
ftype != TRANS_CALL_FUNC {
panic(fmt.Sprintf(
"use of builtin %s not in function call",
n.Name))
}
if !cx.IsUndefined() && cx.T.Kind() == TypeKind {
return constType(n, cx.GetType()), TRANS_CONTINUE
}
return cx, TRANS_CONTINUE
}
if last.GetIsConst(store, n.Name) {
cx := evalConst(store, last, n)
return cx, TRANS_CONTINUE
}
// If name refers to a package, and this is not in
// the context of a selector, fail. Packages cannot
// be used as a value, for go compatibility but also
// to preserve the security expectation regarding imports.
nt := evalStaticTypeOf(store, last, n)
if nt == nil {
// this is fine, e.g. for TRANS_ASSIGN_LHS (define) etc.
} else if ftype != TRANS_SELECTOR_X {
nk := nt.Kind()
if nk == PackageKind {
panic(fmt.Sprintf(
"package %s cannot only be referred to in a selector expression",
n.Name))
}
}
}
// TRANS_LEAVE -----------------------
case *BasicLitExpr:
// Replace with *ConstExpr.
cx := evalConst(store, last, n)
return cx, TRANS_CONTINUE
// TRANS_LEAVE -----------------------
case *BinaryExpr:
lt := evalStaticTypeOf(store, last, n.Left)
rt := evalStaticTypeOf(store, last, n.Right)
// Special (recursive) case if shift and right isn't uint.
isShift := n.Op == SHL || n.Op == SHR
if isShift && baseOf(rt) != UintType {
// convert n.Right to (gno) uint type,
rn := Expr(Call("uint", n.Right))
// reset/create n2 to preprocess right child.
n2 := &BinaryExpr{
Left: n.Left,
Op: n.Op,
Right: rn,
}
resn := Preprocess(store, last, n2)
return resn, TRANS_CONTINUE
}
// General case.
lcx, lic := n.Left.(*ConstExpr)
rcx, ric := n.Right.(*ConstExpr)
if lic {
if ric {
// Left const, Right const ----------------------
// Replace with *ConstExpr if const operands.
// First, convert untyped as necessary.
if !isShift {
cmp := cmpSpecificity(lcx.T, rcx.T)
if cmp < 0 {
// convert n.Left to right type.
checkOrConvertType(store, last, &n.Left, rcx.T, false)
} else if cmp == 0 {
// NOTE: the following doesn't work.
// TODO: make it work.
// convert n.Left to right type,
// or check for compatibility.
// (the other way around would work too)
// checkOrConvertType(store, last, n.Left, rcx.T, false)
} else {
checkOrConvertType(store, last, &n.Right, lcx.T, false)
}
}
// Then, evaluate the expression.
cx := evalConst(store, last, n)
return cx, TRANS_CONTINUE
} else if isUntyped(lcx.T) {
// Left untyped const, Right not ----------------
if rnt, ok := rt.(*NativeType); ok {
if isShift {
panic("should not happen")
}
// get concrete native base type.
pt := go2GnoBaseType(rnt.Type).(PrimitiveType)
// convert n.Left to pt type,
checkOrConvertType(store, last, &n.Left, pt, false)
// convert n.Right to (gno) pt type,
rn := Expr(Call(pt.String(), n.Right))
// and convert result back.
tx := constType(n, rnt)
// reset/create n2 to preprocess right child.
n2 := &BinaryExpr{
Left: n.Left,
Op: n.Op,
Right: rn,
}
resn := Node(Call(tx, n2))
resn = Preprocess(store, last, resn)
return resn, TRANS_CONTINUE
// NOTE: binary operations are always computed in
// gno, never with reflect.
} else {
if isShift {
// nothing to do, right type is (already) uint type.
// we don't yet know what this type should be,
// but another checkOrConvertType() later does.
// (e.g. from AssignStmt or other).
} else {
// convert n.Left to right type.
checkOrConvertType(store, last, &n.Left, rt, false)
}
}
} else if lcx.T == nil {
// convert n.Left to typed-nil type.
checkOrConvertType(store, last, &n.Left, rt, false)
}
} else if ric {
if isUntyped(rcx.T) {
// Left not, Right untyped const ----------------
if isShift {
if baseOf(rt) != UintType {
// convert n.Right to (gno) uint type.
checkOrConvertType(store, last, &n.Right, UintType, false)
} else {
// leave n.Left as is and baseOf(n.Right) as UintType.
}
} else {
if lnt, ok := lt.(*NativeType); ok {
// get concrete native base type.
pt := go2GnoBaseType(lnt.Type).(PrimitiveType)
// convert n.Left to (gno) pt type,
ln := Expr(Call(pt.String(), n.Left))
// convert n.Right to pt type,
checkOrConvertType(store, last, &n.Right, pt, false)
// and convert result back.
tx := constType(n, lnt)
// reset/create n2 to preprocess left child.
n2 := &BinaryExpr{
Left: ln,
Op: n.Op,
Right: n.Right,
}
resn := Node(Call(tx, n2))
resn = Preprocess(store, last, resn)
return resn, TRANS_CONTINUE
// NOTE: binary operations are always computed in
// gno, never with reflect.
} else {
// convert n.Right to left type.
checkOrConvertType(store, last, &n.Right, lt, false)
}
}
} else if rcx.T == nil {
// convert n.Right to typed-nil type.
checkOrConvertType(store, last, &n.Right, lt, false)
}
} else {
// Left not const, Right not const ------------------
if n.Op == EQL || n.Op == NEQ {
// If == or !=, no conversions.
} else if lnt, ok := lt.(*NativeType); ok {
if debug {
if !isShift {
assertSameTypes(lt, rt)
}
}
// If left and right are native type,
// convert left and right to gno, then
// convert result back to native.
//
// get concrete native base type.
pt := go2GnoBaseType(lnt.Type).(PrimitiveType)
// convert n.Left to (gno) pt type,
ln := Expr(Call(pt.String(), n.Left))
// convert n.Right to pt or uint type,
rn := n.Right
if isShift {
if baseOf(rt) != UintType {
rn = Expr(Call("uint", n.Right))
}
} else {
rn = Expr(Call(pt.String(), n.Right))
}
// and convert result back.
tx := constType(n, lnt)
// reset/create n2 to preprocess
// children.
n2 := &BinaryExpr{
Left: ln,
Op: n.Op,
Right: rn,
}
resn := Node(Call(tx, n2))
resn = Preprocess(store, last, resn)
return resn, TRANS_CONTINUE
// NOTE: binary operations are always
// computed in gno, never with
// reflect.
} else if n.Op == SHL || n.Op == SHR {
// shift operator, nothing yet to do.
} else {
// non-shift non-const binary operator.
liu, riu := isUntyped(lt), isUntyped(rt)
if liu {
if riu {
if lt.TypeID() != rt.TypeID() {
panic(fmt.Sprintf(
"incompatible types in binary expression: %v %v %v",
n.Left, n.Op, n.Right))
}
} else {
checkOrConvertType(store, last, &n.Left, rt, false)
}
} else {
if riu {
checkOrConvertType(store, last, &n.Right, lt, false)
} else {
if lt.TypeID() != rt.TypeID() {
panic(fmt.Sprintf(
"incompatible types in binary expression: %v %v %v",
n.Left, n.Op, n.Right))
}
}
}
}
}
// TRANS_LEAVE -----------------------
case *CallExpr:
// Func type evaluation.
var ft *FuncType
ift := evalStaticTypeOf(store, last, n.Func)
switch cft := baseOf(ift).(type) {
case *FuncType:
ft = cft
case *NativeType:
ft = store.Go2GnoType(cft.Type).(*FuncType)
case *TypeType:
if len(n.Args) != 1 {
panic("type conversion requires single argument")
}
n.NumArgs = 1
if _, ok := n.Args[0].(*ConstExpr); ok {
convertIfConst(store, last, n.Args[0])
cx := evalConst(store, last, n)
// Though cx may be undefined if ct is interface,
// the ATTR_TYPEOF_VALUE is still interface.
ct := evalStaticType(store, last, n.Func)
cx.SetAttribute(ATTR_TYPEOF_VALUE, ct)
return cx, TRANS_CONTINUE
} else {
ct := evalStaticType(store, last, n.Func)
n.SetAttribute(ATTR_TYPEOF_VALUE, ct)
return n, TRANS_CONTINUE
}
default:
panic(fmt.Sprintf(
"unexpected func type %v (%v)",
ift, reflect.TypeOf(ift)))
}
// Handle special cases.
// NOTE: these appear to be actually special cases in go.
// In general, a string is not assignable to []bytes
// without conversion.
if cx, ok := n.Func.(*ConstExpr); ok {
fv := cx.GetFunc()
if fv.PkgPath == ".uverse" && fv.Name == "append" {
if n.Varg && len(n.Args) == 2 {
// If the second argument is a string,
// convert to byteslice.
args1 := n.Args[1]
if evalStaticTypeOf(store, last, args1).Kind() == StringKind {
bsx := constType(nil, gByteSliceType)
args1 = Call(bsx, args1)
args1 = Preprocess(nil, last, args1).(Expr)
n.Args[1] = args1
}
}
} else if fv.PkgPath == ".uverse" && fv.Name == "copy" {
if len(n.Args) == 2 {
// If the second argument is a string,
// convert to byteslice.
args1 := n.Args[1]
if evalStaticTypeOf(store, last, args1).Kind() == StringKind {
bsx := constType(nil, gByteSliceType)
args1 = Call(bsx, args1)
args1 = Preprocess(nil, last, args1).(Expr)
n.Args[1] = args1
}
}
}
}
// Continue with general case.
hasVarg := ft.HasVarg()