...

Source file src/pkg/cmd/compile/internal/gc/noder.go

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

View as plain text