This repository has been archived by the owner on Apr 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
stmt.go
1407 lines (1221 loc) · 32 KB
/
stmt.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.
// go/importer is only available in go1.6 and later
// +build go1.6
package eval
import (
"go/ast"
"go/build"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
"math/big"
"path/filepath"
"strconv"
)
const (
returnPC = ^uint(0)
badPC = ^uint(1)
)
// default importer of packages
var g_importer types.Importer = importer.Default()
/*
* Statement compiler
*/
type stmtCompiler struct {
*blockCompiler
pos token.Pos
// This statement's label, or nil if it is not labeled.
stmtLabel *label
}
func (a *stmtCompiler) diag(format string, args ...interface{}) {
a.diagAt(a.pos, format, args...)
}
/*
* Flow checker
*/
type flowEnt struct {
// Whether this flow entry is conditional. If true, flow can
// continue to the next PC.
cond bool
// True if this will terminate flow (e.g., a return statement).
// cond must be false and jumps must be nil if this is true.
term bool
// PC's that can be reached from this flow entry.
jumps []*uint
// Whether this flow entry has been visited by reachesEnd.
visited bool
}
type flowBlock struct {
// If this is a goto, the target label.
target string
// The inner-most block containing definitions.
block *block
// The numVars from each block leading to the root of the
// scope, starting at block.
numVars []int
}
type flowBuf struct {
cb *codeBuf
// ents is a map from PC's to flow entries. Any PC missing
// from this map is assumed to reach only PC+1.
ents map[uint]*flowEnt
// gotos is a map from goto positions to information on the
// block at the point of the goto.
gotos map[token.Pos]*flowBlock
// labels is a map from label name to information on the block
// at the point of the label. labels are tracked by name,
// since multiple labels at the same PC can have different
// blocks.
labels map[string]*flowBlock
}
func newFlowBuf(cb *codeBuf) *flowBuf {
return &flowBuf{cb, make(map[uint]*flowEnt), make(map[token.Pos]*flowBlock), make(map[string]*flowBlock)}
}
// put creates a flow control point for the next PC in the code buffer.
// This should be done before pushing the instruction into the code buffer.
func (f *flowBuf) put(cond bool, term bool, jumps []*uint) {
pc := f.cb.nextPC()
if ent, ok := f.ents[pc]; ok {
log.Panicf("Flow entry already exists at PC %d: %+v", pc, ent)
}
f.ents[pc] = &flowEnt{cond, term, jumps, false}
}
// putTerm creates a flow control point at the next PC that
// unconditionally terminates execution.
func (f *flowBuf) putTerm() { f.put(false, true, nil) }
// put1 creates a flow control point at the next PC that jumps to one
// PC and, if cond is true, can also continue to the PC following the
// next PC.
func (f *flowBuf) put1(cond bool, jumpPC *uint) {
f.put(cond, false, []*uint{jumpPC})
}
func newFlowBlock(target string, b *block) *flowBlock {
// Find the inner-most block containing definitions
for b.numVars == 0 && b.outer != nil && b.outer.scope == b.scope {
b = b.outer
}
// Count parents leading to the root of the scope
n := 0
for bp := b; bp.scope == b.scope; bp = bp.outer {
n++
}
// Capture numVars from each block to the root of the scope
numVars := make([]int, n)
i := 0
for bp := b; i < n; bp = bp.outer {
numVars[i] = bp.numVars
i++
}
return &flowBlock{target, b, numVars}
}
// putGoto captures the block at a goto statement. This should be
// called in addition to putting a flow control point.
func (f *flowBuf) putGoto(pos token.Pos, target string, b *block) {
f.gotos[pos] = newFlowBlock(target, b)
}
// putLabel captures the block at a label.
func (f *flowBuf) putLabel(name string, b *block) {
f.labels[name] = newFlowBlock("", b)
}
// reachesEnd returns true if the end of f's code buffer can be
// reached from the given program counter. Error reporting is the
// caller's responsibility.
func (f *flowBuf) reachesEnd(pc uint) bool {
endPC := f.cb.nextPC()
if pc > endPC {
log.Panicf("Reached bad PC %d past end PC %d", pc, endPC)
}
for ; pc < endPC; pc++ {
ent, ok := f.ents[pc]
if !ok {
continue
}
if ent.visited {
return false
}
ent.visited = true
if ent.term {
return false
}
// If anything can reach the end, we can reach the end
// from pc.
for _, j := range ent.jumps {
if f.reachesEnd(*j) {
return true
}
}
// If the jump was conditional, we can reach the next
// PC, so try reaching the end from it.
if ent.cond {
continue
}
return false
}
return true
}
// gotosObeyScopes returns true if no goto statement causes any
// variables to come into scope that were not in scope at the point of
// the goto. Reports any errors using the given compiler.
func (f *flowBuf) gotosObeyScopes(a *compiler) {
for pos, src := range f.gotos {
tgt := f.labels[src.target]
// The target block must be a parent of this block
numVars := src.numVars
b := src.block
for len(numVars) > 0 && b != tgt.block {
b = b.outer
numVars = numVars[1:]
}
if b != tgt.block {
// We jumped into a deeper block
a.diagAt(pos, "goto causes variables to come into scope")
return
}
// There must be no variables in the target block that
// did not exist at the jump
tgtNumVars := tgt.numVars
for i := range numVars {
if tgtNumVars[i] > numVars[i] {
a.diagAt(pos, "goto causes variables to come into scope")
return
}
}
}
}
/*
* Statement generation helpers
*/
func (a *stmtCompiler) defineVar(ident *ast.Ident, t Type) *Variable {
v, prev := a.block.DefineVar(ident.Name, ident.Pos(), t)
if prev != nil {
if prev.Pos().IsValid() {
a.diagAt(ident.Pos(), "variable %s redeclared in this block\n\tprevious declaration at %s", ident.Name, a.fset.Position(prev.Pos()))
} else {
a.diagAt(ident.Pos(), "variable %s redeclared in this block", ident.Name)
}
return nil
}
// Initialize the variable
index := v.Index
if v.Index >= 0 {
a.push(func(v *Thread) { v.f.Vars[index] = t.Zero() })
}
return v
}
func (a *stmtCompiler) definePkg(ident ast.Node, id, path string) *PkgIdent {
v, prev := a.block.DefinePackage(id, path, ident.Pos())
if prev != nil {
a.diagAt(ident.Pos(), "%s redeclared as imported package name\n\tprevious declaration at %s", id, a.fset.Position(prev.Pos()))
return nil
}
return v
}
// TODO(austin) Move doAssign to here
/*
* Statement compiler
*/
func (a *stmtCompiler) compile(s ast.Stmt) {
if a.block.inner != nil {
log.Panic("Child scope still entered")
}
notimpl := false
switch s := s.(type) {
case *ast.BadStmt:
// Error already reported by parser.
a.silentErrors++
case *ast.DeclStmt:
a.compileDeclStmt(s)
case *ast.EmptyStmt:
// Do nothing.
case *ast.LabeledStmt:
a.compileLabeledStmt(s)
case *ast.ExprStmt:
a.compileExprStmt(s)
case *ast.IncDecStmt:
a.compileIncDecStmt(s)
case *ast.AssignStmt:
a.compileAssignStmt(s)
case *ast.GoStmt:
notimpl = true
case *ast.DeferStmt:
notimpl = true
case *ast.ReturnStmt:
a.compileReturnStmt(s)
case *ast.BranchStmt:
a.compileBranchStmt(s)
case *ast.BlockStmt:
a.compileBlockStmt(s)
case *ast.IfStmt:
a.compileIfStmt(s)
case *ast.CaseClause:
a.diag("case clause outside switch")
case *ast.SwitchStmt:
a.compileSwitchStmt(s)
case *ast.TypeSwitchStmt:
notimpl = true
case *ast.CommClause:
notimpl = true
case *ast.SelectStmt:
notimpl = true
case *ast.ForStmt:
a.compileForStmt(s)
case *ast.RangeStmt:
notimpl = true
default:
log.Panicf("unexpected ast node type %T", s)
}
if notimpl {
a.diag("%T statement node not implemented", s)
}
if a.block.inner != nil {
log.Panic("Forgot to exit child scope")
}
}
func (a *stmtCompiler) compileDeclStmt(s *ast.DeclStmt) {
switch decl := s.Decl.(type) {
case *ast.BadDecl:
// Do nothing. Already reported by parser.
a.silentErrors++
case *ast.FuncDecl:
if !a.block.global {
log.Panic("FuncDecl at statement level")
}
case *ast.GenDecl:
if decl.Tok == token.IMPORT && !a.block.global {
log.Panic("import at statement level")
}
default:
log.Panicf("Unexpected Decl type %T", s.Decl)
}
a.compileDecl(s.Decl)
}
func (a *stmtCompiler) compileVarDecl(decl *ast.GenDecl) {
for _, spec := range decl.Specs {
spec := spec.(*ast.ValueSpec)
if spec.Values == nil {
// Declaration without assignment
if spec.Type == nil {
// Parser should have caught
log.Panic("Type and Values nil")
}
t := a.compileType(a.block, spec.Type)
// Define placeholders only if type compile succeeded
if t != nil {
for _, n := range spec.Names {
a.defineVar(n, t)
}
}
} else {
// Declaration with assignment
lhs := make([]ast.Expr, len(spec.Names))
for i, n := range spec.Names {
lhs[i] = n
}
a.doAssign(lhs, spec.Values, decl.Tok, spec.Type)
}
}
}
func (a *stmtCompiler) compileImportDecl(decl *ast.GenDecl) {
for _, spec := range decl.Specs {
spec := spec.(*ast.ImportSpec)
path, _ := strconv.Unquote(spec.Path.Value)
n := path
if spec.Name != nil {
n = spec.Name.Name
}
pkg, err := srcImporter(g_importer, path)
if err != nil {
a.diagAt(spec.Pos(), "could not import package [%s]: %v",
path, err)
continue
}
if spec.Name != nil {
a.definePkg(spec.Name, n, path)
} else {
n = pkg.Name()
a.definePkg(spec.Path, n, path)
}
}
}
func (a *stmtCompiler) compileConstDecl(decl *ast.GenDecl) {
log.Panicf("%v not implemented", decl.Tok)
}
func (a *stmtCompiler) compileDecl(decl ast.Decl) {
switch d := decl.(type) {
case *ast.BadDecl:
// Do nothing. Already reported by parser.
a.silentErrors++
case *ast.FuncDecl:
//fmt.Printf("...compileDecl(%s)...\n", d.Name.Name)
decl := a.compileFuncType(a.block, d.Type)
if decl == nil {
return
}
// Declare and initialize v before compiling func
// so that body can refer to itself.
c, prev := a.block.DefineConst(d.Name.Name, a.pos, decl.Type, decl.Type.Zero())
if prev != nil {
pos := prev.Pos()
if pos.IsValid() {
a.diagAt(d.Name.Pos(), "identifier %s redeclared in this block\n\tprevious declaration at %s", d.Name.Name, a.fset.Position(pos))
} else {
a.diagAt(d.Name.Pos(), "identifier %s redeclared in this block", d.Name.Name)
}
}
fn := a.compileFunc(a.block, decl, d.Body)
if c == nil || fn == nil {
//when compile error, remove func identifier from the table
a.block.undefine(d.Name.Name)
return
}
var zeroThread Thread
c.Value.(FuncValue).Set(nil, fn(&zeroThread))
case *ast.GenDecl:
switch d.Tok {
case token.IMPORT:
a.compileImportDecl(d)
case token.CONST:
a.compileConstDecl(d)
case token.TYPE:
name := d.Specs[0].(*ast.TypeSpec).Name.Name
_, level, dup := a.block.Lookup(name)
if dup != nil && level == 0 {
a.diag(
"%s redeclared in this block\n\tprevious declaration at %s",
name,
a.fset.Position(dup.Pos()),
)
return
}
ok := a.compileTypeDecl(a.block, d)
if !ok {
a.block.undefine(name)
}
case token.VAR:
a.compileVarDecl(d)
default:
log.Panicf("unknown ast.GenDecl token: %v\n", d.Tok)
}
default:
log.Panicf("Unexpected Decl type %T", decl)
}
}
func (a *stmtCompiler) compileLabeledStmt(s *ast.LabeledStmt) {
// Define label
l, ok := a.labels[s.Label.Name]
if ok {
if l.resolved.IsValid() {
a.diag("label %s redeclared in this block\n\tprevious declaration at %s", s.Label.Name, a.fset.Position(l.resolved))
}
} else {
pc := badPC
l = &label{name: s.Label.Name, gotoPC: &pc}
a.labels[l.name] = l
}
l.desc = "regular label"
l.resolved = s.Pos()
// Set goto PC
*l.gotoPC = a.nextPC()
// Define flow entry so we can check for jumps over declarations.
a.flow.putLabel(l.name, a.block)
// Compile the statement. Reuse our stmtCompiler for simplicity.
sc := &stmtCompiler{a.blockCompiler, s.Stmt.Pos(), l}
sc.compile(s.Stmt)
}
func (a *stmtCompiler) compileExprStmt(s *ast.ExprStmt) {
bc := a.enterChild()
defer bc.exit()
e := a.compileExpr(bc.block, false, s.X)
if e == nil {
return
}
if e.exec == nil {
a.diag("%s cannot be used as expression statement", e.desc)
return
}
a.push(e.exec)
}
func (a *stmtCompiler) compileIncDecStmt(s *ast.IncDecStmt) {
// Create temporary block for extractEffect
bc := a.enterChild()
defer bc.exit()
l := a.compileExpr(bc.block, false, s.X)
if l == nil {
return
}
if l.evalAddr == nil {
l.diag("cannot assign to %s", l.desc)
return
}
if !(l.t.isInteger() || l.t.isFloat()) {
l.diagOpType(s.Tok, l.t)
return
}
var op token.Token
var desc string
switch s.Tok {
case token.INC:
op = token.ADD
desc = "increment statement"
case token.DEC:
op = token.SUB
desc = "decrement statement"
default:
log.Panicf("Unexpected IncDec token %v", s.Tok)
}
effect, l := l.extractEffect(bc.block, desc)
one := l.newExpr(IdealIntType, "constant")
one.pos = s.Pos()
one.eval = func() *big.Int { return big.NewInt(1) }
binop := l.compileBinaryExpr(op, l, one)
if binop == nil {
return
}
assign := a.compileAssign(s.Pos(), bc.block, l.t, []*expr{binop}, "", "")
if assign == nil {
log.Panicf("compileAssign type check failed")
}
lf := l.evalAddr
a.push(func(v *Thread) {
effect(v)
assign(lf(v), v)
})
}
func (a *stmtCompiler) doAssign(lhs []ast.Expr, rhs []ast.Expr, tok token.Token, declTypeExpr ast.Expr) {
nerr := a.numError()
// Compile right side first so we have the types when
// compiling the left side and so we don't see definitions
// made on the left side.
rs := make([]*expr, len(rhs))
for i, re := range rhs {
rs[i] = a.compileExpr(a.block, false, re)
}
// Check if compileExpr failed on any expr
for _, r := range rs {
if r == nil {
return
}
}
errOp := "assignment"
if tok == token.DEFINE || tok == token.VAR {
errOp = "declaration"
}
ac, ok := a.checkAssign(a.pos, rs, errOp, "value")
ac.allowMapForms(len(lhs))
// If this is a definition and the LHS is too big, we won't be
// able to produce the usual error message because we can't
// begin to infer the types of the LHS.
if (tok == token.DEFINE || tok == token.VAR) && len(lhs) > len(ac.rmt.Elems) {
a.diag("not enough values for definition")
}
// Compile left type if there is one
var declType Type
if declTypeExpr != nil {
declType = a.compileType(a.block, declTypeExpr)
}
// Compile left side
ls := make([]*expr, len(lhs))
nDefs := 0
for i, le := range lhs {
// If this is a definition, get the identifier and its type
var ident *ast.Ident
var lt Type
switch tok {
case token.DEFINE:
// Check that it's an identifier
ident, ok = le.(*ast.Ident)
if !ok {
a.diagAt(le.Pos(), "left side of := must be a name")
// Suppress new definitions errors
nDefs++
continue
}
// Is this simply an assignment?
if _, ok := a.block.defs[ident.Name]; ok {
ident = nil
break
}
nDefs++
case token.VAR:
ident = le.(*ast.Ident)
}
// If it's a definition, get or infer its type.
if ident != nil {
// Compute the identifier's type from the RHS
// type. We use the computed MultiType so we
// don't have to worry about unpacking.
switch {
case declTypeExpr != nil:
// We have a declaration type, use it.
// If declType is nil, we gave an
// error when we compiled it.
lt = declType
case i >= len(ac.rmt.Elems):
// Define a placeholder. We already
// gave the "not enough" error above.
lt = nil
case ac.rmt.Elems[i] == nil:
// We gave the error when we compiled
// the RHS.
lt = nil
case ac.rmt.Elems[i].isIdeal():
// If the type is absent and the
// corresponding expression is a
// constant expression of ideal
// integer or ideal float type, the
// type of the declared variable is
// int or float respectively.
switch {
case ac.rmt.Elems[i].isInteger():
lt = IntType
case ac.rmt.Elems[i].isFloat():
lt = Float64Type
default:
log.Panicf("unexpected ideal type %v", rs[i].t)
}
default:
lt = ac.rmt.Elems[i]
}
}
// If it's a definition, define the identifier
if ident != nil {
if a.defineVar(ident, lt) == nil {
continue
}
}
// Compile LHS
ls[i] = a.compileExpr(a.block, false, le)
if ls[i] == nil {
continue
}
if ls[i].evalMapValue != nil {
// Map indexes are not generally addressable,
// but they are assignable.
//
// TODO(austin) Now that the expression
// compiler uses semantic values, this might
// be easier to implement as a function call.
sub := ls[i]
ls[i] = ls[i].newExpr(sub.t, sub.desc)
ls[i].evalMapValue = sub.evalMapValue
mvf := sub.evalMapValue
et := sub.t
ls[i].evalAddr = func(t *Thread) Value {
m, k := mvf(t)
e := m.Elem(t, k)
if e == nil {
e = et.Zero()
m.SetElem(t, k, e)
}
return e
}
} else if ls[i].evalAddr == nil {
ls[i].diag("cannot assign to %s", ls[i].desc)
continue
}
}
// A short variable declaration may redeclare variables
// provided they were originally declared in the same block
// with the same type, and at least one of the variables is
// new.
if tok == token.DEFINE && nDefs == 0 {
a.diag("at least one new variable must be declared")
return
}
// If there have been errors, our arrays are full of nil's so
// get out of here now.
if nerr != a.numError() {
return
}
// Check for 'a[x] = r, ok'
if len(ls) == 1 && len(rs) == 2 && ls[0].evalMapValue != nil {
a.diag("a[x] = r, ok form not implemented")
return
}
// Create assigner
var lt Type
n := len(lhs)
if n == 1 {
lt = ls[0].t
} else {
lts := make([]Type, len(ls))
for i, l := range ls {
if l != nil {
lts[i] = l.t
}
}
lt = NewMultiType(lts)
}
bc := a.enterChild()
defer bc.exit()
assign := ac.compile(bc.block, lt)
if assign == nil {
return
}
// Compile
if n == 1 {
// Don't need temporaries and can avoid []Value.
lf := ls[0].evalAddr
a.push(func(t *Thread) { assign(lf(t), t) })
} else if tok == token.VAR || (tok == token.DEFINE && nDefs == n) {
// Don't need temporaries
lfs := make([]func(*Thread) Value, n)
for i, l := range ls {
lfs[i] = l.evalAddr
}
a.push(func(t *Thread) {
dest := make([]Value, n)
for i, lf := range lfs {
dest[i] = lf(t)
}
assign(multiV(dest), t)
})
} else {
// Need temporaries
lmt := lt.(*MultiType)
lfs := make([]func(*Thread) Value, n)
for i, l := range ls {
lfs[i] = l.evalAddr
}
a.push(func(t *Thread) {
temp := lmt.Zero().(multiV)
assign(temp, t)
// Copy to destination
for i := 0; i < n; i++ {
// TODO(austin) Need to evaluate LHS
// before RHS
lfs[i](t).Assign(t, temp[i])
}
})
}
}
var assignOpToOp = map[token.Token]token.Token{
token.ADD_ASSIGN: token.ADD,
token.SUB_ASSIGN: token.SUB,
token.MUL_ASSIGN: token.MUL,
token.QUO_ASSIGN: token.QUO,
token.REM_ASSIGN: token.REM,
token.AND_ASSIGN: token.AND,
token.OR_ASSIGN: token.OR,
token.XOR_ASSIGN: token.XOR,
token.SHL_ASSIGN: token.SHL,
token.SHR_ASSIGN: token.SHR,
token.AND_NOT_ASSIGN: token.AND_NOT,
}
func (a *stmtCompiler) doAssignOp(s *ast.AssignStmt) {
if len(s.Lhs) != 1 || len(s.Rhs) != 1 {
a.diag("tuple assignment cannot be combined with an arithmetic operation")
return
}
// Create temporary block for extractEffect
bc := a.enterChild()
defer bc.exit()
l := a.compileExpr(bc.block, false, s.Lhs[0])
r := a.compileExpr(bc.block, false, s.Rhs[0])
if l == nil || r == nil {
return
}
if l.evalAddr == nil {
l.diag("cannot assign to %s", l.desc)
return
}
effect, l := l.extractEffect(bc.block, "operator-assignment")
binop := r.compileBinaryExpr(assignOpToOp[s.Tok], l, r)
if binop == nil {
return
}
assign := a.compileAssign(s.Pos(), bc.block, l.t, []*expr{binop}, "assignment", "value")
if assign == nil {
log.Panicf("compileAssign type check failed")
}
lf := l.evalAddr
a.push(func(t *Thread) {
effect(t)
assign(lf(t), t)
})
}
func (a *stmtCompiler) compileAssignStmt(s *ast.AssignStmt) {
switch s.Tok {
case token.ASSIGN, token.DEFINE:
a.doAssign(s.Lhs, s.Rhs, s.Tok, nil)
default:
a.doAssignOp(s)
}
}
func (a *stmtCompiler) compileReturnStmt(s *ast.ReturnStmt) {
if a.fnType == nil {
a.diag("cannot return at the top level")
return
}
if len(s.Results) == 0 && (len(a.fnType.Out) == 0 || a.outVarsNamed) {
// Simple case. Simply exit from the function.
a.flow.putTerm()
a.push(func(v *Thread) { v.pc = returnPC })
return
}
bc := a.enterChild()
defer bc.exit()
// Compile expressions
bad := false
rs := make([]*expr, len(s.Results))
for i, re := range s.Results {
rs[i] = a.compileExpr(bc.block, false, re)
if rs[i] == nil {
bad = true
}
}
if bad {
return
}
// Create assigner
// However, if the expression list in the "return" statement
// is a single call to a multi-valued function, the values
// returned from the called function will be returned from
// this one.
assign := a.compileAssign(s.Pos(), bc.block, NewMultiType(a.fnType.Out), rs, "return", "value")
// XXX(Spec) "The result types of the current function and the
// called function must match." Match is fuzzy. It should
// say that they must be assignment compatible.
// Compile
start := len(a.fnType.In)
nout := len(a.fnType.Out)
a.flow.putTerm()
a.push(func(t *Thread) {
assign(multiV(t.f.Vars[start:start+nout]), t)
t.pc = returnPC
})
}
func (a *stmtCompiler) findLexicalLabel(name *ast.Ident, pred func(*label) bool, errOp, errCtx string) *label {
bc := a.blockCompiler
for ; bc != nil; bc = bc.parent {
if bc.label == nil {
continue
}
l := bc.label
if name == nil && pred(l) {
return l
}
if name != nil && l.name == name.Name {
if !pred(l) {
a.diag("cannot %s to %s %s", errOp, l.desc, l.name)
return nil
}
return l
}
}
if name == nil {
a.diag("%s outside %s", errOp, errCtx)
} else {
a.diag("%s label %s not defined", errOp, name.Name)
}
return nil
}
func (a *stmtCompiler) compileBranchStmt(s *ast.BranchStmt) {
var pc *uint
switch s.Tok {
case token.BREAK:
l := a.findLexicalLabel(s.Label, func(l *label) bool { return l.breakPC != nil }, "break", "for loop, switch, or select")
if l == nil {
return
}
pc = l.breakPC
case token.CONTINUE:
l := a.findLexicalLabel(s.Label, func(l *label) bool { return l.continuePC != nil }, "continue", "for loop")
if l == nil {
return
}
pc = l.continuePC
case token.GOTO:
l, ok := a.labels[s.Label.Name]
if !ok {
pc := badPC
l = &label{name: s.Label.Name, desc: "unresolved label", gotoPC: &pc, used: s.Pos()}
a.labels[l.name] = l
}
pc = l.gotoPC
a.flow.putGoto(s.Pos(), l.name, a.block)
case token.FALLTHROUGH:
a.diag("fallthrough outside switch")
return
default:
log.Panicf("Unexpected branch token %v", s.Tok)
}
a.flow.put1(false, pc)
a.push(func(v *Thread) { v.pc = *pc })
}
func (a *stmtCompiler) compileBlockStmt(s *ast.BlockStmt) {
bc := a.enterChild()
bc.compileStmts(s)
bc.exit()
}
func (a *stmtCompiler) compileIfStmt(s *ast.IfStmt) {
// The scope of any variables declared by [the init] statement