github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/src/cmd/compile/internal/gc/noder.go (about)

     1  // Copyright 2016 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 gc
     6  
     7  import (
     8  	"fmt"
     9  	"os"
    10  	"path/filepath"
    11  	"runtime"
    12  	"strconv"
    13  	"strings"
    14  	"unicode/utf8"
    15  
    16  	"cmd/compile/internal/syntax"
    17  	"cmd/compile/internal/types"
    18  	"cmd/internal/objabi"
    19  	"cmd/internal/src"
    20  )
    21  
    22  // parseFiles concurrently parses files into *syntax.File structures.
    23  // Each declaration in every *syntax.File is converted to a syntax tree
    24  // and its root represented by *Node is appended to xtop.
    25  // Returns the total count of parsed lines.
    26  func parseFiles(filenames []string) uint {
    27  	var noders []*noder
    28  	// Limit the number of simultaneously open files.
    29  	sem := make(chan struct{}, runtime.GOMAXPROCS(0)+10)
    30  
    31  	for _, filename := range filenames {
    32  		p := &noder{
    33  			basemap: make(map[*syntax.PosBase]*src.PosBase),
    34  			err:     make(chan syntax.Error),
    35  		}
    36  		noders = append(noders, p)
    37  
    38  		go func(filename string) {
    39  			sem <- struct{}{}
    40  			defer func() { <-sem }()
    41  			defer close(p.err)
    42  			base := syntax.NewFileBase(filename)
    43  
    44  			f, err := os.Open(filename)
    45  			if err != nil {
    46  				p.error(syntax.Error{Pos: syntax.MakePos(base, 0, 0), Msg: err.Error()})
    47  				return
    48  			}
    49  			defer f.Close()
    50  
    51  			p.file, _ = syntax.Parse(base, f, p.error, p.pragma, syntax.CheckBranches) // errors are tracked via p.error
    52  		}(filename)
    53  	}
    54  
    55  	var lines uint
    56  	for _, p := range noders {
    57  		for e := range p.err {
    58  			p.yyerrorpos(e.Pos, "%s", e.Msg)
    59  		}
    60  
    61  		p.node()
    62  		lines += p.file.Lines
    63  		p.file = nil // release memory
    64  
    65  		if nsyntaxerrors != 0 {
    66  			errorexit()
    67  		}
    68  		// Always run testdclstack here, even when debug_dclstack is not set, as a sanity measure.
    69  		testdclstack()
    70  	}
    71  
    72  	localpkg.Height = myheight
    73  
    74  	return lines
    75  }
    76  
    77  // makeSrcPosBase translates from a *syntax.PosBase to a *src.PosBase.
    78  func (p *noder) makeSrcPosBase(b0 *syntax.PosBase) *src.PosBase {
    79  	// fast path: most likely PosBase hasn't changed
    80  	if p.basecache.last == b0 {
    81  		return p.basecache.base
    82  	}
    83  
    84  	b1, ok := p.basemap[b0]
    85  	if !ok {
    86  		fn := b0.Filename()
    87  		if b0.IsFileBase() {
    88  			b1 = src.NewFileBase(fn, absFilename(fn))
    89  		} else {
    90  			// line directive base
    91  			p0 := b0.Pos()
    92  			p1 := src.MakePos(p.makeSrcPosBase(p0.Base()), p0.Line(), p0.Col())
    93  			b1 = src.NewLinePragmaBase(p1, fn, fileh(fn), b0.Line(), b0.Col())
    94  		}
    95  		p.basemap[b0] = b1
    96  	}
    97  
    98  	// update cache
    99  	p.basecache.last = b0
   100  	p.basecache.base = b1
   101  
   102  	return b1
   103  }
   104  
   105  func (p *noder) makeXPos(pos syntax.Pos) (_ src.XPos) {
   106  	return Ctxt.PosTable.XPos(src.MakePos(p.makeSrcPosBase(pos.Base()), pos.Line(), pos.Col()))
   107  }
   108  
   109  func (p *noder) yyerrorpos(pos syntax.Pos, format string, args ...interface{}) {
   110  	yyerrorl(p.makeXPos(pos), format, args...)
   111  }
   112  
   113  var pathPrefix string
   114  
   115  // TODO(gri) Can we eliminate fileh in favor of absFilename?
   116  func fileh(name string) string {
   117  	return objabi.AbsFile("", name, pathPrefix)
   118  }
   119  
   120  func absFilename(name string) string {
   121  	return objabi.AbsFile(Ctxt.Pathname, name, pathPrefix)
   122  }
   123  
   124  // noder transforms package syntax's AST into a Node tree.
   125  type noder struct {
   126  	basemap   map[*syntax.PosBase]*src.PosBase
   127  	basecache struct {
   128  		last *syntax.PosBase
   129  		base *src.PosBase
   130  	}
   131  
   132  	file       *syntax.File
   133  	linknames  []linkname
   134  	pragcgobuf [][]string
   135  	err        chan syntax.Error
   136  	scope      ScopeID
   137  
   138  	// scopeVars is a stack tracking the number of variables declared in the
   139  	// current function at the moment each open scope was opened.
   140  	scopeVars []int
   141  
   142  	lastCloseScopePos syntax.Pos
   143  }
   144  
   145  func (p *noder) funcBody(fn *Node, block *syntax.BlockStmt) {
   146  	oldScope := p.scope
   147  	p.scope = 0
   148  	funchdr(fn)
   149  
   150  	if block != nil {
   151  		body := p.stmts(block.List)
   152  		if body == nil {
   153  			body = []*Node{nod(OEMPTY, nil, nil)}
   154  		}
   155  		fn.Nbody.Set(body)
   156  
   157  		lineno = p.makeXPos(block.Rbrace)
   158  		fn.Func.Endlineno = lineno
   159  	}
   160  
   161  	funcbody()
   162  	p.scope = oldScope
   163  }
   164  
   165  func (p *noder) openScope(pos syntax.Pos) {
   166  	types.Markdcl()
   167  
   168  	if trackScopes {
   169  		Curfn.Func.Parents = append(Curfn.Func.Parents, p.scope)
   170  		p.scopeVars = append(p.scopeVars, len(Curfn.Func.Dcl))
   171  		p.scope = ScopeID(len(Curfn.Func.Parents))
   172  
   173  		p.markScope(pos)
   174  	}
   175  }
   176  
   177  func (p *noder) closeScope(pos syntax.Pos) {
   178  	p.lastCloseScopePos = pos
   179  	types.Popdcl()
   180  
   181  	if trackScopes {
   182  		scopeVars := p.scopeVars[len(p.scopeVars)-1]
   183  		p.scopeVars = p.scopeVars[:len(p.scopeVars)-1]
   184  		if scopeVars == len(Curfn.Func.Dcl) {
   185  			// no variables were declared in this scope, so we can retract it.
   186  
   187  			if int(p.scope) != len(Curfn.Func.Parents) {
   188  				Fatalf("scope tracking inconsistency, no variables declared but scopes were not retracted")
   189  			}
   190  
   191  			p.scope = Curfn.Func.Parents[p.scope-1]
   192  			Curfn.Func.Parents = Curfn.Func.Parents[:len(Curfn.Func.Parents)-1]
   193  
   194  			nmarks := len(Curfn.Func.Marks)
   195  			Curfn.Func.Marks[nmarks-1].Scope = p.scope
   196  			prevScope := ScopeID(0)
   197  			if nmarks >= 2 {
   198  				prevScope = Curfn.Func.Marks[nmarks-2].Scope
   199  			}
   200  			if Curfn.Func.Marks[nmarks-1].Scope == prevScope {
   201  				Curfn.Func.Marks = Curfn.Func.Marks[:nmarks-1]
   202  			}
   203  			return
   204  		}
   205  
   206  		p.scope = Curfn.Func.Parents[p.scope-1]
   207  
   208  		p.markScope(pos)
   209  	}
   210  }
   211  
   212  func (p *noder) markScope(pos syntax.Pos) {
   213  	xpos := p.makeXPos(pos)
   214  	if i := len(Curfn.Func.Marks); i > 0 && Curfn.Func.Marks[i-1].Pos == xpos {
   215  		Curfn.Func.Marks[i-1].Scope = p.scope
   216  	} else {
   217  		Curfn.Func.Marks = append(Curfn.Func.Marks, Mark{xpos, p.scope})
   218  	}
   219  }
   220  
   221  // closeAnotherScope is like closeScope, but it reuses the same mark
   222  // position as the last closeScope call. This is useful for "for" and
   223  // "if" statements, as their implicit blocks always end at the same
   224  // position as an explicit block.
   225  func (p *noder) closeAnotherScope() {
   226  	p.closeScope(p.lastCloseScopePos)
   227  }
   228  
   229  // linkname records a //go:linkname directive.
   230  type linkname struct {
   231  	pos    syntax.Pos
   232  	local  string
   233  	remote string
   234  }
   235  
   236  func (p *noder) node() {
   237  	types.Block = 1
   238  	imported_unsafe = false
   239  
   240  	p.lineno(p.file.PkgName)
   241  	mkpackage(p.file.PkgName.Value)
   242  
   243  	xtop = append(xtop, p.decls(p.file.DeclList)...)
   244  
   245  	for _, n := range p.linknames {
   246  		if imported_unsafe {
   247  			lookup(n.local).Linkname = n.remote
   248  		} else {
   249  			p.yyerrorpos(n.pos, "//go:linkname only allowed in Go files that import \"unsafe\"")
   250  		}
   251  	}
   252  
   253  	pragcgobuf = append(pragcgobuf, p.pragcgobuf...)
   254  	lineno = src.NoXPos
   255  	clearImports()
   256  }
   257  
   258  func (p *noder) decls(decls []syntax.Decl) (l []*Node) {
   259  	var cs constState
   260  
   261  	for _, decl := range decls {
   262  		p.lineno(decl)
   263  		switch decl := decl.(type) {
   264  		case *syntax.ImportDecl:
   265  			p.importDecl(decl)
   266  
   267  		case *syntax.VarDecl:
   268  			l = append(l, p.varDecl(decl)...)
   269  
   270  		case *syntax.ConstDecl:
   271  			l = append(l, p.constDecl(decl, &cs)...)
   272  
   273  		case *syntax.TypeDecl:
   274  			l = append(l, p.typeDecl(decl))
   275  
   276  		case *syntax.FuncDecl:
   277  			l = append(l, p.funcDecl(decl))
   278  
   279  		default:
   280  			panic("unhandled Decl")
   281  		}
   282  	}
   283  
   284  	return
   285  }
   286  
   287  func (p *noder) importDecl(imp *syntax.ImportDecl) {
   288  	val := p.basicLit(imp.Path)
   289  	ipkg := importfile(&val)
   290  
   291  	if ipkg == nil {
   292  		if nerrors == 0 {
   293  			Fatalf("phase error in import")
   294  		}
   295  		return
   296  	}
   297  
   298  	ipkg.Direct = true
   299  
   300  	var my *types.Sym
   301  	if imp.LocalPkgName != nil {
   302  		my = p.name(imp.LocalPkgName)
   303  	} else {
   304  		my = lookup(ipkg.Name)
   305  	}
   306  
   307  	pack := p.nod(imp, OPACK, nil, nil)
   308  	pack.Sym = my
   309  	pack.Name.Pkg = ipkg
   310  
   311  	switch my.Name {
   312  	case ".":
   313  		importdot(ipkg, pack)
   314  		return
   315  	case "init":
   316  		yyerrorl(pack.Pos, "cannot import package as init - init must be a func")
   317  		return
   318  	case "_":
   319  		return
   320  	}
   321  	if my.Def != nil {
   322  		redeclare(pack.Pos, my, "as imported package name")
   323  	}
   324  	my.Def = asTypesNode(pack)
   325  	my.Lastlineno = pack.Pos
   326  	my.Block = 1 // at top level
   327  }
   328  
   329  func (p *noder) varDecl(decl *syntax.VarDecl) []*Node {
   330  	names := p.declNames(decl.NameList)
   331  	typ := p.typeExprOrNil(decl.Type)
   332  
   333  	var exprs []*Node
   334  	if decl.Values != nil {
   335  		exprs = p.exprList(decl.Values)
   336  	}
   337  
   338  	p.lineno(decl)
   339  	return variter(names, typ, exprs)
   340  }
   341  
   342  // constState tracks state between constant specifiers within a
   343  // declaration group. This state is kept separate from noder so nested
   344  // constant declarations are handled correctly (e.g., issue 15550).
   345  type constState struct {
   346  	group  *syntax.Group
   347  	typ    *Node
   348  	values []*Node
   349  	iota   int64
   350  }
   351  
   352  func (p *noder) constDecl(decl *syntax.ConstDecl, cs *constState) []*Node {
   353  	if decl.Group == nil || decl.Group != cs.group {
   354  		*cs = constState{
   355  			group: decl.Group,
   356  		}
   357  	}
   358  
   359  	names := p.declNames(decl.NameList)
   360  	typ := p.typeExprOrNil(decl.Type)
   361  
   362  	var values []*Node
   363  	if decl.Values != nil {
   364  		values = p.exprList(decl.Values)
   365  		cs.typ, cs.values = typ, values
   366  	} else {
   367  		if typ != nil {
   368  			yyerror("const declaration cannot have type without expression")
   369  		}
   370  		typ, values = cs.typ, cs.values
   371  	}
   372  
   373  	var nn []*Node
   374  	for i, n := range names {
   375  		if i >= len(values) {
   376  			yyerror("missing value in const declaration")
   377  			break
   378  		}
   379  		v := values[i]
   380  		if decl.Values == nil {
   381  			v = treecopy(v, n.Pos)
   382  		}
   383  
   384  		n.Op = OLITERAL
   385  		declare(n, dclcontext)
   386  
   387  		n.Name.Param.Ntype = typ
   388  		n.Name.Defn = v
   389  		n.SetIota(cs.iota)
   390  
   391  		nn = append(nn, p.nod(decl, ODCLCONST, n, nil))
   392  	}
   393  
   394  	if len(values) > len(names) {
   395  		yyerror("extra expression in const declaration")
   396  	}
   397  
   398  	cs.iota++
   399  
   400  	return nn
   401  }
   402  
   403  func (p *noder) typeDecl(decl *syntax.TypeDecl) *Node {
   404  	n := p.declName(decl.Name)
   405  	n.Op = OTYPE
   406  	declare(n, dclcontext)
   407  
   408  	// decl.Type may be nil but in that case we got a syntax error during parsing
   409  	typ := p.typeExprOrNil(decl.Type)
   410  
   411  	param := n.Name.Param
   412  	param.Ntype = typ
   413  	param.Pragma = decl.Pragma
   414  	param.Alias = decl.Alias
   415  	if param.Alias && param.Pragma != 0 {
   416  		yyerror("cannot specify directive with type alias")
   417  		param.Pragma = 0
   418  	}
   419  
   420  	return p.nod(decl, ODCLTYPE, n, nil)
   421  
   422  }
   423  
   424  func (p *noder) declNames(names []*syntax.Name) []*Node {
   425  	var nodes []*Node
   426  	for _, name := range names {
   427  		nodes = append(nodes, p.declName(name))
   428  	}
   429  	return nodes
   430  }
   431  
   432  func (p *noder) declName(name *syntax.Name) *Node {
   433  	return p.setlineno(name, dclname(p.name(name)))
   434  }
   435  
   436  func (p *noder) funcDecl(fun *syntax.FuncDecl) *Node {
   437  	name := p.name(fun.Name)
   438  	t := p.signature(fun.Recv, fun.Type)
   439  	f := p.nod(fun, ODCLFUNC, nil, nil)
   440  
   441  	if fun.Recv == nil {
   442  		if name.Name == "init" {
   443  			name = renameinit()
   444  			if t.List.Len() > 0 || t.Rlist.Len() > 0 {
   445  				yyerrorl(f.Pos, "func init must have no arguments and no return values")
   446  			}
   447  		}
   448  
   449  		if localpkg.Name == "main" && name.Name == "main" {
   450  			if t.List.Len() > 0 || t.Rlist.Len() > 0 {
   451  				yyerrorl(f.Pos, "func main must have no arguments and no return values")
   452  			}
   453  		}
   454  	} else {
   455  		f.Func.Shortname = name
   456  		name = nblank.Sym // filled in by typecheckfunc
   457  	}
   458  
   459  	f.Func.Nname = p.setlineno(fun.Name, newfuncname(name))
   460  	f.Func.Nname.Name.Defn = f
   461  	f.Func.Nname.Name.Param.Ntype = t
   462  
   463  	pragma := fun.Pragma
   464  	f.Func.Pragma = fun.Pragma
   465  	f.SetNoescape(pragma&Noescape != 0)
   466  	if pragma&Systemstack != 0 && pragma&Nosplit != 0 {
   467  		yyerrorl(f.Pos, "go:nosplit and go:systemstack cannot be combined")
   468  	}
   469  
   470  	if fun.Recv == nil {
   471  		declare(f.Func.Nname, PFUNC)
   472  	}
   473  
   474  	p.funcBody(f, fun.Body)
   475  
   476  	if fun.Body != nil {
   477  		if f.Noescape() {
   478  			yyerrorl(f.Pos, "can only use //go:noescape with external func implementations")
   479  		}
   480  	} else {
   481  		if pure_go || strings.HasPrefix(f.funcname(), "init.") {
   482  			yyerrorl(f.Pos, "missing function body")
   483  		}
   484  	}
   485  
   486  	return f
   487  }
   488  
   489  func (p *noder) signature(recv *syntax.Field, typ *syntax.FuncType) *Node {
   490  	n := p.nod(typ, OTFUNC, nil, nil)
   491  	if recv != nil {
   492  		n.Left = p.param(recv, false, false)
   493  	}
   494  	n.List.Set(p.params(typ.ParamList, true))
   495  	n.Rlist.Set(p.params(typ.ResultList, false))
   496  	return n
   497  }
   498  
   499  func (p *noder) params(params []*syntax.Field, dddOk bool) []*Node {
   500  	var nodes []*Node
   501  	for i, param := range params {
   502  		p.lineno(param)
   503  		nodes = append(nodes, p.param(param, dddOk, i+1 == len(params)))
   504  	}
   505  	return nodes
   506  }
   507  
   508  func (p *noder) param(param *syntax.Field, dddOk, final bool) *Node {
   509  	var name *types.Sym
   510  	if param.Name != nil {
   511  		name = p.name(param.Name)
   512  	}
   513  
   514  	typ := p.typeExpr(param.Type)
   515  	n := p.nodSym(param, ODCLFIELD, typ, name)
   516  
   517  	// rewrite ...T parameter
   518  	if typ.Op == ODDD {
   519  		if !dddOk {
   520  			yyerror("cannot use ... in receiver or result parameter list")
   521  		} else if !final {
   522  			yyerror("can only use ... with final parameter in list")
   523  		}
   524  		typ.Op = OTARRAY
   525  		typ.Right = typ.Left
   526  		typ.Left = nil
   527  		n.SetIsddd(true)
   528  		if n.Left != nil {
   529  			n.Left.SetIsddd(true)
   530  		}
   531  	}
   532  
   533  	return n
   534  }
   535  
   536  func (p *noder) exprList(expr syntax.Expr) []*Node {
   537  	if list, ok := expr.(*syntax.ListExpr); ok {
   538  		return p.exprs(list.ElemList)
   539  	}
   540  	return []*Node{p.expr(expr)}
   541  }
   542  
   543  func (p *noder) exprs(exprs []syntax.Expr) []*Node {
   544  	var nodes []*Node
   545  	for _, expr := range exprs {
   546  		nodes = append(nodes, p.expr(expr))
   547  	}
   548  	return nodes
   549  }
   550  
   551  func (p *noder) expr(expr syntax.Expr) *Node {
   552  	p.lineno(expr)
   553  	switch expr := expr.(type) {
   554  	case nil, *syntax.BadExpr:
   555  		return nil
   556  	case *syntax.Name:
   557  		return p.mkname(expr)
   558  	case *syntax.BasicLit:
   559  		return p.setlineno(expr, nodlit(p.basicLit(expr)))
   560  
   561  	case *syntax.CompositeLit:
   562  		n := p.nod(expr, OCOMPLIT, nil, nil)
   563  		if expr.Type != nil {
   564  			n.Right = p.expr(expr.Type)
   565  		}
   566  		l := p.exprs(expr.ElemList)
   567  		for i, e := range l {
   568  			l[i] = p.wrapname(expr.ElemList[i], e)
   569  		}
   570  		n.List.Set(l)
   571  		lineno = p.makeXPos(expr.Rbrace)
   572  		return n
   573  	case *syntax.KeyValueExpr:
   574  		// use position of expr.Key rather than of expr (which has position of ':')
   575  		return p.nod(expr.Key, OKEY, p.expr(expr.Key), p.wrapname(expr.Value, p.expr(expr.Value)))
   576  	case *syntax.FuncLit:
   577  		return p.funcLit(expr)
   578  	case *syntax.ParenExpr:
   579  		return p.nod(expr, OPAREN, p.expr(expr.X), nil)
   580  	case *syntax.SelectorExpr:
   581  		// parser.new_dotname
   582  		obj := p.expr(expr.X)
   583  		if obj.Op == OPACK {
   584  			obj.Name.SetUsed(true)
   585  			return oldname(restrictlookup(expr.Sel.Value, obj.Name.Pkg))
   586  		}
   587  		return p.setlineno(expr, nodSym(OXDOT, obj, p.name(expr.Sel)))
   588  	case *syntax.IndexExpr:
   589  		return p.nod(expr, OINDEX, p.expr(expr.X), p.expr(expr.Index))
   590  	case *syntax.SliceExpr:
   591  		op := OSLICE
   592  		if expr.Full {
   593  			op = OSLICE3
   594  		}
   595  		n := p.nod(expr, op, p.expr(expr.X), nil)
   596  		var index [3]*Node
   597  		for i, x := range expr.Index {
   598  			if x != nil {
   599  				index[i] = p.expr(x)
   600  			}
   601  		}
   602  		n.SetSliceBounds(index[0], index[1], index[2])
   603  		return n
   604  	case *syntax.AssertExpr:
   605  		return p.nod(expr, ODOTTYPE, p.expr(expr.X), p.typeExpr(expr.Type))
   606  	case *syntax.Operation:
   607  		if expr.Op == syntax.Add && expr.Y != nil {
   608  			return p.sum(expr)
   609  		}
   610  		x := p.expr(expr.X)
   611  		if expr.Y == nil {
   612  			if expr.Op == syntax.And {
   613  				x = unparen(x) // TODO(mdempsky): Needed?
   614  				if x.Op == OCOMPLIT {
   615  					// Special case for &T{...}: turn into (*T){...}.
   616  					x.Right = p.nod(expr, OIND, x.Right, nil)
   617  					x.Right.SetImplicit(true)
   618  					return x
   619  				}
   620  			}
   621  			return p.nod(expr, p.unOp(expr.Op), x, nil)
   622  		}
   623  		return p.nod(expr, p.binOp(expr.Op), x, p.expr(expr.Y))
   624  	case *syntax.CallExpr:
   625  		n := p.nod(expr, OCALL, p.expr(expr.Fun), nil)
   626  		n.List.Set(p.exprs(expr.ArgList))
   627  		n.SetIsddd(expr.HasDots)
   628  		return n
   629  
   630  	case *syntax.ArrayType:
   631  		var len *Node
   632  		if expr.Len != nil {
   633  			len = p.expr(expr.Len)
   634  		} else {
   635  			len = p.nod(expr, ODDD, nil, nil)
   636  		}
   637  		return p.nod(expr, OTARRAY, len, p.typeExpr(expr.Elem))
   638  	case *syntax.SliceType:
   639  		return p.nod(expr, OTARRAY, nil, p.typeExpr(expr.Elem))
   640  	case *syntax.DotsType:
   641  		return p.nod(expr, ODDD, p.typeExpr(expr.Elem), nil)
   642  	case *syntax.StructType:
   643  		return p.structType(expr)
   644  	case *syntax.InterfaceType:
   645  		return p.interfaceType(expr)
   646  	case *syntax.FuncType:
   647  		return p.signature(nil, expr)
   648  	case *syntax.MapType:
   649  		return p.nod(expr, OTMAP, p.typeExpr(expr.Key), p.typeExpr(expr.Value))
   650  	case *syntax.ChanType:
   651  		n := p.nod(expr, OTCHAN, p.typeExpr(expr.Elem), nil)
   652  		n.SetTChanDir(p.chanDir(expr.Dir))
   653  		return n
   654  
   655  	case *syntax.TypeSwitchGuard:
   656  		n := p.nod(expr, OTYPESW, nil, p.expr(expr.X))
   657  		if expr.Lhs != nil {
   658  			n.Left = p.declName(expr.Lhs)
   659  			if n.Left.isBlank() {
   660  				yyerror("invalid variable name %v in type switch", n.Left)
   661  			}
   662  		}
   663  		return n
   664  	}
   665  	panic("unhandled Expr")
   666  }
   667  
   668  // sum efficiently handles very large summation expressions (such as
   669  // in issue #16394). In particular, it avoids left recursion and
   670  // collapses string literals.
   671  func (p *noder) sum(x syntax.Expr) *Node {
   672  	// While we need to handle long sums with asymptotic
   673  	// efficiency, the vast majority of sums are very small: ~95%
   674  	// have only 2 or 3 operands, and ~99% of string literals are
   675  	// never concatenated.
   676  
   677  	adds := make([]*syntax.Operation, 0, 2)
   678  	for {
   679  		add, ok := x.(*syntax.Operation)
   680  		if !ok || add.Op != syntax.Add || add.Y == nil {
   681  			break
   682  		}
   683  		adds = append(adds, add)
   684  		x = add.X
   685  	}
   686  
   687  	// nstr is the current rightmost string literal in the
   688  	// summation (if any), and chunks holds its accumulated
   689  	// substrings.
   690  	//
   691  	// Consider the expression x + "a" + "b" + "c" + y. When we
   692  	// reach the string literal "a", we assign nstr to point to
   693  	// its corresponding Node and initialize chunks to {"a"}.
   694  	// Visiting the subsequent string literals "b" and "c", we
   695  	// simply append their values to chunks. Finally, when we
   696  	// reach the non-constant operand y, we'll join chunks to form
   697  	// "abc" and reassign the "a" string literal's value.
   698  	//
   699  	// N.B., we need to be careful about named string constants
   700  	// (indicated by Sym != nil) because 1) we can't modify their
   701  	// value, as doing so would affect other uses of the string
   702  	// constant, and 2) they may have types, which we need to
   703  	// handle correctly. For now, we avoid these problems by
   704  	// treating named string constants the same as non-constant
   705  	// operands.
   706  	var nstr *Node
   707  	chunks := make([]string, 0, 1)
   708  
   709  	n := p.expr(x)
   710  	if Isconst(n, CTSTR) && n.Sym == nil {
   711  		nstr = n
   712  		chunks = append(chunks, nstr.Val().U.(string))
   713  	}
   714  
   715  	for i := len(adds) - 1; i >= 0; i-- {
   716  		add := adds[i]
   717  
   718  		r := p.expr(add.Y)
   719  		if Isconst(r, CTSTR) && r.Sym == nil {
   720  			if nstr != nil {
   721  				// Collapse r into nstr instead of adding to n.
   722  				chunks = append(chunks, r.Val().U.(string))
   723  				continue
   724  			}
   725  
   726  			nstr = r
   727  			chunks = append(chunks, nstr.Val().U.(string))
   728  		} else {
   729  			if len(chunks) > 1 {
   730  				nstr.SetVal(Val{U: strings.Join(chunks, "")})
   731  			}
   732  			nstr = nil
   733  			chunks = chunks[:0]
   734  		}
   735  		n = p.nod(add, OADD, n, r)
   736  	}
   737  	if len(chunks) > 1 {
   738  		nstr.SetVal(Val{U: strings.Join(chunks, "")})
   739  	}
   740  
   741  	return n
   742  }
   743  
   744  func (p *noder) typeExpr(typ syntax.Expr) *Node {
   745  	// TODO(mdempsky): Be stricter? typecheck should handle errors anyway.
   746  	return p.expr(typ)
   747  }
   748  
   749  func (p *noder) typeExprOrNil(typ syntax.Expr) *Node {
   750  	if typ != nil {
   751  		return p.expr(typ)
   752  	}
   753  	return nil
   754  }
   755  
   756  func (p *noder) chanDir(dir syntax.ChanDir) types.ChanDir {
   757  	switch dir {
   758  	case 0:
   759  		return types.Cboth
   760  	case syntax.SendOnly:
   761  		return types.Csend
   762  	case syntax.RecvOnly:
   763  		return types.Crecv
   764  	}
   765  	panic("unhandled ChanDir")
   766  }
   767  
   768  func (p *noder) structType(expr *syntax.StructType) *Node {
   769  	var l []*Node
   770  	for i, field := range expr.FieldList {
   771  		p.lineno(field)
   772  		var n *Node
   773  		if field.Name == nil {
   774  			n = p.embedded(field.Type)
   775  		} else {
   776  			n = p.nodSym(field, ODCLFIELD, p.typeExpr(field.Type), p.name(field.Name))
   777  		}
   778  		if i < len(expr.TagList) && expr.TagList[i] != nil {
   779  			n.SetVal(p.basicLit(expr.TagList[i]))
   780  		}
   781  		l = append(l, n)
   782  	}
   783  
   784  	p.lineno(expr)
   785  	n := p.nod(expr, OTSTRUCT, nil, nil)
   786  	n.List.Set(l)
   787  	return n
   788  }
   789  
   790  func (p *noder) interfaceType(expr *syntax.InterfaceType) *Node {
   791  	var l []*Node
   792  	for _, method := range expr.MethodList {
   793  		p.lineno(method)
   794  		var n *Node
   795  		if method.Name == nil {
   796  			n = p.nodSym(method, ODCLFIELD, oldname(p.packname(method.Type)), nil)
   797  		} else {
   798  			mname := p.name(method.Name)
   799  			sig := p.typeExpr(method.Type)
   800  			sig.Left = fakeRecv()
   801  			n = p.nodSym(method, ODCLFIELD, sig, mname)
   802  			ifacedcl(n)
   803  		}
   804  		l = append(l, n)
   805  	}
   806  
   807  	n := p.nod(expr, OTINTER, nil, nil)
   808  	n.List.Set(l)
   809  	return n
   810  }
   811  
   812  func (p *noder) packname(expr syntax.Expr) *types.Sym {
   813  	switch expr := expr.(type) {
   814  	case *syntax.Name:
   815  		name := p.name(expr)
   816  		if n := oldname(name); n.Name != nil && n.Name.Pack != nil {
   817  			n.Name.Pack.Name.SetUsed(true)
   818  		}
   819  		return name
   820  	case *syntax.SelectorExpr:
   821  		name := p.name(expr.X.(*syntax.Name))
   822  		def := asNode(name.Def)
   823  		if def == nil {
   824  			yyerror("undefined: %v", name)
   825  			return name
   826  		}
   827  		var pkg *types.Pkg
   828  		if def.Op != OPACK {
   829  			yyerror("%v is not a package", name)
   830  			pkg = localpkg
   831  		} else {
   832  			def.Name.SetUsed(true)
   833  			pkg = def.Name.Pkg
   834  		}
   835  		return restrictlookup(expr.Sel.Value, pkg)
   836  	}
   837  	panic(fmt.Sprintf("unexpected packname: %#v", expr))
   838  }
   839  
   840  func (p *noder) embedded(typ syntax.Expr) *Node {
   841  	op, isStar := typ.(*syntax.Operation)
   842  	if isStar {
   843  		if op.Op != syntax.Mul || op.Y != nil {
   844  			panic("unexpected Operation")
   845  		}
   846  		typ = op.X
   847  	}
   848  
   849  	sym := p.packname(typ)
   850  	n := p.nodSym(typ, ODCLFIELD, oldname(sym), lookup(sym.Name))
   851  	n.SetEmbedded(true)
   852  
   853  	if isStar {
   854  		n.Left = p.nod(op, OIND, n.Left, nil)
   855  	}
   856  	return n
   857  }
   858  
   859  func (p *noder) stmts(stmts []syntax.Stmt) []*Node {
   860  	return p.stmtsFall(stmts, false)
   861  }
   862  
   863  func (p *noder) stmtsFall(stmts []syntax.Stmt, fallOK bool) []*Node {
   864  	var nodes []*Node
   865  	for i, stmt := range stmts {
   866  		s := p.stmtFall(stmt, fallOK && i+1 == len(stmts))
   867  		if s == nil {
   868  		} else if s.Op == OBLOCK && s.Ninit.Len() == 0 {
   869  			nodes = append(nodes, s.List.Slice()...)
   870  		} else {
   871  			nodes = append(nodes, s)
   872  		}
   873  	}
   874  	return nodes
   875  }
   876  
   877  func (p *noder) stmt(stmt syntax.Stmt) *Node {
   878  	return p.stmtFall(stmt, false)
   879  }
   880  
   881  func (p *noder) stmtFall(stmt syntax.Stmt, fallOK bool) *Node {
   882  	p.lineno(stmt)
   883  	switch stmt := stmt.(type) {
   884  	case *syntax.EmptyStmt:
   885  		return nil
   886  	case *syntax.LabeledStmt:
   887  		return p.labeledStmt(stmt, fallOK)
   888  	case *syntax.BlockStmt:
   889  		l := p.blockStmt(stmt)
   890  		if len(l) == 0 {
   891  			// TODO(mdempsky): Line number?
   892  			return nod(OEMPTY, nil, nil)
   893  		}
   894  		return liststmt(l)
   895  	case *syntax.ExprStmt:
   896  		return p.wrapname(stmt, p.expr(stmt.X))
   897  	case *syntax.SendStmt:
   898  		return p.nod(stmt, OSEND, p.expr(stmt.Chan), p.expr(stmt.Value))
   899  	case *syntax.DeclStmt:
   900  		return liststmt(p.decls(stmt.DeclList))
   901  	case *syntax.AssignStmt:
   902  		if stmt.Op != 0 && stmt.Op != syntax.Def {
   903  			n := p.nod(stmt, OASOP, p.expr(stmt.Lhs), p.expr(stmt.Rhs))
   904  			n.SetImplicit(stmt.Rhs == syntax.ImplicitOne)
   905  			n.SetSubOp(p.binOp(stmt.Op))
   906  			return n
   907  		}
   908  
   909  		n := p.nod(stmt, OAS, nil, nil) // assume common case
   910  
   911  		rhs := p.exprList(stmt.Rhs)
   912  		lhs := p.assignList(stmt.Lhs, n, stmt.Op == syntax.Def)
   913  
   914  		if len(lhs) == 1 && len(rhs) == 1 {
   915  			// common case
   916  			n.Left = lhs[0]
   917  			n.Right = rhs[0]
   918  		} else {
   919  			n.Op = OAS2
   920  			n.List.Set(lhs)
   921  			n.Rlist.Set(rhs)
   922  		}
   923  		return n
   924  
   925  	case *syntax.BranchStmt:
   926  		var op Op
   927  		switch stmt.Tok {
   928  		case syntax.Break:
   929  			op = OBREAK
   930  		case syntax.Continue:
   931  			op = OCONTINUE
   932  		case syntax.Fallthrough:
   933  			if !fallOK {
   934  				yyerror("fallthrough statement out of place")
   935  			}
   936  			op = OFALL
   937  		case syntax.Goto:
   938  			op = OGOTO
   939  		default:
   940  			panic("unhandled BranchStmt")
   941  		}
   942  		n := p.nod(stmt, op, nil, nil)
   943  		if stmt.Label != nil {
   944  			n.Left = p.newname(stmt.Label)
   945  		}
   946  		return n
   947  	case *syntax.CallStmt:
   948  		var op Op
   949  		switch stmt.Tok {
   950  		case syntax.Defer:
   951  			op = ODEFER
   952  		case syntax.Go:
   953  			op = OPROC
   954  		default:
   955  			panic("unhandled CallStmt")
   956  		}
   957  		return p.nod(stmt, op, p.expr(stmt.Call), nil)
   958  	case *syntax.ReturnStmt:
   959  		var results []*Node
   960  		if stmt.Results != nil {
   961  			results = p.exprList(stmt.Results)
   962  		}
   963  		n := p.nod(stmt, ORETURN, nil, nil)
   964  		n.List.Set(results)
   965  		if n.List.Len() == 0 && Curfn != nil {
   966  			for _, ln := range Curfn.Func.Dcl {
   967  				if ln.Class() == PPARAM {
   968  					continue
   969  				}
   970  				if ln.Class() != PPARAMOUT {
   971  					break
   972  				}
   973  				if asNode(ln.Sym.Def) != ln {
   974  					yyerror("%s is shadowed during return", ln.Sym.Name)
   975  				}
   976  			}
   977  		}
   978  		return n
   979  	case *syntax.IfStmt:
   980  		return p.ifStmt(stmt)
   981  	case *syntax.ForStmt:
   982  		return p.forStmt(stmt)
   983  	case *syntax.SwitchStmt:
   984  		return p.switchStmt(stmt)
   985  	case *syntax.SelectStmt:
   986  		return p.selectStmt(stmt)
   987  	}
   988  	panic("unhandled Stmt")
   989  }
   990  
   991  func (p *noder) assignList(expr syntax.Expr, defn *Node, colas bool) []*Node {
   992  	if !colas {
   993  		return p.exprList(expr)
   994  	}
   995  
   996  	defn.SetColas(true)
   997  
   998  	var exprs []syntax.Expr
   999  	if list, ok := expr.(*syntax.ListExpr); ok {
  1000  		exprs = list.ElemList
  1001  	} else {
  1002  		exprs = []syntax.Expr{expr}
  1003  	}
  1004  
  1005  	res := make([]*Node, len(exprs))
  1006  	seen := make(map[*types.Sym]bool, len(exprs))
  1007  
  1008  	newOrErr := false
  1009  	for i, expr := range exprs {
  1010  		p.lineno(expr)
  1011  		res[i] = nblank
  1012  
  1013  		name, ok := expr.(*syntax.Name)
  1014  		if !ok {
  1015  			p.yyerrorpos(expr.Pos(), "non-name %v on left side of :=", p.expr(expr))
  1016  			newOrErr = true
  1017  			continue
  1018  		}
  1019  
  1020  		sym := p.name(name)
  1021  		if sym.IsBlank() {
  1022  			continue
  1023  		}
  1024  
  1025  		if seen[sym] {
  1026  			p.yyerrorpos(expr.Pos(), "%v repeated on left side of :=", sym)
  1027  			newOrErr = true
  1028  			continue
  1029  		}
  1030  		seen[sym] = true
  1031  
  1032  		if sym.Block == types.Block {
  1033  			res[i] = oldname(sym)
  1034  			continue
  1035  		}
  1036  
  1037  		newOrErr = true
  1038  		n := newname(sym)
  1039  		declare(n, dclcontext)
  1040  		n.Name.Defn = defn
  1041  		defn.Ninit.Append(nod(ODCL, n, nil))
  1042  		res[i] = n
  1043  	}
  1044  
  1045  	if !newOrErr {
  1046  		yyerrorl(defn.Pos, "no new variables on left side of :=")
  1047  	}
  1048  	return res
  1049  }
  1050  
  1051  func (p *noder) blockStmt(stmt *syntax.BlockStmt) []*Node {
  1052  	p.openScope(stmt.Pos())
  1053  	nodes := p.stmts(stmt.List)
  1054  	p.closeScope(stmt.Rbrace)
  1055  	return nodes
  1056  }
  1057  
  1058  func (p *noder) ifStmt(stmt *syntax.IfStmt) *Node {
  1059  	p.openScope(stmt.Pos())
  1060  	n := p.nod(stmt, OIF, nil, nil)
  1061  	if stmt.Init != nil {
  1062  		n.Ninit.Set1(p.stmt(stmt.Init))
  1063  	}
  1064  	if stmt.Cond != nil {
  1065  		n.Left = p.expr(stmt.Cond)
  1066  	}
  1067  	n.Nbody.Set(p.blockStmt(stmt.Then))
  1068  	if stmt.Else != nil {
  1069  		e := p.stmt(stmt.Else)
  1070  		if e.Op == OBLOCK && e.Ninit.Len() == 0 {
  1071  			n.Rlist.Set(e.List.Slice())
  1072  		} else {
  1073  			n.Rlist.Set1(e)
  1074  		}
  1075  	}
  1076  	p.closeAnotherScope()
  1077  	return n
  1078  }
  1079  
  1080  func (p *noder) forStmt(stmt *syntax.ForStmt) *Node {
  1081  	p.openScope(stmt.Pos())
  1082  	var n *Node
  1083  	if r, ok := stmt.Init.(*syntax.RangeClause); ok {
  1084  		if stmt.Cond != nil || stmt.Post != nil {
  1085  			panic("unexpected RangeClause")
  1086  		}
  1087  
  1088  		n = p.nod(r, ORANGE, nil, p.expr(r.X))
  1089  		if r.Lhs != nil {
  1090  			n.List.Set(p.assignList(r.Lhs, n, r.Def))
  1091  		}
  1092  	} else {
  1093  		n = p.nod(stmt, OFOR, nil, nil)
  1094  		if stmt.Init != nil {
  1095  			n.Ninit.Set1(p.stmt(stmt.Init))
  1096  		}
  1097  		if stmt.Cond != nil {
  1098  			n.Left = p.expr(stmt.Cond)
  1099  		}
  1100  		if stmt.Post != nil {
  1101  			n.Right = p.stmt(stmt.Post)
  1102  		}
  1103  	}
  1104  	n.Nbody.Set(p.blockStmt(stmt.Body))
  1105  	p.closeAnotherScope()
  1106  	return n
  1107  }
  1108  
  1109  func (p *noder) switchStmt(stmt *syntax.SwitchStmt) *Node {
  1110  	p.openScope(stmt.Pos())
  1111  	n := p.nod(stmt, OSWITCH, nil, nil)
  1112  	if stmt.Init != nil {
  1113  		n.Ninit.Set1(p.stmt(stmt.Init))
  1114  	}
  1115  	if stmt.Tag != nil {
  1116  		n.Left = p.expr(stmt.Tag)
  1117  	}
  1118  
  1119  	tswitch := n.Left
  1120  	if tswitch != nil && tswitch.Op != OTYPESW {
  1121  		tswitch = nil
  1122  	}
  1123  	n.List.Set(p.caseClauses(stmt.Body, tswitch, stmt.Rbrace))
  1124  
  1125  	p.closeScope(stmt.Rbrace)
  1126  	return n
  1127  }
  1128  
  1129  func (p *noder) caseClauses(clauses []*syntax.CaseClause, tswitch *Node, rbrace syntax.Pos) []*Node {
  1130  	var nodes []*Node
  1131  	for i, clause := range clauses {
  1132  		p.lineno(clause)
  1133  		if i > 0 {
  1134  			p.closeScope(clause.Pos())
  1135  		}
  1136  		p.openScope(clause.Pos())
  1137  
  1138  		n := p.nod(clause, OXCASE, nil, nil)
  1139  		if clause.Cases != nil {
  1140  			n.List.Set(p.exprList(clause.Cases))
  1141  		}
  1142  		if tswitch != nil && tswitch.Left != nil {
  1143  			nn := newname(tswitch.Left.Sym)
  1144  			declare(nn, dclcontext)
  1145  			n.Rlist.Set1(nn)
  1146  			// keep track of the instances for reporting unused
  1147  			nn.Name.Defn = tswitch
  1148  		}
  1149  
  1150  		// Trim trailing empty statements. We omit them from
  1151  		// the Node AST anyway, and it's easier to identify
  1152  		// out-of-place fallthrough statements without them.
  1153  		body := clause.Body
  1154  		for len(body) > 0 {
  1155  			if _, ok := body[len(body)-1].(*syntax.EmptyStmt); !ok {
  1156  				break
  1157  			}
  1158  			body = body[:len(body)-1]
  1159  		}
  1160  
  1161  		n.Nbody.Set(p.stmtsFall(body, true))
  1162  		if l := n.Nbody.Len(); l > 0 && n.Nbody.Index(l-1).Op == OFALL {
  1163  			if tswitch != nil {
  1164  				yyerror("cannot fallthrough in type switch")
  1165  			}
  1166  			if i+1 == len(clauses) {
  1167  				yyerror("cannot fallthrough final case in switch")
  1168  			}
  1169  		}
  1170  
  1171  		nodes = append(nodes, n)
  1172  	}
  1173  	if len(clauses) > 0 {
  1174  		p.closeScope(rbrace)
  1175  	}
  1176  	return nodes
  1177  }
  1178  
  1179  func (p *noder) selectStmt(stmt *syntax.SelectStmt) *Node {
  1180  	n := p.nod(stmt, OSELECT, nil, nil)
  1181  	n.List.Set(p.commClauses(stmt.Body, stmt.Rbrace))
  1182  	return n
  1183  }
  1184  
  1185  func (p *noder) commClauses(clauses []*syntax.CommClause, rbrace syntax.Pos) []*Node {
  1186  	var nodes []*Node
  1187  	for i, clause := range clauses {
  1188  		p.lineno(clause)
  1189  		if i > 0 {
  1190  			p.closeScope(clause.Pos())
  1191  		}
  1192  		p.openScope(clause.Pos())
  1193  
  1194  		n := p.nod(clause, OXCASE, nil, nil)
  1195  		if clause.Comm != nil {
  1196  			n.List.Set1(p.stmt(clause.Comm))
  1197  		}
  1198  		n.Nbody.Set(p.stmts(clause.Body))
  1199  		nodes = append(nodes, n)
  1200  	}
  1201  	if len(clauses) > 0 {
  1202  		p.closeScope(rbrace)
  1203  	}
  1204  	return nodes
  1205  }
  1206  
  1207  func (p *noder) labeledStmt(label *syntax.LabeledStmt, fallOK bool) *Node {
  1208  	lhs := p.nod(label, OLABEL, p.newname(label.Label), nil)
  1209  
  1210  	var ls *Node
  1211  	if label.Stmt != nil { // TODO(mdempsky): Should always be present.
  1212  		ls = p.stmtFall(label.Stmt, fallOK)
  1213  	}
  1214  
  1215  	lhs.Name.Defn = ls
  1216  	l := []*Node{lhs}
  1217  	if ls != nil {
  1218  		if ls.Op == OBLOCK && ls.Ninit.Len() == 0 {
  1219  			l = append(l, ls.List.Slice()...)
  1220  		} else {
  1221  			l = append(l, ls)
  1222  		}
  1223  	}
  1224  	return liststmt(l)
  1225  }
  1226  
  1227  var unOps = [...]Op{
  1228  	syntax.Recv: ORECV,
  1229  	syntax.Mul:  OIND,
  1230  	syntax.And:  OADDR,
  1231  
  1232  	syntax.Not: ONOT,
  1233  	syntax.Xor: OCOM,
  1234  	syntax.Add: OPLUS,
  1235  	syntax.Sub: OMINUS,
  1236  }
  1237  
  1238  func (p *noder) unOp(op syntax.Operator) Op {
  1239  	if uint64(op) >= uint64(len(unOps)) || unOps[op] == 0 {
  1240  		panic("invalid Operator")
  1241  	}
  1242  	return unOps[op]
  1243  }
  1244  
  1245  var binOps = [...]Op{
  1246  	syntax.OrOr:   OOROR,
  1247  	syntax.AndAnd: OANDAND,
  1248  
  1249  	syntax.Eql: OEQ,
  1250  	syntax.Neq: ONE,
  1251  	syntax.Lss: OLT,
  1252  	syntax.Leq: OLE,
  1253  	syntax.Gtr: OGT,
  1254  	syntax.Geq: OGE,
  1255  
  1256  	syntax.Add: OADD,
  1257  	syntax.Sub: OSUB,
  1258  	syntax.Or:  OOR,
  1259  	syntax.Xor: OXOR,
  1260  
  1261  	syntax.Mul:    OMUL,
  1262  	syntax.Div:    ODIV,
  1263  	syntax.Rem:    OMOD,
  1264  	syntax.And:    OAND,
  1265  	syntax.AndNot: OANDNOT,
  1266  	syntax.Shl:    OLSH,
  1267  	syntax.Shr:    ORSH,
  1268  }
  1269  
  1270  func (p *noder) binOp(op syntax.Operator) Op {
  1271  	if uint64(op) >= uint64(len(binOps)) || binOps[op] == 0 {
  1272  		panic("invalid Operator")
  1273  	}
  1274  	return binOps[op]
  1275  }
  1276  
  1277  func (p *noder) basicLit(lit *syntax.BasicLit) Val {
  1278  	// TODO: Don't try to convert if we had syntax errors (conversions may fail).
  1279  	//       Use dummy values so we can continue to compile. Eventually, use a
  1280  	//       form of "unknown" literals that are ignored during type-checking so
  1281  	//       we can continue type-checking w/o spurious follow-up errors.
  1282  	switch s := lit.Value; lit.Kind {
  1283  	case syntax.IntLit:
  1284  		x := new(Mpint)
  1285  		x.SetString(s)
  1286  		return Val{U: x}
  1287  
  1288  	case syntax.FloatLit:
  1289  		x := newMpflt()
  1290  		x.SetString(s)
  1291  		return Val{U: x}
  1292  
  1293  	case syntax.ImagLit:
  1294  		x := new(Mpcplx)
  1295  		x.Imag.SetString(strings.TrimSuffix(s, "i"))
  1296  		return Val{U: x}
  1297  
  1298  	case syntax.RuneLit:
  1299  		var r rune
  1300  		if u, err := strconv.Unquote(s); err == nil && len(u) > 0 {
  1301  			// Package syntax already reported any errors.
  1302  			// Check for them again though because 0 is a
  1303  			// better fallback value for invalid rune
  1304  			// literals than 0xFFFD.
  1305  			if len(u) == 1 {
  1306  				r = rune(u[0])
  1307  			} else {
  1308  				r, _ = utf8.DecodeRuneInString(u)
  1309  			}
  1310  		}
  1311  		x := new(Mpint)
  1312  		x.SetInt64(int64(r))
  1313  		x.Rune = true
  1314  		return Val{U: x}
  1315  
  1316  	case syntax.StringLit:
  1317  		if len(s) > 0 && s[0] == '`' {
  1318  			// strip carriage returns from raw string
  1319  			s = strings.Replace(s, "\r", "", -1)
  1320  		}
  1321  		// Ignore errors because package syntax already reported them.
  1322  		u, _ := strconv.Unquote(s)
  1323  		return Val{U: u}
  1324  
  1325  	default:
  1326  		panic("unhandled BasicLit kind")
  1327  	}
  1328  }
  1329  
  1330  func (p *noder) name(name *syntax.Name) *types.Sym {
  1331  	return lookup(name.Value)
  1332  }
  1333  
  1334  func (p *noder) mkname(name *syntax.Name) *Node {
  1335  	// TODO(mdempsky): Set line number?
  1336  	return mkname(p.name(name))
  1337  }
  1338  
  1339  func (p *noder) newname(name *syntax.Name) *Node {
  1340  	// TODO(mdempsky): Set line number?
  1341  	return newname(p.name(name))
  1342  }
  1343  
  1344  func (p *noder) wrapname(n syntax.Node, x *Node) *Node {
  1345  	// These nodes do not carry line numbers.
  1346  	// Introduce a wrapper node to give them the correct line.
  1347  	switch x.Op {
  1348  	case OTYPE, OLITERAL:
  1349  		if x.Sym == nil {
  1350  			break
  1351  		}
  1352  		fallthrough
  1353  	case ONAME, ONONAME, OPACK:
  1354  		x = p.nod(n, OPAREN, x, nil)
  1355  		x.SetImplicit(true)
  1356  	}
  1357  	return x
  1358  }
  1359  
  1360  func (p *noder) nod(orig syntax.Node, op Op, left, right *Node) *Node {
  1361  	return p.setlineno(orig, nod(op, left, right))
  1362  }
  1363  
  1364  func (p *noder) nodSym(orig syntax.Node, op Op, left *Node, sym *types.Sym) *Node {
  1365  	return p.setlineno(orig, nodSym(op, left, sym))
  1366  }
  1367  
  1368  func (p *noder) setlineno(src_ syntax.Node, dst *Node) *Node {
  1369  	pos := src_.Pos()
  1370  	if !pos.IsKnown() {
  1371  		// TODO(mdempsky): Shouldn't happen. Fix package syntax.
  1372  		return dst
  1373  	}
  1374  	dst.Pos = p.makeXPos(pos)
  1375  	return dst
  1376  }
  1377  
  1378  func (p *noder) lineno(n syntax.Node) {
  1379  	if n == nil {
  1380  		return
  1381  	}
  1382  	pos := n.Pos()
  1383  	if !pos.IsKnown() {
  1384  		// TODO(mdempsky): Shouldn't happen. Fix package syntax.
  1385  		return
  1386  	}
  1387  	lineno = p.makeXPos(pos)
  1388  }
  1389  
  1390  // error is called concurrently if files are parsed concurrently.
  1391  func (p *noder) error(err error) {
  1392  	p.err <- err.(syntax.Error)
  1393  }
  1394  
  1395  // pragmas that are allowed in the std lib, but don't have
  1396  // a syntax.Pragma value (see lex.go) associated with them.
  1397  var allowedStdPragmas = map[string]bool{
  1398  	"go:cgo_export_static":  true,
  1399  	"go:cgo_export_dynamic": true,
  1400  	"go:cgo_import_static":  true,
  1401  	"go:cgo_import_dynamic": true,
  1402  	"go:cgo_ldflag":         true,
  1403  	"go:cgo_dynamic_linker": true,
  1404  	"go:generate":           true,
  1405  }
  1406  
  1407  // pragma is called concurrently if files are parsed concurrently.
  1408  func (p *noder) pragma(pos syntax.Pos, text string) syntax.Pragma {
  1409  	switch {
  1410  	case strings.HasPrefix(text, "line "):
  1411  		// line directives are handled by syntax package
  1412  		panic("unreachable")
  1413  
  1414  	case strings.HasPrefix(text, "go:linkname "):
  1415  		f := strings.Fields(text)
  1416  		if len(f) != 3 {
  1417  			p.error(syntax.Error{Pos: pos, Msg: "usage: //go:linkname localname linkname"})
  1418  			break
  1419  		}
  1420  		p.linknames = append(p.linknames, linkname{pos, f[1], f[2]})
  1421  
  1422  	case strings.HasPrefix(text, "go:cgo_import_dynamic "):
  1423  		// This is permitted for general use because Solaris
  1424  		// code relies on it in golang.org/x/sys/unix and others.
  1425  		fields := pragmaFields(text)
  1426  		if len(fields) >= 4 {
  1427  			lib := strings.Trim(fields[3], `"`)
  1428  			if lib != "" && !safeArg(lib) && !isCgoGeneratedFile(pos) {
  1429  				p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("invalid library name %q in cgo_import_dynamic directive", lib)})
  1430  			}
  1431  			p.pragcgo(pos, text)
  1432  			return pragmaValue("go:cgo_import_dynamic")
  1433  		}
  1434  		fallthrough
  1435  	case strings.HasPrefix(text, "go:cgo_"):
  1436  		// For security, we disallow //go:cgo_* directives other
  1437  		// than cgo_import_dynamic outside cgo-generated files.
  1438  		// Exception: they are allowed in the standard library, for runtime and syscall.
  1439  		if !isCgoGeneratedFile(pos) && !compiling_std {
  1440  			p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("//%s only allowed in cgo-generated code", text)})
  1441  		}
  1442  		p.pragcgo(pos, text)
  1443  		fallthrough // because of //go:cgo_unsafe_args
  1444  	default:
  1445  		verb := text
  1446  		if i := strings.Index(text, " "); i >= 0 {
  1447  			verb = verb[:i]
  1448  		}
  1449  		prag := pragmaValue(verb)
  1450  		const runtimePragmas = Systemstack | Nowritebarrier | Nowritebarrierrec | Yeswritebarrierrec
  1451  		if !compiling_runtime && prag&runtimePragmas != 0 {
  1452  			p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("//%s only allowed in runtime", verb)})
  1453  		}
  1454  		if prag == 0 && !allowedStdPragmas[verb] && compiling_std {
  1455  			p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("//%s is not allowed in the standard library", verb)})
  1456  		}
  1457  		return prag
  1458  	}
  1459  
  1460  	return 0
  1461  }
  1462  
  1463  // isCgoGeneratedFile reports whether pos is in a file
  1464  // generated by cgo, which is to say a file with name
  1465  // beginning with "_cgo_". Such files are allowed to
  1466  // contain cgo directives, and for security reasons
  1467  // (primarily misuse of linker flags), other files are not.
  1468  // See golang.org/issue/23672.
  1469  func isCgoGeneratedFile(pos syntax.Pos) bool {
  1470  	return strings.HasPrefix(filepath.Base(filepath.Clean(fileh(pos.Base().Filename()))), "_cgo_")
  1471  }
  1472  
  1473  // safeArg reports whether arg is a "safe" command-line argument,
  1474  // meaning that when it appears in a command-line, it probably
  1475  // doesn't have some special meaning other than its own name.
  1476  // This is copied from SafeArg in cmd/go/internal/load/pkg.go.
  1477  func safeArg(name string) bool {
  1478  	if name == "" {
  1479  		return false
  1480  	}
  1481  	c := name[0]
  1482  	return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
  1483  }
  1484  
  1485  func mkname(sym *types.Sym) *Node {
  1486  	n := oldname(sym)
  1487  	if n.Name != nil && n.Name.Pack != nil {
  1488  		n.Name.Pack.Name.SetUsed(true)
  1489  	}
  1490  	return n
  1491  }
  1492  
  1493  func unparen(x *Node) *Node {
  1494  	for x.Op == OPAREN {
  1495  		x = x.Left
  1496  	}
  1497  	return x
  1498  }