Source file
src/go/types/stmt.go
1
2
3
4
5
6
7 package types
8
9 import (
10 "go/ast"
11 "go/constant"
12 "go/token"
13 . "internal/types/errors"
14 "slices"
15 )
16
17
18 func (check *Checker) funcBody(decl *declInfo, name string, sig *Signature, body *ast.BlockStmt, iota constant.Value) {
19 if check.conf.IgnoreFuncBodies {
20 panic("function body not ignored")
21 }
22
23 if check.conf._Trace {
24 check.trace(body.Pos(), "-- %s: %s", name, sig)
25 }
26
27
28
29 defer func(env environment, indent int) {
30 check.environment = env
31 check.indent = indent
32 }(check.environment, check.indent)
33 check.environment = environment{
34 decl: decl,
35 scope: sig.scope,
36 version: check.version,
37 iota: iota,
38 sig: sig,
39 }
40 check.indent = 0
41
42 check.stmtList(0, body.List)
43
44 if check.hasLabel {
45 check.labels(body)
46 }
47
48 if sig.results.Len() > 0 && !check.isTerminating(body, "") {
49 check.error(atPos(body.Rbrace), MissingReturn, "missing return")
50 }
51
52
53
54 check.usage(sig.scope)
55 }
56
57 func (check *Checker) usage(scope *Scope) {
58 needUse := func(kind VarKind) bool {
59 return !(kind == RecvVar || kind == ParamVar || kind == ResultVar)
60 }
61 var unused []*Var
62 for name, elem := range scope.elems {
63 elem = resolve(name, elem)
64 if v, _ := elem.(*Var); v != nil && needUse(v.kind) && !check.usedVars[v] {
65 unused = append(unused, v)
66 }
67 }
68 slices.SortFunc(unused, func(a, b *Var) int {
69 return cmpPos(a.pos, b.pos)
70 })
71 for _, v := range unused {
72 check.softErrorf(v, UnusedVar, "declared and not used: %s", v.name)
73 }
74
75 for _, scope := range scope.children {
76
77
78 if !scope.isFunc {
79 check.usage(scope)
80 }
81 }
82 }
83
84
85
86
87
88 type stmtContext uint
89
90 const (
91
92 breakOk stmtContext = 1 << iota
93 continueOk
94 fallthroughOk
95
96
97 finalSwitchCase
98 inTypeSwitch
99 )
100
101 func (check *Checker) simpleStmt(s ast.Stmt) {
102 if s != nil {
103 check.stmt(0, s)
104 }
105 }
106
107 func trimTrailingEmptyStmts(list []ast.Stmt) []ast.Stmt {
108 for i := len(list); i > 0; i-- {
109 if _, ok := list[i-1].(*ast.EmptyStmt); !ok {
110 return list[:i]
111 }
112 }
113 return nil
114 }
115
116 func (check *Checker) stmtList(ctxt stmtContext, list []ast.Stmt) {
117 ok := ctxt&fallthroughOk != 0
118 inner := ctxt &^ fallthroughOk
119 list = trimTrailingEmptyStmts(list)
120 for i, s := range list {
121 inner := inner
122 if ok && i+1 == len(list) {
123 inner |= fallthroughOk
124 }
125 check.stmt(inner, s)
126 }
127 }
128
129 func (check *Checker) multipleDefaults(list []ast.Stmt) {
130 var first ast.Stmt
131 for _, s := range list {
132 var d ast.Stmt
133 switch c := s.(type) {
134 case *ast.CaseClause:
135 if len(c.List) == 0 {
136 d = s
137 }
138 case *ast.CommClause:
139 if c.Comm == nil {
140 d = s
141 }
142 default:
143 check.error(s, InvalidSyntaxTree, "case/communication clause expected")
144 }
145 if d != nil {
146 if first != nil {
147 check.errorf(d, DuplicateDefault, "multiple defaults (first at %s)", check.fset.Position(first.Pos()))
148 } else {
149 first = d
150 }
151 }
152 }
153 }
154
155 func (check *Checker) openScope(node ast.Node, comment string) {
156 scope := NewScope(check.scope, node.Pos(), node.End(), comment)
157 check.recordScope(node, scope)
158 check.scope = scope
159 }
160
161 func (check *Checker) closeScope() {
162 check.scope = check.scope.Parent()
163 }
164
165 func assignOp(op token.Token) token.Token {
166
167 if token.ADD_ASSIGN <= op && op <= token.AND_NOT_ASSIGN {
168 return op + (token.ADD - token.ADD_ASSIGN)
169 }
170 return token.ILLEGAL
171 }
172
173 func (check *Checker) suspendedCall(keyword string, call *ast.CallExpr) {
174 var x operand
175 var msg string
176 var code Code
177 switch check.rawExpr(nil, &x, call, false) {
178 case conversion:
179 msg = "requires function call, not conversion"
180 code = InvalidDefer
181 if keyword == "go" {
182 code = InvalidGo
183 }
184 case expression:
185 msg = "discards result of"
186 code = UnusedResults
187 case statement:
188 return
189 default:
190 panic("unreachable")
191 }
192 check.errorf(&x, code, "%s %s %s", keyword, msg, &x)
193 }
194
195
196 func goVal(val constant.Value) any {
197
198 if val == nil {
199 return nil
200 }
201
202
203
204
205 switch val.Kind() {
206 case constant.Int:
207 if x, ok := constant.Int64Val(val); ok {
208 return x
209 }
210 if x, ok := constant.Uint64Val(val); ok {
211 return x
212 }
213 case constant.Float:
214 if x, ok := constant.Float64Val(val); ok {
215 return x
216 }
217 case constant.String:
218 return constant.StringVal(val)
219 }
220 return nil
221 }
222
223
224
225
226
227
228
229 type (
230 valueMap map[any][]valueType
231 valueType struct {
232 pos token.Pos
233 typ Type
234 }
235 )
236
237 func (check *Checker) caseValues(x *operand, values []ast.Expr, seen valueMap) {
238 L:
239 for _, e := range values {
240 var v operand
241 check.expr(nil, &v, e)
242 if !x.isValid() || !v.isValid() {
243 continue L
244 }
245 check.convertUntyped(&v, x.typ())
246 if !v.isValid() {
247 continue L
248 }
249
250 res := v
251 check.comparison(&res, x, token.EQL, true)
252 if !res.isValid() {
253 continue L
254 }
255 if v.mode() != constant_ {
256 continue L
257 }
258
259 if val := goVal(v.val); val != nil {
260
261
262 for _, vt := range seen[val] {
263 if Identical(v.typ(), vt.typ) {
264 err := check.newError(DuplicateCase)
265 err.addf(&v, "duplicate case %s in expression switch", &v)
266 err.addf(atPos(vt.pos), "previous case")
267 err.report()
268 continue L
269 }
270 }
271 seen[val] = append(seen[val], valueType{v.Pos(), v.typ()})
272 }
273 }
274 }
275
276
277 func (check *Checker) isNil(e ast.Expr) bool {
278
279 if name, _ := ast.Unparen(e).(*ast.Ident); name != nil {
280 _, ok := check.lookup(name.Name).(*Nil)
281 return ok
282 }
283 return false
284 }
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307 func (check *Checker) caseTypes(x *operand, types []ast.Expr, seen map[Type]ast.Expr) Type {
308 var T Type
309 var dummy operand
310 L:
311 for _, e := range types {
312
313 if check.isNil(e) {
314 T = nil
315 check.expr(nil, &dummy, e)
316 } else {
317 T = check.varType(e)
318 if !isValid(T) {
319 continue L
320 }
321 }
322
323
324 for t, other := range seen {
325 if T == nil && t == nil || T != nil && t != nil && Identical(T, t) {
326
327 Ts := "nil"
328 if T != nil {
329 Ts = TypeString(T, check.qualifier)
330 }
331 err := check.newError(DuplicateCase)
332 err.addf(e, "duplicate case %s in type switch", Ts)
333 err.addf(other, "previous case")
334 err.report()
335 continue L
336 }
337 }
338 seen[T] = e
339 if x != nil && T != nil {
340 check.typeAssertion(e, x, T, true)
341 }
342 }
343
344
345
346 if len(types) != 1 || T == nil {
347 T = Typ[Invalid]
348 if x != nil {
349 T = x.typ()
350 }
351 }
352
353 assert(T != nil)
354 return T
355 }
356
357
358
359 func (check *Checker) caseTypes_currently_unused(x *operand, xtyp *Interface, types []ast.Expr, seen map[string]ast.Expr) Type {
360 var T Type
361 var dummy operand
362 L:
363 for _, e := range types {
364
365 var hash string
366 if check.isNil(e) {
367 check.expr(nil, &dummy, e)
368 T = nil
369 hash = "<nil>"
370 } else {
371 T = check.varType(e)
372 if !isValid(T) {
373 continue L
374 }
375 panic("enable typeHash(T, nil)")
376
377 }
378
379 if other := seen[hash]; other != nil {
380
381 Ts := "nil"
382 if T != nil {
383 Ts = TypeString(T, check.qualifier)
384 }
385 err := check.newError(DuplicateCase)
386 err.addf(e, "duplicate case %s in type switch", Ts)
387 err.addf(other, "previous case")
388 err.report()
389 continue L
390 }
391 seen[hash] = e
392 if T != nil {
393 check.typeAssertion(e, x, T, true)
394 }
395 }
396
397
398
399 if len(types) != 1 || T == nil {
400 T = Typ[Invalid]
401 if x != nil {
402 T = x.typ()
403 }
404 }
405
406 assert(T != nil)
407 return T
408 }
409
410
411 func (check *Checker) stmt(ctxt stmtContext, s ast.Stmt) {
412
413 if debug {
414 defer func(scope *Scope) {
415
416 if p := recover(); p != nil {
417 panic(p)
418 }
419 assert(scope == check.scope)
420 }(check.scope)
421 }
422
423
424 defer check.processDelayed(len(check.delayed))
425
426
427 inner := ctxt &^ (fallthroughOk | finalSwitchCase | inTypeSwitch)
428
429 switch s := s.(type) {
430 case *ast.BadStmt, *ast.EmptyStmt:
431
432
433 case *ast.DeclStmt:
434 check.declStmt(s.Decl)
435
436 case *ast.LabeledStmt:
437 check.hasLabel = true
438 check.stmt(ctxt, s.Stmt)
439
440 case *ast.ExprStmt:
441
442
443
444 var x operand
445 kind := check.rawExpr(nil, &x, s.X, false)
446 var msg string
447 var code Code
448 switch x.mode() {
449 default:
450 if kind == statement {
451 return
452 }
453 msg = "is not used"
454 code = UnusedExpr
455 case builtin:
456 msg = "must be called"
457 code = UncalledBuiltin
458 case typexpr:
459 msg = "is not an expression"
460 code = NotAnExpr
461 }
462 check.errorf(&x, code, "%s %s", &x, msg)
463
464 case *ast.SendStmt:
465 var ch, val operand
466 check.expr(nil, &ch, s.Chan)
467 if ch.isValid() {
468
469
470 T := check.chanElem(inNode(s, s.Arrow), &ch, false)
471 check.genericExpr(newTarget(T, "channel send"), &val, s.Value)
472 if T != nil {
473 check.assignment(&val, T, "send")
474 }
475 } else {
476
477 check.genericExpr(nil, &val, s.Value)
478 }
479
480 case *ast.IncDecStmt:
481 var op token.Token
482 switch s.Tok {
483 case token.INC:
484 op = token.ADD
485 case token.DEC:
486 op = token.SUB
487 default:
488 check.errorf(inNode(s, s.TokPos), InvalidSyntaxTree, "unknown inc/dec operation %s", s.Tok)
489 return
490 }
491
492 var x operand
493 check.expr(nil, &x, s.X)
494 if !x.isValid() {
495 return
496 }
497 if !allNumeric(x.typ()) {
498 check.errorf(s.X, NonNumericIncDec, invalidOp+"%s%s (non-numeric type %s)", s.X, s.Tok, x.typ())
499 return
500 }
501
502 Y := &ast.BasicLit{ValuePos: s.X.Pos(), Kind: token.INT, Value: "1"}
503 check.binary(&x, nil, s.X, Y, op, s.TokPos)
504 if !x.isValid() {
505 return
506 }
507 check.assignVar(s.X, nil, &x, "assignment")
508
509 case *ast.AssignStmt:
510 switch s.Tok {
511 case token.ASSIGN, token.DEFINE:
512 if len(s.Lhs) == 0 {
513 check.error(s, InvalidSyntaxTree, "missing lhs in assignment")
514 return
515 }
516 if s.Tok == token.DEFINE {
517 check.shortVarDecl(inNode(s, s.TokPos), s.Lhs, s.Rhs)
518 } else {
519
520 check.assignVars(s.Lhs, s.Rhs)
521 }
522
523 default:
524
525 if len(s.Lhs) != 1 || len(s.Rhs) != 1 {
526 check.errorf(inNode(s, s.TokPos), MultiValAssignOp, "assignment operation %s requires single-valued expressions", s.Tok)
527 return
528 }
529 op := assignOp(s.Tok)
530 if op == token.ILLEGAL {
531 check.errorf(atPos(s.TokPos), InvalidSyntaxTree, "unknown assignment operation %s", s.Tok)
532 return
533 }
534 var x operand
535 check.binary(&x, nil, s.Lhs[0], s.Rhs[0], op, s.TokPos)
536 if !x.isValid() {
537 return
538 }
539 check.assignVar(s.Lhs[0], nil, &x, "assignment")
540 }
541
542 case *ast.GoStmt:
543 check.suspendedCall("go", s.Call)
544
545 case *ast.DeferStmt:
546 check.suspendedCall("defer", s.Call)
547
548 case *ast.ReturnStmt:
549 res := check.sig.results
550
551
552 if len(s.Results) == 0 && res.Len() > 0 && res.vars[0].name != "" {
553
554
555
556 for _, obj := range res.vars {
557 if alt := check.lookup(obj.name); alt != nil && alt != obj {
558 err := check.newError(OutOfScopeResult)
559 err.addf(s, "result parameter %s not in scope at return", obj.name)
560 err.addf(alt, "inner declaration of %s", obj)
561 err.report()
562
563 }
564 }
565 } else {
566 var lhs []*Var
567 if res.Len() > 0 {
568 lhs = res.vars
569 }
570 check.initVars(lhs, s.Results, s)
571 }
572
573 case *ast.BranchStmt:
574 if s.Label != nil {
575 check.hasLabel = true
576 return
577 }
578 switch s.Tok {
579 case token.BREAK:
580 if ctxt&breakOk == 0 {
581 check.error(s, MisplacedBreak, "break not in for, switch, or select statement")
582 }
583 case token.CONTINUE:
584 if ctxt&continueOk == 0 {
585 check.error(s, MisplacedContinue, "continue not in for statement")
586 }
587 case token.FALLTHROUGH:
588 if ctxt&fallthroughOk == 0 {
589 var msg string
590 switch {
591 case ctxt&finalSwitchCase != 0:
592 msg = "cannot fallthrough final case in switch"
593 case ctxt&inTypeSwitch != 0:
594 msg = "cannot fallthrough in type switch"
595 default:
596 msg = "fallthrough statement out of place"
597 }
598 check.error(s, MisplacedFallthrough, msg)
599 }
600 default:
601 check.errorf(s, InvalidSyntaxTree, "branch statement: %s", s.Tok)
602 }
603
604 case *ast.BlockStmt:
605 check.openScope(s, "block")
606 defer check.closeScope()
607
608 check.stmtList(inner, s.List)
609
610 case *ast.IfStmt:
611 check.openScope(s, "if")
612 defer check.closeScope()
613
614 check.simpleStmt(s.Init)
615 var x operand
616 check.expr(nil, &x, s.Cond)
617 if x.isValid() && !allBoolean(x.typ()) {
618 check.error(s.Cond, InvalidCond, "non-boolean condition in if statement")
619 }
620 check.stmt(inner, s.Body)
621
622
623 switch s.Else.(type) {
624 case nil, *ast.BadStmt:
625
626 case *ast.IfStmt, *ast.BlockStmt:
627 check.stmt(inner, s.Else)
628 default:
629 check.error(s.Else, InvalidSyntaxTree, "invalid else branch in if statement")
630 }
631
632 case *ast.SwitchStmt:
633 inner |= breakOk
634 check.openScope(s, "switch")
635 defer check.closeScope()
636
637 check.simpleStmt(s.Init)
638 var x operand
639 if s.Tag != nil {
640 check.expr(nil, &x, s.Tag)
641
642
643 check.assignment(&x, nil, "switch expression")
644 if x.isValid() && !Comparable(x.typ()) && !hasNil(x.typ()) {
645 check.errorf(&x, InvalidExprSwitch, "cannot switch on %s (%s is not comparable)", &x, x.typ())
646 x.invalidate()
647 }
648 } else {
649
650
651 x.mode_ = constant_
652 x.typ_ = Typ[Bool]
653 x.val = constant.MakeBool(true)
654 x.expr = &ast.Ident{NamePos: s.Body.Lbrace, Name: "true"}
655 }
656
657 check.multipleDefaults(s.Body.List)
658
659 seen := make(valueMap)
660 for i, c := range s.Body.List {
661 clause, _ := c.(*ast.CaseClause)
662 if clause == nil {
663 check.error(c, InvalidSyntaxTree, "incorrect expression switch case")
664 continue
665 }
666 check.caseValues(&x, clause.List, seen)
667 check.openScope(clause, "case")
668 inner := inner
669 if i+1 < len(s.Body.List) {
670 inner |= fallthroughOk
671 } else {
672 inner |= finalSwitchCase
673 }
674 check.stmtList(inner, clause.Body)
675 check.closeScope()
676 }
677
678 case *ast.TypeSwitchStmt:
679 inner |= breakOk | inTypeSwitch
680 check.openScope(s, "type switch")
681 defer check.closeScope()
682
683 check.simpleStmt(s.Init)
684
685
686
687
688
689
690
691
692
693 var lhs *ast.Ident
694 var rhs ast.Expr
695 switch guard := s.Assign.(type) {
696 case *ast.ExprStmt:
697 rhs = guard.X
698 case *ast.AssignStmt:
699 if len(guard.Lhs) != 1 || guard.Tok != token.DEFINE || len(guard.Rhs) != 1 {
700 check.error(s, InvalidSyntaxTree, "incorrect form of type switch guard")
701 return
702 }
703
704 lhs, _ = guard.Lhs[0].(*ast.Ident)
705 if lhs == nil {
706 check.error(s, InvalidSyntaxTree, "incorrect form of type switch guard")
707 return
708 }
709
710 if lhs.Name == "_" {
711
712 check.softErrorf(lhs, NoNewVar, "no new variable on left side of :=")
713 lhs = nil
714 } else {
715 check.recordDef(lhs, nil)
716 }
717
718 rhs = guard.Rhs[0]
719
720 default:
721 check.error(s, InvalidSyntaxTree, "incorrect form of type switch guard")
722 return
723 }
724
725
726 expr, _ := rhs.(*ast.TypeAssertExpr)
727 if expr == nil || expr.Type != nil {
728 check.error(s, InvalidSyntaxTree, "incorrect form of type switch guard")
729 return
730 }
731
732 var sx *operand
733 {
734 var x operand
735 check.expr(nil, &x, expr.X)
736 if x.isValid() {
737 if isTypeParam(x.typ()) {
738 check.errorf(&x, InvalidTypeSwitch, "cannot use type switch on type parameter value %s", &x)
739 } else if IsInterface(x.typ()) {
740 sx = &x
741 } else {
742 check.errorf(&x, InvalidTypeSwitch, "%s is not an interface", &x)
743 }
744 }
745 }
746
747 check.multipleDefaults(s.Body.List)
748
749 var lhsVars []*Var
750 seen := make(map[Type]ast.Expr)
751 for _, s := range s.Body.List {
752 clause, _ := s.(*ast.CaseClause)
753 if clause == nil {
754 check.error(s, InvalidSyntaxTree, "incorrect type switch case")
755 continue
756 }
757
758 T := check.caseTypes(sx, clause.List, seen)
759 check.openScope(clause, "case")
760
761 if lhs != nil {
762 obj := newVar(LocalVar, lhs.Pos(), check.pkg, lhs.Name, T)
763 check.declare(check.scope, nil, obj, clause.Colon)
764 check.recordImplicit(clause, obj)
765
766
767
768 lhsVars = append(lhsVars, obj)
769 }
770 check.stmtList(inner, clause.Body)
771 check.closeScope()
772 }
773
774
775
776
777
778 if lhs != nil {
779 var used bool
780 for _, v := range lhsVars {
781 if check.usedVars[v] {
782 used = true
783 }
784 check.usedVars[v] = true
785 }
786 if !used {
787 check.softErrorf(lhs, UnusedVar, "%s declared and not used", lhs.Name)
788 }
789 }
790
791 case *ast.SelectStmt:
792 inner |= breakOk
793
794 check.multipleDefaults(s.Body.List)
795
796 for _, s := range s.Body.List {
797 clause, _ := s.(*ast.CommClause)
798 if clause == nil {
799 continue
800 }
801
802
803 valid := false
804 var rhs ast.Expr
805 switch s := clause.Comm.(type) {
806 case nil, *ast.SendStmt:
807 valid = true
808 case *ast.AssignStmt:
809 if len(s.Rhs) == 1 {
810 rhs = s.Rhs[0]
811 }
812 case *ast.ExprStmt:
813 rhs = s.X
814 }
815
816
817 if rhs != nil {
818 if x, _ := ast.Unparen(rhs).(*ast.UnaryExpr); x != nil && x.Op == token.ARROW {
819 valid = true
820 }
821 }
822
823 if !valid {
824 check.error(clause.Comm, InvalidSelectCase, "select case must be send or receive (possibly with assignment)")
825 continue
826 }
827
828 check.openScope(s, "case")
829 if clause.Comm != nil {
830 check.stmt(inner, clause.Comm)
831 }
832 check.stmtList(inner, clause.Body)
833 check.closeScope()
834 }
835
836 case *ast.ForStmt:
837 inner |= breakOk | continueOk
838 check.openScope(s, "for")
839 defer check.closeScope()
840
841 check.simpleStmt(s.Init)
842 if s.Cond != nil {
843 var x operand
844 check.expr(nil, &x, s.Cond)
845 if x.isValid() && !allBoolean(x.typ()) {
846 check.error(s.Cond, InvalidCond, "non-boolean condition in for statement")
847 }
848 }
849 check.simpleStmt(s.Post)
850
851
852 if s, _ := s.Post.(*ast.AssignStmt); s != nil && s.Tok == token.DEFINE {
853 check.softErrorf(s, InvalidPostDecl, "cannot declare in post statement")
854
855
856
857 check.use(s.Lhs...)
858 }
859 check.stmt(inner, s.Body)
860
861 case *ast.RangeStmt:
862 inner |= breakOk | continueOk
863
864
865 tokPos := s.TokPos
866 if !tokPos.IsValid() {
867 tokPos = s.For
868 }
869 check.rangeStmt(inner, s, inNode(s, tokPos), s.Key, s.Value, nil, s.X, s.Tok == token.DEFINE)
870
871 default:
872 check.error(s, InvalidSyntaxTree, "invalid statement")
873 }
874 }
875
View as plain text