Debian Codegraph @

interp/cfg.go

raw symbols SCIP
1 package interp
2
3 import (
4 "fmt"
5 "go/constant"
6 "log"
7 "math"
8 "path"
9 "reflect"
10 "strings"
11 "unicode"
12 )
13
14 // A cfgError represents an error during CFG build stage.
15 type cfgError struct {
16 *node
17 error
18 }
19
20 func (c *cfgError) Error() string { return c.error.Error() }
21
22 var constOp = map[action]func(*node){
23 aAdd: addConst,
24 aSub: subConst,
25 aMul: mulConst,
26 aQuo: quoConst,
27 aRem: remConst,
28 aAnd: andConst,
29 aOr: orConst,
30 aShl: shlConst,
31 aShr: shrConst,
32 aAndNot: andNotConst,
33 aXor: xorConst,
34 aNot: notConst,
35 aBitNot: bitNotConst,
36 aNeg: negConst,
37 aPos: posConst,
38 }
39
40 var constBltn = map[string]func(*node){
41 bltnComplex: complexConst,
42 bltnImag: imagConst,
43 bltnReal: realConst,
44 }
45
46 const nilIdent = "nil"
47
48 func init() {
49 // Use init() to avoid initialization cycles for the following constant builtins.
50 constBltn[bltnAlignof] = alignof
51 constBltn[bltnOffsetof] = offsetof
52 constBltn[bltnSizeof] = sizeof
53 }
54
55 // cfg generates a control flow graph (CFG) from AST (wiring successors in AST)
56 // and pre-compute frame sizes and indexes for all un-named (temporary) and named
57 // variables. A list of nodes of init functions is returned.
58 // Following this pass, the CFG is ready to run.
59 func (interp *Interpreter) cfg(root *node, sc *scope, importPath, pkgName string) ([]*node, error) {
60 if sc == nil {
61 sc = interp.initScopePkg(importPath, pkgName)
62 }
63 check := typecheck{scope: sc}
64 var initNodes []*node
65 var err error
66
67 baseName := path.Base(interp.fset.Position(root.pos).Filename)
68
69 root.Walk(func(n *node) bool {
70 // Pre-order processing
71 if err != nil {
72 return false
73 }
74 if n.scope == nil {
75 n.scope = sc
76 }
77 tracePrintln(n)
78
79 switch n.kind {
80 case binaryExpr, unaryExpr, parenExpr:
81 if isBoolAction(n) {
82 break
83 }
84 // Gather assigned type if set, to give context for type propagation at post-order.
85 switch n.anc.kind {
86 case assignStmt, defineStmt:
87 a := n.anc
88 i := childPos(n) - a.nright
89 if i < 0 {
90 break
91 }
92 if len(a.child) > a.nright+a.nleft {
93 i--
94 }
95 dest := a.child[i]
96 if dest.typ == nil {
97 break
98 }
99 if dest.typ.incomplete {
100 err = n.cfgErrorf("invalid type declaration")
101 return false
102 }
103 if !isInterface(dest.typ) {
104 // Interface type are not propagated, and will be resolved at post-order.
105 n.typ = dest.typ
106 }
107 case binaryExpr, unaryExpr, parenExpr:
108 n.typ = n.anc.typ
109 }
110
111 case defineStmt:
112 // Determine type of variables initialized at declaration, so it can be propagated.
113 if n.nleft+n.nright == len(n.child) {
114 // No type was specified on the left hand side, it will resolved at post-order.
115 break
116 }
117 n.typ, err = nodeType(interp, sc, n.child[n.nleft])
118 if err != nil {
119 break
120 }
121 for i := 0; i < n.nleft; i++ {
122 n.child[i].typ = n.typ
123 }
124
125 case blockStmt:
126 var rangek, rangev *node
127 if n.anc != nil && n.anc.kind == rangeStmt {
128 // For range block: ensure that array or map type is propagated to iterators
129 // prior to process block. We cannot perform this at RangeStmt pre-order because
130 // type of array like value is not yet known. This could be fixed in ast structure
131 // by setting array/map node as 1st child of ForRangeStmt instead of 3rd child of
132 // RangeStmt. The following workaround is less elegant but ok.
133 c := n.anc.child[1]
134 if c != nil && c.typ != nil && isSendChan(c.typ) {
135 err = c.cfgErrorf("invalid operation: range %s receive from send-only channel", c.ident)
136 return false
137 }
138
139 if t := sc.rangeChanType(n.anc); t != nil {
140 // range over channel
141 e := n.anc.child[0]
142 index := sc.add(t.val)
143 sc.sym[e.ident] = &symbol{index: index, kind: varSym, typ: t.val}
144 e.typ = t.val
145 e.findex = index
146 n.anc.gen = rangeChan
147 } else {
148 // range over array or map
149 var ktyp, vtyp *itype
150 var k, v, o *node
151 if len(n.anc.child) == 4 {
152 k, v, o = n.anc.child[0], n.anc.child[1], n.anc.child[2]
153 if v.ident == "_" {
154 v = nil // Do not assign to _ value.
155 }
156 } else {
157 k, o = n.anc.child[0], n.anc.child[1]
158 }
159
160 switch o.typ.cat {
161 case valueT, linkedT:
162 typ := o.typ.rtype
163 if o.typ.cat == linkedT {
164 typ = o.typ.val.TypeOf()
165 }
166 switch typ.Kind() {
167 case reflect.Map:
168 n.anc.gen = rangeMap
169 ityp := valueTOf(reflect.TypeOf((*reflect.MapIter)(nil)))
170 sc.add(ityp)
171 ktyp = valueTOf(typ.Key())
172 vtyp = valueTOf(typ.Elem())
173 case reflect.String:
174 sc.add(sc.getType("int")) // Add a dummy type to store array shallow copy for range
175 sc.add(sc.getType("int")) // Add a dummy type to store index for range
176 ktyp = sc.getType("int")
177 vtyp = sc.getType("rune")
178 case reflect.Array, reflect.Slice:
179 sc.add(sc.getType("int")) // Add a dummy type to store array shallow copy for range
180 ktyp = sc.getType("int")
181 vtyp = valueTOf(typ.Elem())
182 }
183 case mapT:
184 n.anc.gen = rangeMap
185 ityp := valueTOf(reflect.TypeOf((*reflect.MapIter)(nil)))
186 sc.add(ityp)
187 ktyp = o.typ.key
188 vtyp = o.typ.val
189 case ptrT:
190 ktyp = sc.getType("int")
191 vtyp = o.typ.val
192 if vtyp.cat == valueT {
193 vtyp = valueTOf(vtyp.rtype.Elem())
194 } else {
195 vtyp = vtyp.val
196 }
197 case stringT:
198 sc.add(sc.getType("int")) // Add a dummy type to store array shallow copy for range
199 sc.add(sc.getType("int")) // Add a dummy type to store index for range
200 ktyp = sc.getType("int")
201 vtyp = sc.getType("rune")
202 case arrayT, sliceT, variadicT:
203 sc.add(sc.getType("int")) // Add a dummy type to store array shallow copy for range
204 ktyp = sc.getType("int")
205 vtyp = o.typ.val
206 case intT:
207 n.anc.gen = rangeInt
208 sc.add(sc.getType("int"))
209 ktyp = sc.getType("int")
210 }
211
212 kindex := sc.add(ktyp)
213 sc.sym[k.ident] = &symbol{index: kindex, kind: varSym, typ: ktyp}
214 k.typ = ktyp
215 k.findex = kindex
216 rangek = k
217
218 if v != nil {
219 vindex := sc.add(vtyp)
220 sc.sym[v.ident] = &symbol{index: vindex, kind: varSym, typ: vtyp}
221 v.typ = vtyp
222 v.findex = vindex
223 rangev = v
224 }
225 }
226 }
227
228 n.findex = -1
229 n.val = nil
230 sc = sc.pushBloc()
231
232 if n.anc != nil && n.anc.kind == rangeStmt {
233 lk := n.child[0]
234 if rangek != nil {
235 lk.ident = rangek.ident
236 lk.typ = rangek.typ
237 kindex := sc.add(lk.typ)
238 sc.sym[lk.ident] = &symbol{index: kindex, kind: varSym, typ: lk.typ}
239 lk.findex = kindex
240 lk.gen = loopVarKey
241 }
242 lv := n.child[1]
243 if rangev != nil {
244 lv.ident = rangev.ident
245 lv.typ = rangev.typ
246 vindex := sc.add(lv.typ)
247 sc.sym[lv.ident] = &symbol{index: vindex, kind: varSym, typ: lv.typ}
248 lv.findex = vindex
249 lv.gen = loopVarVal
250 }
251 }
252 if n.anc != nil && n.anc.kind == forStmt7 {
253 lv := n.child[0]
254 init := n.anc.child[0]
255 if init.kind == defineStmt && len(init.child) >= 2 && init.child[0].kind == identExpr {
256 fi := init.child[0]
257 lv.ident = fi.ident
258 lv.typ = fi.typ
259 vindex := sc.add(lv.typ)
260 sc.sym[lv.ident] = &symbol{index: vindex, kind: varSym, typ: lv.typ}
261 lv.findex = vindex
262 lv.gen = loopVarFor
263 }
264 }
265
266 // Pre-define symbols for labels defined in this block, so we are sure that
267 // they are already defined when met.
268 // TODO(marc): labels must be stored outside of symbols to avoid collisions.
269 for _, c := range n.child {
270 if c.kind != labeledStmt {
271 continue
272 }
273 label := c.child[0].ident
274 sym := &symbol{kind: labelSym, node: c, index: -1}
275 sc.sym[label] = sym
276 c.sym = sym
277 }
278 // If block is the body of a function, get declared variables in current scope.
279 // This is done in order to add the func signature symbols into sc.sym,
280 // as we will need them in post-processing.
281 if n.anc != nil && n.anc.kind == funcDecl {
282 for k, v := range sc.anc.sym {
283 sc.sym[k] = v
284 }
285 }
286
287 case breakStmt, continueStmt, gotoStmt:
288 if len(n.child) == 0 {
289 break
290 }
291 // Handle labeled statements.
292 label := n.child[0].ident
293 if sym, _, ok := sc.lookup(label); ok {
294 if sym.kind != labelSym {
295 err = n.child[0].cfgErrorf("label %s not defined", label)
296 break
297 }
298 n.sym = sym
299 } else {
300 n.sym = &symbol{kind: labelSym, index: -1}
301 sc.sym[label] = n.sym
302 }
303 if n.kind == gotoStmt {
304 n.sym.from = append(n.sym.from, n) // To allow forward goto statements.
305 }
306
307 case caseClause:
308 sc = sc.pushBloc()
309 if sn := n.anc.anc; sn.kind == typeSwitch && sn.child[1].action == aAssign {
310 // Type switch clause with a var defined in switch guard.
311 var typ *itype
312 if len(n.child) == 2 {
313 // 1 type in clause: define the var with this type in the case clause scope.
314 switch {
315 case n.child[0].ident == nilIdent:
316 typ = sc.getType("interface{}")
317 case !n.child[0].isType(sc):
318 err = n.cfgErrorf("%s is not a type", n.child[0].ident)
319 default:
320 typ, err = nodeType(interp, sc, n.child[0])
321 }
322 } else {
323 // Define the var with the type in the switch guard expression.
324 typ = sn.child[1].child[1].child[0].typ
325 }
326 if err != nil {
327 return false
328 }
329 nod := n.lastChild().child[0]
330 index := sc.add(typ)
331 sc.sym[nod.ident] = &symbol{index: index, kind: varSym, typ: typ}
332 nod.findex = index
333 nod.typ = typ
334 }
335
336 case commClauseDefault:
337 sc = sc.pushBloc()
338
339 case commClause:
340 sc = sc.pushBloc()
341 if len(n.child) > 0 && n.child[0].action == aAssign {
342 ch := n.child[0].child[1].child[0]
343 var typ *itype
344 if typ, err = nodeType(interp, sc, ch); err != nil {
345 return false
346 }
347 if !isChan(typ) {
348 err = n.cfgErrorf("invalid operation: receive from non-chan type")
349 return false
350 }
351 elem := chanElement(typ)
352 assigned := n.child[0].child[0]
353 index := sc.add(elem)
354 sc.sym[assigned.ident] = &symbol{index: index, kind: varSym, typ: elem}
355 assigned.findex = index
356 assigned.typ = elem
357 }
358
359 case compositeLitExpr:
360 if len(n.child) > 0 && n.child[0].isType(sc) {
361 // Get type from 1st child.
362 if n.typ, err = nodeType(interp, sc, n.child[0]); err != nil {
363 return false
364 }
365 // Indicate that the first child is the type.
366 n.nleft = 1
367 } else {
368 // Get type from ancestor (implicit type).
369 if n.anc.kind == keyValueExpr && n == n.anc.child[0] {
370 n.typ = n.anc.typ.key
371 } else if atyp := n.anc.typ; atyp != nil {
372 if atyp.cat == valueT && hasElem(atyp.rtype) {
373 n.typ = valueTOf(atyp.rtype.Elem())
374 } else {
375 n.typ = atyp.val
376 }
377 }
378 if n.typ == nil {
379 // A nil type indicates either an error or a generic type.
380 // A child indexExpr or indexListExpr is used for type parameters,
381 // it indicates an instanciated generic.
382 if n.child[0].kind != indexExpr && n.child[0].kind != indexListExpr {
383 err = n.cfgErrorf("undefined type")
384 return false
385 }
386 t0, err1 := nodeType(interp, sc, n.child[0].child[0])
387 if err1 != nil {
388 return false
389 }
390 if t0.cat != genericT {
391 err = n.cfgErrorf("undefined type")
392 return false
393 }
394 // We have a composite literal of generic type, instantiate it.
395 lt := []*itype{}
396 for _, n1 := range n.child[0].child[1:] {
397 t1, err1 := nodeType(interp, sc, n1)
398 if err1 != nil {
399 return false
400 }
401 lt = append(lt, t1)
402 }
403 var g *node
404 g, _, err = genAST(sc, t0.node.anc, lt)
405 if err != nil {
406 return false
407 }
408 n.child[0] = g.lastChild()
409 n.typ, err = nodeType(interp, sc, n.child[0])
410 if err != nil {
411 return false
412 }
413 // Generate methods if any.
414 for _, nod := range t0.method {
415 gm, _, err2 := genAST(nod.scope, nod, lt)
416 if err2 != nil {
417 err = err2
418 return false
419 }
420 gm.typ, err = nodeType(interp, nod.scope, gm.child[2])
421 if err != nil {
422 return false
423 }
424 if _, err = interp.cfg(gm, sc, sc.pkgID, sc.pkgName); err != nil {
425 return false
426 }
427 if err = genRun(gm); err != nil {
428 return false
429 }
430 n.typ.addMethod(gm)
431 }
432 n.nleft = 1 // Indictate the type of composite literal.
433 }
434 }
435
436 child := n.child
437 if n.nleft > 0 {
438 n.child[0].typ = n.typ
439 child = n.child[1:]
440 }
441 // Propagate type to children, to handle implicit types
442 for _, c := range child {
443 if isBlank(c) {
444 err = n.cfgErrorf("cannot use _ as value")
445 return false
446 }
447 switch c.kind {
448 case binaryExpr, unaryExpr, compositeLitExpr:
449 // Do not attempt to propagate composite type to operator expressions,
450 // it breaks constant folding.
451 case keyValueExpr, typeAssertExpr, indexExpr:
452 c.typ = n.typ
453 default:
454 if c.ident == nilIdent {
455 c.typ = sc.getType(nilIdent)
456 continue
457 }
458 if c.typ, err = nodeType(interp, sc, c); err != nil {
459 return false
460 }
461 }
462 }
463
464 case forStmt0, forStmt1, forStmt2, forStmt3, forStmt4, forStmt5, forStmt6, forStmt7, forRangeStmt:
465 sc = sc.pushBloc()
466 sc.loop, sc.loopRestart = n, n.lastChild()
467
468 case funcLit:
469 n.typ = nil // to force nodeType to recompute the type
470 if n.typ, err = nodeType(interp, sc, n); err != nil {
471 return false
472 }
473 n.findex = sc.add(n.typ)
474 fallthrough
475
476 case funcDecl:
477 // Do not allow function declarations without body.
478 if len(n.child) < 4 {
479 err = n.cfgErrorf("missing function body")
480 return false
481 }
482 n.val = n
483
484 // Skip substree in case of a generic function.
485 if len(n.child[2].child[0].child) > 0 {
486 return false
487 }
488
489 // Skip subtree if the function is a method with a generic receiver.
490 if len(n.child[0].child) > 0 {
491 recvTypeNode := n.child[0].child[0].lastChild()
492 typ, err := nodeType(interp, sc, recvTypeNode)
493 if err != nil {
494 return false
495 }
496 if typ.cat == genericT || (typ.val != nil && typ.val.cat == genericT) {
497 return false
498 }
499 if typ.cat == ptrT {
500 rc0 := recvTypeNode.child[0]
501 rt0, err := nodeType(interp, sc, rc0)
502 if err != nil {
503 return false
504 }
505 if rc0.kind == indexExpr && rt0.cat == structT {
506 return false
507 }
508 }
509 }
510
511 // Compute function type before entering local scope to avoid
512 // possible collisions with function argument names.
513 n.child[2].typ, err = nodeType(interp, sc, n.child[2])
514 if err != nil {
515 return false
516 }
517 n.typ = n.child[2].typ
518
519 // Add a frame indirection level as we enter in a func.
520 sc = sc.pushFunc()
521 sc.def = n
522
523 // Allocate frame space for return values, define output symbols.
524 if len(n.child[2].child) == 3 {
525 for _, c := range n.child[2].child[2].child {
526 var typ *itype
527 if typ, err = nodeType(interp, sc, c.lastChild()); err != nil {
528 return false
529 }
530 if len(c.child) > 1 {
531 for _, cc := range c.child[:len(c.child)-1] {
532 sc.sym[cc.ident] = &symbol{index: sc.add(typ), kind: varSym, typ: typ}
533 }
534 } else {
535 sc.add(typ)
536 }
537 }
538 }
539
540 // Define receiver symbol.
541 if len(n.child[0].child) > 0 {
542 var typ *itype
543 fr := n.child[0].child[0]
544 recvTypeNode := fr.lastChild()
545 if typ, err = nodeType(interp, sc, recvTypeNode); err != nil {
546 return false
547 }
548 if typ.cat == nilT {
549 // This may happen when instantiating generic methods.
550 s2, _, ok := sc.lookup(typ.id())
551 if !ok {
552 err = n.cfgErrorf("type not found: %s", typ.id())
553 break
554 }
555 typ = s2.typ
556 if typ.cat == nilT {
557 err = n.cfgErrorf("nil type: %s", typ.id())
558 break
559 }
560 }
561 recvTypeNode.typ = typ
562 n.child[2].typ.recv = typ
563 n.typ.recv = typ
564 index := sc.add(typ)
565 if len(fr.child) > 1 {
566 sc.sym[fr.child[0].ident] = &symbol{index: index, kind: varSym, typ: typ}
567 }
568 }
569
570 // Define input parameter symbols.
571 for _, c := range n.child[2].child[1].child {
572 var typ *itype
573 if typ, err = nodeType(interp, sc, c.lastChild()); err != nil {
574 return false
575 }
576 for _, cc := range c.child[:len(c.child)-1] {
577 sc.sym[cc.ident] = &symbol{index: sc.add(typ), kind: varSym, typ: typ}
578 }
579 }
580
581 if n.child[1].ident == "init" && len(n.child[0].child) == 0 {
582 initNodes = append(initNodes, n)
583 }
584
585 case ifStmt0, ifStmt1, ifStmt2, ifStmt3:
586 sc = sc.pushBloc()
587
588 case switchStmt, switchIfStmt, typeSwitch:
589 // Make sure default clause is in last position.
590 c := n.lastChild().child
591 if i, l := getDefault(n), len(c)-1; i >= 0 && i != l {
592 c[i], c[l] = c[l], c[i]
593 }
594 sc = sc.pushBloc()
595 sc.loop = n
596
597 case importSpec:
598 // Already all done in GTA.
599 return false
600
601 case typeSpec:
602 // Processing already done in GTA pass for global types, only parses inlined types.
603 if sc.def == nil {
604 return false
605 }
606 typeName := n.child[0].ident
607 var typ *itype
608 if typ, err = nodeType(interp, sc, n.child[1]); err != nil {
609 return false
610 }
611 if typ.incomplete {
612 // Type may still be incomplete in case of a local recursive struct declaration.
613 if typ, err = typ.finalize(); err != nil {
614 err = n.cfgErrorf("invalid type declaration")
615 return false
616 }
617 }
618
619 switch n.child[1].kind {
620 case identExpr, selectorExpr:
621 n.typ = namedOf(typ, pkgName, typeName)
622 default:
623 n.typ = typ
624 n.typ.name = typeName
625 }
626 sc.sym[typeName] = &symbol{kind: typeSym, typ: n.typ}
627 return false
628
629 case constDecl:
630 // Early parse of constDecl subtrees, to compute all constant
631 // values which may be used in further declarations.
632 if !sc.global {
633 for _, c := range n.child {
634 if _, err = interp.cfg(c, sc, importPath, pkgName); err != nil {
635 // No error processing here, to allow recovery in subtree nodes.
636 err = nil
637 }
638 }
639 }
640
641 case arrayType, basicLit, chanType, chanTypeRecv, chanTypeSend, funcType, interfaceType, mapType, structType:
642 n.typ, err = nodeType(interp, sc, n)
643 return false
644 }
645 return true
646 }, func(n *node) {
647 // Post-order processing
648 if err != nil {
649 return
650 }
651
652 defer func() {
653 if r := recover(); r != nil {
654 // Display the exact location in input source which triggered the panic
655 panic(n.cfgErrorf("CFG post-order panic: %v", r))
656 }
657 }()
658
659 switch n.kind {
660 case addressExpr:
661 if isBlank(n.child[0]) {
662 err = n.cfgErrorf("cannot use _ as value")
663 break
664 }
665 wireChild(n)
666
667 err = check.addressExpr(n)
668 if err != nil {
669 break
670 }
671
672 n.typ = ptrOf(n.child[0].typ)
673 n.findex = sc.add(n.typ)
674
675 case assignStmt, defineStmt:
676 if n.anc.kind == typeSwitch && n.anc.child[1] == n {
677 // type switch guard assignment: assign dest to concrete value of src
678 n.gen = nop
679 break
680 }
681
682 var atyp *itype
683 if n.nleft+n.nright < len(n.child) {
684 if atyp, err = nodeType(interp, sc, n.child[n.nleft]); err != nil {
685 break
686 }
687 }
688
689 var sbase int
690 if n.nright > 0 {
691 sbase = len(n.child) - n.nright
692 }
693
694 // If len(RHS) > 1, each node must be single-valued, and the nth expression
695 // on the right is assigned to the nth operand on the left, so the number of
696 // nodes on the left and right sides must be equal
697 if n.nright > 1 && n.nright != n.nleft {
698 err = n.cfgErrorf("cannot assign %d values to %d variables", n.nright, n.nleft)
699 return
700 }
701
702 wireChild(n)
703 for i := 0; i < n.nleft; i++ {
704 dest, src := n.child[i], n.child[sbase+i]
705 updateSym := false
706 var sym *symbol
707 var level int
708
709 if dest.rval.IsValid() && !dest.rval.CanSet() && isConstType(dest.typ) {
710 err = n.cfgErrorf("cannot assign to %s (%s constant)", dest.rval, dest.typ.str)
711 break
712 }
713 if isBlank(src) {
714 err = n.cfgErrorf("cannot use _ as value")
715 break
716 }
717 if n.kind == defineStmt || (n.kind == assignStmt && dest.ident == "_") {
718 if atyp != nil {
719 dest.typ = atyp
720 } else {
721 if src.typ, err = nodeType(interp, sc, src); err != nil {
722 return
723 }
724 if src.typ.isBinMethod {
725 dest.typ = valueTOf(src.typ.methodCallType())
726 } else {
727 // In a new definition, propagate the source type to the destination
728 // type. If the source is an untyped constant, make sure that the
729 // type matches a default type.
730 dest.typ = sc.fixType(src.typ)
731 }
732 }
733 if dest.typ.incomplete {
734 return
735 }
736 if sc.global || sc.isRedeclared(dest) {
737 if n.anc != nil && n.anc.anc != nil && (n.anc.anc.kind == forStmt7 || n.anc.anc.kind == rangeStmt) {
738 // check for redefine of for loop variables, which are now auto-defined in go1.22
739 init := n.anc.anc.child[0]
740 var fi *node // for ident
741 if n.anc.anc.kind == forStmt7 {
742 if init.kind == defineStmt && len(init.child) >= 2 && init.child[0].kind == identExpr {
743 fi = init.child[0]
744 }
745 } else { // range
746 fi = init
747 }
748 if fi != nil && dest.ident == fi.ident {
749 n.gen = nop
750 break
751 }
752 }
753 // Do not overload existing symbols (defined in GTA) in global scope.
754 sym, _, _ = sc.lookup(dest.ident)
755 }
756 if sym == nil {
757 sym = &symbol{index: sc.add(dest.typ), kind: varSym, typ: dest.typ}
758 sc.sym[dest.ident] = sym
759 }
760 dest.val = src.val
761 dest.recv = src.recv
762 dest.findex = sym.index
763 updateSym = true
764 } else {
765 sym, level, _ = sc.lookup(dest.ident)
766 }
767
768 err = check.assignExpr(n, dest, src)
769 if err != nil {
770 break
771 }
772
773 if updateSym {
774 sym.typ = dest.typ
775 sym.rval = src.rval
776 // As we are updating the sym type, we need to update the sc.type
777 // when the sym has an index.
778 if sym.index >= 0 {
779 sc.types[sym.index] = sym.typ.frameType()
780 }
781 }
782 n.findex = dest.findex
783 n.level = dest.level
784
785 // In the following, we attempt to optimize by skipping the assign
786 // operation and setting the source location directly to the destination
787 // location in the frame.
788 //
789 switch {
790 case n.action != aAssign:
791 // Do not skip assign operation if it is combined with another operator.
792 case src.rval.IsValid():
793 // Do not skip assign operation if setting from a constant value.
794 case isMapEntry(dest):
795 // Setting a map entry requires an additional step, do not optimize.
796 // As we only write, skip the default useless getIndexMap dest action.
797 dest.gen = nop
798 case isFuncField(dest):
799 // Setting a struct field of function type requires an extra step. Do not optimize.
800 case isCall(src) && !isInterfaceSrc(dest.typ) && n.kind != defineStmt:
801 // Call action may perform the assignment directly.
802 if dest.typ.id() != src.typ.id() {
803 // Skip optimitization if returned type doesn't match assigned one.
804 break
805 }
806 n.gen = nop
807 src.level = level
808 src.findex = dest.findex
809 if src.typ.untyped && !dest.typ.untyped {
810 src.typ = dest.typ
811 }
812 case src.action == aRecv:
813 // Assign by reading from a receiving channel.
814 n.gen = nop
815 src.findex = dest.findex // Set recv address to LHS.
816 dest.typ = src.typ
817 case src.action == aCompositeLit:
818 if dest.typ.cat == valueT && dest.typ.rtype.Kind() == reflect.Interface {
819 // Skip optimisation for assigned interface.
820 break
821 }
822 if dest.action == aGetIndex || dest.action == aStar {
823 // Skip optimization, as it does not work when assigning to a struct field or a dereferenced pointer.
824 break
825 }
826 n.gen = nop
827 src.findex = dest.findex
828 src.level = level
829 case len(n.child) < 4 && n.kind != defineStmt && isArithmeticAction(src) && !isInterface(dest.typ):
830 // Optimize single assignments from some arithmetic operations.
831 src.typ = dest.typ
832 src.findex = dest.findex
833 src.level = level
834 n.gen = nop
835 case src.kind == basicLit:
836 // Assign to nil.
837 src.rval = reflect.New(dest.typ.TypeOf()).Elem()
838 case n.nright == 0:
839 n.gen = reset
840 }
841
842 n.typ = dest.typ
843 if sym != nil {
844 sym.typ = n.typ
845 sym.recv = src.recv
846 }
847
848 n.level = level
849
850 if n.anc.kind == constDecl {
851 n.gen = nop
852 n.findex = notInFrame
853 if sym, _, ok := sc.lookup(dest.ident); ok {
854 sym.kind = constSym
855 }
856 if childPos(n) == len(n.anc.child)-1 {
857 sc.iota = 0
858 } else {
859 sc.iota++
860 }
861 }
862 }
863
864 case incDecStmt:
865 err = check.unaryExpr(n)
866 if err != nil {
867 break
868 }
869 wireChild(n)
870 n.findex = n.child[0].findex
871 n.level = n.child[0].level
872 n.typ = n.child[0].typ
873 if sym, level, ok := sc.lookup(n.child[0].ident); ok {
874 sym.typ = n.typ
875 n.level = level
876 }
877
878 case assignXStmt:
879 wireChild(n)
880 l := len(n.child) - 1
881 switch lc := n.child[l]; lc.kind {
882 case callExpr:
883 if n.child[l-1].isType(sc) {
884 l--
885 }
886 if r := lc.child[0].typ.numOut(); r != l {
887 err = n.cfgErrorf("assignment mismatch: %d variables but %s returns %d values", l, lc.child[0].name(), r)
888 }
889 if isBinCall(lc, sc) {
890 n.gen = nop
891 } else {
892 // TODO (marc): skip if no conversion or wrapping is needed.
893 n.gen = assignFromCall
894 }
895 case indexExpr:
896 lc.gen = getIndexMap2
897 n.gen = nop
898 case typeAssertExpr:
899 if n.child[0].ident == "_" {
900 lc.gen = typeAssertStatus
901 } else {
902 lc.gen = typeAssertLong
903 }
904 n.gen = nop
905 case unaryExpr:
906 if lc.action == aRecv {
907 lc.gen = recv2
908 n.gen = nop
909 }
910 }
911
912 case defineXStmt:
913 wireChild(n)
914 if sc.def == nil {
915 // In global scope, type definition already handled by GTA.
916 break
917 }
918 err = compDefineX(sc, n)
919
920 case binaryExpr:
921 wireChild(n)
922 nilSym := interp.universe.sym[nilIdent]
923 c0, c1 := n.child[0], n.child[1]
924
925 err = check.binaryExpr(n)
926 if err != nil {
927 break
928 }
929
930 switch n.action {
931 case aRem:
932 n.typ = c0.typ
933 case aShl, aShr:
934 if c0.typ.untyped {
935 break
936 }
937 n.typ = c0.typ
938 case aEqual, aNotEqual:
939 n.typ = sc.getType("bool")
940 if c0.sym == nilSym || c1.sym == nilSym {
941 if n.action == aEqual {
942 if c1.sym == nilSym {
943 n.gen = isNilChild(0)
944 } else {
945 n.gen = isNilChild(1)
946 }
947 } else {
948 n.gen = isNotNil
949 }
950 }
951 case aGreater, aGreaterEqual, aLower, aLowerEqual:
952 n.typ = sc.getType("bool")
953 }
954 if err != nil {
955 break
956 }
957 if n.typ == nil {
958 if n.typ, err = nodeType(interp, sc, n); err != nil {
959 break
960 }
961 }
962 if c0.rval.IsValid() && c1.rval.IsValid() && (!isInterface(n.typ)) && constOp[n.action] != nil {
963 n.typ.TypeOf() // Force compute of reflection type.
964 constOp[n.action](n) // Compute a constant result now rather than during exec.
965 }
966 switch {
967 case n.rval.IsValid():
968 // This operation involved constants, and the result is already computed
969 // by constOp and available in n.rval. Nothing else to do at execution.
970 n.gen = nop
971 n.findex = notInFrame
972 case n.anc.kind == assignStmt && n.anc.action == aAssign && n.anc.nleft == 1:
973 // To avoid a copy in frame, if the result is to be assigned, store it directly
974 // at the frame location of destination.
975 dest := n.anc.child[childPos(n)-n.anc.nright]
976 n.typ = dest.typ
977 n.findex = dest.findex
978 n.level = dest.level
979 case n.anc.kind == returnStmt:
980 // To avoid a copy in frame, if the result is to be returned, store it directly
981 // at the frame location reserved for output arguments.
982 n.findex = childPos(n)
983 default:
984 // Allocate a new location in frame, and store the result here.
985 n.findex = sc.add(n.typ)
986 }
987 if n.typ != nil && !n.typ.untyped {
988 fixUntyped(n, sc)
989 }
990
991 case indexExpr:
992 if isBlank(n.child[0]) {
993 err = n.cfgErrorf("cannot use _ as value")
994 break
995 }
996 wireChild(n)
997 t := n.child[0].typ
998 for t.cat == linkedT {
999 t = t.val
1000 }
1001 switch t.cat {
1002 case ptrT:
1003 n.typ = t.val
1004 if t.val.cat == valueT {
1005 n.typ = valueTOf(t.val.rtype.Elem())
1006 } else {
1007 n.typ = t.val.val
1008 }
1009 case stringT:
1010 n.typ = sc.getType("byte")
1011 case valueT:
1012 if t.rtype.Kind() == reflect.String {
1013 n.typ = sc.getType("byte")
1014 } else {
1015 n.typ = valueTOf(t.rtype.Elem())
1016 }
1017 case funcT:
1018 // A function indexed by a type means an instantiated generic function.
1019 c1 := n.child[1]
1020 if !c1.isType(sc) {
1021 n.typ = t
1022 return
1023 }
1024 g, found, err := genAST(sc, t.node.anc, []*itype{c1.typ})
1025 if err != nil {
1026 return
1027 }
1028 if !found {
1029 if _, err = interp.cfg(g, t.node.anc.scope, importPath, pkgName); err != nil {
1030 return
1031 }
1032 // Generate closures for function body.
1033 if err = genRun(g.child[3]); err != nil {
1034 return
1035 }
1036 }
1037 // Replace generic func node by instantiated one.
1038 n.anc.child[childPos(n)] = g
1039 n.typ = g.typ
1040 return
1041 case genericT:
1042 name := t.id() + "[" + n.child[1].typ.id() + "]"
1043 sym, _, ok := sc.lookup(name)
1044 if !ok {
1045 err = n.cfgErrorf("type not found: %s", name)
1046 return
1047 }
1048 n.gen = nop
1049 n.typ = sym.typ
1050 return
1051 case structT:
1052 // A struct indexed by a Type means an instantiated generic struct.
1053 name := t.name + "[" + n.child[1].ident + "]"
1054 sym, _, ok := sc.lookup(name)
1055 if ok {
1056 n.typ = sym.typ
1057 n.findex = sc.add(n.typ)
1058 n.gen = nop
1059 return
1060 }
1061
1062 default:
1063 n.typ = t.val
1064 }
1065 n.findex = sc.add(n.typ)
1066 typ := t.TypeOf()
1067 if typ.Kind() == reflect.Map {
1068 err = check.assignment(n.child[1], t.key, "map index")
1069 n.gen = getIndexMap
1070 break
1071 }
1072
1073 l := -1
1074 switch k := typ.Kind(); k {
1075 case reflect.Array:
1076 l = typ.Len()
1077 fallthrough
1078 case reflect.Slice, reflect.String:
1079 n.gen = getIndexArray
1080 case reflect.Ptr:
1081 if typ2 := typ.Elem(); typ2.Kind() == reflect.Array {
1082 l = typ2.Len()
1083 n.gen = getIndexArray
1084 } else {
1085 err = n.cfgErrorf("type %v does not support indexing", typ)
1086 }
1087 default:
1088 err = n.cfgErrorf("type is not an array, slice, string or map: %v", t.id())
1089 }
1090
1091 err = check.index(n.child[1], l)
1092
1093 case blockStmt:
1094 wireChild(n)
1095 if len(n.child) > 0 {
1096 l := n.lastChild()
1097 n.findex = l.findex
1098 n.level = l.level
1099 n.val = l.val
1100 n.sym = l.sym
1101 n.typ = l.typ
1102 n.rval = l.rval
1103 }
1104 sc = sc.pop()
1105
1106 case constDecl:
1107 wireChild(n)
1108
1109 case varDecl:
1110 // Global varDecl do not need to be wired as this
1111 // will be handled after cfg.
1112 if n.anc.kind == fileStmt {
1113 break
1114 }
1115 wireChild(n)
1116
1117 case sendStmt:
1118 if !isChan(n.child[0].typ) {
1119 err = n.cfgErrorf("invalid operation: cannot send to non-channel %s", n.child[0].typ.id())
1120 break
1121 }
1122 fallthrough
1123
1124 case declStmt, exprStmt:
1125 wireChild(n)
1126 l := n.lastChild()
1127 n.findex = l.findex
1128 n.level = l.level
1129 n.val = l.val
1130 n.sym = l.sym
1131 n.typ = l.typ
1132 n.rval = l.rval
1133
1134 case breakStmt:
1135 if len(n.child) == 0 {
1136 n.tnext = sc.loop
1137 break
1138 }
1139 if !n.hasAnc(n.sym.node) {
1140 err = n.cfgErrorf("invalid break label %s", n.child[0].ident)
1141 break
1142 }
1143 n.tnext = n.sym.node
1144
1145 case continueStmt:
1146 if len(n.child) == 0 {
1147 n.tnext = sc.loopRestart
1148 break
1149 }
1150 if !n.hasAnc(n.sym.node) {
1151 err = n.cfgErrorf("invalid continue label %s", n.child[0].ident)
1152 break
1153 }
1154 n.tnext = n.sym.node.child[1].lastChild().start
1155
1156 case gotoStmt:
1157 if n.sym.node == nil {
1158 // It can be only due to a forward goto, to be resolved at labeledStmt.
1159 // Invalid goto labels are catched at AST parsing.
1160 break
1161 }
1162 n.tnext = n.sym.node.start
1163
1164 case labeledStmt:
1165 wireChild(n)
1166 if len(n.child) > 1 {
1167 n.start = n.child[1].start
1168 }
1169 for _, c := range n.sym.from {
1170 c.tnext = n.start // Resolve forward goto.
1171 }
1172
1173 case callExpr:
1174 for _, c := range n.child {
1175 if isBlank(c) {
1176 err = n.cfgErrorf("cannot use _ as value")
1177 return
1178 }
1179 }
1180 wireChild(n)
1181 switch c0 := n.child[0]; {
1182 case c0.kind == indexListExpr:
1183 // Instantiate a generic function then call it.
1184 fun := c0.child[0].sym.node
1185 lt := []*itype{}
1186 for _, c := range c0.child[1:] {
1187 lt = append(lt, c.typ)
1188 }
1189 g, found, err := genAST(sc, fun, lt)
1190 if err != nil {
1191 return
1192 }
1193 if !found {
1194 _, err = interp.cfg(g, fun.scope, importPath, pkgName)
1195 if err != nil {
1196 return
1197 }
1198 err = genRun(g.child[3]) // Generate closures for function body.
1199 if err != nil {
1200 return
1201 }
1202 }
1203 n.child[0] = g
1204 c0 = n.child[0]
1205 wireChild(n)
1206 if typ := c0.typ; len(typ.ret) > 0 {
1207 n.typ = typ.ret[0]
1208 if n.anc.kind == returnStmt && n.typ.id() == sc.def.typ.ret[0].id() {
1209 // Store the result directly to the return value area of frame.
1210 // It can be done only if no type conversion at return is involved.
1211 n.findex = childPos(n)
1212 } else {
1213 n.findex = sc.add(n.typ)
1214 for _, t := range typ.ret[1:] {
1215 sc.add(t)
1216 }
1217 }
1218 } else {
1219 n.findex = notInFrame
1220 }
1221
1222 case isBuiltinCall(n, sc):
1223 bname := c0.ident
1224 err = check.builtin(bname, n, n.child[1:], n.action == aCallSlice)
1225 if err != nil {
1226 break
1227 }
1228
1229 n.gen = c0.sym.builtin
1230 c0.typ = &itype{cat: builtinT, name: bname}
1231 if n.typ, err = nodeType(interp, sc, n); err != nil {
1232 return
1233 }
1234 switch {
1235 case n.typ.cat == builtinT:
1236 n.findex = notInFrame
1237 n.val = nil
1238 switch bname {
1239 case "unsafe.alignOf", "unsafe.Offsetof", "unsafe.Sizeof":
1240 n.gen = nop
1241 }
1242 case n.anc.kind == returnStmt:
1243 // Store result directly to frame output location, to avoid a frame copy.
1244 n.findex = 0
1245 case bname == "cap" && isInConstOrTypeDecl(n):
1246 t := n.child[1].typ.TypeOf()
1247 for t.Kind() == reflect.Ptr {
1248 t = t.Elem()
1249 }
1250 switch t.Kind() {
1251 case reflect.Array, reflect.Chan:
1252 capConst(n)
1253 default:
1254 err = n.cfgErrorf("cap argument is not an array or channel")
1255 }
1256 n.findex = notInFrame
1257 n.gen = nop
1258 case bname == "len" && isInConstOrTypeDecl(n):
1259 t := n.child[1].typ.TypeOf()
1260 for t.Kind() == reflect.Ptr {
1261 t = t.Elem()
1262 }
1263 switch t.Kind() {
1264 case reflect.Array, reflect.Chan, reflect.String:
1265 lenConst(n)
1266 default:
1267 err = n.cfgErrorf("len argument is not an array, channel or string")
1268 }
1269 n.findex = notInFrame
1270 n.gen = nop
1271 default:
1272 n.findex = sc.add(n.typ)
1273 }
1274 if op, ok := constBltn[bname]; ok {
1275 op(n)
1276 }
1277
1278 case c0.isType(sc):
1279 // Type conversion expression
1280 c1 := n.child[1]
1281 switch len(n.child) {
1282 case 1:
1283 err = n.cfgErrorf("missing argument in conversion to %s", c0.typ.id())
1284 case 2:
1285 err = check.conversion(c1, c0.typ)
1286 default:
1287 err = n.cfgErrorf("too many arguments in conversion to %s", c0.typ.id())
1288 }
1289 if err != nil {
1290 break
1291 }
1292
1293 n.action = aConvert
1294 switch {
1295 case isInterface(c0.typ) && !c1.isNil():
1296 // Convert to interface: just check that all required methods are defined by concrete type.
1297 if !c1.typ.implements(c0.typ) {
1298 err = n.cfgErrorf("type %v does not implement interface %v", c1.typ.id(), c0.typ.id())
1299 }
1300 // Convert type to interface while keeping a reference to the original concrete type.
1301 // besides type, the node value remains preserved.
1302 n.gen = nop
1303 t := *c0.typ
1304 n.typ = &t
1305 n.typ.val = c1.typ
1306 n.findex = c1.findex
1307 n.level = c1.level
1308 n.val = c1.val
1309 n.rval = c1.rval
1310 case c1.rval.IsValid() && isConstType(c0.typ):
1311 n.gen = nop
1312 n.findex = notInFrame
1313 n.typ = c0.typ
1314 if c, ok := c1.rval.Interface().(constant.Value); ok {
1315 i, _ := constant.Int64Val(constant.ToInt(c))
1316 n.rval = reflect.ValueOf(i).Convert(c0.typ.rtype)
1317 } else {
1318 n.rval = c1.rval.Convert(c0.typ.rtype)
1319 }
1320 default:
1321 n.gen = convert
1322 n.typ = c0.typ
1323 n.findex = sc.add(n.typ)
1324 }
1325
1326 case isBinCall(n, sc):
1327 err = check.arguments(n, n.child[1:], c0, n.action == aCallSlice)
1328 if err != nil {
1329 break
1330 }
1331
1332 n.gen = callBin
1333 typ := c0.typ.rtype
1334 if typ.NumOut() > 0 {
1335 if funcType := c0.typ.val; funcType != nil {
1336 // Use the original unwrapped function type, to allow future field and
1337 // methods resolutions, otherwise impossible on the opaque bin type.
1338 n.typ = funcType.ret[0]
1339 n.findex = sc.add(n.typ)
1340 for i := 1; i < len(funcType.ret); i++ {
1341 sc.add(funcType.ret[i])
1342 }
1343 } else {
1344 n.typ = valueTOf(typ.Out(0))
1345 if n.anc.kind == returnStmt {
1346 n.findex = childPos(n)
1347 } else {
1348 n.findex = sc.add(n.typ)
1349 for i := 1; i < typ.NumOut(); i++ {
1350 sc.add(valueTOf(typ.Out(i)))
1351 }
1352 }
1353 }
1354 }
1355
1356 default:
1357 // The call may be on a generic function. In that case, replace the
1358 // generic function AST by an instantiated one before going further.
1359 if isGeneric(c0.typ) {
1360 fun := c0.typ.node.anc
1361 var g *node
1362 var types []*itype
1363 var found bool
1364
1365 // Infer type parameter from function call arguments.
1366 if types, err = inferTypesFromCall(sc, fun, n.child[1:]); err != nil {
1367 break
1368 }
1369 // Generate an instantiated AST from the generic function one.
1370 if g, found, err = genAST(sc, fun, types); err != nil {
1371 break
1372 }
1373 if !found {
1374 // Compile the generated function AST, so it becomes part of the scope.
1375 if _, err = interp.cfg(g, fun.scope, importPath, pkgName); err != nil {
1376 break
1377 }
1378 // AST compilation part 2: Generate closures for function body.
1379 if err = genRun(g.child[3]); err != nil {
1380 break
1381 }
1382 }
1383 n.child[0] = g
1384 c0 = n.child[0]
1385 }
1386
1387 err = check.arguments(n, n.child[1:], c0, n.action == aCallSlice)
1388 if err != nil {
1389 break
1390 }
1391
1392 if c0.action == aGetFunc {
1393 // Allocate a frame entry to store the anonymous function definition.
1394 sc.add(c0.typ)
1395 }
1396 if typ := c0.typ; len(typ.ret) > 0 {
1397 n.typ = typ.ret[0]
1398 if n.anc.kind == returnStmt && n.typ.id() == sc.def.typ.ret[0].id() {
1399 // Store the result directly to the return value area of frame.
1400 // It can be done only if no type conversion at return is involved.
1401 n.findex = childPos(n)
1402 } else {
1403 n.findex = sc.add(n.typ)
1404 for _, t := range typ.ret[1:] {
1405 sc.add(t)
1406 }
1407 }
1408 } else {
1409 n.findex = notInFrame
1410 }
1411 }
1412
1413 case caseBody:
1414 wireChild(n)
1415 switch {
1416 case typeSwichAssign(n) && len(n.child) > 1:
1417 n.start = n.child[1].start
1418 case len(n.child) == 0:
1419 // Empty case body: jump to switch node (exit node).
1420 n.start = n.anc.anc.anc
1421 default:
1422 n.start = n.child[0].start
1423 }
1424
1425 case caseClause:
1426 sc = sc.pop()
1427
1428 case commClauseDefault:
1429 wireChild(n)
1430 sc = sc.pop()
1431 if len(n.child) == 0 {
1432 return
1433 }
1434 n.start = n.child[0].start
1435 n.lastChild().tnext = n.anc.anc // exit node is selectStmt
1436
1437 case commClause:
1438 wireChild(n)
1439 sc = sc.pop()
1440 if len(n.child) == 0 {
1441 return
1442 }
1443 if len(n.child) > 1 {
1444 n.start = n.child[1].start // Skip chan operation, performed by select
1445 }
1446 n.lastChild().tnext = n.anc.anc // exit node is selectStmt
1447
1448 case compositeLitExpr:
1449 wireChild(n)
1450
1451 child := n.child
1452 if n.nleft > 0 {
1453 child = child[1:]
1454 }
1455
1456 switch n.typ.cat {
1457 case arrayT, sliceT:
1458 err = check.arrayLitExpr(child, n.typ)
1459 case mapT:
1460 err = check.mapLitExpr(child, n.typ.key, n.typ.val)
1461 case structT:
1462 err = check.structLitExpr(child, n.typ)
1463 case valueT:
1464 rtype := n.typ.rtype
1465 switch rtype.Kind() {
1466 case reflect.Struct:
1467 err = check.structBinLitExpr(child, rtype)
1468 case reflect.Map:
1469 ktyp := valueTOf(rtype.Key())
1470 vtyp := valueTOf(rtype.Elem())
1471 err = check.mapLitExpr(child, ktyp, vtyp)
1472 }
1473 }
1474 if err != nil {
1475 break
1476 }
1477
1478 n.findex = sc.add(n.typ)
1479 // TODO: Check that composite literal expr matches corresponding type
1480 n.gen = compositeGenerator(n, n.typ, nil)
1481
1482 case fallthroughtStmt:
1483 if n.anc.kind != caseBody {
1484 err = n.cfgErrorf("fallthrough statement out of place")
1485 }
1486
1487 case fileStmt:
1488 wireChild(n, varDecl)
1489 sc = sc.pop()
1490 n.findex = notInFrame
1491
1492 case forStmt0: // for {}
1493 body := n.child[0]
1494 n.start = body.start
1495 body.tnext = n.start
1496 sc = sc.pop()
1497
1498 case forStmt1: // for init; ; {}
1499 init, body := n.child[0], n.child[1]
1500 n.start = init.start
1501 init.tnext = body.start
1502 body.tnext = n.start
1503 sc = sc.pop()
1504
1505 case forStmt2: // for cond {}
1506 cond, body := n.child[0], n.child[1]
1507 if !isBool(cond.typ) {
1508 err = cond.cfgErrorf("non-bool used as for condition")
1509 }
1510 if cond.rval.IsValid() {
1511 // Condition is known at compile time, bypass test.
1512 if cond.rval.Bool() {
1513 n.start = body.start
1514 body.tnext = body.start
1515 }
1516 } else {
1517 n.start = cond.start
1518 cond.tnext = body.start
1519 body.tnext = cond.start
1520 }
1521 setFNext(cond, n)
1522 sc = sc.pop()
1523
1524 case forStmt3: // for init; cond; {}
1525 init, cond, body := n.child[0], n.child[1], n.child[2]
1526 if !isBool(cond.typ) {
1527 err = cond.cfgErrorf("non-bool used as for condition")
1528 }
1529 n.start = init.start
1530 if cond.rval.IsValid() {
1531 // Condition is known at compile time, bypass test.
1532 if cond.rval.Bool() {
1533 init.tnext = body.start
1534 body.tnext = body.start
1535 } else {
1536 init.tnext = n
1537 }
1538 } else {
1539 init.tnext = cond.start
1540 body.tnext = cond.start
1541 }
1542 cond.tnext = body.start
1543 setFNext(cond, n)
1544 sc = sc.pop()
1545
1546 case forStmt4: // for ; ; post {}
1547 post, body := n.child[0], n.child[1]
1548 n.start = body.start
1549 post.tnext = body.start
1550 body.tnext = post.start
1551 sc = sc.pop()
1552
1553 case forStmt5: // for ; cond; post {}
1554 cond, post, body := n.child[0], n.child[1], n.child[2]
1555 if !isBool(cond.typ) {
1556 err = cond.cfgErrorf("non-bool used as for condition")
1557 }
1558 if cond.rval.IsValid() {
1559 // Condition is known at compile time, bypass test.
1560 if cond.rval.Bool() {
1561 n.start = body.start
1562 post.tnext = body.start
1563 }
1564 } else {
1565 n.start = cond.start
1566 post.tnext = cond.start
1567 }
1568 cond.tnext = body.start
1569 setFNext(cond, n)
1570 body.tnext = post.start
1571 sc = sc.pop()
1572
1573 case forStmt6: // for init; ; post {}
1574 init, post, body := n.child[0], n.child[1], n.child[2]
1575 n.start = init.start
1576 init.tnext = body.start
1577 body.tnext = post.start
1578 post.tnext = body.start
1579 sc = sc.pop()
1580
1581 case forStmt7: // for init; cond; post {}
1582 init, cond, post, body := n.child[0], n.child[1], n.child[2], n.child[3]
1583 if !isBool(cond.typ) {
1584 err = cond.cfgErrorf("non-bool used as for condition")
1585 }
1586 n.start = init.start
1587 body.start = body.child[0] // loopvar
1588 if cond.rval.IsValid() {
1589 // Condition is known at compile time, bypass test.
1590 if cond.rval.Bool() {
1591 init.tnext = body.start
1592 post.tnext = body.start
1593 } else {
1594 init.tnext = n
1595 }
1596 } else {
1597 init.tnext = cond.start
1598 post.tnext = cond.start
1599 }
1600 cond.tnext = body.start
1601 setFNext(cond, n)
1602 body.tnext = post.start
1603 sc = sc.pop()
1604
1605 case forRangeStmt:
1606 n.start = n.child[0].start
1607 setFNext(n.child[0], n)
1608 sc = sc.pop()
1609
1610 case funcDecl:
1611 n.start = n.child[3].start
1612 n.types, n.scope = sc.types, sc
1613 sc = sc.pop()
1614 funcName := n.child[1].ident
1615 if sym := sc.sym[funcName]; !isMethod(n) && sym != nil && !isGeneric(sym.typ) {
1616 sym.index = -1 // to force value to n.val
1617 sym.typ = n.typ
1618 sym.kind = funcSym
1619 sym.node = n
1620 }
1621
1622 case funcLit:
1623 n.types, n.scope = sc.types, sc
1624 sc = sc.pop()
1625 err = genRun(n)
1626
1627 case deferStmt, goStmt:
1628 wireChild(n)
1629
1630 case identExpr:
1631 if isKey(n) || isNewDefine(n, sc) {
1632 break
1633 }
1634 if n.anc.kind == funcDecl && n.anc.child[1] == n {
1635 // Dont process a function name identExpr.
1636 break
1637 }
1638
1639 sym, level, found := sc.lookup(n.ident)
1640 if !found {
1641 if n.typ != nil {
1642 // Node is a generic instance with an already populated type.
1643 break
1644 }
1645 // retry with the filename, in case ident is a package name.
1646 sym, level, found = sc.lookup(path.Join(n.ident, baseName))
1647 if !found {
1648 err = n.cfgErrorf("undefined: %s", n.ident)
1649 break
1650 }
1651 }
1652 // Found symbol, populate node info
1653 n.sym, n.typ, n.findex, n.level = sym, sym.typ, sym.index, level
1654 if n.findex < 0 {
1655 n.val = sym.node
1656 } else {
1657 switch {
1658 case sym.kind == constSym && sym.rval.IsValid():
1659 n.rval = sym.rval
1660 n.kind = basicLit
1661 case n.ident == "iota":
1662 n.rval = reflect.ValueOf(constant.MakeInt64(int64(sc.iota)))
1663 n.kind = basicLit
1664 case n.ident == nilIdent:
1665 n.kind = basicLit
1666 case sym.kind == binSym:
1667 n.typ = sym.typ
1668 n.rval = sym.rval
1669 case sym.kind == bltnSym:
1670 if n.anc.kind != callExpr {
1671 err = n.cfgErrorf("use of builtin %s not in function call", n.ident)
1672 }
1673 }
1674 }
1675 if n.sym != nil {
1676 n.recv = n.sym.recv
1677 }
1678
1679 case ifStmt0: // if cond {}
1680 cond, tbody := n.child[0], n.child[1]
1681 if !isBool(cond.typ) {
1682 err = cond.cfgErrorf("non-bool used as if condition")
1683 }
1684 if cond.rval.IsValid() {
1685 // Condition is known at compile time, bypass test.
1686 if cond.rval.Bool() {
1687 n.start = tbody.start
1688 }
1689 } else {
1690 n.start = cond.start
1691 cond.tnext = tbody.start
1692 }
1693 setFNext(cond, n)
1694 tbody.tnext = n
1695 sc = sc.pop()
1696
1697 case ifStmt1: // if cond {} else {}
1698 cond, tbody, fbody := n.child[0], n.child[1], n.child[2]
1699 if !isBool(cond.typ) {
1700 err = cond.cfgErrorf("non-bool used as if condition")
1701 }
1702 if cond.rval.IsValid() {
1703 // Condition is known at compile time, bypass test and the useless branch.
1704 if cond.rval.Bool() {
1705 n.start = tbody.start
1706 } else {
1707 n.start = fbody.start
1708 }
1709 } else {
1710 n.start = cond.start
1711 cond.tnext = tbody.start
1712 setFNext(cond, fbody.start)
1713 }
1714 tbody.tnext = n
1715 fbody.tnext = n
1716 sc = sc.pop()
1717
1718 case ifStmt2: // if init; cond {}
1719 init, cond, tbody := n.child[0], n.child[1], n.child[2]
1720 if !isBool(cond.typ) {
1721 err = cond.cfgErrorf("non-bool used as if condition")
1722 }
1723 n.start = init.start
1724 if cond.rval.IsValid() {
1725 // Condition is known at compile time, bypass test.
1726 if cond.rval.Bool() {
1727 init.tnext = tbody.start
1728 } else {
1729 init.tnext = n
1730 }
1731 } else {
1732 init.tnext = cond.start
1733 cond.tnext = tbody.start
1734 }
1735 tbody.tnext = n
1736 setFNext(cond, n)
1737 sc = sc.pop()
1738
1739 case ifStmt3: // if init; cond {} else {}
1740 init, cond, tbody, fbody := n.child[0], n.child[1], n.child[2], n.child[3]
1741 if !isBool(cond.typ) {
1742 err = cond.cfgErrorf("non-bool used as if condition")
1743 }
1744 n.start = init.start
1745 if cond.rval.IsValid() {
1746 // Condition is known at compile time, bypass test.
1747 if cond.rval.Bool() {
1748 init.tnext = tbody.start
1749 } else {
1750 init.tnext = fbody.start
1751 }
1752 } else {
1753 init.tnext = cond.start
1754 cond.tnext = tbody.start
1755 setFNext(cond, fbody.start)
1756 }
1757 tbody.tnext = n
1758 fbody.tnext = n
1759 sc = sc.pop()
1760
1761 case keyValueExpr:
1762 if isBlank(n.child[1]) {
1763 err = n.cfgErrorf("cannot use _ as value")
1764 break
1765 }
1766 wireChild(n)
1767
1768 case landExpr:
1769 if isBlank(n.child[0]) || isBlank(n.child[1]) {
1770 err = n.cfgErrorf("cannot use _ as value")
1771 break
1772 }
1773 n.start = n.child[0].start
1774 n.child[0].tnext = n.child[1].start
1775 setFNext(n.child[0], n)
1776 n.child[1].tnext = n
1777 n.typ = n.child[0].typ
1778 n.findex = sc.add(n.typ)
1779 if n.start.action == aNop {
1780 n.start.gen = branch
1781 }
1782
1783 case lorExpr:
1784 if isBlank(n.child[0]) || isBlank(n.child[1]) {
1785 err = n.cfgErrorf("cannot use _ as value")
1786 break
1787 }
1788 n.start = n.child[0].start
1789 n.child[0].tnext = n
1790 setFNext(n.child[0], n.child[1].start)
1791 n.child[1].tnext = n
1792 n.typ = n.child[0].typ
1793 n.findex = sc.add(n.typ)
1794 if n.start.action == aNop {
1795 n.start.gen = branch
1796 }
1797
1798 case parenExpr:
1799 wireChild(n)
1800 c := n.lastChild()
1801 n.findex = c.findex
1802 n.level = c.level
1803 n.typ = c.typ
1804 n.rval = c.rval
1805
1806 case rangeStmt:
1807 if sc.rangeChanType(n) != nil {
1808 n.start = n.child[1].start // Get chan
1809 n.child[1].tnext = n // then go to range function
1810 n.tnext = n.child[2].start // then go to range body
1811 n.child[2].tnext = n // then body go to range function (loop)
1812 n.child[0].gen = empty
1813 } else {
1814 var k, o, body *node
1815 if len(n.child) == 4 {
1816 k, o, body = n.child[0], n.child[2], n.child[3]
1817 } else {
1818 k, o, body = n.child[0], n.child[1], n.child[2]
1819 }
1820 n.start = o.start // Get array or map object
1821 o.tnext = k.start // then go to iterator init
1822 k.tnext = n // then go to range function
1823 body.start = body.child[0] // loopvar
1824 n.tnext = body.start // then go to range body
1825 body.tnext = n // then body go to range function (loop)
1826 k.gen = empty // init filled later by generator
1827 }
1828
1829 case returnStmt:
1830 if len(n.child) > sc.def.typ.numOut() {
1831 err = n.cfgErrorf("too many arguments to return")
1832 break
1833 }
1834 for _, c := range n.child {
1835 if isBlank(c) {
1836 err = n.cfgErrorf("cannot use _ as value")
1837 return
1838 }
1839 }
1840 returnSig := sc.def.child[2]
1841 if mustReturnValue(returnSig) {
1842 nret := len(n.child)
1843 if nret == 1 && isCall(n.child[0]) {
1844 nret = n.child[0].child[0].typ.numOut()
1845 }
1846 if nret < sc.def.typ.numOut() {
1847 err = n.cfgErrorf("not enough arguments to return")
1848 break
1849 }
1850 }
1851 wireChild(n)
1852 n.tnext = nil
1853 n.val = sc.def
1854 for i, c := range n.child {
1855 var typ *itype
1856 typ, err = nodeType(interp, sc.upperLevel(), returnSig.child[2].fieldType(i))
1857 if err != nil {
1858 return
1859 }
1860 // TODO(mpl): move any of that code to typecheck?
1861 c.typ.node = c
1862 if !c.typ.assignableTo(typ) {
1863 err = c.cfgErrorf("cannot use %v (type %v) as type %v in return argument", c.ident, c.typ.cat, typ.cat)
1864 return
1865 }
1866 if c.typ.cat == nilT {
1867 // nil: Set node value to zero of return type
1868 c.rval = reflect.New(typ.TypeOf()).Elem()
1869 }
1870 }
1871
1872 case selectorExpr:
1873 wireChild(n)
1874 n.typ = n.child[0].typ
1875 n.recv = n.child[0].recv
1876 if n.typ == nil {
1877 err = n.cfgErrorf("undefined type")
1878 break
1879 }
1880 switch {
1881 case n.typ.cat == binPkgT:
1882 // Resolve binary package symbol: a type or a value
1883 name := n.child[1].ident
1884 pkg := n.child[0].sym.typ.path
1885 if s, ok := interp.binPkg[pkg][name]; ok {
1886 if isBinType(s) {
1887 n.typ = valueTOf(s.Type().Elem())
1888 } else {
1889 n.typ = valueTOf(fixPossibleConstType(s.Type()), withUntyped(isValueUntyped(s)))
1890 n.rval = s
1891 if pkg == "unsafe" && (name == "AlignOf" || name == "Offsetof" || name == "Sizeof") {
1892 n.sym = &symbol{kind: bltnSym, node: n, rval: s}
1893 n.ident = pkg + "." + name
1894 }
1895 }
1896 n.action = aGetSym
1897 n.gen = nop
1898 } else {
1899 err = n.cfgErrorf("package %s \"%s\" has no symbol %s", n.child[0].ident, pkg, name)
1900 }
1901 case n.typ.cat == srcPkgT:
1902 pkg, name := n.child[0].sym.typ.path, n.child[1].ident
1903 // Resolve source package symbol
1904 if sym, ok := interp.srcPkg[pkg][name]; ok {
1905 n.findex = sym.index
1906 if sym.global {
1907 n.level = globalFrame
1908 }
1909 n.val = sym.node
1910 n.gen = nop
1911 n.action = aGetSym
1912 n.typ = sym.typ
1913 n.sym = sym
1914 n.recv = sym.recv
1915 n.rval = sym.rval
1916 } else {
1917 err = n.cfgErrorf("undefined selector: %s.%s", pkg, name)
1918 }
1919 case isStruct(n.typ) || isInterfaceSrc(n.typ):
1920 // Find a matching field.
1921 if ti := n.typ.lookupField(n.child[1].ident); len(ti) > 0 {
1922 if isStruct(n.typ) {
1923 // If a method of the same name exists, use it if it is shallower than the struct field.
1924 // if method's depth is the same as field's, this is an error.
1925 d := n.typ.methodDepth(n.child[1].ident)
1926 if d >= 0 && d < len(ti) {
1927 goto tryMethods
1928 }
1929 if d == len(ti) {
1930 err = n.cfgErrorf("ambiguous selector: %s", n.child[1].ident)
1931 break
1932 }
1933 }
1934 n.val = ti
1935 switch {
1936 case isInterfaceSrc(n.typ):
1937 n.typ = n.typ.fieldSeq(ti)
1938 n.gen = getMethodByName
1939 n.action = aMethod
1940 case n.typ.cat == ptrT:
1941 n.typ = n.typ.fieldSeq(ti)
1942 n.gen = getPtrIndexSeq
1943 if n.typ.cat == funcT {
1944 // Function in a struct field is always wrapped in reflect.Value.
1945 n.typ = wrapperValueTOf(n.typ.TypeOf(), n.typ)
1946 }
1947 default:
1948 n.gen = getIndexSeq
1949 n.typ = n.typ.fieldSeq(ti)
1950 if n.typ.cat == funcT {
1951 // Function in a struct field is always wrapped in reflect.Value.
1952 n.typ = wrapperValueTOf(n.typ.TypeOf(), n.typ)
1953 }
1954 }
1955 break
1956 }
1957 if s, lind, ok := n.typ.lookupBinField(n.child[1].ident); ok {
1958 // Handle an embedded binary field into a struct field.
1959 n.gen = getIndexSeqField
1960 lind = append(lind, s.Index...)
1961 if isStruct(n.typ) {
1962 // If a method of the same name exists, use it if it is shallower than the struct field.
1963 // if method's depth is the same as field's, this is an error.
1964 d := n.typ.methodDepth(n.child[1].ident)
1965 if d >= 0 && d < len(lind) {
1966 goto tryMethods
1967 }
1968 if d == len(lind) {
1969 err = n.cfgErrorf("ambiguous selector: %s", n.child[1].ident)
1970 break
1971 }
1972 }
1973 n.val = lind
1974 n.typ = valueTOf(s.Type)
1975 break
1976 }
1977 // No field (embedded or not) matched. Try to match a method.
1978 tryMethods:
1979 fallthrough
1980 default:
1981 err = matchSelectorMethod(sc, n)
1982 }
1983 if err == nil && n.findex != -1 && n.typ.cat != genericT {
1984 n.findex = sc.add(n.typ)
1985 }
1986
1987 case selectStmt:
1988 wireChild(n)
1989 // Move action to block statement, so select node can be an exit point.
1990 n.child[0].gen = _select
1991 // Chain channel init actions in commClauses prior to invoking select.
1992 var cur *node
1993 for _, c := range n.child[0].child {
1994 if c.kind == commClauseDefault {
1995 // No channel init in this case.
1996 continue
1997 }
1998 var an, pn *node // channel init action nodes
1999 if len(c.child) > 0 {
2000 switch c0 := c.child[0]; {
2001 case c0.kind == exprStmt && len(c0.child) == 1 && c0.child[0].action == aRecv:
2002 an = c0.child[0].child[0]
2003 pn = an
2004 case c0.action == aAssign:
2005 an = c0.lastChild().child[0]
2006 pn = an
2007 case c0.kind == sendStmt:
2008 an = c0.child[0]
2009 pn = c0.child[1]
2010 }
2011 }
2012 if an == nil {
2013 continue
2014 }
2015 if cur == nil {
2016 // First channel init action, the entry point for the select block.
2017 n.start = an.start
2018 } else {
2019 // Chain channel init action to the previous one.
2020 cur.tnext = an.start
2021 }
2022 if pn != nil {
2023 // Chain channect init action to send data init action.
2024 // (already done by wireChild, but let's be explicit).
2025 an.tnext = pn
2026 cur = pn
2027 }
2028 }
2029 if cur == nil {
2030 // There is no channel init action, call select directly.
2031 n.start = n.child[0]
2032 } else {
2033 // Select is called after the last channel init action.
2034 cur.tnext = n.child[0]
2035 }
2036
2037 case starExpr:
2038 if isBlank(n.child[0]) {
2039 err = n.cfgErrorf("cannot use _ as value")
2040 break
2041 }
2042 switch {
2043 case n.anc.kind == defineStmt && len(n.anc.child) == 3 && n.anc.child[1] == n:
2044 // pointer type expression in a var definition
2045 n.gen = nop
2046 case n.anc.kind == valueSpec && n.anc.lastChild() == n:
2047 // pointer type expression in a value spec
2048 n.gen = nop
2049 case n.anc.kind == fieldExpr:
2050 // pointer type expression in a field expression (arg or struct field)
2051 n.gen = nop
2052 case n.child[0].isType(sc):
2053 // pointer type expression
2054 n.gen = nop
2055 n.typ = ptrOf(n.child[0].typ)
2056 default:
2057 // dereference expression
2058 wireChild(n)
2059
2060 err = check.starExpr(n.child[0])
2061 if err != nil {
2062 break
2063 }
2064
2065 if c0 := n.child[0]; c0.typ.cat == valueT {
2066 n.typ = valueTOf(c0.typ.rtype.Elem())
2067 } else {
2068 n.typ = c0.typ.val
2069 }
2070 n.findex = sc.add(n.typ)
2071 }
2072
2073 case typeSwitch:
2074 // Check that cases expressions are all different
2075 usedCase := map[string]bool{}
2076 for _, c := range n.lastChild().child {
2077 for _, t := range c.child[:len(c.child)-1] {
2078 tid := t.typ.id()
2079 if usedCase[tid] {
2080 err = c.cfgErrorf("duplicate case %s in type switch", t.ident)
2081 return
2082 }
2083 usedCase[tid] = true
2084 }
2085 }
2086 fallthrough
2087
2088 case switchStmt:
2089 sc = sc.pop()
2090 sbn := n.lastChild() // switch block node
2091 clauses := sbn.child
2092 l := len(clauses)
2093 if l == 0 {
2094 // Switch is empty
2095 break
2096 }
2097 // Chain case clauses.
2098 for i := l - 1; i >= 0; i-- {
2099 c := clauses[i]
2100 if len(c.child) == 0 {
2101 c.tnext = n // Clause body is empty, exit.
2102 } else {
2103 body := c.lastChild()
2104 c.tnext = body.start
2105 c.child[0].tnext = c
2106 c.start = c.child[0].start
2107
2108 if i < l-1 && len(body.child) > 0 && body.lastChild().kind == fallthroughtStmt {
2109 if n.kind == typeSwitch {
2110 err = body.lastChild().cfgErrorf("cannot fallthrough in type switch")
2111 }
2112 if len(clauses[i+1].child) == 0 {
2113 body.tnext = n // Fallthrough to next with empty body, just exit.
2114 } else {
2115 body.tnext = clauses[i+1].lastChild().start
2116 }
2117 } else {
2118 body.tnext = n // Exit switch at end of clause body.
2119 }
2120 }
2121
2122 if i == l-1 {
2123 setFNext(clauses[i], n)
2124 continue
2125 }
2126 if len(clauses[i+1].child) > 1 {
2127 setFNext(c, clauses[i+1].start)
2128 } else {
2129 setFNext(c, clauses[i+1])
2130 }
2131 }
2132 sbn.start = clauses[0].start
2133 n.start = n.child[0].start
2134 if n.kind == typeSwitch {
2135 // Handle the typeSwitch init (the type assert expression).
2136 init := n.child[1].lastChild().child[0]
2137 init.tnext = sbn.start
2138 n.child[0].tnext = init.start
2139 } else {
2140 n.child[0].tnext = sbn.start
2141 }
2142
2143 case switchIfStmt: // like an if-else chain
2144 sc = sc.pop()
2145 sbn := n.lastChild() // switch block node
2146 clauses := sbn.child
2147 l := len(clauses)
2148 if l == 0 {
2149 // Switch is empty
2150 break
2151 }
2152 // Wire case clauses in reverse order so the next start node is already resolved when used.
2153 for i := l - 1; i >= 0; i-- {
2154 c := clauses[i]
2155 c.gen = nop
2156 if len(c.child) == 0 {
2157 c.tnext = n
2158 c.fnext = n
2159 } else {
2160 body := c.lastChild()
2161 if len(c.child) > 1 {
2162 cond := c.child[0]
2163 cond.tnext = body.start
2164 if i == l-1 {
2165 setFNext(cond, n)
2166 } else {
2167 setFNext(cond, clauses[i+1].start)
2168 }
2169 c.start = cond.start
2170 } else {
2171 c.start = body.start
2172 }
2173 // If last case body statement is a fallthrough, then jump to next case body
2174 if i < l-1 && len(body.child) > 0 && body.lastChild().kind == fallthroughtStmt {
2175 body.tnext = clauses[i+1].lastChild().start
2176 } else {
2177 body.tnext = n
2178 }
2179 }
2180 }
2181 sbn.start = clauses[0].start
2182 n.start = n.child[0].start
2183 n.child[0].tnext = sbn.start
2184
2185 case typeAssertExpr:
2186 if len(n.child) == 1 {
2187 // The "o.(type)" is handled by typeSwitch.
2188 n.gen = nop
2189 break
2190 }
2191
2192 wireChild(n)
2193 c0, c1 := n.child[0], n.child[1]
2194 if isBlank(c0) || isBlank(c1) {
2195 err = n.cfgErrorf("cannot use _ as value")
2196 break
2197 }
2198 if c1.typ == nil {
2199 if c1.typ, err = nodeType(interp, sc, c1); err != nil {
2200 return
2201 }
2202 }
2203
2204 err = check.typeAssertionExpr(c0, c1.typ)
2205 if err != nil {
2206 break
2207 }
2208
2209 if n.anc.action != aAssignX {
2210 if c0.typ.cat == valueT && isFunc(c1.typ) {
2211 // Avoid special wrapping of interfaces and func types.
2212 n.typ = valueTOf(c1.typ.TypeOf())
2213 } else {
2214 n.typ = c1.typ
2215 }
2216 n.findex = sc.add(n.typ)
2217 }
2218
2219 case sliceExpr:
2220 wireChild(n)
2221
2222 err = check.sliceExpr(n)
2223 if err != nil {
2224 break
2225 }
2226
2227 if n.typ, err = nodeType(interp, sc, n); err != nil {
2228 return
2229 }
2230 n.findex = sc.add(n.typ)
2231
2232 case unaryExpr:
2233 wireChild(n)
2234
2235 err = check.unaryExpr(n)
2236 if err != nil {
2237 break
2238 }
2239
2240 n.typ = n.child[0].typ
2241 if n.action == aRecv {
2242 // Channel receive operation: set type to the channel data type
2243 if n.typ.cat == valueT {
2244 n.typ = valueTOf(n.typ.rtype.Elem())
2245 } else {
2246 n.typ = n.typ.val
2247 }
2248 }
2249 if n.typ == nil {
2250 if n.typ, err = nodeType(interp, sc, n); err != nil {
2251 return
2252 }
2253 }
2254
2255 // TODO: Optimisation: avoid allocation if boolean branch op (i.e. '!' in an 'if' expr)
2256 if n.child[0].rval.IsValid() && !isInterface(n.typ) && constOp[n.action] != nil {
2257 n.typ.TypeOf() // init reflect type
2258 constOp[n.action](n)
2259 }
2260 switch {
2261 case n.rval.IsValid():
2262 n.gen = nop
2263 n.findex = notInFrame
2264 case n.anc.kind == assignStmt && n.anc.action == aAssign && n.anc.nright == 1:
2265 dest := n.anc.child[childPos(n)-n.anc.nright]
2266 n.typ = dest.typ
2267 n.findex = dest.findex
2268 n.level = dest.level
2269 case n.anc.kind == returnStmt:
2270 pos := childPos(n)
2271 n.typ = sc.def.typ.ret[pos]
2272 n.findex = pos
2273 default:
2274 n.findex = sc.add(n.typ)
2275 }
2276
2277 case valueSpec:
2278 n.gen = reset
2279 l := len(n.child) - 1
2280 if n.typ = n.child[l].typ; n.typ == nil {
2281 if n.typ, err = nodeType(interp, sc, n.child[l]); err != nil {
2282 return
2283 }
2284 }
2285
2286 for _, c := range n.child[:l] {
2287 var index int
2288 if sc.global {
2289 // Global object allocation is already performed in GTA.
2290 index = sc.sym[c.ident].index
2291 c.level = globalFrame
2292 } else {
2293 index = sc.add(n.typ)
2294 sc.sym[c.ident] = &symbol{index: index, kind: varSym, typ: n.typ}
2295 }
2296 c.typ = n.typ
2297 c.findex = index
2298 }
2299 }
2300 })
2301
2302 if sc != interp.universe {
2303 sc.pop()
2304 }
2305 return initNodes, err
2306 }
2307
2308 // fixUntyped propagates implicit type conversions for untyped binary expressions.
2309 func fixUntyped(nod *node, sc *scope) {
2310 nod.Walk(func(n *node) bool {
2311 if n == nod || (n.kind != binaryExpr && n.kind != parenExpr) || !n.typ.untyped {
2312 return true
2313 }
2314 n.typ = nod.typ
2315 if n.findex >= 0 {
2316 sc.types[n.findex] = nod.typ.frameType()
2317 }
2318 return true
2319 }, nil)
2320 }
2321
2322 func compDefineX(sc *scope, n *node) error {
2323 l := len(n.child) - 1
2324 types := []*itype{}
2325
2326 switch src := n.child[l]; src.kind {
2327 case callExpr:
2328 funtype, err := nodeType(n.interp, sc, src.child[0])
2329 if err != nil {
2330 return err
2331 }
2332 for funtype.cat == valueT && funtype.val != nil {
2333 // Retrieve original interpreter type from a wrapped function.
2334 // Struct fields of function types are always wrapped in valueT to ensure
2335 // their possible use in runtime. In that case, the val field retains the
2336 // original interpreter type, which is used now.
2337 funtype = funtype.val
2338 }
2339 if funtype.cat == valueT {
2340 // Handle functions imported from runtime.
2341 for i := 0; i < funtype.rtype.NumOut(); i++ {
2342 types = append(types, valueTOf(funtype.rtype.Out(i)))
2343 }
2344 } else {
2345 types = funtype.ret
2346 }
2347 if n.anc.kind == varDecl && n.child[l-1].isType(sc) {
2348 l--
2349 }
2350 if len(types) != l {
2351 return n.cfgErrorf("assignment mismatch: %d variables but %s returns %d values", l, src.child[0].name(), len(types))
2352 }
2353 if isBinCall(src, sc) {
2354 n.gen = nop
2355 } else {
2356 // TODO (marc): skip if no conversion or wrapping is needed.
2357 n.gen = assignFromCall
2358 }
2359
2360 case indexExpr:
2361 types = append(types, src.typ, sc.getType("bool"))
2362 n.child[l].gen = getIndexMap2
2363 n.gen = nop
2364
2365 case typeAssertExpr:
2366 if n.child[0].ident == "_" {
2367 n.child[l].gen = typeAssertStatus
2368 } else {
2369 n.child[l].gen = typeAssertLong
2370 }
2371 types = append(types, n.child[l].child[1].typ, sc.getType("bool"))
2372 n.gen = nop
2373
2374 case unaryExpr:
2375 if n.child[l].action == aRecv {
2376 types = append(types, src.typ, sc.getType("bool"))
2377 n.child[l].gen = recv2
2378 n.gen = nop
2379 }
2380
2381 default:
2382 return n.cfgErrorf("unsupported assign expression")
2383 }
2384
2385 // Handle redeclarations: find out new symbols vs existing ones.
2386 symIsNew := map[string]bool{}
2387 hasNewSymbol := false
2388 for i := range types {
2389 id := n.child[i].ident
2390 if id == "_" || id == "" {
2391 continue
2392 }
2393 if _, found := symIsNew[id]; found {
2394 return n.cfgErrorf("%s repeated on left side of :=", id)
2395 }
2396 // A new symbol doesn't exist in current scope. Upper scopes are not
2397 // taken into accout here, as a new symbol can shadow an existing one.
2398 if _, found := sc.sym[id]; found {
2399 symIsNew[id] = false
2400 } else {
2401 symIsNew[id] = true
2402 hasNewSymbol = true
2403 }
2404 }
2405
2406 for i, t := range types {
2407 var index int
2408 id := n.child[i].ident
2409 // A variable can be redeclared if at least one other not blank variable is created.
2410 // The redeclared variable must be of same type (it is reassigned, not created).
2411 // Careful to not reuse a variable which has been shadowed (it must not be a newSym).
2412 sym, level, ok := sc.lookup(id)
2413 canRedeclare := hasNewSymbol && len(symIsNew) > 1 && !symIsNew[id] && ok
2414 if canRedeclare && level == n.child[i].level && sym.kind == varSym && sym.typ.id() == t.id() {
2415 index = sym.index
2416 n.child[i].redeclared = true
2417 } else {
2418 index = sc.add(t)
2419 sc.sym[id] = &symbol{index: index, kind: varSym, typ: t}
2420 }
2421 n.child[i].typ = t
2422 n.child[i].findex = index
2423 }
2424 return nil
2425 }
2426
2427 // TODO used for allocation optimization, temporarily disabled
2428 // func isAncBranch(n *node) bool {
2429 // switch n.anc.kind {
2430 // case If0, If1, If2, If3:
2431 // return true
2432 // }
2433 // return false
2434 // }
2435
2436 func childPos(n *node) int {
2437 for i, c := range n.anc.child {
2438 if n == c {
2439 return i
2440 }
2441 }
2442 return -1
2443 }
2444
2445 func (n *node) cfgErrorf(format string, a ...interface{}) *cfgError {
2446 pos := n.interp.fset.Position(n.pos)
2447 posString := n.interp.fset.Position(n.pos).String()
2448 if pos.Filename == DefaultSourceName {
2449 posString = strings.TrimPrefix(posString, DefaultSourceName+":")
2450 }
2451 a = append([]interface{}{posString}, a...)
2452 return &cfgError{n, fmt.Errorf("%s: "+format, a...)}
2453 }
2454
2455 func genRun(nod *node) error {
2456 var err error
2457 seen := map[*node]bool{}
2458
2459 nod.Walk(func(n *node) bool {
2460 if err != nil || seen[n] {
2461 return false
2462 }
2463 seen[n] = true
2464 switch n.kind {
2465 case funcType:
2466 if len(n.anc.child) == 4 {
2467 // function body entry point
2468 setExec(n.anc.child[3].start)
2469 }
2470 // continue in function body as there may be inner function definitions
2471 case constDecl, varDecl:
2472 setExec(n.start)
2473 return false
2474 }
2475 return true
2476 }, nil)
2477
2478 return err
2479 }
2480
2481 func genGlobalVars(roots []*node, sc *scope) (*node, error) {
2482 var vars []*node
2483 for _, n := range roots {
2484 vars = append(vars, getVars(n)...)
2485 }
2486
2487 if len(vars) == 0 {
2488 return nil, nil
2489 }
2490
2491 varNode, err := genGlobalVarDecl(vars, sc)
2492 if err != nil {
2493 return nil, err
2494 }
2495 setExec(varNode.start)
2496 return varNode, nil
2497 }
2498
2499 func getVars(n *node) (vars []*node) {
2500 for _, child := range n.child {
2501 if child.kind == varDecl {
2502 vars = append(vars, child.child...)
2503 }
2504 }
2505 return vars
2506 }
2507
2508 func genGlobalVarDecl(nodes []*node, sc *scope) (*node, error) {
2509 varNode := &node{kind: varDecl, action: aNop, gen: nop}
2510
2511 deps := map[*node][]*node{}
2512 for _, n := range nodes {
2513 deps[n] = getVarDependencies(n, sc)
2514 }
2515
2516 inited := map[*node]bool{}
2517 revisit := []*node{}
2518 for {
2519 for _, n := range nodes {
2520 canInit := true
2521 for _, d := range deps[n] {
2522 if !inited[d] {
2523 canInit = false
2524 }
2525 }
2526 if !canInit {
2527 revisit = append(revisit, n)
2528 continue
2529 }
2530
2531 varNode.child = append(varNode.child, n)
2532 inited[n] = true
2533 }
2534
2535 if len(revisit) == 0 || equalNodes(nodes, revisit) {
2536 break
2537 }
2538
2539 nodes = revisit
2540 revisit = []*node{}
2541 }
2542
2543 if len(revisit) > 0 {
2544 return nil, revisit[0].cfgErrorf("variable definition loop")
2545 }
2546 wireChild(varNode)
2547 return varNode, nil
2548 }
2549
2550 func getVarDependencies(nod *node, sc *scope) (deps []*node) {
2551 nod.Walk(func(n *node) bool {
2552 if n.kind != identExpr {
2553 return true
2554 }
2555 // Process ident nodes, and avoid false dependencies.
2556 if n.anc.kind == selectorExpr && childPos(n) == 1 {
2557 return false
2558 }
2559 sym, _, ok := sc.lookup(n.ident)
2560 if !ok {
2561 return false
2562 }
2563 if sym.kind != varSym || !sym.global || sym.node == nod {
2564 return false
2565 }
2566 deps = append(deps, sym.node)
2567 return false
2568 }, nil)
2569 return deps
2570 }
2571
2572 // setFnext sets the cond fnext field to next, propagates it for parenthesis blocks
2573 // and sets the action to branch.
2574 func setFNext(cond, next *node) {
2575 if cond.action == aNop {
2576 cond.action = aBranch
2577 cond.gen = branch
2578 cond.fnext = next
2579 }
2580 if cond.kind == parenExpr {
2581 setFNext(cond.lastChild(), next)
2582 return
2583 }
2584 cond.fnext = next
2585 }
2586
2587 // GetDefault return the index of default case clause in a switch statement, or -1.
2588 func getDefault(n *node) int {
2589 for i, c := range n.lastChild().child {
2590 switch len(c.child) {
2591 case 0:
2592 return i
2593 case 1:
2594 if c.child[0].kind == caseBody {
2595 return i
2596 }
2597 }
2598 }
2599 return -1
2600 }
2601
2602 func isBinType(v reflect.Value) bool { return v.IsValid() && v.Kind() == reflect.Ptr && v.IsNil() }
2603
2604 // isType returns true if node refers to a type definition, false otherwise.
2605 func (n *node) isType(sc *scope) bool {
2606 switch n.kind {
2607 case arrayType, chanType, chanTypeRecv, chanTypeSend, funcType, interfaceType, mapType, structType:
2608 return true
2609 case parenExpr, starExpr:
2610 if len(n.child) == 1 {
2611 return n.child[0].isType(sc)
2612 }
2613 case selectorExpr:
2614 pkg, name := n.child[0].ident, n.child[1].ident
2615 baseName := path.Base(n.interp.fset.Position(n.pos).Filename)
2616 suffixedPkg := path.Join(pkg, baseName)
2617 sym, _, ok := sc.lookup(suffixedPkg)
2618 if !ok {
2619 sym, _, ok = sc.lookup(pkg)
2620 if !ok {
2621 return false
2622 }
2623 }
2624 if sym.kind != pkgSym {
2625 return false
2626 }
2627 path := sym.typ.path
2628 if p, ok := n.interp.binPkg[path]; ok && isBinType(p[name]) {
2629 return true // Imported binary type
2630 }
2631 if p, ok := n.interp.srcPkg[path]; ok && p[name] != nil && p[name].kind == typeSym {
2632 return true // Imported source type
2633 }
2634 case identExpr:
2635 return sc.getType(n.ident) != nil
2636 case indexExpr:
2637 // Maybe a generic type.
2638 sym, _, ok := sc.lookup(n.child[0].ident)
2639 return ok && sym.kind == typeSym
2640 }
2641 return false
2642 }
2643
2644 // wireChild wires AST nodes for CFG in subtree.
2645 func wireChild(n *node, exclude ...nkind) {
2646 child := excludeNodeKind(n.child, exclude)
2647
2648 // Set start node, in subtree (propagated to ancestors by post-order processing)
2649 for _, c := range child {
2650 switch c.kind {
2651 case arrayType, chanType, chanTypeRecv, chanTypeSend, funcDecl, importDecl, mapType, basicLit, identExpr, typeDecl:
2652 continue
2653 default:
2654 n.start = c.start
2655 }
2656 break
2657 }
2658
2659 // Chain sequential operations inside a block (next is right sibling)
2660 for i := 1; i < len(child); i++ {
2661 switch child[i].kind {
2662 case funcDecl:
2663 child[i-1].tnext = child[i]
2664 default:
2665 switch child[i-1].kind {
2666 case breakStmt, continueStmt, gotoStmt, returnStmt:
2667 // tnext is already computed, no change
2668 default:
2669 child[i-1].tnext = child[i].start
2670 }
2671 }
2672 }
2673
2674 // Chain subtree next to self
2675 for i := len(child) - 1; i >= 0; i-- {
2676 switch child[i].kind {
2677 case arrayType, chanType, chanTypeRecv, chanTypeSend, importDecl, mapType, funcDecl, basicLit, identExpr, typeDecl:
2678 continue
2679 case breakStmt, continueStmt, gotoStmt, returnStmt:
2680 // tnext is already computed, no change
2681 default:
2682 child[i].tnext = n
2683 }
2684 break
2685 }
2686 }
2687
2688 func excludeNodeKind(child []*node, kinds []nkind) []*node {
2689 if len(kinds) == 0 {
2690 return child
2691 }
2692 var res []*node
2693 for _, c := range child {
2694 exclude := false
2695 for _, k := range kinds {
2696 if c.kind == k {
2697 exclude = true
2698 }
2699 }
2700 if !exclude {
2701 res = append(res, c)
2702 }
2703 }
2704 return res
2705 }
2706
2707 func (n *node) name() (s string) {
2708 switch {
2709 case n.ident != "":
2710 s = n.ident
2711 case n.action == aGetSym:
2712 s = n.child[0].ident + "." + n.child[1].ident
2713 }
2714 return s
2715 }
2716
2717 // isNatural returns true if node type is natural, false otherwise.
2718 func (n *node) isNatural() bool {
2719 if isUint(n.typ.TypeOf()) {
2720 return true
2721 }
2722 if n.rval.IsValid() {
2723 t := n.rval.Type()
2724 if isUint(t) {
2725 return true
2726 }
2727 if isInt(t) && n.rval.Int() >= 0 {
2728 // positive untyped integer constant is ok
2729 return true
2730 }
2731 if isFloat(t) {
2732 // positive untyped float constant with null decimal part is ok
2733 f := n.rval.Float()
2734 if f == math.Trunc(f) && f >= 0 {
2735 n.rval = reflect.ValueOf(uint(f))
2736 n.typ.rtype = n.rval.Type()
2737 return true
2738 }
2739 }
2740 if isConstantValue(t) {
2741 c := n.rval.Interface().(constant.Value)
2742 switch c.Kind() {
2743 case constant.Int:
2744 i, _ := constant.Int64Val(c)
2745 if i >= 0 {
2746 return true
2747 }
2748 case constant.Float:
2749 f, _ := constant.Float64Val(c)
2750 if f == math.Trunc(f) {
2751 n.rval = reflect.ValueOf(constant.ToInt(c))
2752 n.typ.rtype = n.rval.Type()
2753 return true
2754 }
2755 }
2756 }
2757 }
2758 return false
2759 }
2760
2761 // isNil returns true if node is a literal nil value, false otherwise.
2762 func (n *node) isNil() bool { return n.kind == basicLit && !n.rval.IsValid() }
2763
2764 // fieldType returns the nth parameter field node (type) of a fieldList node.
2765 func (n *node) fieldType(m int) *node {
2766 k := 0
2767 l := len(n.child)
2768 for i := 0; i < l; i++ {
2769 cl := len(n.child[i].child)
2770 if cl < 2 {
2771 if k == m {
2772 return n.child[i].lastChild()
2773 }
2774 k++
2775 continue
2776 }
2777 for j := 0; j < cl-1; j++ {
2778 if k == m {
2779 return n.child[i].lastChild()
2780 }
2781 k++
2782 }
2783 }
2784 return nil
2785 }
2786
2787 // lastChild returns the last child of a node.
2788 func (n *node) lastChild() *node { return n.child[len(n.child)-1] }
2789
2790 func (n *node) hasAnc(nod *node) bool {
2791 for a := n.anc; a != nil; a = a.anc {
2792 if a == nod {
2793 return true
2794 }
2795 }
2796 return false
2797 }
2798
2799 func isKey(n *node) bool {
2800 return n.anc.kind == fileStmt ||
2801 (n.anc.kind == selectorExpr && n.anc.child[0] != n) ||
2802 (n.anc.kind == funcDecl && isMethod(n.anc)) ||
2803 (n.anc.kind == keyValueExpr && isStruct(n.anc.typ) && n.anc.child[0] == n) ||
2804 (n.anc.kind == fieldExpr && len(n.anc.child) > 1 && n.anc.child[0] == n)
2805 }
2806
2807 func isField(n *node) bool {
2808 return n.kind == selectorExpr && len(n.child) > 0 && n.child[0].typ != nil && isStruct(n.child[0].typ)
2809 }
2810
2811 func isInInterfaceType(n *node) bool {
2812 anc := n.anc
2813 for anc != nil {
2814 if anc.kind == interfaceType {
2815 return true
2816 }
2817 anc = anc.anc
2818 }
2819 return false
2820 }
2821
2822 func isInConstOrTypeDecl(n *node) bool {
2823 anc := n.anc
2824 for anc != nil {
2825 switch anc.kind {
2826 case constDecl, typeDecl, arrayType, chanType:
2827 return true
2828 case varDecl, funcDecl:
2829 return false
2830 }
2831 anc = anc.anc
2832 }
2833 return false
2834 }
2835
2836 // isNewDefine returns true if node refers to a new definition.
2837 func isNewDefine(n *node, sc *scope) bool {
2838 if n.ident == "_" {
2839 return true
2840 }
2841 if (n.anc.kind == defineXStmt || n.anc.kind == defineStmt || n.anc.kind == valueSpec) && childPos(n) < n.anc.nleft {
2842 return true
2843 }
2844 if n.anc.kind == rangeStmt {
2845 if n.anc.child[0] == n {
2846 return true // array or map key, or chan element
2847 }
2848 if sc.rangeChanType(n.anc) == nil && n.anc.child[1] == n && len(n.anc.child) == 4 {
2849 return true // array or map value
2850 }
2851 return false // array, map or channel are always pre-defined in range expression
2852 }
2853 return false
2854 }
2855
2856 func isMethod(n *node) bool {
2857 return len(n.child[0].child) > 0 // receiver defined
2858 }
2859
2860 func isFuncField(n *node) bool {
2861 return isField(n) && isFunc(n.typ)
2862 }
2863
2864 func isMapEntry(n *node) bool {
2865 return n.action == aGetIndex && isMap(n.child[0].typ)
2866 }
2867
2868 func isCall(n *node) bool {
2869 return n.action == aCall || n.action == aCallSlice
2870 }
2871
2872 func isBinCall(n *node, sc *scope) bool {
2873 if !isCall(n) || len(n.child) == 0 {
2874 return false
2875 }
2876 c0 := n.child[0]
2877 if c0.typ == nil {
2878 // If called early in parsing, child type may not be known yet.
2879 c0.typ, _ = nodeType(n.interp, sc, c0)
2880 if c0.typ == nil {
2881 return false
2882 }
2883 }
2884 return c0.typ.cat == valueT && c0.typ.rtype.Kind() == reflect.Func
2885 }
2886
2887 func mustReturnValue(n *node) bool {
2888 if len(n.child) < 3 {
2889 return false
2890 }
2891 for _, f := range n.child[2].child {
2892 if len(f.child) > 1 {
2893 return false
2894 }
2895 }
2896 return true
2897 }
2898
2899 func isRegularCall(n *node) bool {
2900 return isCall(n) && n.child[0].typ.cat == funcT
2901 }
2902
2903 func variadicPos(n *node) int {
2904 if len(n.child[0].typ.arg) == 0 {
2905 return -1
2906 }
2907 last := len(n.child[0].typ.arg) - 1
2908 if n.child[0].typ.arg[last].cat == variadicT {
2909 return last
2910 }
2911 return -1
2912 }
2913
2914 func canExport(name string) bool {
2915 if r := []rune(name); len(r) > 0 && unicode.IsUpper(r[0]) {
2916 return true
2917 }
2918 return false
2919 }
2920
2921 func getExec(n *node) bltn {
2922 if n == nil {
2923 return nil
2924 }
2925 if n.exec == nil {
2926 setExec(n)
2927 }
2928 return n.exec
2929 }
2930
2931 // setExec recursively sets the node exec builtin function by walking the CFG
2932 // from the entry point (first node to exec).
2933 func setExec(n *node) {
2934 if n.exec != nil {
2935 return
2936 }
2937 seen := map[*node]bool{}
2938 var set func(n *node)
2939
2940 set = func(n *node) {
2941 if n == nil || n.exec != nil {
2942 return
2943 }
2944 seen[n] = true
2945 if n.tnext != nil && n.tnext.exec == nil {
2946 if seen[n.tnext] {
2947 m := n.tnext
2948 n.tnext.exec = func(f *frame) bltn { return m.exec(f) }
2949 } else {
2950 set(n.tnext)
2951 }
2952 }
2953 if n.fnext != nil && n.fnext.exec == nil {
2954 if seen[n.fnext] {
2955 m := n.fnext
2956 n.fnext.exec = func(f *frame) bltn { return m.exec(f) }
2957 } else {
2958 set(n.fnext)
2959 }
2960 }
2961 n.gen(n)
2962 }
2963
2964 set(n)
2965 }
2966
2967 func typeSwichAssign(n *node) bool {
2968 ts := n.anc.anc.anc
2969 return ts.kind == typeSwitch && ts.child[1].action == aAssign
2970 }
2971
2972 func compositeGenerator(n *node, typ *itype, rtyp reflect.Type) (gen bltnGenerator) {
2973 switch typ.cat {
2974 case linkedT, ptrT:
2975 gen = compositeGenerator(n, typ.val, rtyp)
2976 case arrayT, sliceT:
2977 gen = arrayLit
2978 case mapT:
2979 gen = mapLit
2980 case structT:
2981 switch {
2982 case len(n.child) == 0:
2983 gen = compositeLitNotype
2984 case n.lastChild().kind == keyValueExpr:
2985 if n.nleft == 1 {
2986 gen = compositeLitKeyed
2987 } else {
2988 gen = compositeLitKeyedNotype
2989 }
2990 default:
2991 if n.nleft == 1 {
2992 gen = compositeLit
2993 } else {
2994 gen = compositeLitNotype
2995 }
2996 }
2997 case valueT:
2998 if rtyp == nil {
2999 rtyp = n.typ.TypeOf()
3000 }
3001 switch k := rtyp.Kind(); k {
3002 case reflect.Struct:
3003 if n.nleft == 1 {
3004 gen = compositeBinStruct
3005 } else {
3006 gen = compositeBinStructNotype
3007 }
3008 case reflect.Map:
3009 // TODO(mpl): maybe needs a NoType version too
3010 gen = compositeBinMap
3011 case reflect.Ptr:
3012 gen = compositeGenerator(n, typ, n.typ.val.rtype)
3013 case reflect.Slice, reflect.Array:
3014 gen = compositeBinSlice
3015 default:
3016 log.Panic(n.cfgErrorf("compositeGenerator not implemented for type kind: %s", k))
3017 }
3018 }
3019 return gen
3020 }
3021
3022 // matchSelectorMethod, given that n represents a selector for a method, tries
3023 // to find the corresponding method, and populates n accordingly.
3024 func matchSelectorMethod(sc *scope, n *node) (err error) {
3025 name := n.child[1].ident
3026 if n.typ.cat == valueT || n.typ.cat == errorT {
3027 switch method, ok := n.typ.rtype.MethodByName(name); {
3028 case ok:
3029 hasRecvType := n.typ.TypeOf().Kind() != reflect.Interface
3030 n.val = method.Index
3031 n.gen = getIndexBinMethod
3032 n.action = aGetMethod
3033 n.recv = &receiver{node: n.child[0]}
3034 n.typ = valueTOf(method.Type, isBinMethod())
3035 if hasRecvType {
3036 n.typ.recv = n.typ
3037 }
3038 case n.typ.TypeOf().Kind() == reflect.Ptr:
3039 if field, ok := n.typ.rtype.Elem().FieldByName(name); ok {
3040 n.typ = valueTOf(field.Type)
3041 n.val = field.Index
3042 n.gen = getPtrIndexSeq
3043 break
3044 }
3045 err = n.cfgErrorf("undefined method: %s", name)
3046 case n.typ.TypeOf().Kind() == reflect.Struct:
3047 if field, ok := n.typ.rtype.FieldByName(name); ok {
3048 n.typ = valueTOf(field.Type)
3049 n.val = field.Index
3050 n.gen = getIndexSeq
3051 break
3052 }
3053 fallthrough
3054 default:
3055 // method lookup failed on type, now lookup on pointer to type
3056 pt := reflect.PtrTo(n.typ.rtype)
3057 if m2, ok2 := pt.MethodByName(name); ok2 {
3058 n.val = m2.Index
3059 n.gen = getIndexBinPtrMethod
3060 n.typ = valueTOf(m2.Type, isBinMethod(), withRecv(valueTOf(pt)))
3061 n.recv = &receiver{node: n.child[0]}
3062 n.action = aGetMethod
3063 break
3064 }
3065 err = n.cfgErrorf("undefined method: %s", name)
3066 }
3067 return err
3068 }
3069
3070 if n.typ.cat == ptrT && (n.typ.val.cat == valueT || n.typ.val.cat == errorT) {
3071 // Handle pointer on object defined in runtime
3072 if method, ok := n.typ.val.rtype.MethodByName(name); ok {
3073 n.val = method.Index
3074 n.typ = valueTOf(method.Type, isBinMethod(), withRecv(n.typ))
3075 n.recv = &receiver{node: n.child[0]}
3076 n.gen = getIndexBinElemMethod
3077 n.action = aGetMethod
3078 } else if method, ok := reflect.PtrTo(n.typ.val.rtype).MethodByName(name); ok {
3079 n.val = method.Index
3080 n.gen = getIndexBinMethod
3081 n.typ = valueTOf(method.Type, withRecv(valueTOf(reflect.PtrTo(n.typ.val.rtype), isBinMethod())))
3082 n.recv = &receiver{node: n.child[0]}
3083 n.action = aGetMethod
3084 } else if field, ok := n.typ.val.rtype.FieldByName(name); ok {
3085 n.typ = valueTOf(field.Type)
3086 n.val = field.Index
3087 n.gen = getPtrIndexSeq
3088 } else {
3089 err = n.cfgErrorf("undefined selector: %s", name)
3090 }
3091 return err
3092 }
3093
3094 if m, lind := n.typ.lookupMethod(name); m != nil {
3095 n.action = aGetMethod
3096 if n.child[0].isType(sc) {
3097 // Handle method as a function with receiver in 1st argument.
3098 n.val = m
3099 n.findex = notInFrame
3100 n.gen = nop
3101 n.typ = &itype{}
3102 *n.typ = *m.typ
3103 n.typ.arg = append([]*itype{n.child[0].typ}, m.typ.arg...)
3104 } else {
3105 // Handle method with receiver.
3106 n.gen = getMethod
3107 n.val = m
3108 n.typ = m.typ
3109 n.recv = &receiver{node: n.child[0], index: lind}
3110 }
3111 return nil
3112 }
3113
3114 if m, lind, isPtr, ok := n.typ.lookupBinMethod(name); ok {
3115 n.action = aGetMethod
3116 switch {
3117 case isPtr && n.typ.fieldSeq(lind).cat != ptrT:
3118 n.gen = getIndexSeqPtrMethod
3119 case isInterfaceSrc(n.typ):
3120 n.gen = getMethodByName
3121 default:
3122 n.gen = getIndexSeqMethod
3123 }
3124 n.recv = &receiver{node: n.child[0], index: lind}
3125 n.val = append([]int{m.Index}, lind...)
3126 n.typ = valueTOf(m.Type, isBinMethod(), withRecv(n.child[0].typ))
3127 return nil
3128 }
3129
3130 if typ := n.typ.interfaceMethod(name); typ != nil {
3131 n.typ = typ
3132 n.action = aGetMethod
3133 n.gen = getMethodByName
3134 return nil
3135 }
3136
3137 return n.cfgErrorf("undefined selector: %s", name)
3138 }
3139
3140 // arrayTypeLen returns the node's array length. If the expression is an
3141 // array variable it is determined from the value's type, otherwise it is
3142 // computed from the source definition.
3143 func arrayTypeLen(n *node, sc *scope) (int, error) {
3144 if n.typ != nil && n.typ.cat == arrayT {
3145 return n.typ.length, nil
3146 }
3147 max := -1
3148 for _, c := range n.child[1:] {
3149 var r int
3150
3151 if c.kind != keyValueExpr {
3152 r = max + 1
3153 max = r
3154 continue
3155 }
3156
3157 c0 := c.child[0]
3158 v := c0.rval
3159 if v.IsValid() {
3160 r = int(v.Int())
3161 } else {
3162 // Resolve array key value as a constant.
3163 if c0.kind == identExpr {
3164 // Key is defined by a symbol which must be a constant integer.
3165 sym, _, ok := sc.lookup(c0.ident)
3166 if !ok {
3167 return 0, c0.cfgErrorf("undefined: %s", c0.ident)
3168 }
3169 if sym.kind != constSym {
3170 return 0, c0.cfgErrorf("non-constant array bound %q", c0.ident)
3171 }
3172 r = int(vInt(sym.rval))
3173 } else {
3174 // Key is defined by a numeric constant expression.
3175 if _, err := c0.interp.cfg(c0, sc, sc.pkgID, sc.pkgName); err != nil {
3176 return 0, err
3177 }
3178 cv, ok := c0.rval.Interface().(constant.Value)
3179 if !ok {
3180 return 0, c0.cfgErrorf("non-constant expression")
3181 }
3182 r = constToInt(cv)
3183 }
3184 }
3185
3186 if r > max {
3187 max = r
3188 }
3189 }
3190 return max + 1, nil
3191 }
3192
3193 // isValueUntyped returns true if value is untyped.
3194 func isValueUntyped(v reflect.Value) bool {
3195 // Consider only constant values.
3196 if v.CanSet() {
3197 return false
3198 }
3199 return v.Type().Implements(constVal)
3200 }
3201
3202 // isArithmeticAction returns true if the node action is an arithmetic operator.
3203 func isArithmeticAction(n *node) bool {
3204 switch n.action {
3205 case aAdd, aAnd, aAndNot, aBitNot, aMul, aNeg, aOr, aPos, aQuo, aRem, aShl, aShr, aSub, aXor:
3206 return true
3207 }
3208 return false
3209 }
3210
3211 func isBoolAction(n *node) bool {
3212 switch n.action {
3213 case aEqual, aGreater, aGreaterEqual, aLand, aLor, aLower, aLowerEqual, aNot, aNotEqual:
3214 return true
3215 }
3216 return false
3217 }
3218
3219 func isBlank(n *node) bool {
3220 if n.kind == parenExpr && len(n.child) > 0 {
3221 return isBlank(n.child[0])
3222 }
3223 return n.ident == "_"
3224 }
3225
3226 func alignof(n *node) {
3227 n.gen = nop
3228 n.typ = n.scope.getType("uintptr")
3229 n.rval = reflect.ValueOf(uintptr(n.child[1].typ.TypeOf().Align()))
3230 }
3231
3232 func offsetof(n *node) {
3233 n.gen = nop
3234 n.typ = n.scope.getType("uintptr")
3235 c1 := n.child[1]
3236 if field, ok := c1.child[0].typ.rtype.FieldByName(c1.child[1].ident); ok {
3237 n.rval = reflect.ValueOf(field.Offset)
3238 }
3239 }
3240
3241 func sizeof(n *node) {
3242 n.gen = nop
3243 n.typ = n.scope.getType("uintptr")
3244 n.rval = reflect.ValueOf(n.child[1].typ.TypeOf().Size())
3245 }