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

View as plain text