forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 1
/
preprocess.go
2934 lines (2816 loc) · 79.3 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"
)
// 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 {
if ctx == nil {
panic("Preprocess requires context")
}
// create stack of BlockNodes.
var stack []BlockNode = make([]BlockNode, 0, 32)
var last BlockNode = ctx
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 {
for i, sbn := range stack {
fmt.Printf("stack #%d: %s\n", i, sbn.String())
}
panic(r)
}
}()
if debug {
debug.Printf("Transcribe %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 = "_"
}
}
}
// TRANS_ENTER -----------------------
return n, TRANS_CONTINUE
//----------------------------------------
case TRANS_BLOCK:
switch n := n.(type) {
// TRANS_BLOCK -----------------------
case *BlockStmt:
pushBlock(n, &last, &stack)
// TRANS_BLOCK -----------------------
case *ForStmt:
pushBlock(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.
pushBlock(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:
pushBlock(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.
pushBlock(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:
pushBlock(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.
pushBlock(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 {
// 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)
n.Cases[i] = cx
checkOrConvertType(store, last, cx, tt)
}
}
// 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.
pushBlock(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.
pushBlock(n, &last, &stack)
{
// This logic supports out-of-order
// declarations. this is required
// separately from the direct
// predefineNow() entry callbacks above,
// for otherwise out-of-order
// declarations would not get pre-defined
// before (say) the body of a function
// declaration or literl can refer to it.
// (this must happen after pushBlock
// above, otherwise it would happen @
// *FileNode:ENTER)
// Predefine all type decls and import decls.
for i := 0; i < len(n.Decls); i++ {
d := n.Decls[i]
switch d.(type) {
case *ImportDecl, *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:
// 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:
// Replace n with *constExpr.
fillNameExprPath(last, n)
cv := evalConst(store, last, n)
return cv, 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)
cv := evalConst(store, last, n)
return cv, 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:
fillNameExprPath(last, n)
// If uverse, return a *constExpr.
if n.Path.Depth == 0 { // uverse
cv := evalConst(store, last, n)
// built-in functions must be called.
if !cv.IsUndefined() &&
cv.T.Kind() == FuncKind &&
ftype != TRANS_CALL_FUNC {
panic(fmt.Sprintf(
"use of builtin %s not in function call",
n.Name))
}
if !cv.IsUndefined() && cv.T.Kind() == TypeKind {
return constType(n, cv.GetType()), TRANS_CONTINUE
}
return cv, TRANS_CONTINUE
}
// If untyped const, return it as *constExpr.
nt := evalStaticTypeOf(store, last, n)
if isUntyped(nt) {
cx := evalConst(store, last, n)
return cx, TRANS_CONTINUE
}
}
// TRANS_LEAVE -----------------------
case *BasicLitExpr:
// Replace with *constExpr.
cv := evalConst(store, last, n)
return cv, 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.
cv := evalConst(store, last, n)
return cv, 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)
// 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.
} else {
// convert n.Left to right type.
checkOrConvertType(store, last, n.Left, rt)
}
}
} else if lcx.T == nil {
// convert n.Left to typed-nil type.
checkOrConvertType(store, last, n.Left, rt)
}
} 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)
} 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)
// 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)
}
}
} else if rcx.T == nil {
// convert n.Right to typed-nil type.
checkOrConvertType(store, last, n.Right, lt)
}
} 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 {
// nothing to do.
}
}
// 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 = go2GnoFuncType(cft.Type)
case *TypeType:
if len(n.Args) != 1 {
panic("type conversion requires single argument")
}
if _, ok := n.Args[0].(*constExpr); ok {
convertIfConst(store, last, n.Args[0])
cv := evalConst(store, last, n)
return cv, 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)))
}
hasVarg := ft.HasVarg()
isVarg := n.Varg
embedded := false
argTVs := []TypedValue{}
minArgs := len(ft.Params)
if hasVarg {
minArgs--
}
numArgs := countNumArgs(store, last, n) // isVarg?
n.NumArgs = numArgs
// Check input arg count.
if len(n.Args) == 1 && numArgs > 1 {
// special case of x(f()) form:
// use the number of results instead.
if isVarg {
panic("should not happen")
}
embedded = true
pcx := n.Args[0].(*CallExpr)
argTVs = getResultTypedValues(pcx)
if !hasVarg {
if numArgs != len(ft.Params) {
panic(fmt.Sprintf(
"wrong argument count in call to %s; want %d got %d (with embedded call expr as arg)",
n.Func.String(),
len(ft.Params),
numArgs,
))
}
} else if hasVarg && !isVarg {
if numArgs < len(ft.Params)-1 {
panic(fmt.Sprintf(
"not enough arguments in call to %s; want %d (besides variadic) got %d (with embedded call expr as arg)",
n.Func.String(),
len(ft.Params)-1,
numArgs))
}
}
} else if !hasVarg {
argTVs = evalStaticTypedValues(store, last, n.Args...)
if len(n.Args) != len(ft.Params) {
panic(fmt.Sprintf(
"wrong argument count in call to %s; want %d got %d",
n.Func.String(),
len(ft.Params),
len(n.Args),
))
}
} else if hasVarg && !isVarg {
argTVs = evalStaticTypedValues(store, last, n.Args...)
if len(n.Args) < len(ft.Params)-1 {
panic(fmt.Sprintf(
"not enough arguments in call to %s; want %d (besides variadic) got %d",
n.Func.String(),
len(ft.Params)-1,
len(n.Args)))
}
} else if hasVarg && isVarg {
argTVs = evalStaticTypedValues(store, last, n.Args...)
if len(n.Args) != len(ft.Params) {
panic(fmt.Sprintf(
"not enough arguments in call to %s; want %d (including variadic) got %d",
n.Func.String(),
len(ft.Params),
len(n.Args)))
}
} else {
panic("should not happen")
}
// Specify function param/result generics.
sft := ft.Specify(argTVs, isVarg)
spts := sft.Params
srts := FieldTypeList(sft.Results).Types()
n.SetAttribute(ATTR_TYPEOF_VALUE,
&tupleType{Elts: srts})
// Replace const Args with *constExpr.
if !embedded {
for i, arg := range n.Args {
if hasVarg {
if (len(spts) - 1) <= i {
if isVarg {
if len(spts) <= i {
panic("expected final vargs slice but got many")
}
checkOrConvertType(store, last, arg, spts[i].Type)
} else {
checkOrConvertType(store, last, arg,
spts[len(spts)-1].Type.Elem())
}
} else {
checkOrConvertType(store, last, arg, spts[i].Type)
}
} else {
checkOrConvertType(store, last, arg, spts[i].Type)
}
}
}
// TODO in the future, pure results
// TRANS_LEAVE -----------------------
case *IndexExpr:
dt := evalStaticTypeOf(store, last, n.X)
if dt.Kind() == PointerKind {
// if a is a pointer to an array,
// a[low : high : max] is shorthand
// for (*a)[low : high : max]
dt = dt.Elem()
n.X = &StarExpr{X: n.X}
n.X.SetAttribute(ATTR_PREPROCESSED, true)
}
switch dt.Kind() {
case StringKind, ArrayKind, SliceKind:
// Replace const index with int *constExpr,
// or if not const, assert integer type..
checkOrConvertIntegerType(store, last, n.Index)
case MapKind:
mt := baseOf(gnoTypeOf(dt)).(*MapType)
checkOrConvertType(store, last, n.Index, mt.Key)
default:
panic(fmt.Sprintf(
"unexpected index base kind for type %s",
dt.String()))
}
// TRANS_LEAVE -----------------------
case *SliceExpr:
// Replace const L/H/M with int *constExpr,
// or if not const, assert integer type..
checkOrConvertIntegerType(store, last, n.Low)
checkOrConvertIntegerType(store, last, n.High)
checkOrConvertIntegerType(store, last, n.Max)
// TRANS_LEAVE -----------------------
case *TypeAssertExpr:
if n.Type == nil {
panic("should not happen")
}
// ExprStmt of form `x.(<type>)`,
// or special case form `c, ok := x.(<type>)`.
evalStaticType(store, last, n.Type)
// TRANS_LEAVE -----------------------
case *UnaryExpr:
xt := evalStaticTypeOf(store, last, n.X)
if xnt, ok := xt.(*nativeType); ok {
// get concrete native base type.
pt := go2GnoBaseType(xnt.Type).(PrimitiveType)
// convert n.X to gno type,
xn := Expr(Call(pt.String(), n.X))
// and convert result back.
tx := constType(n, xnt)
// reset/create n2 to preprocess children.
n2 := &UnaryExpr{
X: xn,
Op: n.Op,
}
resn := Node(Call(tx, n2))
resn = Preprocess(store, last, resn)
return resn, TRANS_CONTINUE
// NOTE: like binary operations, unary operations are
// always computed in gno, never with reflect.
}
// Replace with *constExpr if const X.
if isConst(n.X) {
cv := evalConst(store, last, n)
return cv, TRANS_CONTINUE
}
// TRANS_LEAVE -----------------------
case *CompositeLitExpr:
// Get or evaluate composite type.
clt := evalStaticType(store, last, n.Type)
// Replace const Elts with default *constExpr.
CLT_TYPE_SWITCH:
switch cclt := baseOf(clt).(type) {
case *StructType:
if n.IsKeyed() {
for i := 0; i < len(n.Elts); i++ {
key := n.Elts[i].Key.(*NameExpr).Name
path := cclt.GetPathForName(key)
ft := cclt.GetStaticTypeOfAt(path)
checkOrConvertType(store, last, n.Elts[i].Value, ft)
}
} else {
for i := 0; i < len(n.Elts); i++ {
ft := cclt.Fields[i].Type
checkOrConvertType(store, last, n.Elts[i].Value, ft)
}
}
case *ArrayType:
for i := 0; i < len(n.Elts); i++ {
checkOrConvertType(store, last, n.Elts[i].Key, IntType)
checkOrConvertType(store, last, n.Elts[i].Value, cclt.Elt)
}
case *SliceType:
for i := 0; i < len(n.Elts); i++ {
checkOrConvertType(store, last, n.Elts[i].Key, IntType)
checkOrConvertType(store, last, n.Elts[i].Value, cclt.Elt)
}
case *MapType:
for i := 0; i < len(n.Elts); i++ {
checkOrConvertType(store, last, n.Elts[i].Key, cclt.Key)
checkOrConvertType(store, last, n.Elts[i].Value, cclt.Value)
}
case *nativeType:
clt = cclt.GnoType()
goto CLT_TYPE_SWITCH
default:
panic(fmt.Sprintf(
"unexpected composite type %s",
clt.String()))
}
// If variadic array lit, measure.
if at, ok := clt.(*ArrayType); ok {
if at.Vrd {
idx := 0
for _, elt := range n.Elts {
if elt.Key == nil {
idx++
} else {
// XXX why convert?
k := evalConst(store, last, elt.Key).ConvertGetInt()
if idx <= k {
idx = k + 1
} else {
panic("array lit key out of order")
}
}
}
// update type
// (dontcare)
// at.Vrd = false
at.Len = idx
// update node
cx := constInt(n, idx)
n.Type.(*ArrayTypeExpr).Len = cx
}
}
// TRANS_LEAVE -----------------------
case *KeyValueExpr:
// NOTE: For simplicity we just
// use the *CompositeLitExpr.
// TRANS_LEAVE -----------------------
case *SelectorExpr:
xt := evalStaticTypeOf(store, last, n.X)
// Set selector path based on xt's type.
switch cxt := xt.(type) {
case *PointerType, *DeclaredType, *StructType, *InterfaceType:
tr, _, rcvr, _ := findEmbeddedFieldType(cxt, n.Sel)
if tr == nil {
panic(fmt.Sprintf("missing field %s in %s", n.Sel,
cxt.String()))
}
if len(tr) > 1 {
// (the last vp, tr[len(tr)-1], is for n.Sel)
if debug {
if tr[len(tr)-1].Name != n.Sel {
panic("should not happen")
}
}
// replace n.X w/ tr[:len-1] selectors applied.
nx2 := n.X
for _, vp := range tr[:len(tr)-1] {
nx2 = &SelectorExpr{
X: nx2,
Path: vp,
Sel: vp.Name,
}
}
// recursively preprocess new n.X.
n.X = Preprocess(store, last, nx2).(Expr)
}
// nxt2 may not be xt anymore.
// (even the dereferenced of xt and nxt2 may not
// be the same, with embedded fields)
nxt2 := evalStaticTypeOf(store, last, n.X)
// Case 1: If receiver is pointer type but n.X is
// not:
if rcvr != nil &&
rcvr.Kind() == PointerKind &&
nxt2.Kind() != PointerKind {