Source file src/cmd/compile/internal/types2/labels.go

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package types2
     6  
     7  import (
     8  	"cmd/compile/internal/syntax"
     9  	. "internal/types/errors"
    10  )
    11  
    12  // labels checks correct label use in body.
    13  func (check *Checker) labels(body *syntax.BlockStmt) {
    14  	// set of all labels in this body
    15  	all := NewScope(nil, body.Pos(), syntax.EndPos(body), "label")
    16  
    17  	fwdJumps := check.blockBranches(all, nil, nil, body.List)
    18  
    19  	// If there are any forward jumps left, no label was found for
    20  	// the corresponding goto statements. Either those labels were
    21  	// never defined, or they are inside blocks and not reachable
    22  	// for the respective gotos.
    23  	for _, jmp := range fwdJumps {
    24  		var msg string
    25  		var code Code
    26  		name := jmp.Label.Value
    27  		if alt := all.Lookup(name); alt != nil {
    28  			msg = "goto %s jumps into block"
    29  			alt.(*Label).used = true // avoid another error
    30  			code = JumpIntoBlock
    31  			// don't quote name here because "goto L" matches the code
    32  		} else {
    33  			msg = "label %s not declared"
    34  			code = UndeclaredLabel
    35  			name = quote(name)
    36  		}
    37  		check.errorf(jmp.Label, code, msg, name)
    38  	}
    39  
    40  	// spec: "It is illegal to define a label that is never used."
    41  	for name, obj := range all.elems {
    42  		obj = resolve(name, obj)
    43  		if lbl := obj.(*Label); !lbl.used {
    44  			check.softErrorf(lbl.pos, UnusedLabel, "label %s declared and not used", quote(lbl.name))
    45  		}
    46  	}
    47  }
    48  
    49  // A block tracks label declarations in a block and its enclosing blocks.
    50  type block struct {
    51  	parent *block                         // enclosing block
    52  	lstmt  *syntax.LabeledStmt            // labeled statement to which this block belongs, or nil
    53  	labels map[string]*syntax.LabeledStmt // allocated lazily
    54  }
    55  
    56  // insert records a new label declaration for the current block.
    57  // The label must not have been declared before in any block.
    58  func (b *block) insert(s *syntax.LabeledStmt) {
    59  	name := s.Label.Value
    60  	if debug {
    61  		assert(b.gotoTarget(name) == nil)
    62  	}
    63  	labels := b.labels
    64  	if labels == nil {
    65  		labels = make(map[string]*syntax.LabeledStmt)
    66  		b.labels = labels
    67  	}
    68  	labels[name] = s
    69  }
    70  
    71  // gotoTarget returns the labeled statement in the current
    72  // or an enclosing block with the given label name, or nil.
    73  func (b *block) gotoTarget(name string) *syntax.LabeledStmt {
    74  	for s := b; s != nil; s = s.parent {
    75  		if t := s.labels[name]; t != nil {
    76  			return t
    77  		}
    78  	}
    79  	return nil
    80  }
    81  
    82  // enclosingTarget returns the innermost enclosing labeled
    83  // statement with the given label name, or nil.
    84  func (b *block) enclosingTarget(name string) *syntax.LabeledStmt {
    85  	for s := b; s != nil; s = s.parent {
    86  		if t := s.lstmt; t != nil && t.Label.Value == name {
    87  			return t
    88  		}
    89  	}
    90  	return nil
    91  }
    92  
    93  // blockBranches processes a block's statement list and returns the set of outgoing forward jumps.
    94  // all is the scope of all declared labels, parent the set of labels declared in the immediately
    95  // enclosing block, and lstmt is the labeled statement this block is associated with (or nil).
    96  func (check *Checker) blockBranches(all *Scope, parent *block, lstmt *syntax.LabeledStmt, list []syntax.Stmt) []*syntax.BranchStmt {
    97  	b := &block{parent, lstmt, nil}
    98  
    99  	var (
   100  		varDeclPos         syntax.Pos
   101  		fwdJumps, badJumps []*syntax.BranchStmt
   102  	)
   103  
   104  	// All forward jumps jumping over a variable declaration are possibly
   105  	// invalid (they may still jump out of the block and be ok).
   106  	// recordVarDecl records them for the given position.
   107  	recordVarDecl := func(pos syntax.Pos) {
   108  		varDeclPos = pos
   109  		badJumps = append(badJumps[:0], fwdJumps...) // copy fwdJumps to badJumps
   110  	}
   111  
   112  	jumpsOverVarDecl := func(jmp *syntax.BranchStmt) bool {
   113  		if varDeclPos.IsKnown() {
   114  			for _, bad := range badJumps {
   115  				if jmp == bad {
   116  					return true
   117  				}
   118  			}
   119  		}
   120  		return false
   121  	}
   122  
   123  	var stmtBranches func(syntax.Stmt)
   124  	stmtBranches = func(s syntax.Stmt) {
   125  		switch s := s.(type) {
   126  		case *syntax.DeclStmt:
   127  			for _, d := range s.DeclList {
   128  				if d, _ := d.(*syntax.VarDecl); d != nil {
   129  					recordVarDecl(d.Pos())
   130  				}
   131  			}
   132  
   133  		case *syntax.LabeledStmt:
   134  			// declare non-blank label
   135  			if name := s.Label.Value; name != "_" {
   136  				lbl := NewLabel(s.Label.Pos(), check.pkg, name)
   137  				if alt := all.Insert(lbl); alt != nil {
   138  					err := check.newError(DuplicateLabel)
   139  					err.soft = true
   140  					err.addf(lbl.pos, "label %s already declared", quote(name))
   141  					err.addAltDecl(alt)
   142  					err.report()
   143  					// ok to continue
   144  				} else {
   145  					b.insert(s)
   146  					check.recordDef(s.Label, lbl)
   147  				}
   148  				// resolve matching forward jumps and remove them from fwdJumps
   149  				i := 0
   150  				for _, jmp := range fwdJumps {
   151  					if jmp.Label.Value == name {
   152  						// match
   153  						lbl.used = true
   154  						check.recordUse(jmp.Label, lbl)
   155  						if jumpsOverVarDecl(jmp) {
   156  							check.softErrorf(
   157  								jmp.Label,
   158  								JumpOverDecl,
   159  								"goto %s jumps over variable declaration at line %d",
   160  								name,
   161  								varDeclPos.Line(),
   162  							)
   163  							// ok to continue
   164  						}
   165  					} else {
   166  						// no match - record new forward jump
   167  						fwdJumps[i] = jmp
   168  						i++
   169  					}
   170  				}
   171  				fwdJumps = fwdJumps[:i]
   172  				lstmt = s
   173  			}
   174  			stmtBranches(s.Stmt)
   175  
   176  		case *syntax.BranchStmt:
   177  			if s.Label == nil {
   178  				return // checked in 1st pass (check.stmt)
   179  			}
   180  
   181  			// determine and validate target
   182  			name := s.Label.Value
   183  			switch s.Tok {
   184  			case syntax.Break:
   185  				// spec: "If there is a label, it must be that of an enclosing
   186  				// "for", "switch", or "select" statement, and that is the one
   187  				// whose execution terminates."
   188  				valid := false
   189  				if t := b.enclosingTarget(name); t != nil {
   190  					switch t.Stmt.(type) {
   191  					case *syntax.SwitchStmt, *syntax.SelectStmt, *syntax.ForStmt:
   192  						valid = true
   193  					}
   194  				}
   195  				if !valid {
   196  					check.errorf(s.Label, MisplacedLabel, "invalid break label %s", quote(name))
   197  					return
   198  				}
   199  
   200  			case syntax.Continue:
   201  				// spec: "If there is a label, it must be that of an enclosing
   202  				// "for" statement, and that is the one whose execution advances."
   203  				valid := false
   204  				if t := b.enclosingTarget(name); t != nil {
   205  					switch t.Stmt.(type) {
   206  					case *syntax.ForStmt:
   207  						valid = true
   208  					}
   209  				}
   210  				if !valid {
   211  					check.errorf(s.Label, MisplacedLabel, "invalid continue label %s", quote(name))
   212  					return
   213  				}
   214  
   215  			case syntax.Goto:
   216  				if b.gotoTarget(name) == nil {
   217  					// label may be declared later - add branch to forward jumps
   218  					fwdJumps = append(fwdJumps, s)
   219  					return
   220  				}
   221  
   222  			default:
   223  				check.errorf(s, InvalidSyntaxTree, "branch statement: %s %s", s.Tok, name)
   224  				return
   225  			}
   226  
   227  			// record label use
   228  			obj := all.Lookup(name)
   229  			obj.(*Label).used = true
   230  			check.recordUse(s.Label, obj)
   231  
   232  		case *syntax.AssignStmt:
   233  			if s.Op == syntax.Def {
   234  				recordVarDecl(s.Pos())
   235  			}
   236  
   237  		case *syntax.BlockStmt:
   238  			// Unresolved forward jumps inside the nested block
   239  			// become forward jumps in the current block.
   240  			fwdJumps = append(fwdJumps, check.blockBranches(all, b, lstmt, s.List)...)
   241  
   242  		case *syntax.IfStmt:
   243  			stmtBranches(s.Then)
   244  			if s.Else != nil {
   245  				stmtBranches(s.Else)
   246  			}
   247  
   248  		case *syntax.SwitchStmt:
   249  			b := &block{b, lstmt, nil}
   250  			for _, s := range s.Body {
   251  				fwdJumps = append(fwdJumps, check.blockBranches(all, b, nil, s.Body)...)
   252  			}
   253  
   254  		case *syntax.SelectStmt:
   255  			b := &block{b, lstmt, nil}
   256  			for _, s := range s.Body {
   257  				fwdJumps = append(fwdJumps, check.blockBranches(all, b, nil, s.Body)...)
   258  			}
   259  
   260  		case *syntax.ForStmt:
   261  			stmtBranches(s.Body)
   262  		}
   263  	}
   264  
   265  	for _, s := range list {
   266  		stmtBranches(s)
   267  	}
   268  
   269  	return fwdJumps
   270  }
   271  

View as plain text