This repository was archived by the owner on Apr 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathexpr.go
2564 lines (2303 loc) · 61.4 KB
/
expr.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
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package eval
import (
"errors"
"fmt"
"go/ast"
"go/token"
"log"
"math/big"
"strconv"
"strings"
)
var (
idealZero = big.NewInt(0)
idealOne = big.NewInt(1)
)
// An expr is the result of compiling an expression. It stores the
// type of the expression and its evaluator function.
type expr struct {
*exprInfo
t Type
// Evaluate this node as the given type.
eval interface{}
// Map index expressions permit special forms of assignment,
// for which we need to know the Map and key.
evalMapValue func(t *Thread) (Map, interface{})
// Evaluate to the "address of" this value; that is, the
// settable Value object. nil for expressions whose address
// cannot be taken.
evalAddr func(t *Thread) Value
// Execute this expression as a statement. Only expressions
// that are valid expression statements should set this.
exec func(t *Thread)
// If this expression is a type, this is its compiled type.
// This is only permitted in the function position of a call
// expression. In this case, t should be nil.
valType Type
// A short string describing this expression for error
// messages.
desc string
}
// exprInfo stores information needed to compile any expression node.
// Each expr also stores its exprInfo so further expressions can be
// compiled from it.
type exprInfo struct {
*compiler
pos token.Pos
}
func (a *exprInfo) newExpr(t Type, desc string) *expr {
return &expr{exprInfo: a, t: t, desc: desc}
}
func (a *exprInfo) diag(format string, args ...interface{}) {
a.diagAt(a.pos, format, args...)
}
func (a *exprInfo) diagOpType(op token.Token, vt Type) {
a.diag("illegal operand type for '%v' operator\n\t%v", op, vt)
}
func (a *exprInfo) diagOpTypes(op token.Token, lt Type, rt Type) {
a.diag("illegal operand types for '%v' operator\n\t%v\n\t%v", op, lt, rt)
}
/*
* Common expression manipulations
*/
// a.convertTo(t) converts the value of the analyzed expression a,
// which must be a constant, ideal number, to a new analyzed
// expression with a constant value of type t.
//
// TODO(austin) Rename to resolveIdeal or something?
func (a *expr) convertTo(t Type) *expr {
if !a.t.isIdeal() {
log.Panicf("attempted to convert from %v, expected ideal", a.t)
}
var rat *big.Rat
// XXX(Spec) The spec says "It is erroneous".
//
// It is an error to assign a value with a non-zero fractional
// part to an integer, or if the assignment would overflow or
// underflow, or in general if the value cannot be represented
// by the type of the variable.
switch a.t {
case IdealFloatType:
rat = a.asIdealFloat()()
if t.isInteger() && !rat.IsInt() {
a.diag("constant %v truncated to integer", rat.FloatString(6))
return nil
}
case IdealIntType:
i := a.asIdealInt()()
rat = new(big.Rat).SetInt(i)
default:
log.Panicf("unexpected ideal type %v", a.t)
}
// Check bounds
if t, ok := t.lit().(BoundedType); ok {
if rat.Cmp(t.minVal()) < 0 {
a.diag("constant %v underflows %v", rat.FloatString(6), t)
return nil
}
if rat.Cmp(t.maxVal()) > 0 {
a.diag("constant %v overflows %v", rat.FloatString(6), t)
return nil
}
}
// Convert rat to type t.
res := a.newExpr(t, a.desc)
switch t := t.lit().(type) {
case *uintType:
n, d := rat.Num(), rat.Denom()
f := new(big.Int).Quo(n, d)
f = f.Abs(f)
v := uint64(f.Int64())
res.eval = func(*Thread) uint64 { return v }
case *intType:
n, d := rat.Num(), rat.Denom()
f := new(big.Int).Quo(n, d)
v := f.Int64()
res.eval = func(*Thread) int64 { return v }
case *idealIntType:
n, d := rat.Num(), rat.Denom()
f := new(big.Int).Quo(n, d)
res.eval = func() *big.Int { return f }
case *floatType:
n, d := rat.Num(), rat.Denom()
v := float64(n.Int64()) / float64(d.Int64())
res.eval = func(*Thread) float64 { return v }
case *idealFloatType:
res.eval = func() *big.Rat { return rat }
default:
log.Panicf("cannot convert to type %T", t)
}
return res
}
// convertToInt converts this expression to an integer, if possible,
// or produces an error if not. This accepts ideal ints, uints, and
// ints. If max is not -1, produces an error if possible if the value
// exceeds max. If negErr is not "", produces an error if possible if
// the value is negative.
func (a *expr) convertToInt(max int64, negErr string, errOp string) *expr {
switch a.t.lit().(type) {
case *idealIntType:
val := a.asIdealInt()()
if negErr != "" && val.Sign() < 0 {
a.diag("negative %s: %s", negErr, val)
return nil
}
bound := max
if negErr == "slice" {
bound++
}
if max != -1 && val.Cmp(big.NewInt(bound)) >= 0 {
a.diag("index %s exceeds length %d", val, max)
return nil
}
return a.convertTo(IntType)
case *uintType:
// Convert to int
na := a.newExpr(IntType, a.desc)
af := a.asUint()
na.eval = func(t *Thread) int64 { return int64(af(t)) }
return na
case *intType:
// Good as is
return a
}
a.diag("illegal operand type for %s\n\t%v", errOp, a.t)
return nil
}
// derefArray returns an expression of array type if the given
// expression is a *array type. Otherwise, returns the given
// expression.
func (a *expr) derefArray() *expr {
if pt, ok := a.t.lit().(*PtrType); ok {
if _, ok := pt.Elem.lit().(*ArrayType); ok {
deref := a.compileStarExpr(a)
if deref == nil {
log.Panicf("failed to dereference *array")
}
return deref
}
}
return a
}
// asValue returns a closure around a Value, according to the
// type of the underlying expression
func (a *expr) asValue() func(t *Thread) Value {
var fct func(t *Thread) Value
switch ty := a.t.lit().(type) {
case *boolType:
fct = func(t *Thread) Value {
b := boolV(a.asBool()(t))
var val Value = &b
return val
}
case *uintType:
v := a.asUint()
switch ty.Bits {
case 0:
switch ty.Ptr {
case true:
fct = func(t *Thread) Value {
vv := uintptrV(v(t))
var val Value = &vv
return val
}
case false:
fct = func(t *Thread) Value {
vv := uintV(v(t))
var val Value = &vv
return val
}
}
case 8:
fct = func(t *Thread) Value {
vv := uint8V(v(t))
return &vv
}
case 16:
fct = func(t *Thread) Value {
vv := uint16V(v(t))
return &vv
}
case 32:
fct = func(t *Thread) Value {
vv := uint32V(v(t))
return &vv
}
case 64:
fct = func(t *Thread) Value {
vv := uint64V(v(t))
return &vv
}
}
case *intType:
v := a.asInt()
switch ty.Bits {
case 0:
fct = func(t *Thread) Value {
vv := intV(v(t))
return &vv
}
case 8:
fct = func(t *Thread) Value {
vv := int8V(v(t))
return &vv
}
case 16:
fct = func(t *Thread) Value {
vv := int16V(v(t))
return &vv
}
case 32:
fct = func(t *Thread) Value {
vv := int32V(v(t))
return &vv
}
case 64:
fct = func(t *Thread) Value {
vv := int64V(v(t))
return &vv
}
}
case *idealIntType:
fct = func(t *Thread) Value {
v := a.asIdealInt()()
vv := idealIntV{v}
return &vv
}
case *floatType:
v := a.asFloat()
switch ty.Bits {
case 32:
fct = func(t *Thread) Value {
vv := float32V(v(t))
return &vv
}
case 64:
fct = func(t *Thread) Value {
vv := float64V(v(t))
return &vv
}
}
case *idealFloatType:
fct = func(t *Thread) Value {
v := a.asIdealFloat()()
vv := idealFloatV{v}
return &vv
}
case *stringType:
fct = func(t *Thread) Value {
v := a.asString()
vv := stringV(v(t))
return &vv
}
case *ArrayType:
fct = func(t *Thread) Value {
v := a.asArray()
vv := v(t).Get(t)
return vv
}
case *StructType:
fct = func(t *Thread) Value {
v := a.asStruct()
vv := v(t).Get(t)
return vv
}
case *PtrType:
fct = func(t *Thread) Value {
return a.asPtr()(t)
}
//case *FuncType:
//case *InterfaceType:
//case *SliceType:
//case *MapType:
//case *ChanType:
//case *NamedType:
//case *MultiType:
case *packageType:
fct = func(t *Thread) Value {
return a.asPackage()(t)
}
default:
a.diag("unhandled type: %v", ty.String())
}
return fct
}
func (a *expr) asPackage() func(*Thread) PackageValue {
return a.eval.(func(*Thread) PackageValue)
}
/*
* Assignments
*/
// An assignCompiler compiles assignment operations. Anything other
// than short declarations should use the compileAssign wrapper.
//
// There are three valid types of assignment:
// 1) T = T
// Assigning a single expression with single-valued type to a
// single-valued type.
// 2) MT = T, T, ...
// Assigning multiple expressions with single-valued types to a
// multi-valued type.
// 3) MT = MT
// Assigning a single expression with multi-valued type to a
// multi-valued type.
type assignCompiler struct {
*compiler
pos token.Pos
// The RHS expressions. This may include nil's for
// expressions that failed to compile.
rs []*expr
// The (possibly unary) MultiType of the RHS.
rmt *MultiType
// Whether this is an unpack assignment (case 3).
isUnpack bool
// Whether map special assignment forms are allowed.
allowMap bool
// Whether this is a "r, ok = a[x]" assignment.
isMapUnpack bool
// The operation name to use in error messages, such as
// "assignment" or "function call".
errOp string
// The name to use for positions in error messages, such as
// "argument".
errPosName string
}
// Type check the RHS of an assignment, returning a new assignCompiler
// and indicating if the type check succeeded. This always returns an
// assignCompiler with rmt set, but if type checking fails, slots in
// the MultiType may be nil. If rs contains nil's, type checking will
// fail and these expressions given a nil type.
func (a *compiler) checkAssign(pos token.Pos, rs []*expr, errOp, errPosName string) (*assignCompiler, bool) {
c := &assignCompiler{
compiler: a,
pos: pos,
rs: rs,
errOp: errOp,
errPosName: errPosName,
}
// Is this an unpack?
if len(rs) == 1 && rs[0] != nil {
if rmt, isUnpack := rs[0].t.(*MultiType); isUnpack {
c.rmt = rmt
c.isUnpack = true
return c, true
}
}
// Create MultiType for RHS and check that all RHS expressions
// are single-valued.
rts := make([]Type, len(rs))
ok := true
for i, r := range rs {
if r == nil {
ok = false
continue
}
if _, isMT := r.t.(*MultiType); isMT {
r.diag("multi-valued expression not allowed in %s", errOp)
ok = false
continue
}
rts[i] = r.t
}
c.rmt = NewMultiType(rts)
return c, ok
}
func (a *assignCompiler) allowMapForms(nls int) {
a.allowMap = true
// Update unpacking info if this is r, ok = a[x]
if nls == 2 && len(a.rs) == 1 && a.rs[0] != nil && a.rs[0].evalMapValue != nil {
a.isUnpack = true
a.rmt = NewMultiType([]Type{a.rs[0].t, BoolType})
a.isMapUnpack = true
}
}
// compile type checks and compiles an assignment operation, returning
// a function that expects an l-value and the frame in which to
// evaluate the RHS expressions. The l-value must have exactly the
// type given by lt. Returns nil if type checking fails.
func (a *assignCompiler) compile(b *block, lt Type) func(Value, *Thread) {
lmt, isMT := lt.(*MultiType)
rmt, isUnpack := a.rmt, a.isUnpack
// Create unary MultiType for single LHS
if !isMT {
lmt = NewMultiType([]Type{lt})
}
// Check that the assignment count matches
lcount := len(lmt.Elems)
rcount := len(rmt.Elems)
if lcount != rcount {
msg := "not enough"
pos := a.pos
if rcount > lcount {
msg = "too many"
if lcount > 0 {
pos = a.rs[lcount-1].pos
}
}
a.diagAt(pos, "%s %ss for %s\n\t%s\n\t%s", msg, a.errPosName, a.errOp, lt, rmt)
return nil
}
bad := false
// If this is an unpack, create a temporary to store the
// multi-value and replace the RHS with expressions to pull
// out values from the temporary. Technically, this is only
// necessary when we need to perform assignment conversions.
var effect func(*Thread)
if isUnpack {
// This leaks a slot, but is definitely safe.
temp := b.DefineTemp(a.rmt)
tempIdx := temp.Index
if tempIdx < 0 {
panic(fmt.Sprintln("tempidx", tempIdx))
}
if a.isMapUnpack {
rf := a.rs[0].evalMapValue
vt := a.rmt.Elems[0]
effect = func(t *Thread) {
m, k := rf(t)
v := m.Elem(t, k)
found := boolV(true)
if v == nil {
found = boolV(false)
v = vt.Zero()
}
t.f.Vars[tempIdx] = multiV([]Value{v, &found})
}
} else {
rf := a.rs[0].asMulti()
effect = func(t *Thread) { t.f.Vars[tempIdx] = multiV(rf(t)) }
}
orig := a.rs[0]
a.rs = make([]*expr, len(a.rmt.Elems))
for i, t := range a.rmt.Elems {
if t.isIdeal() {
log.Panicf("Right side of unpack contains ideal: %s", rmt)
}
a.rs[i] = orig.newExpr(t, orig.desc)
index := i
a.rs[i].genValue(func(t *Thread) Value { return t.f.Vars[tempIdx].(multiV)[index] })
}
}
// Now len(a.rs) == len(a.rmt) and we've reduced any unpacking
// to multi-assignment.
// TODO(austin) Deal with assignment special cases.
// Values of any type may always be assigned to variables of
// compatible static type.
for i, lt := range lmt.Elems {
rt := rmt.Elems[i]
// When [an ideal is] (used in an expression) assigned
// to a variable or typed constant, the destination
// must be able to represent the assigned value.
if rt.isIdeal() {
a.rs[i] = a.rs[i].convertTo(lmt.Elems[i])
if a.rs[i] == nil {
bad = true
continue
}
rt = a.rs[i].t
}
// A pointer p to an array can be assigned to a slice
// variable v with compatible element type if the type
// of p or v is unnamed.
if rpt, ok := rt.lit().(*PtrType); ok {
if at, ok := rpt.Elem.lit().(*ArrayType); ok {
if lst, ok := lt.lit().(*SliceType); ok {
if lst.Elem.compat(at.Elem, false) && (rt.lit() == Type(rt) || lt.lit() == Type(lt)) {
rf := a.rs[i].asPtr()
a.rs[i] = a.rs[i].newExpr(lt, a.rs[i].desc)
len := at.Len
a.rs[i].eval = func(t *Thread) Slice { return Slice{rf(t).(ArrayValue), len, len} }
rt = a.rs[i].t
}
}
}
}
if !lt.compat(rt, false) {
if len(a.rs) == 1 {
a.rs[0].diag("illegal operand types for %s\n\t%v\n\t%v", a.errOp, lt, rt)
} else {
a.rs[i].diag("illegal operand types in %s %d of %s\n\t%v\n\t%v", a.errPosName, i+1, a.errOp, lt, rt)
}
bad = true
}
}
if bad {
return nil
}
// Compile
if !isMT {
// Case 1
return genAssign(lt, a.rs[0])
}
// Case 2 or 3
as := make([]func(lv Value, t *Thread), len(a.rs))
for i, r := range a.rs {
as[i] = genAssign(lmt.Elems[i], r)
}
return func(lv Value, t *Thread) {
if effect != nil {
effect(t)
}
lmv := lv.(multiV)
for i, a := range as {
a(lmv[i], t)
}
}
}
// compileAssign compiles an assignment operation without the full
// generality of an assignCompiler. See assignCompiler for a
// description of the arguments.
func (a *compiler) compileAssign(pos token.Pos, b *block, lt Type, rs []*expr, errOp, errPosName string) func(Value, *Thread) {
ac, ok := a.checkAssign(pos, rs, errOp, errPosName)
if !ok {
return nil
}
return ac.compile(b, lt)
}
/*
* Expression compiler
*/
// An exprCompiler stores information used throughout the compilation
// of a single expression. It does not embed funcCompiler because
// expressions can appear at top level.
type exprCompiler struct {
*compiler
// The block this expression is being compiled in.
block *block
// Whether this expression is used in a constant context.
constant bool
}
// compile compiles an expression AST. callCtx should be true if this
// AST is in the function position of a function call node; it allows
// the returned expression to be a type or a built-in function (which
// otherwise result in errors).
func (a *exprCompiler) compile(x ast.Expr, callCtx bool) *expr {
ei := &exprInfo{a.compiler, x.Pos()}
switch x := x.(type) {
// Literals
case *ast.BasicLit:
switch x.Kind {
case token.INT:
return ei.compileIntLit(string(x.Value))
case token.FLOAT:
return ei.compileFloatLit(string(x.Value))
case token.CHAR:
return ei.compileCharLit(string(x.Value))
case token.STRING:
return ei.compileStringLit(string(x.Value))
default:
log.Panicf("unexpected basic literal type %v", x.Kind)
}
case *ast.CompositeLit:
var ty *expr
if x.Type != nil {
// special case for array literal: [...]T{x,y,z}
// we only know the number of elements here, so create the array type
// just now.
switch xt := x.Type.(type) {
case *ast.ArrayType:
if _, ok := xt.Len.(*ast.Ellipsis); ok {
elmt_ty := a.compileType(a.block, xt.Elt)
ty = ei.exprFromType(NewArrayType(int64(len(x.Elts)), elmt_ty))
} else {
ty = a.compile(x.Type, true)
}
default:
ty = a.compile(x.Type, true)
}
}
keys := make([]interface{}, 0, len(x.Elts))
vals := make([]*expr, len(x.Elts))
for i := range x.Elts {
switch x.Elts[i].(type) {
case *ast.KeyValueExpr:
kv := x.Elts[i].(*ast.KeyValueExpr)
switch kk := kv.Key.(type) {
case *ast.Ident:
switch x.Type.(type) {
case *ast.Ident:
keys = append(keys, kk.Name)
default:
keys = append(keys, a.compile(kv.Key, callCtx))
}
default:
ekey := a.compile(kv.Key, callCtx)
keys = append(keys, ekey)
}
vals[i] = a.compile(kv.Value, callCtx)
default:
vals[i] = a.compile(x.Elts[i], callCtx)
}
}
return ei.compileCompositeLit(ty, keys, vals)
case *ast.FuncLit:
decl := ei.compileFuncType(a.block, x.Type)
if decl == nil {
// TODO(austin) Try compiling the body,
// perhaps with dummy argument definitions
return nil
}
fn := ei.compileFunc(a.block, decl, x.Body)
if fn == nil {
return nil
}
if a.constant {
a.diagAt(x.Pos(), "function literal used in constant expression")
return nil
}
return ei.compileFuncLit(decl, fn)
// Types
case *ast.ArrayType:
switch x.Len.(type) {
case *ast.Ellipsis:
a.diagAt(x.Pos(), "array literal with ellipsis is not implemented")
return nil
default:
// TODO(austin) Use a multi-type case
goto typeexpr
}
case *ast.ChanType:
goto typeexpr
case *ast.Ellipsis:
goto typeexpr
case *ast.FuncType:
goto typeexpr
case *ast.InterfaceType:
goto typeexpr
case *ast.MapType:
goto typeexpr
// Remaining expressions
case *ast.BadExpr:
// Error already reported by parser
a.silentErrors++
return nil
case *ast.BinaryExpr:
l, r := a.compile(x.X, false), a.compile(x.Y, false)
if l == nil || r == nil {
return nil
}
return ei.compileBinaryExpr(x.Op, l, r)
case *ast.CallExpr:
l := a.compile(x.Fun, true)
args := make([]*expr, len(x.Args))
bad := false
for i, arg := range x.Args {
if i == 0 && l != nil && (l.t == Type(makeType) || l.t == Type(newType)) {
argei := &exprInfo{a.compiler, arg.Pos()}
args[i] = argei.exprFromType(a.compileType(a.block, arg))
} else {
args[i] = a.compile(arg, false)
}
if args[i] == nil {
bad = true
}
}
if bad || l == nil {
return nil
}
if a.constant {
a.diagAt(x.Pos(), "function call in constant context")
return nil
}
if l.valType != nil {
a.diagAt(x.Pos(), "type conversions not implemented")
return nil
} else if ft, ok := l.t.(*FuncType); ok && ft.builtin != "" {
return ei.compileBuiltinCallExpr(a.block, ft, args)
} else {
return ei.compileCallExpr(a.block, l, args)
}
case *ast.Ident:
return ei.compileIdent(a.block, a.constant, callCtx, x.Name)
case *ast.IndexExpr:
l, r := a.compile(x.X, false), a.compile(x.Index, false)
if l == nil || r == nil {
return nil
}
return ei.compileIndexExpr(l, r)
case *ast.SliceExpr:
var lo, hi *expr
arr := a.compile(x.X, false)
if x.Low == nil {
// beginning was omitted, so we need to provide it
ei := &exprInfo{a.compiler, x.Pos()}
lo = ei.compileIntLit("0")
} else {
lo = a.compile(x.Low, false)
}
if x.High == nil {
// End was omitted, so we need to compute len(x.X)
ei := &exprInfo{a.compiler, x.Pos()}
hi = ei.compileBuiltinCallExpr(a.block, lenType, []*expr{arr})
} else {
hi = a.compile(x.High, false)
}
if arr == nil || lo == nil || hi == nil {
return nil
}
return ei.compileSliceExpr(arr, lo, hi)
case *ast.KeyValueExpr:
var key, val *expr
key = a.compile(x.Key, true)
val = a.compile(x.Value, true)
if key == nil {
a.diagAt(x.Key.Pos(), "could not compile 'key' expression")
return nil
}
if val == nil {
a.diagAt(x.Value.Pos(), "could not compile 'value' expression")
return nil
}
e := ei.compileKeyValueExpr(key, val)
return e
case *ast.ParenExpr:
return a.compile(x.X, callCtx)
case *ast.SelectorExpr:
v := a.compile(x.X, false)
if v == nil {
return nil
}
return ei.compileSelectorExpr(v, x.Sel.Name)
case *ast.StarExpr:
// We pass down our call context because this could be
// a pointer type (and thus a type conversion)
v := a.compile(x.X, callCtx)
if v == nil {
return nil
}
if v.valType != nil {
// Turns out this was a pointer type, not a dereference
return ei.exprFromType(NewPtrType(v.valType))
}
return ei.compileStarExpr(v)
case *ast.StructType:
goto notimpl
case *ast.TypeAssertExpr:
goto notimpl
case *ast.UnaryExpr:
v := a.compile(x.X, false)
if v == nil {
return nil
}
return ei.compileUnaryExpr(x.Op, v)
}
log.Panicf("unexpected ast node type %T", x)
panic("unreachable")
typeexpr:
if !callCtx {
a.diagAt(x.Pos(), "type used as expression")
return nil
}
return ei.exprFromType(a.compileType(a.block, x))
notimpl:
a.diagAt(x.Pos(), "%T expression node not implemented", x)
return nil
}
func (a *exprInfo) exprFromType(t Type) *expr {
if t == nil {
return nil
}
expr := a.newExpr(nil, "type")
expr.valType = t
return expr
}
func (a *exprInfo) compileIdent(b *block, constant bool, callCtx bool, name string) *expr {
bl, level, def := b.Lookup(name)
if def == nil {
a.diag("%s: undefined", name)
return nil
}
switch def := def.(type) {
case *Constant:
expr := a.newExpr(def.Type, "constant")
if ft, ok := def.Type.(*FuncType); ok && ft.builtin != "" {
// XXX(Spec) I don't think anything says that
// built-in functions can't be used as values.
if !callCtx {
a.diag("built-in function %s cannot be used as a value", ft.builtin)
return nil
}
// Otherwise, we leave the evaluators empty
// because this is handled specially
} else {
expr.genConstant(def.Value)
}
return expr
case *Variable:
if constant {
a.diag("variable %s used in constant expression", name)
return nil
}
if bl.global {
return a.compileGlobalVariable(def)
}
return a.compileVariable(level, def)
case Type:
if callCtx {
return a.exprFromType(def)
}
a.diag("type %v used as expression", name)
return nil
case *PkgIdent:
return a.compilePackageImport(name, def, constant, true)
}
log.Panicf("name %s has unknown type %T", name, def)
panic("unreachable")
}
func (a *exprInfo) compileVariable(level int, v *Variable) *expr {
if v.Type == nil {
// Placeholder definition from an earlier error
a.silentErrors++
return nil
}
expr := a.newExpr(v.Type, "variable")
expr.genIdentOp(level, v.Index)
return expr
}
func (a *exprInfo) compileGlobalVariable(v *Variable) *expr {
if v.Type == nil {
// Placeholder definition from an earlier error
a.silentErrors++
return nil
}
if v.Init == nil {
v.Init = v.Type.Zero()
}
expr := a.newExpr(v.Type, "variable")
val := v.Init
expr.genValue(func(t *Thread) Value { return val })
return expr
}
func (a *exprInfo) compileIdealInt(i *big.Int, desc string) *expr {
expr := a.newExpr(IdealIntType, desc)
expr.eval = func() *big.Int { return i }
return expr
}
func (a *exprInfo) compileIntLit(lit string) *expr {
i, _ := new(big.Int).SetString(lit, 0)
return a.compileIdealInt(i, "integer literal")
}
func (a *exprInfo) compileCharLit(lit string) *expr {
if lit[0] != '\'' {
// Caught by parser
a.silentErrors++
return nil
}
v, _, tail, err := strconv.UnquoteChar(lit[1:], '\'')
if err != nil || tail != "'" {
// Caught by parser
a.silentErrors++
return nil
}
return a.compileIdealInt(big.NewInt(int64(v)), "character literal")
}
func (a *exprInfo) compileFloatLit(lit string) *expr {
f, ok := new(big.Rat).SetString(lit)
if !ok {
log.Panicf("malformed float literal %s at %v passed parser", lit, a.pos)
}
expr := a.newExpr(IdealFloatType, "float literal")
expr.eval = func() *big.Rat { return f }
return expr
}
func (a *exprInfo) compileString(s string) *expr {
// Ideal strings don't have a named type but they are
// compatible with type string.
// TODO(austin) Use unnamed string type.
expr := a.newExpr(StringType, "string literal")
expr.eval = func(*Thread) string { return s }
return expr