...

Source file src/pkg/cmd/compile/internal/syntax/parser.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 syntax
     6	
     7	import (
     8		"fmt"
     9		"io"
    10		"strconv"
    11		"strings"
    12	)
    13	
    14	const debug = false
    15	const trace = false
    16	
    17	type parser struct {
    18		file *PosBase
    19		errh ErrorHandler
    20		mode Mode
    21		scanner
    22	
    23		base   *PosBase // current position base
    24		first  error    // first error encountered
    25		errcnt int      // number of errors encountered
    26		pragma Pragma   // pragma flags
    27	
    28		fnest  int    // function nesting level (for error handling)
    29		xnest  int    // expression nesting level (for complit ambiguity resolution)
    30		indent []byte // tracing support
    31	}
    32	
    33	func (p *parser) init(file *PosBase, r io.Reader, errh ErrorHandler, pragh PragmaHandler, mode Mode) {
    34		p.file = file
    35		p.errh = errh
    36		p.mode = mode
    37		p.scanner.init(
    38			r,
    39			// Error and directive handler for scanner.
    40			// Because the (line, col) positions passed to the
    41			// handler is always at or after the current reading
    42			// position, it is safe to use the most recent position
    43			// base to compute the corresponding Pos value.
    44			func(line, col uint, msg string) {
    45				if msg[0] != '/' {
    46					p.errorAt(p.posAt(line, col), msg)
    47					return
    48				}
    49	
    50				// otherwise it must be a comment containing a line or go: directive
    51				text := commentText(msg)
    52				if strings.HasPrefix(text, "line ") {
    53					var pos Pos // position immediately following the comment
    54					if msg[1] == '/' {
    55						// line comment (newline is part of the comment)
    56						pos = MakePos(p.file, line+1, colbase)
    57					} else {
    58						// regular comment
    59						// (if the comment spans multiple lines it's not
    60						// a valid line directive and will be discarded
    61						// by updateBase)
    62						pos = MakePos(p.file, line, col+uint(len(msg)))
    63					}
    64					p.updateBase(pos, line, col+2+5, text[5:]) // +2 to skip over // or /*
    65					return
    66				}
    67	
    68				// go: directive (but be conservative and test)
    69				if pragh != nil && strings.HasPrefix(text, "go:") {
    70					p.pragma |= pragh(p.posAt(line, col+2), text) // +2 to skip over // or /*
    71				}
    72			},
    73			directives,
    74		)
    75	
    76		p.base = file
    77		p.first = nil
    78		p.errcnt = 0
    79		p.pragma = 0
    80	
    81		p.fnest = 0
    82		p.xnest = 0
    83		p.indent = nil
    84	}
    85	
    86	// updateBase sets the current position base to a new line base at pos.
    87	// The base's filename, line, and column values are extracted from text
    88	// which is positioned at (tline, tcol) (only needed for error messages).
    89	func (p *parser) updateBase(pos Pos, tline, tcol uint, text string) {
    90		i, n, ok := trailingDigits(text)
    91		if i == 0 {
    92			return // ignore (not a line directive)
    93		}
    94		// i > 0
    95	
    96		if !ok {
    97			// text has a suffix :xxx but xxx is not a number
    98			p.errorAt(p.posAt(tline, tcol+i), "invalid line number: "+text[i:])
    99			return
   100		}
   101	
   102		var line, col uint
   103		i2, n2, ok2 := trailingDigits(text[:i-1])
   104		if ok2 {
   105			//line filename:line:col
   106			i, i2 = i2, i
   107			line, col = n2, n
   108			if col == 0 || col > PosMax {
   109				p.errorAt(p.posAt(tline, tcol+i2), "invalid column number: "+text[i2:])
   110				return
   111			}
   112			text = text[:i2-1] // lop off ":col"
   113		} else {
   114			//line filename:line
   115			line = n
   116		}
   117	
   118		if line == 0 || line > PosMax {
   119			p.errorAt(p.posAt(tline, tcol+i), "invalid line number: "+text[i:])
   120			return
   121		}
   122	
   123		// If we have a column (//line filename:line:col form),
   124		// an empty filename means to use the previous filename.
   125		filename := text[:i-1] // lop off ":line"
   126		if filename == "" && ok2 {
   127			filename = p.base.Filename()
   128		}
   129	
   130		p.base = NewLineBase(pos, filename, line, col)
   131	}
   132	
   133	func commentText(s string) string {
   134		if s[:2] == "/*" {
   135			return s[2 : len(s)-2] // lop off /* and */
   136		}
   137	
   138		// line comment (does not include newline)
   139		// (on Windows, the line comment may end in \r\n)
   140		i := len(s)
   141		if s[i-1] == '\r' {
   142			i--
   143		}
   144		return s[2:i] // lop off //, and \r at end, if any
   145	}
   146	
   147	func trailingDigits(text string) (uint, uint, bool) {
   148		// Want to use LastIndexByte below but it's not defined in Go1.4 and bootstrap fails.
   149		i := strings.LastIndex(text, ":") // look from right (Windows filenames may contain ':')
   150		if i < 0 {
   151			return 0, 0, false // no ":"
   152		}
   153		// i >= 0
   154		n, err := strconv.ParseUint(text[i+1:], 10, 0)
   155		return uint(i + 1), uint(n), err == nil
   156	}
   157	
   158	func (p *parser) got(tok token) bool {
   159		if p.tok == tok {
   160			p.next()
   161			return true
   162		}
   163		return false
   164	}
   165	
   166	func (p *parser) want(tok token) {
   167		if !p.got(tok) {
   168			p.syntaxError("expecting " + tokstring(tok))
   169			p.advance()
   170		}
   171	}
   172	
   173	// gotAssign is like got(_Assign) but it also accepts ":="
   174	// (and reports an error) for better parser error recovery.
   175	func (p *parser) gotAssign() bool {
   176		switch p.tok {
   177		case _Define:
   178			p.syntaxError("expecting =")
   179			fallthrough
   180		case _Assign:
   181			p.next()
   182			return true
   183		}
   184		return false
   185	}
   186	
   187	// ----------------------------------------------------------------------------
   188	// Error handling
   189	
   190	// posAt returns the Pos value for (line, col) and the current position base.
   191	func (p *parser) posAt(line, col uint) Pos {
   192		return MakePos(p.base, line, col)
   193	}
   194	
   195	// error reports an error at the given position.
   196	func (p *parser) errorAt(pos Pos, msg string) {
   197		err := Error{pos, msg}
   198		if p.first == nil {
   199			p.first = err
   200		}
   201		p.errcnt++
   202		if p.errh == nil {
   203			panic(p.first)
   204		}
   205		p.errh(err)
   206	}
   207	
   208	// syntaxErrorAt reports a syntax error at the given position.
   209	func (p *parser) syntaxErrorAt(pos Pos, msg string) {
   210		if trace {
   211			p.print("syntax error: " + msg)
   212		}
   213	
   214		if p.tok == _EOF && p.first != nil {
   215			return // avoid meaningless follow-up errors
   216		}
   217	
   218		// add punctuation etc. as needed to msg
   219		switch {
   220		case msg == "":
   221			// nothing to do
   222		case strings.HasPrefix(msg, "in "), strings.HasPrefix(msg, "at "), strings.HasPrefix(msg, "after "):
   223			msg = " " + msg
   224		case strings.HasPrefix(msg, "expecting "):
   225			msg = ", " + msg
   226		default:
   227			// plain error - we don't care about current token
   228			p.errorAt(pos, "syntax error: "+msg)
   229			return
   230		}
   231	
   232		// determine token string
   233		var tok string
   234		switch p.tok {
   235		case _Name, _Semi:
   236			tok = p.lit
   237		case _Literal:
   238			tok = "literal " + p.lit
   239		case _Operator:
   240			tok = p.op.String()
   241		case _AssignOp:
   242			tok = p.op.String() + "="
   243		case _IncOp:
   244			tok = p.op.String()
   245			tok += tok
   246		default:
   247			tok = tokstring(p.tok)
   248		}
   249	
   250		p.errorAt(pos, "syntax error: unexpected "+tok+msg)
   251	}
   252	
   253	// tokstring returns the English word for selected punctuation tokens
   254	// for more readable error messages.
   255	func tokstring(tok token) string {
   256		switch tok {
   257		case _Comma:
   258			return "comma"
   259		case _Semi:
   260			return "semicolon or newline"
   261		}
   262		return tok.String()
   263	}
   264	
   265	// Convenience methods using the current token position.
   266	func (p *parser) pos() Pos               { return p.posAt(p.line, p.col) }
   267	func (p *parser) syntaxError(msg string) { p.syntaxErrorAt(p.pos(), msg) }
   268	
   269	// The stopset contains keywords that start a statement.
   270	// They are good synchronization points in case of syntax
   271	// errors and (usually) shouldn't be skipped over.
   272	const stopset uint64 = 1<<_Break |
   273		1<<_Const |
   274		1<<_Continue |
   275		1<<_Defer |
   276		1<<_Fallthrough |
   277		1<<_For |
   278		1<<_Go |
   279		1<<_Goto |
   280		1<<_If |
   281		1<<_Return |
   282		1<<_Select |
   283		1<<_Switch |
   284		1<<_Type |
   285		1<<_Var
   286	
   287	// Advance consumes tokens until it finds a token of the stopset or followlist.
   288	// The stopset is only considered if we are inside a function (p.fnest > 0).
   289	// The followlist is the list of valid tokens that can follow a production;
   290	// if it is empty, exactly one (non-EOF) token is consumed to ensure progress.
   291	func (p *parser) advance(followlist ...token) {
   292		if trace {
   293			p.print(fmt.Sprintf("advance %s", followlist))
   294		}
   295	
   296		// compute follow set
   297		// (not speed critical, advance is only called in error situations)
   298		var followset uint64 = 1 << _EOF // don't skip over EOF
   299		if len(followlist) > 0 {
   300			if p.fnest > 0 {
   301				followset |= stopset
   302			}
   303			for _, tok := range followlist {
   304				followset |= 1 << tok
   305			}
   306		}
   307	
   308		for !contains(followset, p.tok) {
   309			if trace {
   310				p.print("skip " + p.tok.String())
   311			}
   312			p.next()
   313			if len(followlist) == 0 {
   314				break
   315			}
   316		}
   317	
   318		if trace {
   319			p.print("next " + p.tok.String())
   320		}
   321	}
   322	
   323	// usage: defer p.trace(msg)()
   324	func (p *parser) trace(msg string) func() {
   325		p.print(msg + " (")
   326		const tab = ". "
   327		p.indent = append(p.indent, tab...)
   328		return func() {
   329			p.indent = p.indent[:len(p.indent)-len(tab)]
   330			if x := recover(); x != nil {
   331				panic(x) // skip print_trace
   332			}
   333			p.print(")")
   334		}
   335	}
   336	
   337	func (p *parser) print(msg string) {
   338		fmt.Printf("%5d: %s%s\n", p.line, p.indent, msg)
   339	}
   340	
   341	// ----------------------------------------------------------------------------
   342	// Package files
   343	//
   344	// Parse methods are annotated with matching Go productions as appropriate.
   345	// The annotations are intended as guidelines only since a single Go grammar
   346	// rule may be covered by multiple parse methods and vice versa.
   347	//
   348	// Excluding methods returning slices, parse methods named xOrNil may return
   349	// nil; all others are expected to return a valid non-nil node.
   350	
   351	// SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
   352	func (p *parser) fileOrNil() *File {
   353		if trace {
   354			defer p.trace("file")()
   355		}
   356	
   357		f := new(File)
   358		f.pos = p.pos()
   359	
   360		// PackageClause
   361		if !p.got(_Package) {
   362			p.syntaxError("package statement must be first")
   363			return nil
   364		}
   365		f.PkgName = p.name()
   366		p.want(_Semi)
   367	
   368		// don't bother continuing if package clause has errors
   369		if p.first != nil {
   370			return nil
   371		}
   372	
   373		// { ImportDecl ";" }
   374		for p.got(_Import) {
   375			f.DeclList = p.appendGroup(f.DeclList, p.importDecl)
   376			p.want(_Semi)
   377		}
   378	
   379		// { TopLevelDecl ";" }
   380		for p.tok != _EOF {
   381			switch p.tok {
   382			case _Const:
   383				p.next()
   384				f.DeclList = p.appendGroup(f.DeclList, p.constDecl)
   385	
   386			case _Type:
   387				p.next()
   388				f.DeclList = p.appendGroup(f.DeclList, p.typeDecl)
   389	
   390			case _Var:
   391				p.next()
   392				f.DeclList = p.appendGroup(f.DeclList, p.varDecl)
   393	
   394			case _Func:
   395				p.next()
   396				if d := p.funcDeclOrNil(); d != nil {
   397					f.DeclList = append(f.DeclList, d)
   398				}
   399	
   400			default:
   401				if p.tok == _Lbrace && len(f.DeclList) > 0 && isEmptyFuncDecl(f.DeclList[len(f.DeclList)-1]) {
   402					// opening { of function declaration on next line
   403					p.syntaxError("unexpected semicolon or newline before {")
   404				} else {
   405					p.syntaxError("non-declaration statement outside function body")
   406				}
   407				p.advance(_Const, _Type, _Var, _Func)
   408				continue
   409			}
   410	
   411			// Reset p.pragma BEFORE advancing to the next token (consuming ';')
   412			// since comments before may set pragmas for the next function decl.
   413			p.pragma = 0
   414	
   415			if p.tok != _EOF && !p.got(_Semi) {
   416				p.syntaxError("after top level declaration")
   417				p.advance(_Const, _Type, _Var, _Func)
   418			}
   419		}
   420		// p.tok == _EOF
   421	
   422		f.Lines = p.source.line
   423	
   424		return f
   425	}
   426	
   427	func isEmptyFuncDecl(dcl Decl) bool {
   428		f, ok := dcl.(*FuncDecl)
   429		return ok && f.Body == nil
   430	}
   431	
   432	// ----------------------------------------------------------------------------
   433	// Declarations
   434	
   435	// list parses a possibly empty, sep-separated list, optionally
   436	// followed by sep and enclosed by ( and ) or { and }. open is
   437	// one of _Lparen, or _Lbrace, sep is one of _Comma or _Semi,
   438	// and close is expected to be the (closing) opposite of open.
   439	// For each list element, f is called. After f returns true, no
   440	// more list elements are accepted. list returns the position
   441	// of the closing token.
   442	//
   443	// list = "(" { f sep } ")" |
   444	//        "{" { f sep } "}" . // sep is optional before ")" or "}"
   445	//
   446	func (p *parser) list(open, sep, close token, f func() bool) Pos {
   447		p.want(open)
   448	
   449		var done bool
   450		for p.tok != _EOF && p.tok != close && !done {
   451			done = f()
   452			// sep is optional before close
   453			if !p.got(sep) && p.tok != close {
   454				p.syntaxError(fmt.Sprintf("expecting %s or %s", tokstring(sep), tokstring(close)))
   455				p.advance(_Rparen, _Rbrack, _Rbrace)
   456				if p.tok != close {
   457					// position could be better but we had an error so we don't care
   458					return p.pos()
   459				}
   460			}
   461		}
   462	
   463		pos := p.pos()
   464		p.want(close)
   465		return pos
   466	}
   467	
   468	// appendGroup(f) = f | "(" { f ";" } ")" . // ";" is optional before ")"
   469	func (p *parser) appendGroup(list []Decl, f func(*Group) Decl) []Decl {
   470		if p.tok == _Lparen {
   471			g := new(Group)
   472			p.list(_Lparen, _Semi, _Rparen, func() bool {
   473				list = append(list, f(g))
   474				return false
   475			})
   476		} else {
   477			list = append(list, f(nil))
   478		}
   479	
   480		if debug {
   481			for _, d := range list {
   482				if d == nil {
   483					panic("nil list entry")
   484				}
   485			}
   486		}
   487	
   488		return list
   489	}
   490	
   491	// ImportSpec = [ "." | PackageName ] ImportPath .
   492	// ImportPath = string_lit .
   493	func (p *parser) importDecl(group *Group) Decl {
   494		if trace {
   495			defer p.trace("importDecl")()
   496		}
   497	
   498		d := new(ImportDecl)
   499		d.pos = p.pos()
   500	
   501		switch p.tok {
   502		case _Name:
   503			d.LocalPkgName = p.name()
   504		case _Dot:
   505			d.LocalPkgName = p.newName(".")
   506			p.next()
   507		}
   508		d.Path = p.oliteral()
   509		if d.Path == nil {
   510			p.syntaxError("missing import path")
   511			p.advance(_Semi, _Rparen)
   512			return nil
   513		}
   514		d.Group = group
   515	
   516		return d
   517	}
   518	
   519	// ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
   520	func (p *parser) constDecl(group *Group) Decl {
   521		if trace {
   522			defer p.trace("constDecl")()
   523		}
   524	
   525		d := new(ConstDecl)
   526		d.pos = p.pos()
   527	
   528		d.NameList = p.nameList(p.name())
   529		if p.tok != _EOF && p.tok != _Semi && p.tok != _Rparen {
   530			d.Type = p.typeOrNil()
   531			if p.gotAssign() {
   532				d.Values = p.exprList()
   533			}
   534		}
   535		d.Group = group
   536	
   537		return d
   538	}
   539	
   540	// TypeSpec = identifier [ "=" ] Type .
   541	func (p *parser) typeDecl(group *Group) Decl {
   542		if trace {
   543			defer p.trace("typeDecl")()
   544		}
   545	
   546		d := new(TypeDecl)
   547		d.pos = p.pos()
   548	
   549		d.Name = p.name()
   550		d.Alias = p.gotAssign()
   551		d.Type = p.typeOrNil()
   552		if d.Type == nil {
   553			d.Type = p.bad()
   554			p.syntaxError("in type declaration")
   555			p.advance(_Semi, _Rparen)
   556		}
   557		d.Group = group
   558		d.Pragma = p.pragma
   559	
   560		return d
   561	}
   562	
   563	// VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
   564	func (p *parser) varDecl(group *Group) Decl {
   565		if trace {
   566			defer p.trace("varDecl")()
   567		}
   568	
   569		d := new(VarDecl)
   570		d.pos = p.pos()
   571	
   572		d.NameList = p.nameList(p.name())
   573		if p.gotAssign() {
   574			d.Values = p.exprList()
   575		} else {
   576			d.Type = p.type_()
   577			if p.gotAssign() {
   578				d.Values = p.exprList()
   579			}
   580		}
   581		d.Group = group
   582	
   583		return d
   584	}
   585	
   586	// FunctionDecl = "func" FunctionName ( Function | Signature ) .
   587	// FunctionName = identifier .
   588	// Function     = Signature FunctionBody .
   589	// MethodDecl   = "func" Receiver MethodName ( Function | Signature ) .
   590	// Receiver     = Parameters .
   591	func (p *parser) funcDeclOrNil() *FuncDecl {
   592		if trace {
   593			defer p.trace("funcDecl")()
   594		}
   595	
   596		f := new(FuncDecl)
   597		f.pos = p.pos()
   598	
   599		if p.tok == _Lparen {
   600			rcvr := p.paramList()
   601			switch len(rcvr) {
   602			case 0:
   603				p.error("method has no receiver")
   604			default:
   605				p.error("method has multiple receivers")
   606				fallthrough
   607			case 1:
   608				f.Recv = rcvr[0]
   609			}
   610		}
   611	
   612		if p.tok != _Name {
   613			p.syntaxError("expecting name or (")
   614			p.advance(_Lbrace, _Semi)
   615			return nil
   616		}
   617	
   618		f.Name = p.name()
   619		f.Type = p.funcType()
   620		if p.tok == _Lbrace {
   621			f.Body = p.funcBody()
   622		}
   623		f.Pragma = p.pragma
   624	
   625		return f
   626	}
   627	
   628	func (p *parser) funcBody() *BlockStmt {
   629		p.fnest++
   630		errcnt := p.errcnt
   631		body := p.blockStmt("")
   632		p.fnest--
   633	
   634		// Don't check branches if there were syntax errors in the function
   635		// as it may lead to spurious errors (e.g., see test/switch2.go) or
   636		// possibly crashes due to incomplete syntax trees.
   637		if p.mode&CheckBranches != 0 && errcnt == p.errcnt {
   638			checkBranches(body, p.errh)
   639		}
   640	
   641		return body
   642	}
   643	
   644	// ----------------------------------------------------------------------------
   645	// Expressions
   646	
   647	func (p *parser) expr() Expr {
   648		if trace {
   649			defer p.trace("expr")()
   650		}
   651	
   652		return p.binaryExpr(0)
   653	}
   654	
   655	// Expression = UnaryExpr | Expression binary_op Expression .
   656	func (p *parser) binaryExpr(prec int) Expr {
   657		// don't trace binaryExpr - only leads to overly nested trace output
   658	
   659		x := p.unaryExpr()
   660		for (p.tok == _Operator || p.tok == _Star) && p.prec > prec {
   661			t := new(Operation)
   662			t.pos = p.pos()
   663			t.Op = p.op
   664			t.X = x
   665			tprec := p.prec
   666			p.next()
   667			t.Y = p.binaryExpr(tprec)
   668			x = t
   669		}
   670		return x
   671	}
   672	
   673	// UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
   674	func (p *parser) unaryExpr() Expr {
   675		if trace {
   676			defer p.trace("unaryExpr")()
   677		}
   678	
   679		switch p.tok {
   680		case _Operator, _Star:
   681			switch p.op {
   682			case Mul, Add, Sub, Not, Xor:
   683				x := new(Operation)
   684				x.pos = p.pos()
   685				x.Op = p.op
   686				p.next()
   687				x.X = p.unaryExpr()
   688				return x
   689	
   690			case And:
   691				x := new(Operation)
   692				x.pos = p.pos()
   693				x.Op = And
   694				p.next()
   695				// unaryExpr may have returned a parenthesized composite literal
   696				// (see comment in operand) - remove parentheses if any
   697				x.X = unparen(p.unaryExpr())
   698				return x
   699			}
   700	
   701		case _Arrow:
   702			// receive op (<-x) or receive-only channel (<-chan E)
   703			pos := p.pos()
   704			p.next()
   705	
   706			// If the next token is _Chan we still don't know if it is
   707			// a channel (<-chan int) or a receive op (<-chan int(ch)).
   708			// We only know once we have found the end of the unaryExpr.
   709	
   710			x := p.unaryExpr()
   711	
   712			// There are two cases:
   713			//
   714			//   <-chan...  => <-x is a channel type
   715			//   <-x        => <-x is a receive operation
   716			//
   717			// In the first case, <- must be re-associated with
   718			// the channel type parsed already:
   719			//
   720			//   <-(chan E)   =>  (<-chan E)
   721			//   <-(chan<-E)  =>  (<-chan (<-E))
   722	
   723			if _, ok := x.(*ChanType); ok {
   724				// x is a channel type => re-associate <-
   725				dir := SendOnly
   726				t := x
   727				for dir == SendOnly {
   728					c, ok := t.(*ChanType)
   729					if !ok {
   730						break
   731					}
   732					dir = c.Dir
   733					if dir == RecvOnly {
   734						// t is type <-chan E but <-<-chan E is not permitted
   735						// (report same error as for "type _ <-<-chan E")
   736						p.syntaxError("unexpected <-, expecting chan")
   737						// already progressed, no need to advance
   738					}
   739					c.Dir = RecvOnly
   740					t = c.Elem
   741				}
   742				if dir == SendOnly {
   743					// channel dir is <- but channel element E is not a channel
   744					// (report same error as for "type _ <-chan<-E")
   745					p.syntaxError(fmt.Sprintf("unexpected %s, expecting chan", String(t)))
   746					// already progressed, no need to advance
   747				}
   748				return x
   749			}
   750	
   751			// x is not a channel type => we have a receive op
   752			o := new(Operation)
   753			o.pos = pos
   754			o.Op = Recv
   755			o.X = x
   756			return o
   757		}
   758	
   759		// TODO(mdempsky): We need parens here so we can report an
   760		// error for "(x) := true". It should be possible to detect
   761		// and reject that more efficiently though.
   762		return p.pexpr(true)
   763	}
   764	
   765	// callStmt parses call-like statements that can be preceded by 'defer' and 'go'.
   766	func (p *parser) callStmt() *CallStmt {
   767		if trace {
   768			defer p.trace("callStmt")()
   769		}
   770	
   771		s := new(CallStmt)
   772		s.pos = p.pos()
   773		s.Tok = p.tok // _Defer or _Go
   774		p.next()
   775	
   776		x := p.pexpr(p.tok == _Lparen) // keep_parens so we can report error below
   777		if t := unparen(x); t != x {
   778			p.errorAt(x.Pos(), fmt.Sprintf("expression in %s must not be parenthesized", s.Tok))
   779			// already progressed, no need to advance
   780			x = t
   781		}
   782	
   783		cx, ok := x.(*CallExpr)
   784		if !ok {
   785			p.errorAt(x.Pos(), fmt.Sprintf("expression in %s must be function call", s.Tok))
   786			// already progressed, no need to advance
   787			cx = new(CallExpr)
   788			cx.pos = x.Pos()
   789			cx.Fun = x // assume common error of missing parentheses (function invocation)
   790		}
   791	
   792		s.Call = cx
   793		return s
   794	}
   795	
   796	// Operand     = Literal | OperandName | MethodExpr | "(" Expression ")" .
   797	// Literal     = BasicLit | CompositeLit | FunctionLit .
   798	// BasicLit    = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
   799	// OperandName = identifier | QualifiedIdent.
   800	func (p *parser) operand(keep_parens bool) Expr {
   801		if trace {
   802			defer p.trace("operand " + p.tok.String())()
   803		}
   804	
   805		switch p.tok {
   806		case _Name:
   807			return p.name()
   808	
   809		case _Literal:
   810			return p.oliteral()
   811	
   812		case _Lparen:
   813			pos := p.pos()
   814			p.next()
   815			p.xnest++
   816			x := p.expr()
   817			p.xnest--
   818			p.want(_Rparen)
   819	
   820			// Optimization: Record presence of ()'s only where needed
   821			// for error reporting. Don't bother in other cases; it is
   822			// just a waste of memory and time.
   823	
   824			// Parentheses are not permitted on lhs of := .
   825			// switch x.Op {
   826			// case ONAME, ONONAME, OPACK, OTYPE, OLITERAL, OTYPESW:
   827			// 	keep_parens = true
   828			// }
   829	
   830			// Parentheses are not permitted around T in a composite
   831			// literal T{}. If the next token is a {, assume x is a
   832			// composite literal type T (it may not be, { could be
   833			// the opening brace of a block, but we don't know yet).
   834			if p.tok == _Lbrace {
   835				keep_parens = true
   836			}
   837	
   838			// Parentheses are also not permitted around the expression
   839			// in a go/defer statement. In that case, operand is called
   840			// with keep_parens set.
   841			if keep_parens {
   842				px := new(ParenExpr)
   843				px.pos = pos
   844				px.X = x
   845				x = px
   846			}
   847			return x
   848	
   849		case _Func:
   850			pos := p.pos()
   851			p.next()
   852			t := p.funcType()
   853			if p.tok == _Lbrace {
   854				p.xnest++
   855	
   856				f := new(FuncLit)
   857				f.pos = pos
   858				f.Type = t
   859				f.Body = p.funcBody()
   860	
   861				p.xnest--
   862				return f
   863			}
   864			return t
   865	
   866		case _Lbrack, _Chan, _Map, _Struct, _Interface:
   867			return p.type_() // othertype
   868	
   869		default:
   870			x := p.bad()
   871			p.syntaxError("expecting expression")
   872			p.advance()
   873			return x
   874		}
   875	
   876		// Syntactically, composite literals are operands. Because a complit
   877		// type may be a qualified identifier which is handled by pexpr
   878		// (together with selector expressions), complits are parsed there
   879		// as well (operand is only called from pexpr).
   880	}
   881	
   882	// PrimaryExpr =
   883	// 	Operand |
   884	// 	Conversion |
   885	// 	PrimaryExpr Selector |
   886	// 	PrimaryExpr Index |
   887	// 	PrimaryExpr Slice |
   888	// 	PrimaryExpr TypeAssertion |
   889	// 	PrimaryExpr Arguments .
   890	//
   891	// Selector       = "." identifier .
   892	// Index          = "[" Expression "]" .
   893	// Slice          = "[" ( [ Expression ] ":" [ Expression ] ) |
   894	//                      ( [ Expression ] ":" Expression ":" Expression )
   895	//                  "]" .
   896	// TypeAssertion  = "." "(" Type ")" .
   897	// Arguments      = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
   898	func (p *parser) pexpr(keep_parens bool) Expr {
   899		if trace {
   900			defer p.trace("pexpr")()
   901		}
   902	
   903		x := p.operand(keep_parens)
   904	
   905	loop:
   906		for {
   907			pos := p.pos()
   908			switch p.tok {
   909			case _Dot:
   910				p.next()
   911				switch p.tok {
   912				case _Name:
   913					// pexpr '.' sym
   914					t := new(SelectorExpr)
   915					t.pos = pos
   916					t.X = x
   917					t.Sel = p.name()
   918					x = t
   919	
   920				case _Lparen:
   921					p.next()
   922					if p.got(_Type) {
   923						t := new(TypeSwitchGuard)
   924						// t.Lhs is filled in by parser.simpleStmt
   925						t.pos = pos
   926						t.X = x
   927						x = t
   928					} else {
   929						t := new(AssertExpr)
   930						t.pos = pos
   931						t.X = x
   932						t.Type = p.type_()
   933						x = t
   934					}
   935					p.want(_Rparen)
   936	
   937				default:
   938					p.syntaxError("expecting name or (")
   939					p.advance(_Semi, _Rparen)
   940				}
   941	
   942			case _Lbrack:
   943				p.next()
   944				p.xnest++
   945	
   946				var i Expr
   947				if p.tok != _Colon {
   948					i = p.expr()
   949					if p.got(_Rbrack) {
   950						// x[i]
   951						t := new(IndexExpr)
   952						t.pos = pos
   953						t.X = x
   954						t.Index = i
   955						x = t
   956						p.xnest--
   957						break
   958					}
   959				}
   960	
   961				// x[i:...
   962				t := new(SliceExpr)
   963				t.pos = pos
   964				t.X = x
   965				t.Index[0] = i
   966				p.want(_Colon)
   967				if p.tok != _Colon && p.tok != _Rbrack {
   968					// x[i:j...
   969					t.Index[1] = p.expr()
   970				}
   971				if p.got(_Colon) {
   972					t.Full = true
   973					// x[i:j:...]
   974					if t.Index[1] == nil {
   975						p.error("middle index required in 3-index slice")
   976					}
   977					if p.tok != _Rbrack {
   978						// x[i:j:k...
   979						t.Index[2] = p.expr()
   980					} else {
   981						p.error("final index required in 3-index slice")
   982					}
   983				}
   984				p.want(_Rbrack)
   985	
   986				x = t
   987				p.xnest--
   988	
   989			case _Lparen:
   990				t := new(CallExpr)
   991				t.pos = pos
   992				t.Fun = x
   993				t.ArgList, t.HasDots = p.argList()
   994				x = t
   995	
   996			case _Lbrace:
   997				// operand may have returned a parenthesized complit
   998				// type; accept it but complain if we have a complit
   999				t := unparen(x)
  1000				// determine if '{' belongs to a composite literal or a block statement
  1001				complit_ok := false
  1002				switch t.(type) {
  1003				case *Name, *SelectorExpr:
  1004					if p.xnest >= 0 {
  1005						// x is considered a composite literal type
  1006						complit_ok = true
  1007					}
  1008				case *ArrayType, *SliceType, *StructType, *MapType:
  1009					// x is a comptype
  1010					complit_ok = true
  1011				}
  1012				if !complit_ok {
  1013					break loop
  1014				}
  1015				if t != x {
  1016					p.syntaxError("cannot parenthesize type in composite literal")
  1017					// already progressed, no need to advance
  1018				}
  1019				n := p.complitexpr()
  1020				n.Type = x
  1021				x = n
  1022	
  1023			default:
  1024				break loop
  1025			}
  1026		}
  1027	
  1028		return x
  1029	}
  1030	
  1031	// Element = Expression | LiteralValue .
  1032	func (p *parser) bare_complitexpr() Expr {
  1033		if trace {
  1034			defer p.trace("bare_complitexpr")()
  1035		}
  1036	
  1037		if p.tok == _Lbrace {
  1038			// '{' start_complit braced_keyval_list '}'
  1039			return p.complitexpr()
  1040		}
  1041	
  1042		return p.expr()
  1043	}
  1044	
  1045	// LiteralValue = "{" [ ElementList [ "," ] ] "}" .
  1046	func (p *parser) complitexpr() *CompositeLit {
  1047		if trace {
  1048			defer p.trace("complitexpr")()
  1049		}
  1050	
  1051		x := new(CompositeLit)
  1052		x.pos = p.pos()
  1053	
  1054		p.xnest++
  1055		x.Rbrace = p.list(_Lbrace, _Comma, _Rbrace, func() bool {
  1056			// value
  1057			e := p.bare_complitexpr()
  1058			if p.tok == _Colon {
  1059				// key ':' value
  1060				l := new(KeyValueExpr)
  1061				l.pos = p.pos()
  1062				p.next()
  1063				l.Key = e
  1064				l.Value = p.bare_complitexpr()
  1065				e = l
  1066				x.NKeys++
  1067			}
  1068			x.ElemList = append(x.ElemList, e)
  1069			return false
  1070		})
  1071		p.xnest--
  1072	
  1073		return x
  1074	}
  1075	
  1076	// ----------------------------------------------------------------------------
  1077	// Types
  1078	
  1079	func (p *parser) type_() Expr {
  1080		if trace {
  1081			defer p.trace("type_")()
  1082		}
  1083	
  1084		typ := p.typeOrNil()
  1085		if typ == nil {
  1086			typ = p.bad()
  1087			p.syntaxError("expecting type")
  1088			p.advance(_Comma, _Colon, _Semi, _Rparen, _Rbrack, _Rbrace)
  1089		}
  1090	
  1091		return typ
  1092	}
  1093	
  1094	func newIndirect(pos Pos, typ Expr) Expr {
  1095		o := new(Operation)
  1096		o.pos = pos
  1097		o.Op = Mul
  1098		o.X = typ
  1099		return o
  1100	}
  1101	
  1102	// typeOrNil is like type_ but it returns nil if there was no type
  1103	// instead of reporting an error.
  1104	//
  1105	// Type     = TypeName | TypeLit | "(" Type ")" .
  1106	// TypeName = identifier | QualifiedIdent .
  1107	// TypeLit  = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
  1108	// 	      SliceType | MapType | Channel_Type .
  1109	func (p *parser) typeOrNil() Expr {
  1110		if trace {
  1111			defer p.trace("typeOrNil")()
  1112		}
  1113	
  1114		pos := p.pos()
  1115		switch p.tok {
  1116		case _Star:
  1117			// ptrtype
  1118			p.next()
  1119			return newIndirect(pos, p.type_())
  1120	
  1121		case _Arrow:
  1122			// recvchantype
  1123			p.next()
  1124			p.want(_Chan)
  1125			t := new(ChanType)
  1126			t.pos = pos
  1127			t.Dir = RecvOnly
  1128			t.Elem = p.chanElem()
  1129			return t
  1130	
  1131		case _Func:
  1132			// fntype
  1133			p.next()
  1134			return p.funcType()
  1135	
  1136		case _Lbrack:
  1137			// '[' oexpr ']' ntype
  1138			// '[' _DotDotDot ']' ntype
  1139			p.next()
  1140			p.xnest++
  1141			if p.got(_Rbrack) {
  1142				// []T
  1143				p.xnest--
  1144				t := new(SliceType)
  1145				t.pos = pos
  1146				t.Elem = p.type_()
  1147				return t
  1148			}
  1149	
  1150			// [n]T
  1151			t := new(ArrayType)
  1152			t.pos = pos
  1153			if !p.got(_DotDotDot) {
  1154				t.Len = p.expr()
  1155			}
  1156			p.want(_Rbrack)
  1157			p.xnest--
  1158			t.Elem = p.type_()
  1159			return t
  1160	
  1161		case _Chan:
  1162			// _Chan non_recvchantype
  1163			// _Chan _Comm ntype
  1164			p.next()
  1165			t := new(ChanType)
  1166			t.pos = pos
  1167			if p.got(_Arrow) {
  1168				t.Dir = SendOnly
  1169			}
  1170			t.Elem = p.chanElem()
  1171			return t
  1172	
  1173		case _Map:
  1174			// _Map '[' ntype ']' ntype
  1175			p.next()
  1176			p.want(_Lbrack)
  1177			t := new(MapType)
  1178			t.pos = pos
  1179			t.Key = p.type_()
  1180			p.want(_Rbrack)
  1181			t.Value = p.type_()
  1182			return t
  1183	
  1184		case _Struct:
  1185			return p.structType()
  1186	
  1187		case _Interface:
  1188			return p.interfaceType()
  1189	
  1190		case _Name:
  1191			return p.dotname(p.name())
  1192	
  1193		case _Lparen:
  1194			p.next()
  1195			t := p.type_()
  1196			p.want(_Rparen)
  1197			return t
  1198		}
  1199	
  1200		return nil
  1201	}
  1202	
  1203	func (p *parser) funcType() *FuncType {
  1204		if trace {
  1205			defer p.trace("funcType")()
  1206		}
  1207	
  1208		typ := new(FuncType)
  1209		typ.pos = p.pos()
  1210		typ.ParamList = p.paramList()
  1211		typ.ResultList = p.funcResult()
  1212	
  1213		return typ
  1214	}
  1215	
  1216	func (p *parser) chanElem() Expr {
  1217		if trace {
  1218			defer p.trace("chanElem")()
  1219		}
  1220	
  1221		typ := p.typeOrNil()
  1222		if typ == nil {
  1223			typ = p.bad()
  1224			p.syntaxError("missing channel element type")
  1225			// assume element type is simply absent - don't advance
  1226		}
  1227	
  1228		return typ
  1229	}
  1230	
  1231	func (p *parser) dotname(name *Name) Expr {
  1232		if trace {
  1233			defer p.trace("dotname")()
  1234		}
  1235	
  1236		if p.tok == _Dot {
  1237			s := new(SelectorExpr)
  1238			s.pos = p.pos()
  1239			p.next()
  1240			s.X = name
  1241			s.Sel = p.name()
  1242			return s
  1243		}
  1244		return name
  1245	}
  1246	
  1247	// StructType = "struct" "{" { FieldDecl ";" } "}" .
  1248	func (p *parser) structType() *StructType {
  1249		if trace {
  1250			defer p.trace("structType")()
  1251		}
  1252	
  1253		typ := new(StructType)
  1254		typ.pos = p.pos()
  1255	
  1256		p.want(_Struct)
  1257		p.list(_Lbrace, _Semi, _Rbrace, func() bool {
  1258			p.fieldDecl(typ)
  1259			return false
  1260		})
  1261	
  1262		return typ
  1263	}
  1264	
  1265	// InterfaceType = "interface" "{" { MethodSpec ";" } "}" .
  1266	func (p *parser) interfaceType() *InterfaceType {
  1267		if trace {
  1268			defer p.trace("interfaceType")()
  1269		}
  1270	
  1271		typ := new(InterfaceType)
  1272		typ.pos = p.pos()
  1273	
  1274		p.want(_Interface)
  1275		p.list(_Lbrace, _Semi, _Rbrace, func() bool {
  1276			if m := p.methodDecl(); m != nil {
  1277				typ.MethodList = append(typ.MethodList, m)
  1278			}
  1279			return false
  1280		})
  1281	
  1282		return typ
  1283	}
  1284	
  1285	// Result = Parameters | Type .
  1286	func (p *parser) funcResult() []*Field {
  1287		if trace {
  1288			defer p.trace("funcResult")()
  1289		}
  1290	
  1291		if p.tok == _Lparen {
  1292			return p.paramList()
  1293		}
  1294	
  1295		pos := p.pos()
  1296		if typ := p.typeOrNil(); typ != nil {
  1297			f := new(Field)
  1298			f.pos = pos
  1299			f.Type = typ
  1300			return []*Field{f}
  1301		}
  1302	
  1303		return nil
  1304	}
  1305	
  1306	func (p *parser) addField(styp *StructType, pos Pos, name *Name, typ Expr, tag *BasicLit) {
  1307		if tag != nil {
  1308			for i := len(styp.FieldList) - len(styp.TagList); i > 0; i-- {
  1309				styp.TagList = append(styp.TagList, nil)
  1310			}
  1311			styp.TagList = append(styp.TagList, tag)
  1312		}
  1313	
  1314		f := new(Field)
  1315		f.pos = pos
  1316		f.Name = name
  1317		f.Type = typ
  1318		styp.FieldList = append(styp.FieldList, f)
  1319	
  1320		if debug && tag != nil && len(styp.FieldList) != len(styp.TagList) {
  1321			panic("inconsistent struct field list")
  1322		}
  1323	}
  1324	
  1325	// FieldDecl      = (IdentifierList Type | AnonymousField) [ Tag ] .
  1326	// AnonymousField = [ "*" ] TypeName .
  1327	// Tag            = string_lit .
  1328	func (p *parser) fieldDecl(styp *StructType) {
  1329		if trace {
  1330			defer p.trace("fieldDecl")()
  1331		}
  1332	
  1333		pos := p.pos()
  1334		switch p.tok {
  1335		case _Name:
  1336			name := p.name()
  1337			if p.tok == _Dot || p.tok == _Literal || p.tok == _Semi || p.tok == _Rbrace {
  1338				// embed oliteral
  1339				typ := p.qualifiedName(name)
  1340				tag := p.oliteral()
  1341				p.addField(styp, pos, nil, typ, tag)
  1342				return
  1343			}
  1344	
  1345			// new_name_list ntype oliteral
  1346			names := p.nameList(name)
  1347			typ := p.type_()
  1348			tag := p.oliteral()
  1349	
  1350			for _, name := range names {
  1351				p.addField(styp, name.Pos(), name, typ, tag)
  1352			}
  1353	
  1354		case _Lparen:
  1355			p.next()
  1356			if p.tok == _Star {
  1357				// '(' '*' embed ')' oliteral
  1358				pos := p.pos()
  1359				p.next()
  1360				typ := newIndirect(pos, p.qualifiedName(nil))
  1361				p.want(_Rparen)
  1362				tag := p.oliteral()
  1363				p.addField(styp, pos, nil, typ, tag)
  1364				p.syntaxError("cannot parenthesize embedded type")
  1365	
  1366			} else {
  1367				// '(' embed ')' oliteral
  1368				typ := p.qualifiedName(nil)
  1369				p.want(_Rparen)
  1370				tag := p.oliteral()
  1371				p.addField(styp, pos, nil, typ, tag)
  1372				p.syntaxError("cannot parenthesize embedded type")
  1373			}
  1374	
  1375		case _Star:
  1376			p.next()
  1377			if p.got(_Lparen) {
  1378				// '*' '(' embed ')' oliteral
  1379				typ := newIndirect(pos, p.qualifiedName(nil))
  1380				p.want(_Rparen)
  1381				tag := p.oliteral()
  1382				p.addField(styp, pos, nil, typ, tag)
  1383				p.syntaxError("cannot parenthesize embedded type")
  1384	
  1385			} else {
  1386				// '*' embed oliteral
  1387				typ := newIndirect(pos, p.qualifiedName(nil))
  1388				tag := p.oliteral()
  1389				p.addField(styp, pos, nil, typ, tag)
  1390			}
  1391	
  1392		default:
  1393			p.syntaxError("expecting field name or embedded type")
  1394			p.advance(_Semi, _Rbrace)
  1395		}
  1396	}
  1397	
  1398	func (p *parser) oliteral() *BasicLit {
  1399		if p.tok == _Literal {
  1400			b := new(BasicLit)
  1401			b.pos = p.pos()
  1402			b.Value = p.lit
  1403			b.Kind = p.kind
  1404			p.next()
  1405			return b
  1406		}
  1407		return nil
  1408	}
  1409	
  1410	// MethodSpec        = MethodName Signature | InterfaceTypeName .
  1411	// MethodName        = identifier .
  1412	// InterfaceTypeName = TypeName .
  1413	func (p *parser) methodDecl() *Field {
  1414		if trace {
  1415			defer p.trace("methodDecl")()
  1416		}
  1417	
  1418		switch p.tok {
  1419		case _Name:
  1420			name := p.name()
  1421	
  1422			// accept potential name list but complain
  1423			hasNameList := false
  1424			for p.got(_Comma) {
  1425				p.name()
  1426				hasNameList = true
  1427			}
  1428			if hasNameList {
  1429				p.syntaxError("name list not allowed in interface type")
  1430				// already progressed, no need to advance
  1431			}
  1432	
  1433			f := new(Field)
  1434			f.pos = name.Pos()
  1435			if p.tok != _Lparen {
  1436				// packname
  1437				f.Type = p.qualifiedName(name)
  1438				return f
  1439			}
  1440	
  1441			f.Name = name
  1442			f.Type = p.funcType()
  1443			return f
  1444	
  1445		case _Lparen:
  1446			p.syntaxError("cannot parenthesize embedded type")
  1447			f := new(Field)
  1448			f.pos = p.pos()
  1449			p.next()
  1450			f.Type = p.qualifiedName(nil)
  1451			p.want(_Rparen)
  1452			return f
  1453	
  1454		default:
  1455			p.syntaxError("expecting method or interface name")
  1456			p.advance(_Semi, _Rbrace)
  1457			return nil
  1458		}
  1459	}
  1460	
  1461	// ParameterDecl = [ IdentifierList ] [ "..." ] Type .
  1462	func (p *parser) paramDeclOrNil() *Field {
  1463		if trace {
  1464			defer p.trace("paramDecl")()
  1465		}
  1466	
  1467		f := new(Field)
  1468		f.pos = p.pos()
  1469	
  1470		switch p.tok {
  1471		case _Name:
  1472			f.Name = p.name()
  1473			switch p.tok {
  1474			case _Name, _Star, _Arrow, _Func, _Lbrack, _Chan, _Map, _Struct, _Interface, _Lparen:
  1475				// sym name_or_type
  1476				f.Type = p.type_()
  1477	
  1478			case _DotDotDot:
  1479				// sym dotdotdot
  1480				f.Type = p.dotsType()
  1481	
  1482			case _Dot:
  1483				// name_or_type
  1484				// from dotname
  1485				f.Type = p.dotname(f.Name)
  1486				f.Name = nil
  1487			}
  1488	
  1489		case _Arrow, _Star, _Func, _Lbrack, _Chan, _Map, _Struct, _Interface, _Lparen:
  1490			// name_or_type
  1491			f.Type = p.type_()
  1492	
  1493		case _DotDotDot:
  1494			// dotdotdot
  1495			f.Type = p.dotsType()
  1496	
  1497		default:
  1498			p.syntaxError("expecting )")
  1499			p.advance(_Comma, _Rparen)
  1500			return nil
  1501		}
  1502	
  1503		return f
  1504	}
  1505	
  1506	// ...Type
  1507	func (p *parser) dotsType() *DotsType {
  1508		if trace {
  1509			defer p.trace("dotsType")()
  1510		}
  1511	
  1512		t := new(DotsType)
  1513		t.pos = p.pos()
  1514	
  1515		p.want(_DotDotDot)
  1516		t.Elem = p.typeOrNil()
  1517		if t.Elem == nil {
  1518			t.Elem = p.bad()
  1519			p.syntaxError("final argument in variadic function missing type")
  1520		}
  1521	
  1522		return t
  1523	}
  1524	
  1525	// Parameters    = "(" [ ParameterList [ "," ] ] ")" .
  1526	// ParameterList = ParameterDecl { "," ParameterDecl } .
  1527	func (p *parser) paramList() (list []*Field) {
  1528		if trace {
  1529			defer p.trace("paramList")()
  1530		}
  1531	
  1532		pos := p.pos()
  1533	
  1534		var named int // number of parameters that have an explicit name and type
  1535		p.list(_Lparen, _Comma, _Rparen, func() bool {
  1536			if par := p.paramDeclOrNil(); par != nil {
  1537				if debug && par.Name == nil && par.Type == nil {
  1538					panic("parameter without name or type")
  1539				}
  1540				if par.Name != nil && par.Type != nil {
  1541					named++
  1542				}
  1543				list = append(list, par)
  1544			}
  1545			return false
  1546		})
  1547	
  1548		// distribute parameter types
  1549		if named == 0 {
  1550			// all unnamed => found names are named types
  1551			for _, par := range list {
  1552				if typ := par.Name; typ != nil {
  1553					par.Type = typ
  1554					par.Name = nil
  1555				}
  1556			}
  1557		} else if named != len(list) {
  1558			// some named => all must be named
  1559			ok := true
  1560			var typ Expr
  1561			for i := len(list) - 1; i >= 0; i-- {
  1562				if par := list[i]; par.Type != nil {
  1563					typ = par.Type
  1564					if par.Name == nil {
  1565						ok = false
  1566						n := p.newName("_")
  1567						n.pos = typ.Pos() // correct position
  1568						par.Name = n
  1569					}
  1570				} else if typ != nil {
  1571					par.Type = typ
  1572				} else {
  1573					// par.Type == nil && typ == nil => we only have a par.Name
  1574					ok = false
  1575					t := p.bad()
  1576					t.pos = par.Name.Pos() // correct position
  1577					par.Type = t
  1578				}
  1579			}
  1580			if !ok {
  1581				p.syntaxErrorAt(pos, "mixed named and unnamed function parameters")
  1582			}
  1583		}
  1584	
  1585		return
  1586	}
  1587	
  1588	func (p *parser) bad() *BadExpr {
  1589		b := new(BadExpr)
  1590		b.pos = p.pos()
  1591		return b
  1592	}
  1593	
  1594	// ----------------------------------------------------------------------------
  1595	// Statements
  1596	
  1597	// We represent x++, x-- as assignments x += ImplicitOne, x -= ImplicitOne.
  1598	// ImplicitOne should not be used elsewhere.
  1599	var ImplicitOne = &BasicLit{Value: "1"}
  1600	
  1601	// SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
  1602	func (p *parser) simpleStmt(lhs Expr, keyword token) SimpleStmt {
  1603		if trace {
  1604			defer p.trace("simpleStmt")()
  1605		}
  1606	
  1607		if keyword == _For && p.tok == _Range {
  1608			// _Range expr
  1609			if debug && lhs != nil {
  1610				panic("invalid call of simpleStmt")
  1611			}
  1612			return p.newRangeClause(nil, false)
  1613		}
  1614	
  1615		if lhs == nil {
  1616			lhs = p.exprList()
  1617		}
  1618	
  1619		if _, ok := lhs.(*ListExpr); !ok && p.tok != _Assign && p.tok != _Define {
  1620			// expr
  1621			pos := p.pos()
  1622			switch p.tok {
  1623			case _AssignOp:
  1624				// lhs op= rhs
  1625				op := p.op
  1626				p.next()
  1627				return p.newAssignStmt(pos, op, lhs, p.expr())
  1628	
  1629			case _IncOp:
  1630				// lhs++ or lhs--
  1631				op := p.op
  1632				p.next()
  1633				return p.newAssignStmt(pos, op, lhs, ImplicitOne)
  1634	
  1635			case _Arrow:
  1636				// lhs <- rhs
  1637				s := new(SendStmt)
  1638				s.pos = pos
  1639				p.next()
  1640				s.Chan = lhs
  1641				s.Value = p.expr()
  1642				return s
  1643	
  1644			default:
  1645				// expr
  1646				s := new(ExprStmt)
  1647				s.pos = lhs.Pos()
  1648				s.X = lhs
  1649				return s
  1650			}
  1651		}
  1652	
  1653		// expr_list
  1654		switch p.tok {
  1655		case _Assign, _Define:
  1656			pos := p.pos()
  1657			var op Operator
  1658			if p.tok == _Define {
  1659				op = Def
  1660			}
  1661			p.next()
  1662	
  1663			if keyword == _For && p.tok == _Range {
  1664				// expr_list op= _Range expr
  1665				return p.newRangeClause(lhs, op == Def)
  1666			}
  1667	
  1668			// expr_list op= expr_list
  1669			rhs := p.exprList()
  1670	
  1671			if x, ok := rhs.(*TypeSwitchGuard); ok && keyword == _Switch && op == Def {
  1672				if lhs, ok := lhs.(*Name); ok {
  1673					// switch … lhs := rhs.(type)
  1674					x.Lhs = lhs
  1675					s := new(ExprStmt)
  1676					s.pos = x.Pos()
  1677					s.X = x
  1678					return s
  1679				}
  1680			}
  1681	
  1682			return p.newAssignStmt(pos, op, lhs, rhs)
  1683	
  1684		default:
  1685			p.syntaxError("expecting := or = or comma")
  1686			p.advance(_Semi, _Rbrace)
  1687			// make the best of what we have
  1688			if x, ok := lhs.(*ListExpr); ok {
  1689				lhs = x.ElemList[0]
  1690			}
  1691			s := new(ExprStmt)
  1692			s.pos = lhs.Pos()
  1693			s.X = lhs
  1694			return s
  1695		}
  1696	}
  1697	
  1698	func (p *parser) newRangeClause(lhs Expr, def bool) *RangeClause {
  1699		r := new(RangeClause)
  1700		r.pos = p.pos()
  1701		p.next() // consume _Range
  1702		r.Lhs = lhs
  1703		r.Def = def
  1704		r.X = p.expr()
  1705		return r
  1706	}
  1707	
  1708	func (p *parser) newAssignStmt(pos Pos, op Operator, lhs, rhs Expr) *AssignStmt {
  1709		a := new(AssignStmt)
  1710		a.pos = pos
  1711		a.Op = op
  1712		a.Lhs = lhs
  1713		a.Rhs = rhs
  1714		return a
  1715	}
  1716	
  1717	func (p *parser) labeledStmtOrNil(label *Name) Stmt {
  1718		if trace {
  1719			defer p.trace("labeledStmt")()
  1720		}
  1721	
  1722		s := new(LabeledStmt)
  1723		s.pos = p.pos()
  1724		s.Label = label
  1725	
  1726		p.want(_Colon)
  1727	
  1728		if p.tok == _Rbrace {
  1729			// We expect a statement (incl. an empty statement), which must be
  1730			// terminated by a semicolon. Because semicolons may be omitted before
  1731			// an _Rbrace, seeing an _Rbrace implies an empty statement.
  1732			e := new(EmptyStmt)
  1733			e.pos = p.pos()
  1734			s.Stmt = e
  1735			return s
  1736		}
  1737	
  1738		s.Stmt = p.stmtOrNil()
  1739		if s.Stmt != nil {
  1740			return s
  1741		}
  1742	
  1743		// report error at line of ':' token
  1744		p.syntaxErrorAt(s.pos, "missing statement after label")
  1745		// we are already at the end of the labeled statement - no need to advance
  1746		return nil // avoids follow-on errors (see e.g., fixedbugs/bug274.go)
  1747	}
  1748	
  1749	// context must be a non-empty string unless we know that p.tok == _Lbrace.
  1750	func (p *parser) blockStmt(context string) *BlockStmt {
  1751		if trace {
  1752			defer p.trace("blockStmt")()
  1753		}
  1754	
  1755		s := new(BlockStmt)
  1756		s.pos = p.pos()
  1757	
  1758		// people coming from C may forget that braces are mandatory in Go
  1759		if !p.got(_Lbrace) {
  1760			p.syntaxError("expecting { after " + context)
  1761			p.advance(_Name, _Rbrace)
  1762			s.Rbrace = p.pos() // in case we found "}"
  1763			if p.got(_Rbrace) {
  1764				return s
  1765			}
  1766		}
  1767	
  1768		s.List = p.stmtList()
  1769		s.Rbrace = p.pos()
  1770		p.want(_Rbrace)
  1771	
  1772		return s
  1773	}
  1774	
  1775	func (p *parser) declStmt(f func(*Group) Decl) *DeclStmt {
  1776		if trace {
  1777			defer p.trace("declStmt")()
  1778		}
  1779	
  1780		s := new(DeclStmt)
  1781		s.pos = p.pos()
  1782	
  1783		p.next() // _Const, _Type, or _Var
  1784		s.DeclList = p.appendGroup(nil, f)
  1785	
  1786		return s
  1787	}
  1788	
  1789	func (p *parser) forStmt() Stmt {
  1790		if trace {
  1791			defer p.trace("forStmt")()
  1792		}
  1793	
  1794		s := new(ForStmt)
  1795		s.pos = p.pos()
  1796	
  1797		s.Init, s.Cond, s.Post = p.header(_For)
  1798		s.Body = p.blockStmt("for clause")
  1799	
  1800		return s
  1801	}
  1802	
  1803	func (p *parser) header(keyword token) (init SimpleStmt, cond Expr, post SimpleStmt) {
  1804		p.want(keyword)
  1805	
  1806		if p.tok == _Lbrace {
  1807			if keyword == _If {
  1808				p.syntaxError("missing condition in if statement")
  1809			}
  1810			return
  1811		}
  1812		// p.tok != _Lbrace
  1813	
  1814		outer := p.xnest
  1815		p.xnest = -1
  1816	
  1817		if p.tok != _Semi {
  1818			// accept potential varDecl but complain
  1819			if p.got(_Var) {
  1820				p.syntaxError(fmt.Sprintf("var declaration not allowed in %s initializer", keyword.String()))
  1821			}
  1822			init = p.simpleStmt(nil, keyword)
  1823			// If we have a range clause, we are done (can only happen for keyword == _For).
  1824			if _, ok := init.(*RangeClause); ok {
  1825				p.xnest = outer
  1826				return
  1827			}
  1828		}
  1829	
  1830		var condStmt SimpleStmt
  1831		var semi struct {
  1832			pos Pos
  1833			lit string // valid if pos.IsKnown()
  1834		}
  1835		if p.tok != _Lbrace {
  1836			if p.tok == _Semi {
  1837				semi.pos = p.pos()
  1838				semi.lit = p.lit
  1839				p.next()
  1840			} else {
  1841				// asking for a '{' rather than a ';' here leads to a better error message
  1842				p.want(_Lbrace)
  1843			}
  1844			if keyword == _For {
  1845				if p.tok != _Semi {
  1846					if p.tok == _Lbrace {
  1847						p.syntaxError("expecting for loop condition")
  1848						goto done
  1849					}
  1850					condStmt = p.simpleStmt(nil, 0 /* range not permitted */)
  1851				}
  1852				p.want(_Semi)
  1853				if p.tok != _Lbrace {
  1854					post = p.simpleStmt(nil, 0 /* range not permitted */)
  1855					if a, _ := post.(*AssignStmt); a != nil && a.Op == Def {
  1856						p.syntaxErrorAt(a.Pos(), "cannot declare in post statement of for loop")
  1857					}
  1858				}
  1859			} else if p.tok != _Lbrace {
  1860				condStmt = p.simpleStmt(nil, keyword)
  1861			}
  1862		} else {
  1863			condStmt = init
  1864			init = nil
  1865		}
  1866	
  1867	done:
  1868		// unpack condStmt
  1869		switch s := condStmt.(type) {
  1870		case nil:
  1871			if keyword == _If && semi.pos.IsKnown() {
  1872				if semi.lit != "semicolon" {
  1873					p.syntaxErrorAt(semi.pos, fmt.Sprintf("unexpected %s, expecting { after if clause", semi.lit))
  1874				} else {
  1875					p.syntaxErrorAt(semi.pos, "missing condition in if statement")
  1876				}
  1877			}
  1878		case *ExprStmt:
  1879			cond = s.X
  1880		default:
  1881			// A common syntax error is to write '=' instead of '==',
  1882			// which turns an expression into an assignment. Provide
  1883			// a more explicit error message in that case to prevent
  1884			// further confusion.
  1885			str := String(s)
  1886			if as, ok := s.(*AssignStmt); ok && as.Op == 0 {
  1887				str = "assignment " + str
  1888			}
  1889			p.syntaxError(fmt.Sprintf("%s used as value", str))
  1890		}
  1891	
  1892		p.xnest = outer
  1893		return
  1894	}
  1895	
  1896	func (p *parser) ifStmt() *IfStmt {
  1897		if trace {
  1898			defer p.trace("ifStmt")()
  1899		}
  1900	
  1901		s := new(IfStmt)
  1902		s.pos = p.pos()
  1903	
  1904		s.Init, s.Cond, _ = p.header(_If)
  1905		s.Then = p.blockStmt("if clause")
  1906	
  1907		if p.got(_Else) {
  1908			switch p.tok {
  1909			case _If:
  1910				s.Else = p.ifStmt()
  1911			case _Lbrace:
  1912				s.Else = p.blockStmt("")
  1913			default:
  1914				p.syntaxError("else must be followed by if or statement block")
  1915				p.advance(_Name, _Rbrace)
  1916			}
  1917		}
  1918	
  1919		return s
  1920	}
  1921	
  1922	func (p *parser) switchStmt() *SwitchStmt {
  1923		if trace {
  1924			defer p.trace("switchStmt")()
  1925		}
  1926	
  1927		s := new(SwitchStmt)
  1928		s.pos = p.pos()
  1929	
  1930		s.Init, s.Tag, _ = p.header(_Switch)
  1931	
  1932		if !p.got(_Lbrace) {
  1933			p.syntaxError("missing { after switch clause")
  1934			p.advance(_Case, _Default, _Rbrace)
  1935		}
  1936		for p.tok != _EOF && p.tok != _Rbrace {
  1937			s.Body = append(s.Body, p.caseClause())
  1938		}
  1939		s.Rbrace = p.pos()
  1940		p.want(_Rbrace)
  1941	
  1942		return s
  1943	}
  1944	
  1945	func (p *parser) selectStmt() *SelectStmt {
  1946		if trace {
  1947			defer p.trace("selectStmt")()
  1948		}
  1949	
  1950		s := new(SelectStmt)
  1951		s.pos = p.pos()
  1952	
  1953		p.want(_Select)
  1954		if !p.got(_Lbrace) {
  1955			p.syntaxError("missing { after select clause")
  1956			p.advance(_Case, _Default, _Rbrace)
  1957		}
  1958		for p.tok != _EOF && p.tok != _Rbrace {
  1959			s.Body = append(s.Body, p.commClause())
  1960		}
  1961		s.Rbrace = p.pos()
  1962		p.want(_Rbrace)
  1963	
  1964		return s
  1965	}
  1966	
  1967	func (p *parser) caseClause() *CaseClause {
  1968		if trace {
  1969			defer p.trace("caseClause")()
  1970		}
  1971	
  1972		c := new(CaseClause)
  1973		c.pos = p.pos()
  1974	
  1975		switch p.tok {
  1976		case _Case:
  1977			p.next()
  1978			c.Cases = p.exprList()
  1979	
  1980		case _Default:
  1981			p.next()
  1982	
  1983		default:
  1984			p.syntaxError("expecting case or default or }")
  1985			p.advance(_Colon, _Case, _Default, _Rbrace)
  1986		}
  1987	
  1988		c.Colon = p.pos()
  1989		p.want(_Colon)
  1990		c.Body = p.stmtList()
  1991	
  1992		return c
  1993	}
  1994	
  1995	func (p *parser) commClause() *CommClause {
  1996		if trace {
  1997			defer p.trace("commClause")()
  1998		}
  1999	
  2000		c := new(CommClause)
  2001		c.pos = p.pos()
  2002	
  2003		switch p.tok {
  2004		case _Case:
  2005			p.next()
  2006			c.Comm = p.simpleStmt(nil, 0)
  2007	
  2008			// The syntax restricts the possible simple statements here to:
  2009			//
  2010			//     lhs <- x (send statement)
  2011			//     <-x
  2012			//     lhs = <-x
  2013			//     lhs := <-x
  2014			//
  2015			// All these (and more) are recognized by simpleStmt and invalid
  2016			// syntax trees are flagged later, during type checking.
  2017			// TODO(gri) eventually may want to restrict valid syntax trees
  2018			// here.
  2019	
  2020		case _Default:
  2021			p.next()
  2022	
  2023		default:
  2024			p.syntaxError("expecting case or default or }")
  2025			p.advance(_Colon, _Case, _Default, _Rbrace)
  2026		}
  2027	
  2028		c.Colon = p.pos()
  2029		p.want(_Colon)
  2030		c.Body = p.stmtList()
  2031	
  2032		return c
  2033	}
  2034	
  2035	// Statement =
  2036	// 	Declaration | LabeledStmt | SimpleStmt |
  2037	// 	GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
  2038	// 	FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
  2039	// 	DeferStmt .
  2040	func (p *parser) stmtOrNil() Stmt {
  2041		if trace {
  2042			defer p.trace("stmt " + p.tok.String())()
  2043		}
  2044	
  2045		// Most statements (assignments) start with an identifier;
  2046		// look for it first before doing anything more expensive.
  2047		if p.tok == _Name {
  2048			lhs := p.exprList()
  2049			if label, ok := lhs.(*Name); ok && p.tok == _Colon {
  2050				return p.labeledStmtOrNil(label)
  2051			}
  2052			return p.simpleStmt(lhs, 0)
  2053		}
  2054	
  2055		switch p.tok {
  2056		case _Lbrace:
  2057			return p.blockStmt("")
  2058	
  2059		case _Var:
  2060			return p.declStmt(p.varDecl)
  2061	
  2062		case _Const:
  2063			return p.declStmt(p.constDecl)
  2064	
  2065		case _Type:
  2066			return p.declStmt(p.typeDecl)
  2067	
  2068		case _Operator, _Star:
  2069			switch p.op {
  2070			case Add, Sub, Mul, And, Xor, Not:
  2071				return p.simpleStmt(nil, 0) // unary operators
  2072			}
  2073	
  2074		case _Literal, _Func, _Lparen, // operands
  2075			_Lbrack, _Struct, _Map, _Chan, _Interface, // composite types
  2076			_Arrow: // receive operator
  2077			return p.simpleStmt(nil, 0)
  2078	
  2079		case _For:
  2080			return p.forStmt()
  2081	
  2082		case _Switch:
  2083			return p.switchStmt()
  2084	
  2085		case _Select:
  2086			return p.selectStmt()
  2087	
  2088		case _If:
  2089			return p.ifStmt()
  2090	
  2091		case _Fallthrough:
  2092			s := new(BranchStmt)
  2093			s.pos = p.pos()
  2094			p.next()
  2095			s.Tok = _Fallthrough
  2096			return s
  2097	
  2098		case _Break, _Continue:
  2099			s := new(BranchStmt)
  2100			s.pos = p.pos()
  2101			s.Tok = p.tok
  2102			p.next()
  2103			if p.tok == _Name {
  2104				s.Label = p.name()
  2105			}
  2106			return s
  2107	
  2108		case _Go, _Defer:
  2109			return p.callStmt()
  2110	
  2111		case _Goto:
  2112			s := new(BranchStmt)
  2113			s.pos = p.pos()
  2114			s.Tok = _Goto
  2115			p.next()
  2116			s.Label = p.name()
  2117			return s
  2118	
  2119		case _Return:
  2120			s := new(ReturnStmt)
  2121			s.pos = p.pos()
  2122			p.next()
  2123			if p.tok != _Semi && p.tok != _Rbrace {
  2124				s.Results = p.exprList()
  2125			}
  2126			return s
  2127	
  2128		case _Semi:
  2129			s := new(EmptyStmt)
  2130			s.pos = p.pos()
  2131			return s
  2132		}
  2133	
  2134		return nil
  2135	}
  2136	
  2137	// StatementList = { Statement ";" } .
  2138	func (p *parser) stmtList() (l []Stmt) {
  2139		if trace {
  2140			defer p.trace("stmtList")()
  2141		}
  2142	
  2143		for p.tok != _EOF && p.tok != _Rbrace && p.tok != _Case && p.tok != _Default {
  2144			s := p.stmtOrNil()
  2145			if s == nil {
  2146				break
  2147			}
  2148			l = append(l, s)
  2149			// ";" is optional before "}"
  2150			if !p.got(_Semi) && p.tok != _Rbrace {
  2151				p.syntaxError("at end of statement")
  2152				p.advance(_Semi, _Rbrace, _Case, _Default)
  2153				p.got(_Semi) // avoid spurious empty statement
  2154			}
  2155		}
  2156		return
  2157	}
  2158	
  2159	// Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
  2160	func (p *parser) argList() (list []Expr, hasDots bool) {
  2161		if trace {
  2162			defer p.trace("argList")()
  2163		}
  2164	
  2165		p.xnest++
  2166		p.list(_Lparen, _Comma, _Rparen, func() bool {
  2167			list = append(list, p.expr())
  2168			hasDots = p.got(_DotDotDot)
  2169			return hasDots
  2170		})
  2171		p.xnest--
  2172	
  2173		return
  2174	}
  2175	
  2176	// ----------------------------------------------------------------------------
  2177	// Common productions
  2178	
  2179	func (p *parser) newName(value string) *Name {
  2180		n := new(Name)
  2181		n.pos = p.pos()
  2182		n.Value = value
  2183		return n
  2184	}
  2185	
  2186	func (p *parser) name() *Name {
  2187		// no tracing to avoid overly verbose output
  2188	
  2189		if p.tok == _Name {
  2190			n := p.newName(p.lit)
  2191			p.next()
  2192			return n
  2193		}
  2194	
  2195		n := p.newName("_")
  2196		p.syntaxError("expecting name")
  2197		p.advance()
  2198		return n
  2199	}
  2200	
  2201	// IdentifierList = identifier { "," identifier } .
  2202	// The first name must be provided.
  2203	func (p *parser) nameList(first *Name) []*Name {
  2204		if trace {
  2205			defer p.trace("nameList")()
  2206		}
  2207	
  2208		if debug && first == nil {
  2209			panic("first name not provided")
  2210		}
  2211	
  2212		l := []*Name{first}
  2213		for p.got(_Comma) {
  2214			l = append(l, p.name())
  2215		}
  2216	
  2217		return l
  2218	}
  2219	
  2220	// The first name may be provided, or nil.
  2221	func (p *parser) qualifiedName(name *Name) Expr {
  2222		if trace {
  2223			defer p.trace("qualifiedName")()
  2224		}
  2225	
  2226		switch {
  2227		case name != nil:
  2228			// name is provided
  2229		case p.tok == _Name:
  2230			name = p.name()
  2231		default:
  2232			name = p.newName("_")
  2233			p.syntaxError("expecting name")
  2234			p.advance(_Dot, _Semi, _Rbrace)
  2235		}
  2236	
  2237		return p.dotname(name)
  2238	}
  2239	
  2240	// ExpressionList = Expression { "," Expression } .
  2241	func (p *parser) exprList() Expr {
  2242		if trace {
  2243			defer p.trace("exprList")()
  2244		}
  2245	
  2246		x := p.expr()
  2247		if p.got(_Comma) {
  2248			list := []Expr{x, p.expr()}
  2249			for p.got(_Comma) {
  2250				list = append(list, p.expr())
  2251			}
  2252			t := new(ListExpr)
  2253			t.pos = x.Pos()
  2254			t.ElemList = list
  2255			x = t
  2256		}
  2257		return x
  2258	}
  2259	
  2260	// unparen removes all parentheses around an expression.
  2261	func unparen(x Expr) Expr {
  2262		for {
  2263			p, ok := x.(*ParenExpr)
  2264			if !ok {
  2265				break
  2266			}
  2267			x = p.X
  2268		}
  2269		return x
  2270	}
  2271	

View as plain text