github.com/euank/go@v0.0.0-20160829210321-495514729181/src/cmd/compile/internal/gc/parser.go (about)

     1  // Copyright 2015 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gc
     6  
     7  // The recursive-descent parser is built around a slighty modified grammar
     8  // of Go to accommodate for the constraints imposed by strict one token look-
     9  // ahead, and for better error handling. Subsequent checks of the constructed
    10  // syntax tree restrict the language accepted by the compiler to proper Go.
    11  //
    12  // Semicolons are inserted by the lexer. The parser uses one-token look-ahead
    13  // to handle optional commas and semicolons before a closing ) or } .
    14  
    15  import (
    16  	"bufio"
    17  	"fmt"
    18  	"os"
    19  	"strconv"
    20  	"strings"
    21  )
    22  
    23  const trace = false // if set, parse tracing can be enabled with -x
    24  
    25  // oldParseFile parses a single Go source file.
    26  func oldParseFile(infile string) {
    27  	f, err := os.Open(infile)
    28  	if err != nil {
    29  		fmt.Printf("open %s: %v\n", infile, err)
    30  		errorexit()
    31  	}
    32  	defer f.Close()
    33  	bin := bufio.NewReader(f)
    34  
    35  	// Skip initial BOM if present.
    36  	if r, _, _ := bin.ReadRune(); r != BOM {
    37  		bin.UnreadRune()
    38  	}
    39  	newparser(bin, nil).file()
    40  }
    41  
    42  type parser struct {
    43  	lexer
    44  	fnest  int    // function nesting level (for error handling)
    45  	xnest  int    // expression nesting level (for complit ambiguity resolution)
    46  	indent []byte // tracing support
    47  }
    48  
    49  // newparser returns a new parser ready to parse from src.
    50  // indent is the initial indentation for tracing output.
    51  func newparser(src *bufio.Reader, indent []byte) *parser {
    52  	var p parser
    53  	p.bin = src
    54  	p.indent = indent
    55  	p.next()
    56  	return &p
    57  }
    58  
    59  func (p *parser) got(tok int32) bool {
    60  	if p.tok == tok {
    61  		p.next()
    62  		return true
    63  	}
    64  	return false
    65  }
    66  
    67  func (p *parser) want(tok int32) {
    68  	if !p.got(tok) {
    69  		p.syntax_error("expecting " + tokstring(tok))
    70  		p.advance()
    71  	}
    72  }
    73  
    74  // ----------------------------------------------------------------------------
    75  // Syntax error handling
    76  
    77  func (p *parser) syntax_error(msg string) {
    78  	if trace && Debug['x'] != 0 {
    79  		defer p.trace("syntax_error (" + msg + ")")()
    80  	}
    81  
    82  	if p.tok == EOF && nerrors > 0 {
    83  		return // avoid meaningless follow-up errors
    84  	}
    85  
    86  	// add punctuation etc. as needed to msg
    87  	switch {
    88  	case msg == "":
    89  		// nothing to do
    90  	case strings.HasPrefix(msg, "in"), strings.HasPrefix(msg, "at"), strings.HasPrefix(msg, "after"):
    91  		msg = " " + msg
    92  	case strings.HasPrefix(msg, "expecting"):
    93  		msg = ", " + msg
    94  	default:
    95  		// plain error - we don't care about current token
    96  		Yyerror("syntax error: %s", msg)
    97  		return
    98  	}
    99  
   100  	// determine token string
   101  	var tok string
   102  	switch p.tok {
   103  	case LNAME:
   104  		if p.sym_ != nil && p.sym_.Name != "" {
   105  			tok = p.sym_.Name
   106  		} else {
   107  			tok = "name"
   108  		}
   109  	case LLITERAL:
   110  		if litbuf == "" {
   111  			litbuf = "literal " + lexbuf.String()
   112  		}
   113  		tok = litbuf
   114  	case LOPER:
   115  		tok = goopnames[p.op]
   116  	case LASOP:
   117  		tok = goopnames[p.op] + "="
   118  	case LINCOP:
   119  		tok = goopnames[p.op] + goopnames[p.op]
   120  	default:
   121  		tok = tokstring(p.tok)
   122  	}
   123  
   124  	Yyerror("syntax error: unexpected %s", tok+msg)
   125  }
   126  
   127  // Like syntax_error, but reports error at given line rather than current lexer line.
   128  func (p *parser) syntax_error_at(lno int32, msg string) {
   129  	defer func(lno int32) {
   130  		lineno = lno
   131  	}(lineno)
   132  	lineno = lno
   133  	p.syntax_error(msg)
   134  }
   135  
   136  // The stoplist contains keywords that start a statement.
   137  // They are good synchronization points in case of syntax
   138  // errors and (usually) shouldn't be skipped over.
   139  var stoplist = map[int32]bool{
   140  	LBREAK:    true,
   141  	LCONST:    true,
   142  	LCONTINUE: true,
   143  	LDEFER:    true,
   144  	LFALL:     true,
   145  	LFOR:      true,
   146  	LFUNC:     true,
   147  	LGO:       true,
   148  	LGOTO:     true,
   149  	LIF:       true,
   150  	LRETURN:   true,
   151  	LSELECT:   true,
   152  	LSWITCH:   true,
   153  	LTYPE:     true,
   154  	LVAR:      true,
   155  }
   156  
   157  // Advance consumes tokens until it finds a token of the stop- or followlist.
   158  // The stoplist is only considered if we are inside a function (p.fnest > 0).
   159  // The followlist is the list of valid tokens that can follow a production;
   160  // if it is empty, exactly one token is consumed to ensure progress.
   161  func (p *parser) advance(followlist ...int32) {
   162  	if len(followlist) == 0 {
   163  		p.next()
   164  		return
   165  	}
   166  	for p.tok != EOF {
   167  		if p.fnest > 0 && stoplist[p.tok] {
   168  			return
   169  		}
   170  		for _, follow := range followlist {
   171  			if p.tok == follow {
   172  				return
   173  			}
   174  		}
   175  		p.next()
   176  	}
   177  }
   178  
   179  func tokstring(tok int32) string {
   180  	switch tok {
   181  	case EOF:
   182  		return "EOF"
   183  	case ',':
   184  		return "comma"
   185  	case ';':
   186  		return "semicolon or newline"
   187  	}
   188  	if 0 <= tok && tok < 128 {
   189  		// get invisibles properly backslashed
   190  		s := strconv.QuoteRune(tok)
   191  		if n := len(s); n > 0 && s[0] == '\'' && s[n-1] == '\'' {
   192  			s = s[1 : n-1]
   193  		}
   194  		return s
   195  	}
   196  	if s := tokstrings[tok]; s != "" {
   197  		return s
   198  	}
   199  	// catchall
   200  	return fmt.Sprintf("tok-%v", tok)
   201  }
   202  
   203  var tokstrings = map[int32]string{
   204  	LNAME:    "NAME",
   205  	LLITERAL: "LITERAL",
   206  
   207  	LOPER:  "op",
   208  	LASOP:  "op=",
   209  	LINCOP: "opop",
   210  
   211  	LCOLAS: ":=",
   212  	LCOMM:  "<-",
   213  	LDDD:   "...",
   214  
   215  	LBREAK:     "break",
   216  	LCASE:      "case",
   217  	LCHAN:      "chan",
   218  	LCONST:     "const",
   219  	LCONTINUE:  "continue",
   220  	LDEFAULT:   "default",
   221  	LDEFER:     "defer",
   222  	LELSE:      "else",
   223  	LFALL:      "fallthrough",
   224  	LFOR:       "for",
   225  	LFUNC:      "func",
   226  	LGO:        "go",
   227  	LGOTO:      "goto",
   228  	LIF:        "if",
   229  	LIMPORT:    "import",
   230  	LINTERFACE: "interface",
   231  	LMAP:       "map",
   232  	LPACKAGE:   "package",
   233  	LRANGE:     "range",
   234  	LRETURN:    "return",
   235  	LSELECT:    "select",
   236  	LSTRUCT:    "struct",
   237  	LSWITCH:    "switch",
   238  	LTYPE:      "type",
   239  	LVAR:       "var",
   240  }
   241  
   242  // usage: defer p.trace(msg)()
   243  func (p *parser) trace(msg string) func() {
   244  	fmt.Printf("%5d: %s%s (\n", lineno, p.indent, msg)
   245  	const tab = ". "
   246  	p.indent = append(p.indent, tab...)
   247  	return func() {
   248  		p.indent = p.indent[:len(p.indent)-len(tab)]
   249  		if x := recover(); x != nil {
   250  			panic(x) // skip print_trace
   251  		}
   252  		fmt.Printf("%5d: %s)\n", lineno, p.indent)
   253  	}
   254  }
   255  
   256  // ----------------------------------------------------------------------------
   257  // Parsing package files
   258  //
   259  // Parse methods are annotated with matching Go productions as appropriate.
   260  // The annotations are intended as guidelines only since a single Go grammar
   261  // rule may be covered by multiple parse methods and vice versa.
   262  
   263  // SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
   264  func (p *parser) file() {
   265  	if trace && Debug['x'] != 0 {
   266  		defer p.trace("file")()
   267  	}
   268  
   269  	p.package_()
   270  	p.want(';')
   271  
   272  	for p.tok == LIMPORT {
   273  		p.import_()
   274  		p.want(';')
   275  	}
   276  
   277  	xtop = append(xtop, p.xdcl_list()...)
   278  
   279  	p.want(EOF)
   280  }
   281  
   282  // PackageClause = "package" PackageName .
   283  // PackageName   = identifier .
   284  func (p *parser) package_() {
   285  	if trace && Debug['x'] != 0 {
   286  		defer p.trace("package_")()
   287  	}
   288  
   289  	if !p.got(LPACKAGE) {
   290  		p.syntax_error("package statement must be first")
   291  		errorexit()
   292  	}
   293  	mkpackage(p.sym().Name)
   294  }
   295  
   296  // ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
   297  func (p *parser) import_() {
   298  	if trace && Debug['x'] != 0 {
   299  		defer p.trace("import_")()
   300  	}
   301  
   302  	p.want(LIMPORT)
   303  	if p.got('(') {
   304  		for p.tok != EOF && p.tok != ')' {
   305  			p.importdcl()
   306  			if !p.osemi(')') {
   307  				break
   308  			}
   309  		}
   310  		p.want(')')
   311  	} else {
   312  		p.importdcl()
   313  	}
   314  }
   315  
   316  // ImportSpec = [ "." | PackageName ] ImportPath .
   317  // ImportPath = string_lit .
   318  func (p *parser) importdcl() {
   319  	if trace && Debug['x'] != 0 {
   320  		defer p.trace("importdcl")()
   321  	}
   322  
   323  	var my *Sym
   324  	switch p.tok {
   325  	case LNAME:
   326  		// import with given name
   327  		my = p.sym()
   328  
   329  	case '.':
   330  		// import into my name space
   331  		my = Lookup(".")
   332  		p.next()
   333  	}
   334  
   335  	if p.tok != LLITERAL {
   336  		p.syntax_error("missing import path; require quoted string")
   337  		p.advance(';', ')')
   338  		return
   339  	}
   340  
   341  	line := lineno
   342  
   343  	// We need to clear importpkg before calling p.next(),
   344  	// otherwise it will affect lexlineno.
   345  	// TODO(mdempsky): Fix this clumsy API.
   346  	importfile(&p.val, p.indent)
   347  	ipkg := importpkg
   348  	importpkg = nil
   349  
   350  	p.next()
   351  	if ipkg == nil {
   352  		if nerrors == 0 {
   353  			Fatalf("phase error in import")
   354  		}
   355  		return
   356  	}
   357  
   358  	ipkg.Direct = true
   359  
   360  	if my == nil {
   361  		my = Lookup(ipkg.Name)
   362  	}
   363  
   364  	pack := Nod(OPACK, nil, nil)
   365  	pack.Sym = my
   366  	pack.Name.Pkg = ipkg
   367  	pack.Lineno = line
   368  
   369  	if strings.HasPrefix(my.Name, ".") {
   370  		importdot(ipkg, pack)
   371  		return
   372  	}
   373  	if my.Name == "init" {
   374  		lineno = line
   375  		Yyerror("cannot import package as init - init must be a func")
   376  		return
   377  	}
   378  	if my.Name == "_" {
   379  		return
   380  	}
   381  	if my.Def != nil {
   382  		lineno = line
   383  		redeclare(my, "as imported package name")
   384  	}
   385  	my.Def = pack
   386  	my.Lastlineno = line
   387  	my.Block = 1 // at top level
   388  }
   389  
   390  // Declaration = ConstDecl | TypeDecl | VarDecl .
   391  // ConstDecl   = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
   392  // TypeDecl    = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
   393  // VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
   394  func (p *parser) common_dcl() []*Node {
   395  	if trace && Debug['x'] != 0 {
   396  		defer p.trace("common_dcl")()
   397  	}
   398  
   399  	var dcl func() []*Node
   400  	switch p.tok {
   401  	case LVAR:
   402  		dcl = p.vardcl
   403  
   404  	case LCONST:
   405  		iota_ = 0
   406  		dcl = p.constdcl
   407  
   408  	case LTYPE:
   409  		dcl = p.typedcl
   410  
   411  	default:
   412  		panic("unreachable")
   413  	}
   414  
   415  	p.next()
   416  	var s []*Node
   417  	if p.got('(') {
   418  		for p.tok != EOF && p.tok != ')' {
   419  			s = append(s, dcl()...)
   420  			if !p.osemi(')') {
   421  				break
   422  			}
   423  		}
   424  		p.want(')')
   425  	} else {
   426  		s = dcl()
   427  	}
   428  
   429  	iota_ = -100000
   430  	lastconst = nil
   431  
   432  	return s
   433  }
   434  
   435  // VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
   436  func (p *parser) vardcl() []*Node {
   437  	if trace && Debug['x'] != 0 {
   438  		defer p.trace("vardcl")()
   439  	}
   440  
   441  	names := p.dcl_name_list()
   442  	var typ *Node
   443  	var exprs []*Node
   444  	if p.got('=') {
   445  		exprs = p.expr_list()
   446  	} else {
   447  		typ = p.ntype()
   448  		if p.got('=') {
   449  			exprs = p.expr_list()
   450  		}
   451  	}
   452  
   453  	return variter(names, typ, exprs)
   454  }
   455  
   456  // ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
   457  func (p *parser) constdcl() []*Node {
   458  	if trace && Debug['x'] != 0 {
   459  		defer p.trace("constdcl")()
   460  	}
   461  
   462  	names := p.dcl_name_list()
   463  	var typ *Node
   464  	var exprs []*Node
   465  	if p.tok != EOF && p.tok != ';' && p.tok != ')' {
   466  		typ = p.try_ntype()
   467  		if p.got('=') {
   468  			exprs = p.expr_list()
   469  		}
   470  	}
   471  
   472  	return constiter(names, typ, exprs)
   473  }
   474  
   475  // TypeSpec = identifier Type .
   476  func (p *parser) typedcl() []*Node {
   477  	if trace && Debug['x'] != 0 {
   478  		defer p.trace("typedcl")()
   479  	}
   480  
   481  	name := typedcl0(p.sym())
   482  
   483  	typ := p.try_ntype()
   484  	// handle case where type is missing
   485  	if typ == nil {
   486  		p.syntax_error("in type declaration")
   487  		p.advance(';', ')')
   488  	}
   489  
   490  	return []*Node{typedcl1(name, typ, true)}
   491  }
   492  
   493  // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
   494  //
   495  // simple_stmt may return missing_stmt if labelOk is set.
   496  func (p *parser) simple_stmt(labelOk, rangeOk bool) *Node {
   497  	if trace && Debug['x'] != 0 {
   498  		defer p.trace("simple_stmt")()
   499  	}
   500  
   501  	if rangeOk && p.got(LRANGE) {
   502  		// LRANGE expr
   503  		r := Nod(ORANGE, nil, p.expr())
   504  		r.Etype = 0 // := flag
   505  		return r
   506  	}
   507  
   508  	lhs := p.expr_list()
   509  
   510  	if len(lhs) == 1 && p.tok != '=' && p.tok != LCOLAS && p.tok != LRANGE {
   511  		// expr
   512  		lhs := lhs[0]
   513  		switch p.tok {
   514  		case LASOP:
   515  			// expr LASOP expr
   516  			op := p.op
   517  			p.next()
   518  			rhs := p.expr()
   519  
   520  			stmt := Nod(OASOP, lhs, rhs)
   521  			stmt.Etype = EType(op) // rathole to pass opcode
   522  			return stmt
   523  
   524  		case LINCOP:
   525  			// expr LINCOP
   526  			p.next()
   527  
   528  			stmt := Nod(OASOP, lhs, Nodintconst(1))
   529  			stmt.Implicit = true
   530  			stmt.Etype = EType(p.op)
   531  			return stmt
   532  
   533  		case ':':
   534  			// labelname ':' stmt
   535  			if labelOk {
   536  				// If we have a labelname, it was parsed by operand
   537  				// (calling p.name()) and given an ONAME, ONONAME, OTYPE, OPACK, or OLITERAL node.
   538  				// We only have a labelname if there is a symbol (was issue 14006).
   539  				switch lhs.Op {
   540  				case ONAME, ONONAME, OTYPE, OPACK, OLITERAL:
   541  					if lhs.Sym != nil {
   542  						lhs = newname(lhs.Sym)
   543  						break
   544  					}
   545  					fallthrough
   546  				default:
   547  					p.syntax_error("expecting semicolon or newline or }")
   548  					// we already progressed, no need to advance
   549  				}
   550  				lhs := Nod(OLABEL, lhs, nil)
   551  				lhs.Sym = dclstack // context, for goto restrictions
   552  				p.next()           // consume ':' after making label node for correct lineno
   553  				return p.labeled_stmt(lhs)
   554  			}
   555  			fallthrough
   556  
   557  		default:
   558  			// expr
   559  			// Since a bare name used as an expression is an error,
   560  			// introduce a wrapper node where necessary to give the
   561  			// correct line.
   562  			return wrapname(lhs)
   563  		}
   564  	}
   565  
   566  	// expr_list
   567  	switch p.tok {
   568  	case '=':
   569  		p.next()
   570  		if rangeOk && p.got(LRANGE) {
   571  			// expr_list '=' LRANGE expr
   572  			r := Nod(ORANGE, nil, p.expr())
   573  			r.List.Set(lhs)
   574  			r.Etype = 0 // := flag
   575  			return r
   576  		}
   577  
   578  		// expr_list '=' expr_list
   579  		rhs := p.expr_list()
   580  
   581  		if len(lhs) == 1 && len(rhs) == 1 {
   582  			// simple
   583  			return Nod(OAS, lhs[0], rhs[0])
   584  		}
   585  		// multiple
   586  		stmt := Nod(OAS2, nil, nil)
   587  		stmt.List.Set(lhs)
   588  		stmt.Rlist.Set(rhs)
   589  		return stmt
   590  
   591  	case LCOLAS:
   592  		lno := lineno
   593  		p.next()
   594  
   595  		if rangeOk && p.got(LRANGE) {
   596  			// expr_list LCOLAS LRANGE expr
   597  			r := Nod(ORANGE, nil, p.expr())
   598  			r.List.Set(lhs)
   599  			r.Colas = true
   600  			colasdefn(lhs, r)
   601  			return r
   602  		}
   603  
   604  		// expr_list LCOLAS expr_list
   605  		rhs := p.expr_list()
   606  
   607  		if rhs[0].Op == OTYPESW {
   608  			ts := Nod(OTYPESW, nil, rhs[0].Right)
   609  			if len(rhs) > 1 {
   610  				Yyerror("expr.(type) must be alone in list")
   611  			}
   612  			if len(lhs) > 1 {
   613  				Yyerror("argument count mismatch: %d = %d", len(lhs), 1)
   614  			} else if (lhs[0].Op != ONAME && lhs[0].Op != OTYPE && lhs[0].Op != ONONAME && (lhs[0].Op != OLITERAL || lhs[0].Name == nil)) || isblank(lhs[0]) {
   615  				Yyerror("invalid variable name %s in type switch", lhs[0])
   616  			} else {
   617  				ts.Left = dclname(lhs[0].Sym)
   618  			} // it's a colas, so must not re-use an oldname
   619  			return ts
   620  		}
   621  		return colas(lhs, rhs, lno)
   622  
   623  	default:
   624  		p.syntax_error("expecting := or = or comma")
   625  		p.advance(';', '}')
   626  		return nil
   627  	}
   628  }
   629  
   630  // LabeledStmt = Label ":" Statement .
   631  // Label       = identifier .
   632  func (p *parser) labeled_stmt(label *Node) *Node {
   633  	if trace && Debug['x'] != 0 {
   634  		defer p.trace("labeled_stmt")()
   635  	}
   636  
   637  	var ls *Node // labeled statement
   638  	if p.tok != '}' && p.tok != EOF {
   639  		ls = p.stmt()
   640  		if ls == missing_stmt {
   641  			// report error at line of ':' token
   642  			p.syntax_error_at(label.Lineno, "missing statement after label")
   643  			// we are already at the end of the labeled statement - no need to advance
   644  			return missing_stmt
   645  		}
   646  	}
   647  
   648  	label.Name.Defn = ls
   649  	l := []*Node{label}
   650  	if ls != nil {
   651  		if ls.Op == OBLOCK && ls.Ninit.Len() == 0 {
   652  			l = append(l, ls.List.Slice()...)
   653  		} else {
   654  			l = append(l, ls)
   655  		}
   656  	}
   657  	return liststmt(l)
   658  }
   659  
   660  // case_ parses a superset of switch and select statement cases.
   661  // Later checks restrict the syntax to valid forms.
   662  //
   663  // ExprSwitchCase = "case" ExpressionList | "default" .
   664  // TypeSwitchCase = "case" TypeList | "default" .
   665  // TypeList       = Type { "," Type } .
   666  // CommCase       = "case" ( SendStmt | RecvStmt ) | "default" .
   667  // RecvStmt       = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
   668  // RecvExpr       = Expression .
   669  func (p *parser) case_(tswitch *Node) *Node {
   670  	if trace && Debug['x'] != 0 {
   671  		defer p.trace("case_")()
   672  	}
   673  
   674  	switch p.tok {
   675  	case LCASE:
   676  		p.next()
   677  		cases := p.expr_list() // expr_or_type_list
   678  		switch p.tok {
   679  		case ':':
   680  			// LCASE expr_or_type_list ':'
   681  
   682  			// will be converted to OCASE
   683  			// right will point to next case
   684  			// done in casebody()
   685  			markdcl() // matching popdcl in caseblock
   686  			stmt := Nod(OXCASE, nil, nil)
   687  			stmt.List.Set(cases)
   688  			if tswitch != nil {
   689  				if n := tswitch.Left; n != nil {
   690  					// type switch - declare variable
   691  					nn := newname(n.Sym)
   692  					declare(nn, dclcontext)
   693  					stmt.Rlist.Set1(nn)
   694  
   695  					// keep track of the instances for reporting unused
   696  					nn.Name.Defn = tswitch
   697  				}
   698  			}
   699  
   700  			p.next() // consume ':' after declaring type switch var for correct lineno
   701  			return stmt
   702  
   703  		case '=':
   704  			// LCASE expr_or_type_list '=' expr ':'
   705  			p.next()
   706  			rhs := p.expr()
   707  
   708  			// will be converted to OCASE
   709  			// right will point to next case
   710  			// done in casebody()
   711  			markdcl() // matching popdcl in caseblock
   712  			stmt := Nod(OXCASE, nil, nil)
   713  			var n *Node
   714  			if len(cases) == 1 {
   715  				n = Nod(OAS, cases[0], rhs)
   716  			} else {
   717  				n = Nod(OAS2, nil, nil)
   718  				n.List.Set(cases)
   719  				n.Rlist.Set1(rhs)
   720  			}
   721  			stmt.List.Set1(n)
   722  
   723  			p.want(':') // consume ':' after declaring select cases for correct lineno
   724  			return stmt
   725  
   726  		case LCOLAS:
   727  			// LCASE expr_or_type_list LCOLAS expr ':'
   728  			lno := lineno
   729  			p.next()
   730  			rhs := p.expr()
   731  
   732  			// will be converted to OCASE
   733  			// right will point to next case
   734  			// done in casebody()
   735  			markdcl() // matching popdcl in caseblock
   736  			stmt := Nod(OXCASE, nil, nil)
   737  			stmt.List.Set1(colas(cases, []*Node{rhs}, lno))
   738  
   739  			p.want(':') // consume ':' after declaring select cases for correct lineno
   740  			return stmt
   741  
   742  		default:
   743  			markdcl()                     // for matching popdcl in caseblock
   744  			stmt := Nod(OXCASE, nil, nil) // don't return nil
   745  			p.syntax_error("expecting := or = or : or comma")
   746  			p.advance(LCASE, LDEFAULT, '}')
   747  			return stmt
   748  		}
   749  
   750  	case LDEFAULT:
   751  		// LDEFAULT ':'
   752  		p.next()
   753  
   754  		markdcl() // matching popdcl in caseblock
   755  		stmt := Nod(OXCASE, nil, nil)
   756  		if tswitch != nil {
   757  			if n := tswitch.Left; n != nil {
   758  				// type switch - declare variable
   759  				nn := newname(n.Sym)
   760  				declare(nn, dclcontext)
   761  				stmt.Rlist.Set1(nn)
   762  
   763  				// keep track of the instances for reporting unused
   764  				nn.Name.Defn = tswitch
   765  			}
   766  		}
   767  
   768  		p.want(':') // consume ':' after declaring type switch var for correct lineno
   769  		return stmt
   770  
   771  	default:
   772  		markdcl()                     // matching popdcl in caseblock
   773  		stmt := Nod(OXCASE, nil, nil) // don't return nil
   774  		p.syntax_error("expecting case or default or }")
   775  		p.advance(LCASE, LDEFAULT, '}')
   776  		return stmt
   777  	}
   778  }
   779  
   780  // Block         = "{" StatementList "}" .
   781  // StatementList = { Statement ";" } .
   782  func (p *parser) compound_stmt() *Node {
   783  	if trace && Debug['x'] != 0 {
   784  		defer p.trace("compound_stmt")()
   785  	}
   786  
   787  	markdcl()
   788  	p.want('{')
   789  	l := p.stmt_list()
   790  	p.want('}')
   791  	popdcl()
   792  
   793  	if len(l) == 0 {
   794  		return Nod(OEMPTY, nil, nil)
   795  	}
   796  	return liststmt(l)
   797  }
   798  
   799  // caseblock parses a superset of switch and select clauses.
   800  //
   801  // ExprCaseClause = ExprSwitchCase ":" StatementList .
   802  // TypeCaseClause = TypeSwitchCase ":" StatementList .
   803  // CommClause     = CommCase ":" StatementList .
   804  func (p *parser) caseblock(tswitch *Node) *Node {
   805  	if trace && Debug['x'] != 0 {
   806  		defer p.trace("caseblock")()
   807  	}
   808  
   809  	stmt := p.case_(tswitch) // does markdcl
   810  	stmt.Xoffset = int64(block)
   811  	stmt.Nbody.Set(p.stmt_list())
   812  
   813  	popdcl()
   814  
   815  	return stmt
   816  }
   817  
   818  // caseblock_list parses a superset of switch and select clause lists.
   819  func (p *parser) caseblock_list(tswitch *Node) (l []*Node) {
   820  	if trace && Debug['x'] != 0 {
   821  		defer p.trace("caseblock_list")()
   822  	}
   823  
   824  	if !p.got('{') {
   825  		p.syntax_error("missing { after switch clause")
   826  		p.advance(LCASE, LDEFAULT, '}')
   827  	}
   828  
   829  	for p.tok != EOF && p.tok != '}' {
   830  		l = append(l, p.caseblock(tswitch))
   831  	}
   832  	p.want('}')
   833  	return
   834  }
   835  
   836  // loop_body parses if and for statement bodies.
   837  func (p *parser) loop_body(context string) []*Node {
   838  	if trace && Debug['x'] != 0 {
   839  		defer p.trace("loop_body")()
   840  	}
   841  
   842  	markdcl()
   843  	if !p.got('{') {
   844  		p.syntax_error("missing { after " + context)
   845  		p.advance(LNAME, '}')
   846  	}
   847  
   848  	body := p.stmt_list()
   849  	popdcl()
   850  	p.want('}')
   851  
   852  	return body
   853  }
   854  
   855  // for_header parses the header portion of a for statement.
   856  //
   857  // ForStmt   = "for" [ Condition | ForClause | RangeClause ] Block .
   858  // Condition = Expression .
   859  func (p *parser) for_header() *Node {
   860  	if trace && Debug['x'] != 0 {
   861  		defer p.trace("for_header")()
   862  	}
   863  
   864  	init, cond, post := p.header(true)
   865  
   866  	if init != nil || post != nil {
   867  		// init ; test ; incr
   868  		if post != nil && post.Colas {
   869  			Yyerror("cannot declare in the for-increment")
   870  		}
   871  		h := Nod(OFOR, nil, nil)
   872  		if init != nil {
   873  			h.Ninit.Set1(init)
   874  		}
   875  		h.Left = cond
   876  		h.Right = post
   877  		return h
   878  	}
   879  
   880  	if cond != nil && cond.Op == ORANGE {
   881  		// range_stmt - handled by pexpr
   882  		return cond
   883  	}
   884  
   885  	// normal test
   886  	h := Nod(OFOR, nil, nil)
   887  	h.Left = cond
   888  	return h
   889  }
   890  
   891  func (p *parser) for_body() *Node {
   892  	if trace && Debug['x'] != 0 {
   893  		defer p.trace("for_body")()
   894  	}
   895  
   896  	stmt := p.for_header()
   897  	body := p.loop_body("for clause")
   898  
   899  	stmt.Nbody.Append(body...)
   900  	return stmt
   901  }
   902  
   903  // ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
   904  func (p *parser) for_stmt() *Node {
   905  	if trace && Debug['x'] != 0 {
   906  		defer p.trace("for_stmt")()
   907  	}
   908  
   909  	p.want(LFOR)
   910  	markdcl()
   911  	body := p.for_body()
   912  	popdcl()
   913  
   914  	return body
   915  }
   916  
   917  // header parses a combination of if, switch, and for statement headers:
   918  //
   919  // Header   = [ InitStmt ";" ] [ Expression ] .
   920  // Header   = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .  // for_stmt only
   921  // InitStmt = SimpleStmt .
   922  // PostStmt = SimpleStmt .
   923  func (p *parser) header(for_stmt bool) (init, cond, post *Node) {
   924  	if p.tok == '{' {
   925  		return
   926  	}
   927  
   928  	outer := p.xnest
   929  	p.xnest = -1
   930  
   931  	if p.tok != ';' {
   932  		// accept potential vardcl but complain
   933  		// (for test/syntax/forvar.go)
   934  		if for_stmt && p.tok == LVAR {
   935  			Yyerror("var declaration not allowed in for initializer")
   936  			p.next()
   937  		}
   938  		init = p.simple_stmt(false, for_stmt)
   939  		// If we have a range clause, we are done.
   940  		if for_stmt && init.Op == ORANGE {
   941  			cond = init
   942  			init = nil
   943  
   944  			p.xnest = outer
   945  			return
   946  		}
   947  	}
   948  	if p.got(';') {
   949  		if for_stmt {
   950  			if p.tok != ';' {
   951  				cond = p.simple_stmt(false, false)
   952  			}
   953  			p.want(';')
   954  			if p.tok != '{' {
   955  				post = p.simple_stmt(false, false)
   956  			}
   957  		} else if p.tok != '{' {
   958  			cond = p.simple_stmt(false, false)
   959  		}
   960  	} else {
   961  		cond = init
   962  		init = nil
   963  	}
   964  
   965  	p.xnest = outer
   966  	return
   967  }
   968  
   969  func (p *parser) if_header() *Node {
   970  	if trace && Debug['x'] != 0 {
   971  		defer p.trace("if_header")()
   972  	}
   973  
   974  	init, cond, _ := p.header(false)
   975  	h := Nod(OIF, nil, nil)
   976  	if init != nil {
   977  		h.Ninit.Set1(init)
   978  	}
   979  	h.Left = cond
   980  	return h
   981  }
   982  
   983  // IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
   984  func (p *parser) if_stmt() *Node {
   985  	if trace && Debug['x'] != 0 {
   986  		defer p.trace("if_stmt")()
   987  	}
   988  
   989  	p.want(LIF)
   990  
   991  	markdcl()
   992  
   993  	stmt := p.if_header()
   994  	if stmt.Left == nil {
   995  		Yyerror("missing condition in if statement")
   996  	}
   997  
   998  	stmt.Nbody.Set(p.loop_body("if clause"))
   999  
  1000  	if p.got(LELSE) {
  1001  		switch p.tok {
  1002  		case LIF:
  1003  			stmt.Rlist.Set1(p.if_stmt())
  1004  		case '{':
  1005  			cs := p.compound_stmt()
  1006  			if cs.Op == OBLOCK && cs.Ninit.Len() == 0 {
  1007  				stmt.Rlist.Set(cs.List.Slice())
  1008  			} else {
  1009  				stmt.Rlist.Set1(cs)
  1010  			}
  1011  		default:
  1012  			p.syntax_error("else must be followed by if or statement block")
  1013  			p.advance(LNAME, '}')
  1014  		}
  1015  	}
  1016  
  1017  	popdcl()
  1018  	return stmt
  1019  }
  1020  
  1021  // switch_stmt parses both expression and type switch statements.
  1022  //
  1023  // SwitchStmt     = ExprSwitchStmt | TypeSwitchStmt .
  1024  // ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
  1025  // TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
  1026  func (p *parser) switch_stmt() *Node {
  1027  	if trace && Debug['x'] != 0 {
  1028  		defer p.trace("switch_stmt")()
  1029  	}
  1030  
  1031  	p.want(LSWITCH)
  1032  	markdcl()
  1033  
  1034  	hdr := p.if_header()
  1035  	hdr.Op = OSWITCH
  1036  
  1037  	tswitch := hdr.Left
  1038  	if tswitch != nil && tswitch.Op != OTYPESW {
  1039  		tswitch = nil
  1040  	}
  1041  
  1042  	hdr.List.Set(p.caseblock_list(tswitch))
  1043  	popdcl()
  1044  
  1045  	return hdr
  1046  }
  1047  
  1048  // SelectStmt = "select" "{" { CommClause } "}" .
  1049  func (p *parser) select_stmt() *Node {
  1050  	if trace && Debug['x'] != 0 {
  1051  		defer p.trace("select_stmt")()
  1052  	}
  1053  
  1054  	p.want(LSELECT)
  1055  	hdr := Nod(OSELECT, nil, nil)
  1056  	hdr.List.Set(p.caseblock_list(nil))
  1057  	return hdr
  1058  }
  1059  
  1060  // Expression = UnaryExpr | Expression binary_op Expression .
  1061  func (p *parser) bexpr(prec OpPrec) *Node {
  1062  	// don't trace bexpr - only leads to overly nested trace output
  1063  
  1064  	// prec is precedence of the prior/enclosing binary operator (if any),
  1065  	// so we only want to parse tokens of greater precedence.
  1066  
  1067  	x := p.uexpr()
  1068  	for p.prec > prec {
  1069  		op, prec1 := p.op, p.prec
  1070  		p.next()
  1071  		x = Nod(op, x, p.bexpr(prec1))
  1072  	}
  1073  	return x
  1074  }
  1075  
  1076  func (p *parser) expr() *Node {
  1077  	if trace && Debug['x'] != 0 {
  1078  		defer p.trace("expr")()
  1079  	}
  1080  
  1081  	return p.bexpr(0)
  1082  }
  1083  
  1084  func unparen(x *Node) *Node {
  1085  	for x.Op == OPAREN {
  1086  		x = x.Left
  1087  	}
  1088  	return x
  1089  }
  1090  
  1091  // UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
  1092  func (p *parser) uexpr() *Node {
  1093  	if trace && Debug['x'] != 0 {
  1094  		defer p.trace("uexpr")()
  1095  	}
  1096  
  1097  	var op Op
  1098  	switch p.tok {
  1099  	case '*':
  1100  		op = OIND
  1101  
  1102  	case '&':
  1103  		p.next()
  1104  		// uexpr may have returned a parenthesized composite literal
  1105  		// (see comment in operand) - remove parentheses if any
  1106  		x := unparen(p.uexpr())
  1107  		if x.Op == OCOMPLIT {
  1108  			// Special case for &T{...}: turn into (*T){...}.
  1109  			x.Right = Nod(OIND, x.Right, nil)
  1110  			x.Right.Implicit = true
  1111  		} else {
  1112  			x = Nod(OADDR, x, nil)
  1113  		}
  1114  		return x
  1115  
  1116  	case '+':
  1117  		op = OPLUS
  1118  
  1119  	case '-':
  1120  		op = OMINUS
  1121  
  1122  	case '!':
  1123  		op = ONOT
  1124  
  1125  	case '^':
  1126  		op = OCOM
  1127  
  1128  	case LCOMM:
  1129  		// receive op (<-x) or receive-only channel (<-chan E)
  1130  		p.next()
  1131  
  1132  		// If the next token is LCHAN we still don't know if it is
  1133  		// a channel (<-chan int) or a receive op (<-chan int(ch)).
  1134  		// We only know once we have found the end of the uexpr.
  1135  
  1136  		x := p.uexpr()
  1137  
  1138  		// There are two cases:
  1139  		//
  1140  		//   <-chan...  => <-x is a channel type
  1141  		//   <-x        => <-x is a receive operation
  1142  		//
  1143  		// In the first case, <- must be re-associated with
  1144  		// the channel type parsed already:
  1145  		//
  1146  		//   <-(chan E)   =>  (<-chan E)
  1147  		//   <-(chan<-E)  =>  (<-chan (<-E))
  1148  
  1149  		if x.Op == OTCHAN {
  1150  			// x is a channel type => re-associate <-
  1151  			dir := Csend
  1152  			t := x
  1153  			for ; t.Op == OTCHAN && dir == Csend; t = t.Left {
  1154  				dir = ChanDir(t.Etype)
  1155  				if dir == Crecv {
  1156  					// t is type <-chan E but <-<-chan E is not permitted
  1157  					// (report same error as for "type _ <-<-chan E")
  1158  					p.syntax_error("unexpected <-, expecting chan")
  1159  					// already progressed, no need to advance
  1160  				}
  1161  				t.Etype = EType(Crecv)
  1162  			}
  1163  			if dir == Csend {
  1164  				// channel dir is <- but channel element E is not a channel
  1165  				// (report same error as for "type _ <-chan<-E")
  1166  				p.syntax_error(fmt.Sprintf("unexpected %v, expecting chan", t))
  1167  				// already progressed, no need to advance
  1168  			}
  1169  			return x
  1170  		}
  1171  
  1172  		// x is not a channel type => we have a receive op
  1173  		return Nod(ORECV, x, nil)
  1174  
  1175  	default:
  1176  		return p.pexpr(false)
  1177  	}
  1178  
  1179  	// simple uexpr
  1180  	p.next()
  1181  	return Nod(op, p.uexpr(), nil)
  1182  }
  1183  
  1184  // pseudocall parses call-like statements that can be preceded by 'defer' and 'go'.
  1185  func (p *parser) pseudocall() *Node {
  1186  	if trace && Debug['x'] != 0 {
  1187  		defer p.trace("pseudocall")()
  1188  	}
  1189  
  1190  	x := p.pexpr(p.tok == '(') // keep_parens so we can report error below
  1191  	switch x.Op {
  1192  	case OCALL:
  1193  		return x
  1194  	case OPAREN:
  1195  		Yyerror("expression in go/defer must not be parenthesized")
  1196  		// already progressed, no need to advance
  1197  	default:
  1198  		Yyerror("expression in go/defer must be function call")
  1199  		// already progressed, no need to advance
  1200  	}
  1201  	return nil
  1202  }
  1203  
  1204  // Operand     = Literal | OperandName | MethodExpr | "(" Expression ")" .
  1205  // Literal     = BasicLit | CompositeLit | FunctionLit .
  1206  // BasicLit    = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
  1207  // OperandName = identifier | QualifiedIdent.
  1208  func (p *parser) operand(keep_parens bool) *Node {
  1209  	if trace && Debug['x'] != 0 {
  1210  		defer p.trace("operand")()
  1211  	}
  1212  
  1213  	switch p.tok {
  1214  	case LLITERAL:
  1215  		x := nodlit(p.val)
  1216  		p.next()
  1217  		return x
  1218  
  1219  	case LNAME:
  1220  		return p.name()
  1221  
  1222  	case '(':
  1223  		p.next()
  1224  		p.xnest++
  1225  		x := p.expr() // expr_or_type
  1226  		p.xnest--
  1227  		p.want(')')
  1228  
  1229  		// Optimization: Record presence of ()'s only where needed
  1230  		// for error reporting. Don't bother in other cases; it is
  1231  		// just a waste of memory and time.
  1232  
  1233  		// Parentheses are not permitted on lhs of := .
  1234  		switch x.Op {
  1235  		case ONAME, ONONAME, OPACK, OTYPE, OLITERAL, OTYPESW:
  1236  			keep_parens = true
  1237  		}
  1238  
  1239  		// Parentheses are not permitted around T in a composite
  1240  		// literal T{}. If the next token is a {, assume x is a
  1241  		// composite literal type T (it may not be, { could be
  1242  		// the opening brace of a block, but we don't know yet).
  1243  		if p.tok == '{' {
  1244  			keep_parens = true
  1245  		}
  1246  
  1247  		// Parentheses are also not permitted around the expression
  1248  		// in a go/defer statement. In that case, operand is called
  1249  		// with keep_parens set.
  1250  		if keep_parens {
  1251  			x = Nod(OPAREN, x, nil)
  1252  		}
  1253  		return x
  1254  
  1255  	case LFUNC:
  1256  		t := p.ntype() // fntype
  1257  		if p.tok == '{' {
  1258  			// fnlitdcl
  1259  			closurehdr(t)
  1260  			// fnliteral
  1261  			p.next() // consume '{'
  1262  			p.fnest++
  1263  			p.xnest++
  1264  			body := p.stmt_list()
  1265  			p.xnest--
  1266  			p.fnest--
  1267  			p.want('}')
  1268  			return closurebody(body)
  1269  		}
  1270  		return t
  1271  
  1272  	case '[', LCHAN, LMAP, LSTRUCT, LINTERFACE:
  1273  		return p.ntype() // othertype
  1274  
  1275  	case '{':
  1276  		// common case: p.header is missing simple_stmt before { in if, for, switch
  1277  		p.syntax_error("missing operand")
  1278  		// '{' will be consumed in pexpr - no need to consume it here
  1279  		return nil
  1280  
  1281  	default:
  1282  		p.syntax_error("expecting expression")
  1283  		p.advance()
  1284  		return nil
  1285  	}
  1286  
  1287  	// Syntactically, composite literals are operands. Because a complit
  1288  	// type may be a qualified identifier which is handled by pexpr
  1289  	// (together with selector expressions), complits are parsed there
  1290  	// as well (operand is only called from pexpr).
  1291  }
  1292  
  1293  // PrimaryExpr =
  1294  // 	Operand |
  1295  // 	Conversion |
  1296  // 	PrimaryExpr Selector |
  1297  // 	PrimaryExpr Index |
  1298  // 	PrimaryExpr Slice |
  1299  // 	PrimaryExpr TypeAssertion |
  1300  // 	PrimaryExpr Arguments .
  1301  //
  1302  // Selector       = "." identifier .
  1303  // Index          = "[" Expression "]" .
  1304  // Slice          = "[" ( [ Expression ] ":" [ Expression ] ) |
  1305  //                      ( [ Expression ] ":" Expression ":" Expression )
  1306  //                  "]" .
  1307  // TypeAssertion  = "." "(" Type ")" .
  1308  // Arguments      = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
  1309  func (p *parser) pexpr(keep_parens bool) *Node {
  1310  	if trace && Debug['x'] != 0 {
  1311  		defer p.trace("pexpr")()
  1312  	}
  1313  
  1314  	x := p.operand(keep_parens)
  1315  
  1316  loop:
  1317  	for {
  1318  		switch p.tok {
  1319  		case '.':
  1320  			p.next()
  1321  			switch p.tok {
  1322  			case LNAME:
  1323  				// pexpr '.' sym
  1324  				x = p.new_dotname(x)
  1325  
  1326  			case '(':
  1327  				p.next()
  1328  				switch p.tok {
  1329  				default:
  1330  					// pexpr '.' '(' expr_or_type ')'
  1331  					t := p.expr() // expr_or_type
  1332  					p.want(')')
  1333  					x = Nod(ODOTTYPE, x, t)
  1334  
  1335  				case LTYPE:
  1336  					// pexpr '.' '(' LTYPE ')'
  1337  					p.next()
  1338  					p.want(')')
  1339  					x = Nod(OTYPESW, nil, x)
  1340  				}
  1341  
  1342  			default:
  1343  				p.syntax_error("expecting name or (")
  1344  				p.advance(';', '}')
  1345  			}
  1346  
  1347  		case '[':
  1348  			p.next()
  1349  			p.xnest++
  1350  			var index [3]*Node
  1351  			if p.tok != ':' {
  1352  				index[0] = p.expr()
  1353  			}
  1354  			ncol := 0
  1355  			for ncol < len(index)-1 && p.got(':') {
  1356  				ncol++
  1357  				if p.tok != EOF && p.tok != ':' && p.tok != ']' {
  1358  					index[ncol] = p.expr()
  1359  				}
  1360  			}
  1361  			p.xnest--
  1362  			p.want(']')
  1363  
  1364  			switch ncol {
  1365  			case 0:
  1366  				i := index[0]
  1367  				if i == nil {
  1368  					Yyerror("missing index in index expression")
  1369  				}
  1370  				x = Nod(OINDEX, x, i)
  1371  			case 1:
  1372  				x = Nod(OSLICE, x, nil)
  1373  				x.SetSliceBounds(index[0], index[1], nil)
  1374  			case 2:
  1375  				if index[1] == nil {
  1376  					Yyerror("middle index required in 3-index slice")
  1377  				}
  1378  				if index[2] == nil {
  1379  					Yyerror("final index required in 3-index slice")
  1380  				}
  1381  				x = Nod(OSLICE3, x, nil)
  1382  				x.SetSliceBounds(index[0], index[1], index[2])
  1383  
  1384  			default:
  1385  				panic("unreachable")
  1386  			}
  1387  
  1388  		case '(':
  1389  			// convtype '(' expr ocomma ')'
  1390  			args, ddd := p.arg_list()
  1391  
  1392  			// call or conversion
  1393  			x = Nod(OCALL, x, nil)
  1394  			x.List.Set(args)
  1395  			x.Isddd = ddd
  1396  
  1397  		case '{':
  1398  			// operand may have returned a parenthesized complit
  1399  			// type; accept it but complain if we have a complit
  1400  			t := unparen(x)
  1401  			// determine if '{' belongs to a complit or a compound_stmt
  1402  			complit_ok := false
  1403  			switch t.Op {
  1404  			case ONAME, ONONAME, OTYPE, OPACK, OXDOT, ODOT:
  1405  				if p.xnest >= 0 {
  1406  					// x is considered a comptype
  1407  					complit_ok = true
  1408  				}
  1409  			case OTARRAY, OTSTRUCT, OTMAP:
  1410  				// x is a comptype
  1411  				complit_ok = true
  1412  			}
  1413  			if !complit_ok {
  1414  				break loop
  1415  			}
  1416  			if t != x {
  1417  				p.syntax_error("cannot parenthesize type in composite literal")
  1418  				// already progressed, no need to advance
  1419  			}
  1420  			n := p.complitexpr()
  1421  			n.Right = x
  1422  			x = n
  1423  
  1424  		default:
  1425  			break loop
  1426  		}
  1427  	}
  1428  
  1429  	return x
  1430  }
  1431  
  1432  // KeyedElement = [ Key ":" ] Element .
  1433  func (p *parser) keyval() *Node {
  1434  	if trace && Debug['x'] != 0 {
  1435  		defer p.trace("keyval")()
  1436  	}
  1437  
  1438  	// A composite literal commonly spans several lines,
  1439  	// so the line number on errors may be misleading.
  1440  	// Wrap values (but not keys!) that don't carry line
  1441  	// numbers.
  1442  
  1443  	x := p.bare_complitexpr()
  1444  
  1445  	if p.got(':') {
  1446  		// key ':' value
  1447  		return Nod(OKEY, x, wrapname(p.bare_complitexpr()))
  1448  	}
  1449  
  1450  	// value
  1451  	return wrapname(x)
  1452  }
  1453  
  1454  func wrapname(x *Node) *Node {
  1455  	// These nodes do not carry line numbers.
  1456  	// Introduce a wrapper node to give the correct line.
  1457  	switch x.Op {
  1458  	case ONAME, ONONAME, OTYPE, OPACK, OLITERAL:
  1459  		x = Nod(OPAREN, x, nil)
  1460  		x.Implicit = true
  1461  	}
  1462  	return x
  1463  }
  1464  
  1465  // Element = Expression | LiteralValue .
  1466  func (p *parser) bare_complitexpr() *Node {
  1467  	if trace && Debug['x'] != 0 {
  1468  		defer p.trace("bare_complitexpr")()
  1469  	}
  1470  
  1471  	if p.tok == '{' {
  1472  		// '{' start_complit braced_keyval_list '}'
  1473  		return p.complitexpr()
  1474  	}
  1475  
  1476  	return p.expr()
  1477  }
  1478  
  1479  // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
  1480  func (p *parser) complitexpr() *Node {
  1481  	if trace && Debug['x'] != 0 {
  1482  		defer p.trace("complitexpr")()
  1483  	}
  1484  
  1485  	// make node early so we get the right line number
  1486  	n := Nod(OCOMPLIT, nil, nil)
  1487  
  1488  	p.want('{')
  1489  	p.xnest++
  1490  
  1491  	var l []*Node
  1492  	for p.tok != EOF && p.tok != '}' {
  1493  		l = append(l, p.keyval())
  1494  		if !p.ocomma('}') {
  1495  			break
  1496  		}
  1497  	}
  1498  
  1499  	p.xnest--
  1500  	p.want('}')
  1501  
  1502  	n.List.Set(l)
  1503  	return n
  1504  }
  1505  
  1506  // names and types
  1507  //	newname is used before declared
  1508  //	oldname is used after declared
  1509  func (p *parser) new_name(sym *Sym) *Node {
  1510  	if trace && Debug['x'] != 0 {
  1511  		defer p.trace("new_name")()
  1512  	}
  1513  
  1514  	if sym != nil {
  1515  		return newname(sym)
  1516  	}
  1517  	return nil
  1518  }
  1519  
  1520  func (p *parser) dcl_name() *Node {
  1521  	if trace && Debug['x'] != 0 {
  1522  		defer p.trace("dcl_name")()
  1523  	}
  1524  
  1525  	symlineno := lineno
  1526  	sym := p.sym()
  1527  	if sym == nil {
  1528  		yyerrorl(symlineno, "invalid declaration")
  1529  		return nil
  1530  	}
  1531  	return dclname(sym)
  1532  }
  1533  
  1534  func (p *parser) onew_name() *Node {
  1535  	if trace && Debug['x'] != 0 {
  1536  		defer p.trace("onew_name")()
  1537  	}
  1538  
  1539  	if p.tok == LNAME {
  1540  		return p.new_name(p.sym())
  1541  	}
  1542  	return nil
  1543  }
  1544  
  1545  func (p *parser) sym() *Sym {
  1546  	if p.tok == LNAME {
  1547  		s := p.sym_ // from localpkg
  1548  		p.next()
  1549  		return s
  1550  	}
  1551  
  1552  	p.syntax_error("expecting name")
  1553  	p.advance()
  1554  	return new(Sym)
  1555  }
  1556  
  1557  func mkname(sym *Sym) *Node {
  1558  	n := oldname(sym)
  1559  	if n.Name != nil && n.Name.Pack != nil {
  1560  		n.Name.Pack.Used = true
  1561  	}
  1562  	return n
  1563  }
  1564  
  1565  func (p *parser) name() *Node {
  1566  	if trace && Debug['x'] != 0 {
  1567  		defer p.trace("name")()
  1568  	}
  1569  
  1570  	return mkname(p.sym())
  1571  }
  1572  
  1573  // [ "..." ] Type
  1574  func (p *parser) dotdotdot() *Node {
  1575  	if trace && Debug['x'] != 0 {
  1576  		defer p.trace("dotdotdot")()
  1577  	}
  1578  
  1579  	p.want(LDDD)
  1580  	if typ := p.try_ntype(); typ != nil {
  1581  		return Nod(ODDD, typ, nil)
  1582  	}
  1583  
  1584  	Yyerror("final argument in variadic function missing type")
  1585  	return Nod(ODDD, typenod(typ(TINTER)), nil)
  1586  }
  1587  
  1588  func (p *parser) ntype() *Node {
  1589  	if trace && Debug['x'] != 0 {
  1590  		defer p.trace("ntype")()
  1591  	}
  1592  
  1593  	if typ := p.try_ntype(); typ != nil {
  1594  		return typ
  1595  	}
  1596  
  1597  	p.syntax_error("")
  1598  	p.advance()
  1599  	return nil
  1600  }
  1601  
  1602  // signature parses a function signature and returns an OTFUNC node.
  1603  //
  1604  // Signature = Parameters [ Result ] .
  1605  func (p *parser) signature(recv *Node) *Node {
  1606  	if trace && Debug['x'] != 0 {
  1607  		defer p.trace("signature")()
  1608  	}
  1609  
  1610  	params := p.param_list(true)
  1611  
  1612  	var result []*Node
  1613  	if p.tok == '(' {
  1614  		result = p.param_list(false)
  1615  	} else if t := p.try_ntype(); t != nil {
  1616  		result = []*Node{Nod(ODCLFIELD, nil, t)}
  1617  	}
  1618  
  1619  	typ := Nod(OTFUNC, recv, nil)
  1620  	typ.List.Set(params)
  1621  	typ.Rlist.Set(result)
  1622  
  1623  	return typ
  1624  }
  1625  
  1626  // try_ntype is like ntype but it returns nil if there was no type
  1627  // instead of reporting an error.
  1628  //
  1629  // Type     = TypeName | TypeLit | "(" Type ")" .
  1630  // TypeName = identifier | QualifiedIdent .
  1631  // TypeLit  = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
  1632  // 	      SliceType | MapType | ChannelType .
  1633  func (p *parser) try_ntype() *Node {
  1634  	if trace && Debug['x'] != 0 {
  1635  		defer p.trace("try_ntype")()
  1636  	}
  1637  
  1638  	switch p.tok {
  1639  	case LCOMM:
  1640  		// recvchantype
  1641  		p.next()
  1642  		p.want(LCHAN)
  1643  		t := Nod(OTCHAN, p.chan_elem(), nil)
  1644  		t.Etype = EType(Crecv)
  1645  		return t
  1646  
  1647  	case LFUNC:
  1648  		// fntype
  1649  		p.next()
  1650  		return p.signature(nil)
  1651  
  1652  	case '[':
  1653  		// '[' oexpr ']' ntype
  1654  		// '[' LDDD ']' ntype
  1655  		p.next()
  1656  		p.xnest++
  1657  		var len *Node
  1658  		if p.tok != ']' {
  1659  			if p.got(LDDD) {
  1660  				len = Nod(ODDD, nil, nil)
  1661  			} else {
  1662  				len = p.expr()
  1663  			}
  1664  		}
  1665  		p.xnest--
  1666  		p.want(']')
  1667  		return Nod(OTARRAY, len, p.ntype())
  1668  
  1669  	case LCHAN:
  1670  		// LCHAN non_recvchantype
  1671  		// LCHAN LCOMM ntype
  1672  		p.next()
  1673  		var dir = EType(Cboth)
  1674  		if p.got(LCOMM) {
  1675  			dir = EType(Csend)
  1676  		}
  1677  		t := Nod(OTCHAN, p.chan_elem(), nil)
  1678  		t.Etype = dir
  1679  		return t
  1680  
  1681  	case LMAP:
  1682  		// LMAP '[' ntype ']' ntype
  1683  		p.next()
  1684  		p.want('[')
  1685  		key := p.ntype()
  1686  		p.want(']')
  1687  		val := p.ntype()
  1688  		return Nod(OTMAP, key, val)
  1689  
  1690  	case LSTRUCT:
  1691  		return p.structtype()
  1692  
  1693  	case LINTERFACE:
  1694  		return p.interfacetype()
  1695  
  1696  	case '*':
  1697  		// ptrtype
  1698  		p.next()
  1699  		return Nod(OIND, p.ntype(), nil)
  1700  
  1701  	case LNAME:
  1702  		return p.dotname()
  1703  
  1704  	case '(':
  1705  		p.next()
  1706  		t := p.ntype()
  1707  		p.want(')')
  1708  		return t
  1709  
  1710  	default:
  1711  		return nil
  1712  	}
  1713  }
  1714  
  1715  func (p *parser) chan_elem() *Node {
  1716  	if trace && Debug['x'] != 0 {
  1717  		defer p.trace("chan_elem")()
  1718  	}
  1719  
  1720  	if typ := p.try_ntype(); typ != nil {
  1721  		return typ
  1722  	}
  1723  
  1724  	p.syntax_error("missing channel element type")
  1725  	// assume element type is simply absent - don't advance
  1726  	return nil
  1727  }
  1728  
  1729  func (p *parser) new_dotname(obj *Node) *Node {
  1730  	if trace && Debug['x'] != 0 {
  1731  		defer p.trace("new_dotname")()
  1732  	}
  1733  
  1734  	sel := p.sym()
  1735  	if obj.Op == OPACK {
  1736  		s := restrictlookup(sel.Name, obj.Name.Pkg)
  1737  		obj.Used = true
  1738  		return oldname(s)
  1739  	}
  1740  	return NodSym(OXDOT, obj, sel)
  1741  }
  1742  
  1743  func (p *parser) dotname() *Node {
  1744  	if trace && Debug['x'] != 0 {
  1745  		defer p.trace("dotname")()
  1746  	}
  1747  
  1748  	name := p.name()
  1749  	if p.got('.') {
  1750  		return p.new_dotname(name)
  1751  	}
  1752  	return name
  1753  }
  1754  
  1755  // StructType = "struct" "{" { FieldDecl ";" } "}" .
  1756  func (p *parser) structtype() *Node {
  1757  	if trace && Debug['x'] != 0 {
  1758  		defer p.trace("structtype")()
  1759  	}
  1760  
  1761  	p.want(LSTRUCT)
  1762  	p.want('{')
  1763  	var l []*Node
  1764  	for p.tok != EOF && p.tok != '}' {
  1765  		l = append(l, p.structdcl()...)
  1766  		if !p.osemi('}') {
  1767  			break
  1768  		}
  1769  	}
  1770  	p.want('}')
  1771  
  1772  	t := Nod(OTSTRUCT, nil, nil)
  1773  	t.List.Set(l)
  1774  	return t
  1775  }
  1776  
  1777  // InterfaceType = "interface" "{" { MethodSpec ";" } "}" .
  1778  func (p *parser) interfacetype() *Node {
  1779  	if trace && Debug['x'] != 0 {
  1780  		defer p.trace("interfacetype")()
  1781  	}
  1782  
  1783  	p.want(LINTERFACE)
  1784  	p.want('{')
  1785  	var l []*Node
  1786  	for p.tok != EOF && p.tok != '}' {
  1787  		l = append(l, p.interfacedcl())
  1788  		if !p.osemi('}') {
  1789  			break
  1790  		}
  1791  	}
  1792  	p.want('}')
  1793  
  1794  	t := Nod(OTINTER, nil, nil)
  1795  	t.List.Set(l)
  1796  	return t
  1797  }
  1798  
  1799  // Function stuff.
  1800  // All in one place to show how crappy it all is.
  1801  
  1802  func (p *parser) xfndcl() *Node {
  1803  	if trace && Debug['x'] != 0 {
  1804  		defer p.trace("xfndcl")()
  1805  	}
  1806  
  1807  	p.want(LFUNC)
  1808  	f := p.fndcl()
  1809  	body := p.fnbody()
  1810  
  1811  	if f == nil {
  1812  		return nil
  1813  	}
  1814  
  1815  	f.Nbody.Set(body)
  1816  	f.Noescape = p.pragma&Noescape != 0
  1817  	if f.Noescape && len(body) != 0 {
  1818  		Yyerror("can only use //go:noescape with external func implementations")
  1819  	}
  1820  	f.Func.Pragma = p.pragma
  1821  	f.Func.Endlineno = lineno
  1822  
  1823  	funcbody(f)
  1824  
  1825  	return f
  1826  }
  1827  
  1828  // FunctionDecl = "func" FunctionName ( Function | Signature ) .
  1829  // FunctionName = identifier .
  1830  // Function     = Signature FunctionBody .
  1831  // MethodDecl   = "func" Receiver MethodName ( Function | Signature ) .
  1832  // Receiver     = Parameters .
  1833  func (p *parser) fndcl() *Node {
  1834  	if trace && Debug['x'] != 0 {
  1835  		defer p.trace("fndcl")()
  1836  	}
  1837  
  1838  	switch p.tok {
  1839  	case LNAME:
  1840  		// FunctionName Signature
  1841  		name := p.sym()
  1842  		t := p.signature(nil)
  1843  
  1844  		if name.Name == "init" {
  1845  			name = renameinit()
  1846  			if t.List.Len() > 0 || t.Rlist.Len() > 0 {
  1847  				Yyerror("func init must have no arguments and no return values")
  1848  			}
  1849  		}
  1850  
  1851  		if localpkg.Name == "main" && name.Name == "main" {
  1852  			if t.List.Len() > 0 || t.Rlist.Len() > 0 {
  1853  				Yyerror("func main must have no arguments and no return values")
  1854  			}
  1855  		}
  1856  
  1857  		f := Nod(ODCLFUNC, nil, nil)
  1858  		f.Func.Nname = newfuncname(name)
  1859  		f.Func.Nname.Name.Defn = f
  1860  		f.Func.Nname.Name.Param.Ntype = t // TODO: check if nname already has an ntype
  1861  		declare(f.Func.Nname, PFUNC)
  1862  
  1863  		funchdr(f)
  1864  		return f
  1865  
  1866  	case '(':
  1867  		// Receiver MethodName Signature
  1868  		rparam := p.param_list(false)
  1869  		var recv *Node
  1870  		if len(rparam) > 0 {
  1871  			recv = rparam[0]
  1872  		}
  1873  		name := p.sym()
  1874  		t := p.signature(recv)
  1875  
  1876  		// check after parsing header for fault-tolerance
  1877  		if recv == nil {
  1878  			Yyerror("method has no receiver")
  1879  			return nil
  1880  		}
  1881  
  1882  		if len(rparam) > 1 {
  1883  			Yyerror("method has multiple receivers")
  1884  			return nil
  1885  		}
  1886  
  1887  		if recv.Op != ODCLFIELD {
  1888  			Yyerror("bad receiver in method")
  1889  			return nil
  1890  		}
  1891  
  1892  		f := Nod(ODCLFUNC, nil, nil)
  1893  		f.Func.Shortname = newfuncname(name)
  1894  		f.Func.Nname = methodname(f.Func.Shortname, recv.Right)
  1895  		f.Func.Nname.Name.Defn = f
  1896  		f.Func.Nname.Name.Param.Ntype = t
  1897  		declare(f.Func.Nname, PFUNC)
  1898  
  1899  		funchdr(f)
  1900  		return f
  1901  
  1902  	default:
  1903  		p.syntax_error("expecting name or (")
  1904  		p.advance('{', ';')
  1905  		return nil
  1906  	}
  1907  }
  1908  
  1909  // FunctionBody = Block .
  1910  func (p *parser) fnbody() []*Node {
  1911  	if trace && Debug['x'] != 0 {
  1912  		defer p.trace("fnbody")()
  1913  	}
  1914  
  1915  	if p.got('{') {
  1916  		p.fnest++
  1917  		body := p.stmt_list()
  1918  		p.fnest--
  1919  		p.want('}')
  1920  		if body == nil {
  1921  			body = []*Node{Nod(OEMPTY, nil, nil)}
  1922  		}
  1923  		return body
  1924  	}
  1925  
  1926  	return nil
  1927  }
  1928  
  1929  // Declaration  = ConstDecl | TypeDecl | VarDecl .
  1930  // TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
  1931  func (p *parser) xdcl_list() (l []*Node) {
  1932  	if trace && Debug['x'] != 0 {
  1933  		defer p.trace("xdcl_list")()
  1934  	}
  1935  
  1936  	for p.tok != EOF {
  1937  		switch p.tok {
  1938  		case LVAR, LCONST, LTYPE:
  1939  			l = append(l, p.common_dcl()...)
  1940  
  1941  		case LFUNC:
  1942  			l = append(l, p.xfndcl())
  1943  
  1944  		default:
  1945  			if p.tok == '{' && len(l) != 0 && l[len(l)-1].Op == ODCLFUNC && l[len(l)-1].Nbody.Len() == 0 {
  1946  				// opening { of function declaration on next line
  1947  				p.syntax_error("unexpected semicolon or newline before {")
  1948  			} else {
  1949  				p.syntax_error("non-declaration statement outside function body")
  1950  			}
  1951  			p.advance(LVAR, LCONST, LTYPE, LFUNC)
  1952  			continue
  1953  		}
  1954  
  1955  		// Reset p.pragma BEFORE advancing to the next token (consuming ';')
  1956  		// since comments before may set pragmas for the next function decl.
  1957  		p.pragma = 0
  1958  
  1959  		if p.tok != EOF && !p.got(';') {
  1960  			p.syntax_error("after top level declaration")
  1961  			p.advance(LVAR, LCONST, LTYPE, LFUNC)
  1962  		}
  1963  	}
  1964  
  1965  	if nsyntaxerrors == 0 {
  1966  		testdclstack()
  1967  	}
  1968  	return
  1969  }
  1970  
  1971  // FieldDecl      = (IdentifierList Type | AnonymousField) [ Tag ] .
  1972  // AnonymousField = [ "*" ] TypeName .
  1973  // Tag            = string_lit .
  1974  func (p *parser) structdcl() []*Node {
  1975  	if trace && Debug['x'] != 0 {
  1976  		defer p.trace("structdcl")()
  1977  	}
  1978  
  1979  	var sym *Sym
  1980  	switch p.tok {
  1981  	case LNAME:
  1982  		sym = p.sym_
  1983  		p.next()
  1984  		if sym == nil {
  1985  			panic("unreachable") // we must have a sym for LNAME
  1986  		}
  1987  		if p.tok == '.' || p.tok == LLITERAL || p.tok == ';' || p.tok == '}' {
  1988  			// embed oliteral
  1989  			field := p.embed(sym)
  1990  			tag := p.oliteral()
  1991  
  1992  			field.SetVal(tag)
  1993  			return []*Node{field}
  1994  		}
  1995  
  1996  		// new_name_list ntype oliteral
  1997  		fields := p.new_name_list(sym)
  1998  		typ := p.ntype()
  1999  		tag := p.oliteral()
  2000  
  2001  		if len(fields) == 0 || fields[0].Sym.Name == "?" {
  2002  			// ? symbol, during import
  2003  			n := typ
  2004  			if n.Op == OIND {
  2005  				n = n.Left
  2006  			}
  2007  			n = embedded(n.Sym, importpkg)
  2008  			n.Right = typ
  2009  			n.SetVal(tag)
  2010  			return []*Node{n}
  2011  		}
  2012  
  2013  		for i, n := range fields {
  2014  			fields[i] = Nod(ODCLFIELD, n, typ)
  2015  			fields[i].SetVal(tag)
  2016  		}
  2017  		return fields
  2018  
  2019  	case '(':
  2020  		p.next()
  2021  		if p.got('*') {
  2022  			// '(' '*' embed ')' oliteral
  2023  			field := p.embed(nil)
  2024  			p.want(')')
  2025  			tag := p.oliteral()
  2026  
  2027  			field.Right = Nod(OIND, field.Right, nil)
  2028  			field.SetVal(tag)
  2029  			Yyerror("cannot parenthesize embedded type")
  2030  			return []*Node{field}
  2031  
  2032  		} else {
  2033  			// '(' embed ')' oliteral
  2034  			field := p.embed(nil)
  2035  			p.want(')')
  2036  			tag := p.oliteral()
  2037  
  2038  			field.SetVal(tag)
  2039  			Yyerror("cannot parenthesize embedded type")
  2040  			return []*Node{field}
  2041  		}
  2042  
  2043  	case '*':
  2044  		p.next()
  2045  		if p.got('(') {
  2046  			// '*' '(' embed ')' oliteral
  2047  			field := p.embed(nil)
  2048  			p.want(')')
  2049  			tag := p.oliteral()
  2050  
  2051  			field.Right = Nod(OIND, field.Right, nil)
  2052  			field.SetVal(tag)
  2053  			Yyerror("cannot parenthesize embedded type")
  2054  			return []*Node{field}
  2055  
  2056  		} else {
  2057  			// '*' embed oliteral
  2058  			field := p.embed(nil)
  2059  			tag := p.oliteral()
  2060  
  2061  			field.Right = Nod(OIND, field.Right, nil)
  2062  			field.SetVal(tag)
  2063  			return []*Node{field}
  2064  		}
  2065  
  2066  	default:
  2067  		p.syntax_error("expecting field name or embedded type")
  2068  		p.advance(';', '}')
  2069  		return nil
  2070  	}
  2071  }
  2072  
  2073  func (p *parser) oliteral() (v Val) {
  2074  	if p.tok == LLITERAL {
  2075  		v = p.val
  2076  		p.next()
  2077  	}
  2078  	return
  2079  }
  2080  
  2081  func (p *parser) packname(name *Sym) *Sym {
  2082  	if trace && Debug['x'] != 0 {
  2083  		defer p.trace("embed")()
  2084  	}
  2085  
  2086  	if name != nil {
  2087  		// LNAME was already consumed and is coming in as name
  2088  	} else if p.tok == LNAME {
  2089  		name = p.sym_
  2090  		p.next()
  2091  	} else {
  2092  		p.syntax_error("expecting name")
  2093  		p.advance('.', ';', '}')
  2094  		name = new(Sym)
  2095  	}
  2096  
  2097  	if p.got('.') {
  2098  		// LNAME '.' sym
  2099  		s := p.sym()
  2100  
  2101  		var pkg *Pkg
  2102  		if name.Def == nil || name.Def.Op != OPACK {
  2103  			Yyerror("%v is not a package", name)
  2104  			pkg = localpkg
  2105  		} else {
  2106  			name.Def.Used = true
  2107  			pkg = name.Def.Name.Pkg
  2108  		}
  2109  		return restrictlookup(s.Name, pkg)
  2110  	}
  2111  
  2112  	// LNAME
  2113  	if n := oldname(name); n.Name != nil && n.Name.Pack != nil {
  2114  		n.Name.Pack.Used = true
  2115  	}
  2116  	return name
  2117  }
  2118  
  2119  func (p *parser) embed(sym *Sym) *Node {
  2120  	if trace && Debug['x'] != 0 {
  2121  		defer p.trace("embed")()
  2122  	}
  2123  
  2124  	pkgname := p.packname(sym)
  2125  	return embedded(pkgname, localpkg)
  2126  }
  2127  
  2128  // MethodSpec        = MethodName Signature | InterfaceTypeName .
  2129  // MethodName        = identifier .
  2130  // InterfaceTypeName = TypeName .
  2131  func (p *parser) interfacedcl() *Node {
  2132  	if trace && Debug['x'] != 0 {
  2133  		defer p.trace("interfacedcl")()
  2134  	}
  2135  
  2136  	switch p.tok {
  2137  	case LNAME:
  2138  		sym := p.sym_
  2139  		p.next()
  2140  
  2141  		// accept potential name list but complain
  2142  		hasNameList := false
  2143  		for p.got(',') {
  2144  			p.sym()
  2145  			hasNameList = true
  2146  		}
  2147  		if hasNameList {
  2148  			p.syntax_error("name list not allowed in interface type")
  2149  			// already progressed, no need to advance
  2150  		}
  2151  
  2152  		if p.tok != '(' {
  2153  			// packname
  2154  			pname := p.packname(sym)
  2155  			return Nod(ODCLFIELD, nil, oldname(pname))
  2156  		}
  2157  
  2158  		// MethodName Signature
  2159  		mname := newname(sym)
  2160  		sig := p.signature(fakethis())
  2161  
  2162  		meth := Nod(ODCLFIELD, mname, sig)
  2163  		ifacedcl(meth)
  2164  		return meth
  2165  
  2166  	case '(':
  2167  		p.next()
  2168  		pname := p.packname(nil)
  2169  		p.want(')')
  2170  		n := Nod(ODCLFIELD, nil, oldname(pname))
  2171  		Yyerror("cannot parenthesize embedded type")
  2172  		return n
  2173  
  2174  	default:
  2175  		p.syntax_error("")
  2176  		p.advance(';', '}')
  2177  		return nil
  2178  	}
  2179  }
  2180  
  2181  // param parses and returns a function parameter list entry which may be
  2182  // a parameter name and type pair (name, typ), a single type (nil, typ),
  2183  // or a single name (name, nil). In the last case, the name may still be
  2184  // a type name. The result is (nil, nil) in case of a syntax error.
  2185  //
  2186  // [ParameterName] Type
  2187  func (p *parser) param() (name *Sym, typ *Node) {
  2188  	if trace && Debug['x'] != 0 {
  2189  		defer p.trace("param")()
  2190  	}
  2191  
  2192  	switch p.tok {
  2193  	case LNAME:
  2194  		name = p.sym()
  2195  		switch p.tok {
  2196  		case LCOMM, LFUNC, '[', LCHAN, LMAP, LSTRUCT, LINTERFACE, '*', LNAME, '(':
  2197  			// sym name_or_type
  2198  			typ = p.ntype()
  2199  
  2200  		case LDDD:
  2201  			// sym dotdotdot
  2202  			typ = p.dotdotdot()
  2203  
  2204  		default:
  2205  			// name_or_type
  2206  			if p.got('.') {
  2207  				// a qualified name cannot be a parameter name
  2208  				typ = p.new_dotname(mkname(name))
  2209  				name = nil
  2210  			}
  2211  		}
  2212  
  2213  	case LDDD:
  2214  		// dotdotdot
  2215  		typ = p.dotdotdot()
  2216  
  2217  	case LCOMM, LFUNC, '[', LCHAN, LMAP, LSTRUCT, LINTERFACE, '*', '(':
  2218  		// name_or_type
  2219  		typ = p.ntype()
  2220  
  2221  	default:
  2222  		p.syntax_error("expecting )")
  2223  		p.advance(',', ')')
  2224  	}
  2225  
  2226  	return
  2227  }
  2228  
  2229  // Parameters    = "(" [ ParameterList [ "," ] ] ")" .
  2230  // ParameterList = ParameterDecl { "," ParameterDecl } .
  2231  // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
  2232  func (p *parser) param_list(dddOk bool) []*Node {
  2233  	if trace && Debug['x'] != 0 {
  2234  		defer p.trace("param_list")()
  2235  	}
  2236  
  2237  	type param struct {
  2238  		name *Sym
  2239  		typ  *Node
  2240  	}
  2241  	var params []param
  2242  	var named int // number of parameters that have a name and type
  2243  
  2244  	p.want('(')
  2245  	for p.tok != EOF && p.tok != ')' {
  2246  		name, typ := p.param()
  2247  		params = append(params, param{name, typ})
  2248  		if name != nil && typ != nil {
  2249  			named++
  2250  		}
  2251  		if !p.ocomma(')') {
  2252  			break
  2253  		}
  2254  	}
  2255  	p.want(')')
  2256  	// 0 <= named <= len(params)
  2257  
  2258  	// There are 3 cases:
  2259  	//
  2260  	// 1) named == 0:
  2261  	//    No parameter list entry has both a name and a type; i.e. there are only
  2262  	//    unnamed parameters. Any name must be a type name; they are "converted"
  2263  	//    to types when creating the final parameter list.
  2264  	//    In case of a syntax error, there is neither a name nor a type.
  2265  	//    Nil checks take care of this.
  2266  	//
  2267  	// 2) named == len(names):
  2268  	//    All parameter list entries have both a name and a type.
  2269  	//
  2270  	// 3) Otherwise:
  2271  	if named != 0 && named != len(params) {
  2272  		// Some parameter list entries have both a name and a type:
  2273  		// Distribute types backwards and check that there are no
  2274  		// mixed named and unnamed parameters.
  2275  		var T *Node // type T in a parameter sequence: a, b, c T
  2276  		for i := len(params) - 1; i >= 0; i-- {
  2277  			p := &params[i]
  2278  			if t := p.typ; t != nil {
  2279  				// explicit type: use type for earlier parameters
  2280  				T = t
  2281  				// an explicitly typed entry must have a name
  2282  				if p.name == nil {
  2283  					T = nil // error
  2284  				}
  2285  			} else {
  2286  				// no explicit type: use type of next parameter
  2287  				p.typ = T
  2288  			}
  2289  			if T == nil {
  2290  				Yyerror("mixed named and unnamed function parameters")
  2291  				break
  2292  			}
  2293  		}
  2294  		// Unless there was an error, now all parameter entries have a type.
  2295  	}
  2296  
  2297  	// create final parameter list
  2298  	list := make([]*Node, len(params))
  2299  	for i, p := range params {
  2300  		// create dcl node
  2301  		var name, typ *Node
  2302  		if p.typ != nil {
  2303  			typ = p.typ
  2304  			if p.name != nil {
  2305  				// name must be a parameter name
  2306  				name = newname(p.name)
  2307  			}
  2308  		} else if p.name != nil {
  2309  			// p.name must be a type name (or nil in case of syntax error)
  2310  			typ = mkname(p.name)
  2311  		}
  2312  		n := Nod(ODCLFIELD, name, typ)
  2313  
  2314  		// rewrite ...T parameter
  2315  		if typ != nil && typ.Op == ODDD {
  2316  			if !dddOk {
  2317  				Yyerror("cannot use ... in receiver or result parameter list")
  2318  			} else if i+1 < len(params) {
  2319  				Yyerror("can only use ... with final parameter in list")
  2320  			}
  2321  			typ.Op = OTARRAY
  2322  			typ.Right = typ.Left
  2323  			typ.Left = nil
  2324  			n.Isddd = true
  2325  			if n.Left != nil {
  2326  				n.Left.Isddd = true
  2327  			}
  2328  		}
  2329  
  2330  		list[i] = n
  2331  	}
  2332  
  2333  	return list
  2334  }
  2335  
  2336  var missing_stmt = Nod(OXXX, nil, nil)
  2337  
  2338  // Statement =
  2339  // 	Declaration | LabeledStmt | SimpleStmt |
  2340  // 	GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
  2341  // 	FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
  2342  // 	DeferStmt .
  2343  //
  2344  // stmt may return missing_stmt.
  2345  func (p *parser) stmt() *Node {
  2346  	if trace && Debug['x'] != 0 {
  2347  		defer p.trace("stmt")()
  2348  	}
  2349  
  2350  	switch p.tok {
  2351  	case '{':
  2352  		return p.compound_stmt()
  2353  
  2354  	case LVAR, LCONST, LTYPE:
  2355  		return liststmt(p.common_dcl())
  2356  
  2357  	case LNAME, LLITERAL, LFUNC, '(', // operands
  2358  		'[', LSTRUCT, LMAP, LCHAN, LINTERFACE, // composite types
  2359  		'+', '-', '*', '&', '^', LCOMM, '!': // unary operators
  2360  		return p.simple_stmt(true, false)
  2361  
  2362  	case LFOR:
  2363  		return p.for_stmt()
  2364  
  2365  	case LSWITCH:
  2366  		return p.switch_stmt()
  2367  
  2368  	case LSELECT:
  2369  		return p.select_stmt()
  2370  
  2371  	case LIF:
  2372  		return p.if_stmt()
  2373  
  2374  	case LFALL:
  2375  		p.next()
  2376  		// will be converted to OFALL
  2377  		stmt := Nod(OXFALL, nil, nil)
  2378  		stmt.Xoffset = int64(block)
  2379  		return stmt
  2380  
  2381  	case LBREAK:
  2382  		p.next()
  2383  		return Nod(OBREAK, p.onew_name(), nil)
  2384  
  2385  	case LCONTINUE:
  2386  		p.next()
  2387  		return Nod(OCONTINUE, p.onew_name(), nil)
  2388  
  2389  	case LGO:
  2390  		p.next()
  2391  		return Nod(OPROC, p.pseudocall(), nil)
  2392  
  2393  	case LDEFER:
  2394  		p.next()
  2395  		return Nod(ODEFER, p.pseudocall(), nil)
  2396  
  2397  	case LGOTO:
  2398  		p.next()
  2399  		stmt := Nod(OGOTO, p.new_name(p.sym()), nil)
  2400  		stmt.Sym = dclstack // context, for goto restrictions
  2401  		return stmt
  2402  
  2403  	case LRETURN:
  2404  		p.next()
  2405  		var results []*Node
  2406  		if p.tok != ';' && p.tok != '}' {
  2407  			results = p.expr_list()
  2408  		}
  2409  
  2410  		stmt := Nod(ORETURN, nil, nil)
  2411  		stmt.List.Set(results)
  2412  		if stmt.List.Len() == 0 && Curfn != nil {
  2413  			for _, ln := range Curfn.Func.Dcl {
  2414  				if ln.Class == PPARAM {
  2415  					continue
  2416  				}
  2417  				if ln.Class != PPARAMOUT {
  2418  					break
  2419  				}
  2420  				if ln.Sym.Def != ln {
  2421  					Yyerror("%s is shadowed during return", ln.Sym.Name)
  2422  				}
  2423  			}
  2424  		}
  2425  
  2426  		return stmt
  2427  
  2428  	case ';':
  2429  		return nil
  2430  
  2431  	default:
  2432  		return missing_stmt
  2433  	}
  2434  }
  2435  
  2436  // StatementList = { Statement ";" } .
  2437  func (p *parser) stmt_list() (l []*Node) {
  2438  	if trace && Debug['x'] != 0 {
  2439  		defer p.trace("stmt_list")()
  2440  	}
  2441  
  2442  	for p.tok != EOF && p.tok != '}' && p.tok != LCASE && p.tok != LDEFAULT {
  2443  		s := p.stmt()
  2444  		if s == missing_stmt {
  2445  			break
  2446  		}
  2447  		if s == nil {
  2448  		} else if s.Op == OBLOCK && s.Ninit.Len() == 0 {
  2449  			l = append(l, s.List.Slice()...)
  2450  		} else {
  2451  			l = append(l, s)
  2452  		}
  2453  		// customized version of osemi:
  2454  		// ';' is optional before a closing ')' or '}'
  2455  		if p.tok == ')' || p.tok == '}' {
  2456  			continue
  2457  		}
  2458  		if !p.got(';') {
  2459  			p.syntax_error("at end of statement")
  2460  			p.advance(';', '}')
  2461  		}
  2462  	}
  2463  	return
  2464  }
  2465  
  2466  // IdentifierList = identifier { "," identifier } .
  2467  //
  2468  // If first != nil we have the first symbol already.
  2469  func (p *parser) new_name_list(first *Sym) []*Node {
  2470  	if trace && Debug['x'] != 0 {
  2471  		defer p.trace("new_name_list")()
  2472  	}
  2473  
  2474  	if first == nil {
  2475  		first = p.sym() // may still be nil
  2476  	}
  2477  	var l []*Node
  2478  	n := p.new_name(first)
  2479  	if n != nil {
  2480  		l = append(l, n)
  2481  	}
  2482  	for p.got(',') {
  2483  		n = p.new_name(p.sym())
  2484  		if n != nil {
  2485  			l = append(l, n)
  2486  		}
  2487  	}
  2488  	return l
  2489  }
  2490  
  2491  // IdentifierList = identifier { "," identifier } .
  2492  func (p *parser) dcl_name_list() []*Node {
  2493  	if trace && Debug['x'] != 0 {
  2494  		defer p.trace("dcl_name_list")()
  2495  	}
  2496  
  2497  	s := []*Node{p.dcl_name()}
  2498  	for p.got(',') {
  2499  		s = append(s, p.dcl_name())
  2500  	}
  2501  	return s
  2502  }
  2503  
  2504  // ExpressionList = Expression { "," Expression } .
  2505  func (p *parser) expr_list() []*Node {
  2506  	if trace && Debug['x'] != 0 {
  2507  		defer p.trace("expr_list")()
  2508  	}
  2509  
  2510  	l := []*Node{p.expr()}
  2511  	for p.got(',') {
  2512  		l = append(l, p.expr())
  2513  	}
  2514  	return l
  2515  }
  2516  
  2517  // Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
  2518  func (p *parser) arg_list() (l []*Node, ddd bool) {
  2519  	if trace && Debug['x'] != 0 {
  2520  		defer p.trace("arg_list")()
  2521  	}
  2522  
  2523  	p.want('(')
  2524  	p.xnest++
  2525  
  2526  	for p.tok != EOF && p.tok != ')' && !ddd {
  2527  		l = append(l, p.expr()) // expr_or_type
  2528  		ddd = p.got(LDDD)
  2529  		if !p.ocomma(')') {
  2530  			break
  2531  		}
  2532  	}
  2533  
  2534  	p.xnest--
  2535  	p.want(')')
  2536  
  2537  	return
  2538  }
  2539  
  2540  // osemi parses an optional semicolon.
  2541  func (p *parser) osemi(follow int32) bool {
  2542  	switch p.tok {
  2543  	case ';':
  2544  		p.next()
  2545  		return true
  2546  
  2547  	case ')', '}':
  2548  		// semicolon is optional before ) or }
  2549  		return true
  2550  	}
  2551  
  2552  	p.syntax_error("expecting semicolon, newline, or " + tokstring(follow))
  2553  	p.advance(follow)
  2554  	return false
  2555  }
  2556  
  2557  // ocomma parses an optional comma.
  2558  func (p *parser) ocomma(follow int32) bool {
  2559  	switch p.tok {
  2560  	case ',':
  2561  		p.next()
  2562  		return true
  2563  
  2564  	case ')', '}':
  2565  		// comma is optional before ) or }
  2566  		return true
  2567  	}
  2568  
  2569  	p.syntax_error("expecting comma or " + tokstring(follow))
  2570  	p.advance(follow)
  2571  	return false
  2572  }