github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/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  	"strconv"
    19  	"strings"
    20  )
    21  
    22  const trace = false // if set, parse tracing can be enabled with -x
    23  
    24  // parse_import parses the export data of a package that is imported.
    25  func parse_import(bin *bufio.Reader, indent []byte) {
    26  	newparser(bin, indent).import_package()
    27  }
    28  
    29  // parse_file parses a single Go source file.
    30  func parse_file(bin *bufio.Reader) {
    31  	newparser(bin, nil).file()
    32  }
    33  
    34  type parser struct {
    35  	lexer
    36  	fnest  int    // function nesting level (for error handling)
    37  	xnest  int    // expression nesting level (for complit ambiguity resolution)
    38  	indent []byte // tracing support
    39  
    40  	// TODO(gri) remove this once we switch to binary export format
    41  	structpkg *Pkg // for verification in addmethod only
    42  }
    43  
    44  // newparser returns a new parser ready to parse from src.
    45  // indent is the initial indentation for tracing output.
    46  func newparser(src *bufio.Reader, indent []byte) *parser {
    47  	var p parser
    48  	p.bin = src
    49  	p.indent = indent
    50  	p.next()
    51  	return &p
    52  }
    53  
    54  func (p *parser) got(tok int32) bool {
    55  	if p.tok == tok {
    56  		p.next()
    57  		return true
    58  	}
    59  	return false
    60  }
    61  
    62  func (p *parser) want(tok int32) {
    63  	if !p.got(tok) {
    64  		p.syntax_error("expecting " + tokstring(tok))
    65  		p.advance()
    66  	}
    67  }
    68  
    69  // ----------------------------------------------------------------------------
    70  // Syntax error handling
    71  
    72  func (p *parser) syntax_error(msg string) {
    73  	if trace && Debug['x'] != 0 {
    74  		defer p.trace("syntax_error (" + msg + ")")()
    75  	}
    76  
    77  	if p.tok == EOF && nerrors > 0 {
    78  		return // avoid meaningless follow-up errors
    79  	}
    80  
    81  	// add punctuation etc. as needed to msg
    82  	switch {
    83  	case msg == "":
    84  		// nothing to do
    85  	case strings.HasPrefix(msg, "in"), strings.HasPrefix(msg, "at"), strings.HasPrefix(msg, "after"):
    86  		msg = " " + msg
    87  	case strings.HasPrefix(msg, "expecting"):
    88  		msg = ", " + msg
    89  	default:
    90  		// plain error - we don't care about current token
    91  		Yyerror("syntax error: %s", msg)
    92  		return
    93  	}
    94  
    95  	// determine token string
    96  	var tok string
    97  	switch p.tok {
    98  	case LNAME:
    99  		if p.sym_ != nil && p.sym_.Name != "" {
   100  			tok = p.sym_.Name
   101  		} else {
   102  			tok = "name"
   103  		}
   104  	case LLITERAL:
   105  		if litbuf == "" {
   106  			litbuf = "literal " + lexbuf.String()
   107  		}
   108  		tok = litbuf
   109  	case LOPER:
   110  		tok = goopnames[p.op]
   111  	case LASOP:
   112  		tok = goopnames[p.op] + "="
   113  	case LINCOP:
   114  		tok = goopnames[p.op] + goopnames[p.op]
   115  	default:
   116  		tok = tokstring(p.tok)
   117  	}
   118  
   119  	Yyerror("syntax error: unexpected %s", tok+msg)
   120  }
   121  
   122  // Like syntax_error, but reports error at given line rather than current lexer line.
   123  func (p *parser) syntax_error_at(lno int32, msg string) {
   124  	defer func(lno int32) {
   125  		lineno = lno
   126  	}(lineno)
   127  	lineno = lno
   128  	p.syntax_error(msg)
   129  }
   130  
   131  // The stoplist contains keywords that start a statement.
   132  // They are good synchronization points in case of syntax
   133  // errors and (usually) shouldn't be skipped over.
   134  var stoplist = map[int32]bool{
   135  	LBREAK:    true,
   136  	LCONST:    true,
   137  	LCONTINUE: true,
   138  	LDEFER:    true,
   139  	LFALL:     true,
   140  	LFOR:      true,
   141  	LFUNC:     true,
   142  	LGO:       true,
   143  	LGOTO:     true,
   144  	LIF:       true,
   145  	LRETURN:   true,
   146  	LSELECT:   true,
   147  	LSWITCH:   true,
   148  	LTYPE:     true,
   149  	LVAR:      true,
   150  }
   151  
   152  // Advance consumes tokens until it finds a token of the stop- or followlist.
   153  // The stoplist is only considered if we are inside a function (p.fnest > 0).
   154  // The followlist is the list of valid tokens that can follow a production;
   155  // if it is empty, exactly one token is consumed to ensure progress.
   156  func (p *parser) advance(followlist ...int32) {
   157  	if len(followlist) == 0 {
   158  		p.next()
   159  		return
   160  	}
   161  	for p.tok != EOF {
   162  		if p.fnest > 0 && stoplist[p.tok] {
   163  			return
   164  		}
   165  		for _, follow := range followlist {
   166  			if p.tok == follow {
   167  				return
   168  			}
   169  		}
   170  		p.next()
   171  	}
   172  }
   173  
   174  func tokstring(tok int32) string {
   175  	switch tok {
   176  	case EOF:
   177  		return "EOF"
   178  	case ',':
   179  		return "comma"
   180  	case ';':
   181  		return "semicolon or newline"
   182  	}
   183  	if 0 <= tok && tok < 128 {
   184  		// get invisibles properly backslashed
   185  		s := strconv.QuoteRune(tok)
   186  		if n := len(s); n > 0 && s[0] == '\'' && s[n-1] == '\'' {
   187  			s = s[1 : n-1]
   188  		}
   189  		return s
   190  	}
   191  	if s := tokstrings[tok]; s != "" {
   192  		return s
   193  	}
   194  	// catchall
   195  	return fmt.Sprintf("tok-%v", tok)
   196  }
   197  
   198  var tokstrings = map[int32]string{
   199  	LNAME:    "NAME",
   200  	LLITERAL: "LITERAL",
   201  
   202  	LOPER:  "op",
   203  	LASOP:  "op=",
   204  	LINCOP: "opop",
   205  
   206  	LCOLAS: ":=",
   207  	LCOMM:  "<-",
   208  	LDDD:   "...",
   209  
   210  	LBREAK:     "break",
   211  	LCASE:      "case",
   212  	LCHAN:      "chan",
   213  	LCONST:     "const",
   214  	LCONTINUE:  "continue",
   215  	LDEFAULT:   "default",
   216  	LDEFER:     "defer",
   217  	LELSE:      "else",
   218  	LFALL:      "fallthrough",
   219  	LFOR:       "for",
   220  	LFUNC:      "func",
   221  	LGO:        "go",
   222  	LGOTO:      "goto",
   223  	LIF:        "if",
   224  	LIMPORT:    "import",
   225  	LINTERFACE: "interface",
   226  	LMAP:       "map",
   227  	LPACKAGE:   "package",
   228  	LRANGE:     "range",
   229  	LRETURN:    "return",
   230  	LSELECT:    "select",
   231  	LSTRUCT:    "struct",
   232  	LSWITCH:    "switch",
   233  	LTYPE:      "type",
   234  	LVAR:       "var",
   235  }
   236  
   237  // usage: defer p.trace(msg)()
   238  func (p *parser) trace(msg string) func() {
   239  	fmt.Printf("%5d: %s%s (\n", lineno, p.indent, msg)
   240  	const tab = ". "
   241  	p.indent = append(p.indent, tab...)
   242  	return func() {
   243  		p.indent = p.indent[:len(p.indent)-len(tab)]
   244  		if x := recover(); x != nil {
   245  			panic(x) // skip print_trace
   246  		}
   247  		fmt.Printf("%5d: %s)\n", lineno, p.indent)
   248  	}
   249  }
   250  
   251  // ----------------------------------------------------------------------------
   252  // Parsing package files
   253  //
   254  // Parse methods are annotated with matching Go productions as appropriate.
   255  // The annotations are intended as guidelines only since a single Go grammar
   256  // rule may be covered by multiple parse methods and vice versa.
   257  
   258  // SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
   259  func (p *parser) file() {
   260  	if trace && Debug['x'] != 0 {
   261  		defer p.trace("file")()
   262  	}
   263  
   264  	p.package_()
   265  	p.want(';')
   266  
   267  	for p.tok == LIMPORT {
   268  		p.import_()
   269  		p.want(';')
   270  	}
   271  
   272  	xtop = append(xtop, p.xdcl_list()...)
   273  
   274  	p.want(EOF)
   275  }
   276  
   277  // PackageClause = "package" PackageName .
   278  // PackageName   = identifier .
   279  func (p *parser) package_() {
   280  	if trace && Debug['x'] != 0 {
   281  		defer p.trace("package_")()
   282  	}
   283  
   284  	if !p.got(LPACKAGE) {
   285  		p.syntax_error("package statement must be first")
   286  		errorexit()
   287  	}
   288  	mkpackage(p.sym().Name)
   289  }
   290  
   291  // ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
   292  func (p *parser) import_() {
   293  	if trace && Debug['x'] != 0 {
   294  		defer p.trace("import_")()
   295  	}
   296  
   297  	p.want(LIMPORT)
   298  	if p.got('(') {
   299  		for p.tok != EOF && p.tok != ')' {
   300  			p.importdcl()
   301  			if !p.osemi(')') {
   302  				break
   303  			}
   304  		}
   305  		p.want(')')
   306  	} else {
   307  		p.importdcl()
   308  	}
   309  }
   310  
   311  // ImportSpec = [ "." | PackageName ] ImportPath .
   312  // ImportPath = string_lit .
   313  func (p *parser) importdcl() {
   314  	if trace && Debug['x'] != 0 {
   315  		defer p.trace("importdcl")()
   316  	}
   317  
   318  	var my *Sym
   319  	switch p.tok {
   320  	case LNAME, '@', '?':
   321  		// import with given name
   322  		my = p.sym()
   323  
   324  	case '.':
   325  		// import into my name space
   326  		my = Lookup(".")
   327  		p.next()
   328  	}
   329  
   330  	if p.tok != LLITERAL {
   331  		p.syntax_error("missing import path; require quoted string")
   332  		p.advance(';', ')')
   333  		return
   334  	}
   335  
   336  	line := lineno
   337  
   338  	// We need to clear importpkg before calling p.next(),
   339  	// otherwise it will affect lexlineno.
   340  	// TODO(mdempsky): Fix this clumsy API.
   341  	importfile(&p.val, p.indent)
   342  	ipkg := importpkg
   343  	importpkg = nil
   344  
   345  	p.next()
   346  	if ipkg == nil {
   347  		if nerrors == 0 {
   348  			Fatalf("phase error in import")
   349  		}
   350  		return
   351  	}
   352  
   353  	ipkg.Direct = true
   354  
   355  	if my == nil {
   356  		my = Lookup(ipkg.Name)
   357  	}
   358  
   359  	pack := Nod(OPACK, nil, nil)
   360  	pack.Sym = my
   361  	pack.Name.Pkg = ipkg
   362  	pack.Lineno = line
   363  
   364  	if strings.HasPrefix(my.Name, ".") {
   365  		importdot(ipkg, pack)
   366  		return
   367  	}
   368  	if my.Name == "init" {
   369  		lineno = line
   370  		Yyerror("cannot import package as init - init must be a func")
   371  		return
   372  	}
   373  	if my.Name == "_" {
   374  		return
   375  	}
   376  	if my.Def != nil {
   377  		lineno = line
   378  		redeclare(my, "as imported package name")
   379  	}
   380  	my.Def = pack
   381  	my.Lastlineno = line
   382  	my.Block = 1 // at top level
   383  }
   384  
   385  // import_package parses the header of an imported package as exported
   386  // in textual format from another package.
   387  func (p *parser) import_package() {
   388  	if trace && Debug['x'] != 0 {
   389  		defer p.trace("import_package")()
   390  	}
   391  
   392  	p.want(LPACKAGE)
   393  	var name string
   394  	if p.tok == LNAME {
   395  		name = p.sym_.Name
   396  		p.next()
   397  	} else {
   398  		p.import_error()
   399  	}
   400  
   401  	// read but skip "safe" bit (see issue #15772)
   402  	if p.tok == LNAME {
   403  		p.next()
   404  	}
   405  	p.want(';')
   406  
   407  	if importpkg.Name == "" {
   408  		importpkg.Name = name
   409  		numImport[name]++
   410  	} else if importpkg.Name != name {
   411  		Yyerror("conflicting names %s and %s for package %q", importpkg.Name, name, importpkg.Path)
   412  	}
   413  
   414  	typecheckok = true
   415  	defercheckwidth()
   416  
   417  	p.hidden_import_list()
   418  	p.want('$')
   419  	// don't read past 2nd '$'
   420  	if p.tok != '$' {
   421  		p.import_error()
   422  	}
   423  
   424  	resumecheckwidth()
   425  	typecheckok = false
   426  }
   427  
   428  // Declaration = ConstDecl | TypeDecl | VarDecl .
   429  // ConstDecl   = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
   430  // TypeDecl    = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
   431  // VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
   432  func (p *parser) common_dcl() []*Node {
   433  	if trace && Debug['x'] != 0 {
   434  		defer p.trace("common_dcl")()
   435  	}
   436  
   437  	var dcl func() []*Node
   438  	switch p.tok {
   439  	case LVAR:
   440  		dcl = p.vardcl
   441  
   442  	case LCONST:
   443  		iota_ = 0
   444  		dcl = p.constdcl
   445  
   446  	case LTYPE:
   447  		dcl = p.typedcl
   448  
   449  	default:
   450  		panic("unreachable")
   451  	}
   452  
   453  	p.next()
   454  	var s []*Node
   455  	if p.got('(') {
   456  		for p.tok != EOF && p.tok != ')' {
   457  			s = append(s, dcl()...)
   458  			if !p.osemi(')') {
   459  				break
   460  			}
   461  		}
   462  		p.want(')')
   463  	} else {
   464  		s = dcl()
   465  	}
   466  
   467  	iota_ = -100000
   468  	lastconst = nil
   469  
   470  	return s
   471  }
   472  
   473  // VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
   474  func (p *parser) vardcl() []*Node {
   475  	if trace && Debug['x'] != 0 {
   476  		defer p.trace("vardcl")()
   477  	}
   478  
   479  	names := p.dcl_name_list()
   480  	var typ *Node
   481  	var exprs []*Node
   482  	if p.got('=') {
   483  		exprs = p.expr_list()
   484  	} else {
   485  		typ = p.ntype()
   486  		if p.got('=') {
   487  			exprs = p.expr_list()
   488  		}
   489  	}
   490  
   491  	return variter(names, typ, exprs)
   492  }
   493  
   494  // ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
   495  func (p *parser) constdcl() []*Node {
   496  	if trace && Debug['x'] != 0 {
   497  		defer p.trace("constdcl")()
   498  	}
   499  
   500  	names := p.dcl_name_list()
   501  	var typ *Node
   502  	var exprs []*Node
   503  	if p.tok != EOF && p.tok != ';' && p.tok != ')' {
   504  		typ = p.try_ntype()
   505  		if p.got('=') {
   506  			exprs = p.expr_list()
   507  		}
   508  	}
   509  
   510  	return constiter(names, typ, exprs)
   511  }
   512  
   513  // TypeSpec = identifier Type .
   514  func (p *parser) typedcl() []*Node {
   515  	if trace && Debug['x'] != 0 {
   516  		defer p.trace("typedcl")()
   517  	}
   518  
   519  	name := typedcl0(p.sym())
   520  
   521  	typ := p.try_ntype()
   522  	// handle case where type is missing
   523  	if typ == nil {
   524  		p.syntax_error("in type declaration")
   525  		p.advance(';', ')')
   526  	}
   527  
   528  	return []*Node{typedcl1(name, typ, true)}
   529  }
   530  
   531  // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
   532  //
   533  // simple_stmt may return missing_stmt if labelOk is set.
   534  func (p *parser) simple_stmt(labelOk, rangeOk bool) *Node {
   535  	if trace && Debug['x'] != 0 {
   536  		defer p.trace("simple_stmt")()
   537  	}
   538  
   539  	if rangeOk && p.got(LRANGE) {
   540  		// LRANGE expr
   541  		r := Nod(ORANGE, nil, p.expr())
   542  		r.Etype = 0 // := flag
   543  		return r
   544  	}
   545  
   546  	lhs := p.expr_list()
   547  
   548  	if len(lhs) == 1 && p.tok != '=' && p.tok != LCOLAS && p.tok != LRANGE {
   549  		// expr
   550  		lhs := lhs[0]
   551  		switch p.tok {
   552  		case LASOP:
   553  			// expr LASOP expr
   554  			op := p.op
   555  			p.next()
   556  			rhs := p.expr()
   557  
   558  			stmt := Nod(OASOP, lhs, rhs)
   559  			stmt.Etype = EType(op) // rathole to pass opcode
   560  			return stmt
   561  
   562  		case LINCOP:
   563  			// expr LINCOP
   564  			p.next()
   565  
   566  			stmt := Nod(OASOP, lhs, Nodintconst(1))
   567  			stmt.Implicit = true
   568  			stmt.Etype = EType(p.op)
   569  			return stmt
   570  
   571  		case ':':
   572  			// labelname ':' stmt
   573  			if labelOk {
   574  				// If we have a labelname, it was parsed by operand
   575  				// (calling p.name()) and given an ONAME, ONONAME, OTYPE, OPACK, or OLITERAL node.
   576  				// We only have a labelname if there is a symbol (was issue 14006).
   577  				switch lhs.Op {
   578  				case ONAME, ONONAME, OTYPE, OPACK, OLITERAL:
   579  					if lhs.Sym != nil {
   580  						lhs = newname(lhs.Sym)
   581  						break
   582  					}
   583  					fallthrough
   584  				default:
   585  					p.syntax_error("expecting semicolon or newline or }")
   586  					// we already progressed, no need to advance
   587  				}
   588  				lhs := Nod(OLABEL, lhs, nil)
   589  				lhs.Sym = dclstack // context, for goto restrictions
   590  				p.next()           // consume ':' after making label node for correct lineno
   591  				return p.labeled_stmt(lhs)
   592  			}
   593  			fallthrough
   594  
   595  		default:
   596  			// expr
   597  			// Since a bare name used as an expression is an error,
   598  			// introduce a wrapper node where necessary to give the
   599  			// correct line.
   600  			return wrapname(lhs)
   601  		}
   602  	}
   603  
   604  	// expr_list
   605  	switch p.tok {
   606  	case '=':
   607  		p.next()
   608  		if rangeOk && p.got(LRANGE) {
   609  			// expr_list '=' LRANGE expr
   610  			r := Nod(ORANGE, nil, p.expr())
   611  			r.List.Set(lhs)
   612  			r.Etype = 0 // := flag
   613  			return r
   614  		}
   615  
   616  		// expr_list '=' expr_list
   617  		rhs := p.expr_list()
   618  
   619  		if len(lhs) == 1 && len(rhs) == 1 {
   620  			// simple
   621  			return Nod(OAS, lhs[0], rhs[0])
   622  		}
   623  		// multiple
   624  		stmt := Nod(OAS2, nil, nil)
   625  		stmt.List.Set(lhs)
   626  		stmt.Rlist.Set(rhs)
   627  		return stmt
   628  
   629  	case LCOLAS:
   630  		lno := lineno
   631  		p.next()
   632  
   633  		if rangeOk && p.got(LRANGE) {
   634  			// expr_list LCOLAS LRANGE expr
   635  			r := Nod(ORANGE, nil, p.expr())
   636  			r.List.Set(lhs)
   637  			r.Colas = true
   638  			colasdefn(lhs, r)
   639  			return r
   640  		}
   641  
   642  		// expr_list LCOLAS expr_list
   643  		rhs := p.expr_list()
   644  
   645  		if rhs[0].Op == OTYPESW {
   646  			ts := Nod(OTYPESW, nil, rhs[0].Right)
   647  			if len(rhs) > 1 {
   648  				Yyerror("expr.(type) must be alone in list")
   649  			}
   650  			if len(lhs) > 1 {
   651  				Yyerror("argument count mismatch: %d = %d", len(lhs), 1)
   652  			} 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]) {
   653  				Yyerror("invalid variable name %s in type switch", lhs[0])
   654  			} else {
   655  				ts.Left = dclname(lhs[0].Sym)
   656  			} // it's a colas, so must not re-use an oldname
   657  			return ts
   658  		}
   659  		return colas(lhs, rhs, lno)
   660  
   661  	default:
   662  		p.syntax_error("expecting := or = or comma")
   663  		p.advance(';', '}')
   664  		return nil
   665  	}
   666  }
   667  
   668  // LabeledStmt = Label ":" Statement .
   669  // Label       = identifier .
   670  func (p *parser) labeled_stmt(label *Node) *Node {
   671  	if trace && Debug['x'] != 0 {
   672  		defer p.trace("labeled_stmt")()
   673  	}
   674  
   675  	var ls *Node // labeled statement
   676  	if p.tok != '}' && p.tok != EOF {
   677  		ls = p.stmt()
   678  		if ls == missing_stmt {
   679  			// report error at line of ':' token
   680  			p.syntax_error_at(label.Lineno, "missing statement after label")
   681  			// we are already at the end of the labeled statement - no need to advance
   682  			return missing_stmt
   683  		}
   684  	}
   685  
   686  	label.Name.Defn = ls
   687  	l := []*Node{label}
   688  	if ls != nil {
   689  		if ls.Op == OBLOCK && ls.Ninit.Len() == 0 {
   690  			l = append(l, ls.List.Slice()...)
   691  		} else {
   692  			l = append(l, ls)
   693  		}
   694  	}
   695  	return liststmt(l)
   696  }
   697  
   698  // case_ parses a superset of switch and select statement cases.
   699  // Later checks restrict the syntax to valid forms.
   700  //
   701  // ExprSwitchCase = "case" ExpressionList | "default" .
   702  // TypeSwitchCase = "case" TypeList | "default" .
   703  // TypeList       = Type { "," Type } .
   704  // CommCase       = "case" ( SendStmt | RecvStmt ) | "default" .
   705  // RecvStmt       = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
   706  // RecvExpr       = Expression .
   707  func (p *parser) case_(tswitch *Node) *Node {
   708  	if trace && Debug['x'] != 0 {
   709  		defer p.trace("case_")()
   710  	}
   711  
   712  	switch p.tok {
   713  	case LCASE:
   714  		p.next()
   715  		cases := p.expr_list() // expr_or_type_list
   716  		switch p.tok {
   717  		case ':':
   718  			// LCASE expr_or_type_list ':'
   719  
   720  			// will be converted to OCASE
   721  			// right will point to next case
   722  			// done in casebody()
   723  			markdcl() // matching popdcl in caseblock
   724  			stmt := Nod(OXCASE, nil, nil)
   725  			stmt.List.Set(cases)
   726  			if tswitch != nil {
   727  				if n := tswitch.Left; n != nil {
   728  					// type switch - declare variable
   729  					nn := newname(n.Sym)
   730  					declare(nn, dclcontext)
   731  					stmt.Rlist.Set1(nn)
   732  
   733  					// keep track of the instances for reporting unused
   734  					nn.Name.Defn = tswitch
   735  				}
   736  			}
   737  
   738  			p.next() // consume ':' after declaring type switch var for correct lineno
   739  			return stmt
   740  
   741  		case '=':
   742  			// LCASE expr_or_type_list '=' expr ':'
   743  			p.next()
   744  			rhs := p.expr()
   745  
   746  			// will be converted to OCASE
   747  			// right will point to next case
   748  			// done in casebody()
   749  			markdcl() // matching popdcl in caseblock
   750  			stmt := Nod(OXCASE, nil, nil)
   751  			var n *Node
   752  			if len(cases) == 1 {
   753  				n = Nod(OAS, cases[0], rhs)
   754  			} else {
   755  				n = Nod(OAS2, nil, nil)
   756  				n.List.Set(cases)
   757  				n.Rlist.Set1(rhs)
   758  			}
   759  			stmt.List.Set1(n)
   760  
   761  			p.want(':') // consume ':' after declaring select cases for correct lineno
   762  			return stmt
   763  
   764  		case LCOLAS:
   765  			// LCASE expr_or_type_list LCOLAS expr ':'
   766  			lno := lineno
   767  			p.next()
   768  			rhs := p.expr()
   769  
   770  			// will be converted to OCASE
   771  			// right will point to next case
   772  			// done in casebody()
   773  			markdcl() // matching popdcl in caseblock
   774  			stmt := Nod(OXCASE, nil, nil)
   775  			stmt.List.Set1(colas(cases, []*Node{rhs}, lno))
   776  
   777  			p.want(':') // consume ':' after declaring select cases for correct lineno
   778  			return stmt
   779  
   780  		default:
   781  			markdcl()                     // for matching popdcl in caseblock
   782  			stmt := Nod(OXCASE, nil, nil) // don't return nil
   783  			p.syntax_error("expecting := or = or : or comma")
   784  			p.advance(LCASE, LDEFAULT, '}')
   785  			return stmt
   786  		}
   787  
   788  	case LDEFAULT:
   789  		// LDEFAULT ':'
   790  		p.next()
   791  
   792  		markdcl() // matching popdcl in caseblock
   793  		stmt := Nod(OXCASE, nil, nil)
   794  		if tswitch != nil {
   795  			if n := tswitch.Left; n != nil {
   796  				// type switch - declare variable
   797  				nn := newname(n.Sym)
   798  				declare(nn, dclcontext)
   799  				stmt.Rlist.Set1(nn)
   800  
   801  				// keep track of the instances for reporting unused
   802  				nn.Name.Defn = tswitch
   803  			}
   804  		}
   805  
   806  		p.want(':') // consume ':' after declaring type switch var for correct lineno
   807  		return stmt
   808  
   809  	default:
   810  		markdcl()                     // matching popdcl in caseblock
   811  		stmt := Nod(OXCASE, nil, nil) // don't return nil
   812  		p.syntax_error("expecting case or default or }")
   813  		p.advance(LCASE, LDEFAULT, '}')
   814  		return stmt
   815  	}
   816  }
   817  
   818  // Block         = "{" StatementList "}" .
   819  // StatementList = { Statement ";" } .
   820  func (p *parser) compound_stmt() *Node {
   821  	if trace && Debug['x'] != 0 {
   822  		defer p.trace("compound_stmt")()
   823  	}
   824  
   825  	markdcl()
   826  	p.want('{')
   827  	l := p.stmt_list()
   828  	p.want('}')
   829  	popdcl()
   830  
   831  	if len(l) == 0 {
   832  		return Nod(OEMPTY, nil, nil)
   833  	}
   834  	return liststmt(l)
   835  }
   836  
   837  // caseblock parses a superset of switch and select clauses.
   838  //
   839  // ExprCaseClause = ExprSwitchCase ":" StatementList .
   840  // TypeCaseClause = TypeSwitchCase ":" StatementList .
   841  // CommClause     = CommCase ":" StatementList .
   842  func (p *parser) caseblock(tswitch *Node) *Node {
   843  	if trace && Debug['x'] != 0 {
   844  		defer p.trace("caseblock")()
   845  	}
   846  
   847  	stmt := p.case_(tswitch) // does markdcl
   848  	stmt.Xoffset = int64(block)
   849  	stmt.Nbody.Set(p.stmt_list())
   850  
   851  	popdcl()
   852  
   853  	return stmt
   854  }
   855  
   856  // caseblock_list parses a superset of switch and select clause lists.
   857  func (p *parser) caseblock_list(tswitch *Node) (l []*Node) {
   858  	if trace && Debug['x'] != 0 {
   859  		defer p.trace("caseblock_list")()
   860  	}
   861  
   862  	if !p.got('{') {
   863  		p.syntax_error("missing { after switch clause")
   864  		p.advance(LCASE, LDEFAULT, '}')
   865  	}
   866  
   867  	for p.tok != EOF && p.tok != '}' {
   868  		l = append(l, p.caseblock(tswitch))
   869  	}
   870  	p.want('}')
   871  	return
   872  }
   873  
   874  // loop_body parses if and for statement bodies.
   875  func (p *parser) loop_body(context string) []*Node {
   876  	if trace && Debug['x'] != 0 {
   877  		defer p.trace("loop_body")()
   878  	}
   879  
   880  	markdcl()
   881  	if !p.got('{') {
   882  		p.syntax_error("missing { after " + context)
   883  		p.advance(LNAME, '}')
   884  	}
   885  
   886  	body := p.stmt_list()
   887  	popdcl()
   888  	p.want('}')
   889  
   890  	return body
   891  }
   892  
   893  // for_header parses the header portion of a for statement.
   894  //
   895  // ForStmt   = "for" [ Condition | ForClause | RangeClause ] Block .
   896  // Condition = Expression .
   897  func (p *parser) for_header() *Node {
   898  	if trace && Debug['x'] != 0 {
   899  		defer p.trace("for_header")()
   900  	}
   901  
   902  	init, cond, post := p.header(true)
   903  
   904  	if init != nil || post != nil {
   905  		// init ; test ; incr
   906  		if post != nil && post.Colas {
   907  			Yyerror("cannot declare in the for-increment")
   908  		}
   909  		h := Nod(OFOR, nil, nil)
   910  		if init != nil {
   911  			h.Ninit.Set1(init)
   912  		}
   913  		h.Left = cond
   914  		h.Right = post
   915  		return h
   916  	}
   917  
   918  	if cond != nil && cond.Op == ORANGE {
   919  		// range_stmt - handled by pexpr
   920  		return cond
   921  	}
   922  
   923  	// normal test
   924  	h := Nod(OFOR, nil, nil)
   925  	h.Left = cond
   926  	return h
   927  }
   928  
   929  func (p *parser) for_body() *Node {
   930  	if trace && Debug['x'] != 0 {
   931  		defer p.trace("for_body")()
   932  	}
   933  
   934  	stmt := p.for_header()
   935  	body := p.loop_body("for clause")
   936  
   937  	stmt.Nbody.Append(body...)
   938  	return stmt
   939  }
   940  
   941  // ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
   942  func (p *parser) for_stmt() *Node {
   943  	if trace && Debug['x'] != 0 {
   944  		defer p.trace("for_stmt")()
   945  	}
   946  
   947  	p.want(LFOR)
   948  	markdcl()
   949  	body := p.for_body()
   950  	popdcl()
   951  
   952  	return body
   953  }
   954  
   955  // header parses a combination of if, switch, and for statement headers:
   956  //
   957  // Header   = [ InitStmt ";" ] [ Expression ] .
   958  // Header   = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .  // for_stmt only
   959  // InitStmt = SimpleStmt .
   960  // PostStmt = SimpleStmt .
   961  func (p *parser) header(for_stmt bool) (init, cond, post *Node) {
   962  	if p.tok == '{' {
   963  		return
   964  	}
   965  
   966  	outer := p.xnest
   967  	p.xnest = -1
   968  
   969  	if p.tok != ';' {
   970  		// accept potential vardcl but complain
   971  		// (for test/syntax/forvar.go)
   972  		if for_stmt && p.tok == LVAR {
   973  			Yyerror("var declaration not allowed in for initializer")
   974  			p.next()
   975  		}
   976  		init = p.simple_stmt(false, for_stmt)
   977  		// If we have a range clause, we are done.
   978  		if for_stmt && init.Op == ORANGE {
   979  			cond = init
   980  			init = nil
   981  
   982  			p.xnest = outer
   983  			return
   984  		}
   985  	}
   986  	if p.got(';') {
   987  		if for_stmt {
   988  			if p.tok != ';' {
   989  				cond = p.simple_stmt(false, false)
   990  			}
   991  			p.want(';')
   992  			if p.tok != '{' {
   993  				post = p.simple_stmt(false, false)
   994  			}
   995  		} else if p.tok != '{' {
   996  			cond = p.simple_stmt(false, false)
   997  		}
   998  	} else {
   999  		cond = init
  1000  		init = nil
  1001  	}
  1002  
  1003  	p.xnest = outer
  1004  	return
  1005  }
  1006  
  1007  func (p *parser) if_header() *Node {
  1008  	if trace && Debug['x'] != 0 {
  1009  		defer p.trace("if_header")()
  1010  	}
  1011  
  1012  	init, cond, _ := p.header(false)
  1013  	h := Nod(OIF, nil, nil)
  1014  	if init != nil {
  1015  		h.Ninit.Set1(init)
  1016  	}
  1017  	h.Left = cond
  1018  	return h
  1019  }
  1020  
  1021  // IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
  1022  func (p *parser) if_stmt() *Node {
  1023  	if trace && Debug['x'] != 0 {
  1024  		defer p.trace("if_stmt")()
  1025  	}
  1026  
  1027  	p.want(LIF)
  1028  
  1029  	markdcl()
  1030  
  1031  	stmt := p.if_header()
  1032  	if stmt.Left == nil {
  1033  		Yyerror("missing condition in if statement")
  1034  	}
  1035  
  1036  	stmt.Nbody.Set(p.loop_body("if clause"))
  1037  
  1038  	if p.got(LELSE) {
  1039  		switch p.tok {
  1040  		case LIF:
  1041  			stmt.Rlist.Set1(p.if_stmt())
  1042  		case '{':
  1043  			cs := p.compound_stmt()
  1044  			if cs.Op == OBLOCK && cs.Ninit.Len() == 0 {
  1045  				stmt.Rlist.Set(cs.List.Slice())
  1046  			} else {
  1047  				stmt.Rlist.Set1(cs)
  1048  			}
  1049  		default:
  1050  			p.syntax_error("else must be followed by if or statement block")
  1051  			p.advance(LNAME, '}')
  1052  		}
  1053  	}
  1054  
  1055  	popdcl()
  1056  	return stmt
  1057  }
  1058  
  1059  // switch_stmt parses both expression and type switch statements.
  1060  //
  1061  // SwitchStmt     = ExprSwitchStmt | TypeSwitchStmt .
  1062  // ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
  1063  // TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
  1064  func (p *parser) switch_stmt() *Node {
  1065  	if trace && Debug['x'] != 0 {
  1066  		defer p.trace("switch_stmt")()
  1067  	}
  1068  
  1069  	p.want(LSWITCH)
  1070  	markdcl()
  1071  
  1072  	hdr := p.if_header()
  1073  	hdr.Op = OSWITCH
  1074  
  1075  	tswitch := hdr.Left
  1076  	if tswitch != nil && tswitch.Op != OTYPESW {
  1077  		tswitch = nil
  1078  	}
  1079  
  1080  	hdr.List.Set(p.caseblock_list(tswitch))
  1081  	popdcl()
  1082  
  1083  	return hdr
  1084  }
  1085  
  1086  // SelectStmt = "select" "{" { CommClause } "}" .
  1087  func (p *parser) select_stmt() *Node {
  1088  	if trace && Debug['x'] != 0 {
  1089  		defer p.trace("select_stmt")()
  1090  	}
  1091  
  1092  	p.want(LSELECT)
  1093  	hdr := Nod(OSELECT, nil, nil)
  1094  	hdr.List.Set(p.caseblock_list(nil))
  1095  	return hdr
  1096  }
  1097  
  1098  // Expression = UnaryExpr | Expression binary_op Expression .
  1099  func (p *parser) bexpr(prec OpPrec) *Node {
  1100  	// don't trace bexpr - only leads to overly nested trace output
  1101  
  1102  	// prec is precedence of the prior/enclosing binary operator (if any),
  1103  	// so we only want to parse tokens of greater precedence.
  1104  
  1105  	x := p.uexpr()
  1106  	for p.prec > prec {
  1107  		op, prec1 := p.op, p.prec
  1108  		p.next()
  1109  		x = Nod(op, x, p.bexpr(prec1))
  1110  	}
  1111  	return x
  1112  }
  1113  
  1114  func (p *parser) expr() *Node {
  1115  	if trace && Debug['x'] != 0 {
  1116  		defer p.trace("expr")()
  1117  	}
  1118  
  1119  	return p.bexpr(0)
  1120  }
  1121  
  1122  func unparen(x *Node) *Node {
  1123  	for x.Op == OPAREN {
  1124  		x = x.Left
  1125  	}
  1126  	return x
  1127  }
  1128  
  1129  // UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
  1130  func (p *parser) uexpr() *Node {
  1131  	if trace && Debug['x'] != 0 {
  1132  		defer p.trace("uexpr")()
  1133  	}
  1134  
  1135  	var op Op
  1136  	switch p.tok {
  1137  	case '*':
  1138  		op = OIND
  1139  
  1140  	case '&':
  1141  		p.next()
  1142  		// uexpr may have returned a parenthesized composite literal
  1143  		// (see comment in operand) - remove parentheses if any
  1144  		x := unparen(p.uexpr())
  1145  		if x.Op == OCOMPLIT {
  1146  			// Special case for &T{...}: turn into (*T){...}.
  1147  			x.Right = Nod(OIND, x.Right, nil)
  1148  			x.Right.Implicit = true
  1149  		} else {
  1150  			x = Nod(OADDR, x, nil)
  1151  		}
  1152  		return x
  1153  
  1154  	case '+':
  1155  		op = OPLUS
  1156  
  1157  	case '-':
  1158  		op = OMINUS
  1159  
  1160  	case '!':
  1161  		op = ONOT
  1162  
  1163  	case '^':
  1164  		op = OCOM
  1165  
  1166  	case LCOMM:
  1167  		// receive op (<-x) or receive-only channel (<-chan E)
  1168  		p.next()
  1169  
  1170  		// If the next token is LCHAN we still don't know if it is
  1171  		// a channel (<-chan int) or a receive op (<-chan int(ch)).
  1172  		// We only know once we have found the end of the uexpr.
  1173  
  1174  		x := p.uexpr()
  1175  
  1176  		// There are two cases:
  1177  		//
  1178  		//   <-chan...  => <-x is a channel type
  1179  		//   <-x        => <-x is a receive operation
  1180  		//
  1181  		// In the first case, <- must be re-associated with
  1182  		// the channel type parsed already:
  1183  		//
  1184  		//   <-(chan E)   =>  (<-chan E)
  1185  		//   <-(chan<-E)  =>  (<-chan (<-E))
  1186  
  1187  		if x.Op == OTCHAN {
  1188  			// x is a channel type => re-associate <-
  1189  			dir := Csend
  1190  			t := x
  1191  			for ; t.Op == OTCHAN && dir == Csend; t = t.Left {
  1192  				dir = ChanDir(t.Etype)
  1193  				if dir == Crecv {
  1194  					// t is type <-chan E but <-<-chan E is not permitted
  1195  					// (report same error as for "type _ <-<-chan E")
  1196  					p.syntax_error("unexpected <-, expecting chan")
  1197  					// already progressed, no need to advance
  1198  				}
  1199  				t.Etype = EType(Crecv)
  1200  			}
  1201  			if dir == Csend {
  1202  				// channel dir is <- but channel element E is not a channel
  1203  				// (report same error as for "type _ <-chan<-E")
  1204  				p.syntax_error(fmt.Sprintf("unexpected %v, expecting chan", t))
  1205  				// already progressed, no need to advance
  1206  			}
  1207  			return x
  1208  		}
  1209  
  1210  		// x is not a channel type => we have a receive op
  1211  		return Nod(ORECV, x, nil)
  1212  
  1213  	default:
  1214  		return p.pexpr(false)
  1215  	}
  1216  
  1217  	// simple uexpr
  1218  	p.next()
  1219  	return Nod(op, p.uexpr(), nil)
  1220  }
  1221  
  1222  // pseudocall parses call-like statements that can be preceded by 'defer' and 'go'.
  1223  func (p *parser) pseudocall() *Node {
  1224  	if trace && Debug['x'] != 0 {
  1225  		defer p.trace("pseudocall")()
  1226  	}
  1227  
  1228  	x := p.pexpr(p.tok == '(') // keep_parens so we can report error below
  1229  	switch x.Op {
  1230  	case OCALL:
  1231  		return x
  1232  	case OPAREN:
  1233  		Yyerror("expression in go/defer must not be parenthesized")
  1234  		// already progressed, no need to advance
  1235  	default:
  1236  		Yyerror("expression in go/defer must be function call")
  1237  		// already progressed, no need to advance
  1238  	}
  1239  	return nil
  1240  }
  1241  
  1242  // Operand     = Literal | OperandName | MethodExpr | "(" Expression ")" .
  1243  // Literal     = BasicLit | CompositeLit | FunctionLit .
  1244  // BasicLit    = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
  1245  // OperandName = identifier | QualifiedIdent.
  1246  func (p *parser) operand(keep_parens bool) *Node {
  1247  	if trace && Debug['x'] != 0 {
  1248  		defer p.trace("operand")()
  1249  	}
  1250  
  1251  	switch p.tok {
  1252  	case LLITERAL:
  1253  		x := nodlit(p.val)
  1254  		p.next()
  1255  		return x
  1256  
  1257  	case LNAME, '@', '?':
  1258  		return p.name()
  1259  
  1260  	case '(':
  1261  		p.next()
  1262  		p.xnest++
  1263  		x := p.expr() // expr_or_type
  1264  		p.xnest--
  1265  		p.want(')')
  1266  
  1267  		// Optimization: Record presence of ()'s only where needed
  1268  		// for error reporting. Don't bother in other cases; it is
  1269  		// just a waste of memory and time.
  1270  
  1271  		// Parentheses are not permitted on lhs of := .
  1272  		switch x.Op {
  1273  		case ONAME, ONONAME, OPACK, OTYPE, OLITERAL, OTYPESW:
  1274  			keep_parens = true
  1275  		}
  1276  
  1277  		// Parentheses are not permitted around T in a composite
  1278  		// literal T{}. If the next token is a {, assume x is a
  1279  		// composite literal type T (it may not be, { could be
  1280  		// the opening brace of a block, but we don't know yet).
  1281  		if p.tok == '{' {
  1282  			keep_parens = true
  1283  		}
  1284  
  1285  		// Parentheses are also not permitted around the expression
  1286  		// in a go/defer statement. In that case, operand is called
  1287  		// with keep_parens set.
  1288  		if keep_parens {
  1289  			x = Nod(OPAREN, x, nil)
  1290  		}
  1291  		return x
  1292  
  1293  	case LFUNC:
  1294  		t := p.ntype() // fntype
  1295  		if p.tok == '{' {
  1296  			// fnlitdcl
  1297  			closurehdr(t)
  1298  			// fnliteral
  1299  			p.next() // consume '{'
  1300  			p.fnest++
  1301  			p.xnest++
  1302  			body := p.stmt_list()
  1303  			p.xnest--
  1304  			p.fnest--
  1305  			p.want('}')
  1306  			return closurebody(body)
  1307  		}
  1308  		return t
  1309  
  1310  	case '[', LCHAN, LMAP, LSTRUCT, LINTERFACE:
  1311  		return p.ntype() // othertype
  1312  
  1313  	case '{':
  1314  		// common case: p.header is missing simple_stmt before { in if, for, switch
  1315  		p.syntax_error("missing operand")
  1316  		// '{' will be consumed in pexpr - no need to consume it here
  1317  		return nil
  1318  
  1319  	default:
  1320  		p.syntax_error("expecting expression")
  1321  		p.advance()
  1322  		return nil
  1323  	}
  1324  
  1325  	// Syntactically, composite literals are operands. Because a complit
  1326  	// type may be a qualified identifier which is handled by pexpr
  1327  	// (together with selector expressions), complits are parsed there
  1328  	// as well (operand is only called from pexpr).
  1329  }
  1330  
  1331  // PrimaryExpr =
  1332  // 	Operand |
  1333  // 	Conversion |
  1334  // 	PrimaryExpr Selector |
  1335  // 	PrimaryExpr Index |
  1336  // 	PrimaryExpr Slice |
  1337  // 	PrimaryExpr TypeAssertion |
  1338  // 	PrimaryExpr Arguments .
  1339  //
  1340  // Selector       = "." identifier .
  1341  // Index          = "[" Expression "]" .
  1342  // Slice          = "[" ( [ Expression ] ":" [ Expression ] ) |
  1343  //                      ( [ Expression ] ":" Expression ":" Expression )
  1344  //                  "]" .
  1345  // TypeAssertion  = "." "(" Type ")" .
  1346  // Arguments      = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
  1347  func (p *parser) pexpr(keep_parens bool) *Node {
  1348  	if trace && Debug['x'] != 0 {
  1349  		defer p.trace("pexpr")()
  1350  	}
  1351  
  1352  	x := p.operand(keep_parens)
  1353  
  1354  loop:
  1355  	for {
  1356  		switch p.tok {
  1357  		case '.':
  1358  			p.next()
  1359  			switch p.tok {
  1360  			case LNAME, '@', '?':
  1361  				// pexpr '.' sym
  1362  				x = p.new_dotname(x)
  1363  
  1364  			case '(':
  1365  				p.next()
  1366  				switch p.tok {
  1367  				default:
  1368  					// pexpr '.' '(' expr_or_type ')'
  1369  					t := p.expr() // expr_or_type
  1370  					p.want(')')
  1371  					x = Nod(ODOTTYPE, x, t)
  1372  
  1373  				case LTYPE:
  1374  					// pexpr '.' '(' LTYPE ')'
  1375  					p.next()
  1376  					p.want(')')
  1377  					x = Nod(OTYPESW, nil, x)
  1378  				}
  1379  
  1380  			default:
  1381  				p.syntax_error("expecting name or (")
  1382  				p.advance(';', '}')
  1383  			}
  1384  
  1385  		case '[':
  1386  			p.next()
  1387  			p.xnest++
  1388  			var index [3]*Node
  1389  			if p.tok != ':' {
  1390  				index[0] = p.expr()
  1391  			}
  1392  			ncol := 0
  1393  			for ncol < len(index)-1 && p.got(':') {
  1394  				ncol++
  1395  				if p.tok != EOF && p.tok != ':' && p.tok != ']' {
  1396  					index[ncol] = p.expr()
  1397  				}
  1398  			}
  1399  			p.xnest--
  1400  			p.want(']')
  1401  
  1402  			switch ncol {
  1403  			case 0:
  1404  				i := index[0]
  1405  				if i == nil {
  1406  					Yyerror("missing index in index expression")
  1407  				}
  1408  				x = Nod(OINDEX, x, i)
  1409  			case 1:
  1410  				x = Nod(OSLICE, x, nil)
  1411  				x.SetSliceBounds(index[0], index[1], nil)
  1412  			case 2:
  1413  				if index[1] == nil {
  1414  					Yyerror("middle index required in 3-index slice")
  1415  				}
  1416  				if index[2] == nil {
  1417  					Yyerror("final index required in 3-index slice")
  1418  				}
  1419  				x = Nod(OSLICE3, x, nil)
  1420  				x.SetSliceBounds(index[0], index[1], index[2])
  1421  
  1422  			default:
  1423  				panic("unreachable")
  1424  			}
  1425  
  1426  		case '(':
  1427  			// convtype '(' expr ocomma ')'
  1428  			args, ddd := p.arg_list()
  1429  
  1430  			// call or conversion
  1431  			x = Nod(OCALL, x, nil)
  1432  			x.List.Set(args)
  1433  			x.Isddd = ddd
  1434  
  1435  		case '{':
  1436  			// operand may have returned a parenthesized complit
  1437  			// type; accept it but complain if we have a complit
  1438  			t := unparen(x)
  1439  			// determine if '{' belongs to a complit or a compound_stmt
  1440  			complit_ok := false
  1441  			switch t.Op {
  1442  			case ONAME, ONONAME, OTYPE, OPACK, OXDOT, ODOT:
  1443  				if p.xnest >= 0 {
  1444  					// x is considered a comptype
  1445  					complit_ok = true
  1446  				}
  1447  			case OTARRAY, OTSTRUCT, OTMAP:
  1448  				// x is a comptype
  1449  				complit_ok = true
  1450  			}
  1451  			if !complit_ok {
  1452  				break loop
  1453  			}
  1454  			if t != x {
  1455  				p.syntax_error("cannot parenthesize type in composite literal")
  1456  				// already progressed, no need to advance
  1457  			}
  1458  			n := p.complitexpr()
  1459  			n.Right = x
  1460  			x = n
  1461  
  1462  		default:
  1463  			break loop
  1464  		}
  1465  	}
  1466  
  1467  	return x
  1468  }
  1469  
  1470  // KeyedElement = [ Key ":" ] Element .
  1471  func (p *parser) keyval() *Node {
  1472  	if trace && Debug['x'] != 0 {
  1473  		defer p.trace("keyval")()
  1474  	}
  1475  
  1476  	// A composite literal commonly spans several lines,
  1477  	// so the line number on errors may be misleading.
  1478  	// Wrap values (but not keys!) that don't carry line
  1479  	// numbers.
  1480  
  1481  	x := p.bare_complitexpr()
  1482  
  1483  	if p.got(':') {
  1484  		// key ':' value
  1485  		return Nod(OKEY, x, wrapname(p.bare_complitexpr()))
  1486  	}
  1487  
  1488  	// value
  1489  	return wrapname(x)
  1490  }
  1491  
  1492  func wrapname(x *Node) *Node {
  1493  	// These nodes do not carry line numbers.
  1494  	// Introduce a wrapper node to give the correct line.
  1495  	switch x.Op {
  1496  	case ONAME, ONONAME, OTYPE, OPACK, OLITERAL:
  1497  		x = Nod(OPAREN, x, nil)
  1498  		x.Implicit = true
  1499  	}
  1500  	return x
  1501  }
  1502  
  1503  // Element = Expression | LiteralValue .
  1504  func (p *parser) bare_complitexpr() *Node {
  1505  	if trace && Debug['x'] != 0 {
  1506  		defer p.trace("bare_complitexpr")()
  1507  	}
  1508  
  1509  	if p.tok == '{' {
  1510  		// '{' start_complit braced_keyval_list '}'
  1511  		return p.complitexpr()
  1512  	}
  1513  
  1514  	return p.expr()
  1515  }
  1516  
  1517  // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
  1518  func (p *parser) complitexpr() *Node {
  1519  	if trace && Debug['x'] != 0 {
  1520  		defer p.trace("complitexpr")()
  1521  	}
  1522  
  1523  	// make node early so we get the right line number
  1524  	n := Nod(OCOMPLIT, nil, nil)
  1525  
  1526  	p.want('{')
  1527  	p.xnest++
  1528  
  1529  	var l []*Node
  1530  	for p.tok != EOF && p.tok != '}' {
  1531  		l = append(l, p.keyval())
  1532  		if !p.ocomma('}') {
  1533  			break
  1534  		}
  1535  	}
  1536  
  1537  	p.xnest--
  1538  	p.want('}')
  1539  
  1540  	n.List.Set(l)
  1541  	return n
  1542  }
  1543  
  1544  // names and types
  1545  //	newname is used before declared
  1546  //	oldname is used after declared
  1547  func (p *parser) new_name(sym *Sym) *Node {
  1548  	if trace && Debug['x'] != 0 {
  1549  		defer p.trace("new_name")()
  1550  	}
  1551  
  1552  	if sym != nil {
  1553  		return newname(sym)
  1554  	}
  1555  	return nil
  1556  }
  1557  
  1558  func (p *parser) dcl_name() *Node {
  1559  	if trace && Debug['x'] != 0 {
  1560  		defer p.trace("dcl_name")()
  1561  	}
  1562  
  1563  	symlineno := lineno
  1564  	sym := p.sym()
  1565  	if sym == nil {
  1566  		yyerrorl(symlineno, "invalid declaration")
  1567  		return nil
  1568  	}
  1569  	return dclname(sym)
  1570  }
  1571  
  1572  func (p *parser) onew_name() *Node {
  1573  	if trace && Debug['x'] != 0 {
  1574  		defer p.trace("onew_name")()
  1575  	}
  1576  
  1577  	switch p.tok {
  1578  	case LNAME, '@', '?':
  1579  		return p.new_name(p.sym())
  1580  	}
  1581  	return nil
  1582  }
  1583  
  1584  func (p *parser) sym() *Sym {
  1585  	switch p.tok {
  1586  	case LNAME:
  1587  		s := p.sym_ // from localpkg
  1588  		p.next()
  1589  		// during imports, unqualified non-exported identifiers are from builtinpkg
  1590  		if importpkg != nil && !exportname(s.Name) {
  1591  			s = Pkglookup(s.Name, builtinpkg)
  1592  		}
  1593  		return s
  1594  
  1595  	case '@':
  1596  		return p.hidden_importsym()
  1597  
  1598  	case '?':
  1599  		p.next()
  1600  		return nil
  1601  
  1602  	default:
  1603  		p.syntax_error("expecting name")
  1604  		p.advance()
  1605  		return new(Sym)
  1606  	}
  1607  }
  1608  
  1609  func mkname(sym *Sym) *Node {
  1610  	n := oldname(sym)
  1611  	if n.Name != nil && n.Name.Pack != nil {
  1612  		n.Name.Pack.Used = true
  1613  	}
  1614  	return n
  1615  }
  1616  
  1617  func (p *parser) name() *Node {
  1618  	if trace && Debug['x'] != 0 {
  1619  		defer p.trace("name")()
  1620  	}
  1621  
  1622  	return mkname(p.sym())
  1623  }
  1624  
  1625  // [ "..." ] Type
  1626  func (p *parser) dotdotdot() *Node {
  1627  	if trace && Debug['x'] != 0 {
  1628  		defer p.trace("dotdotdot")()
  1629  	}
  1630  
  1631  	p.want(LDDD)
  1632  	if typ := p.try_ntype(); typ != nil {
  1633  		return Nod(ODDD, typ, nil)
  1634  	}
  1635  
  1636  	Yyerror("final argument in variadic function missing type")
  1637  	return Nod(ODDD, typenod(typ(TINTER)), nil)
  1638  }
  1639  
  1640  func (p *parser) ntype() *Node {
  1641  	if trace && Debug['x'] != 0 {
  1642  		defer p.trace("ntype")()
  1643  	}
  1644  
  1645  	if typ := p.try_ntype(); typ != nil {
  1646  		return typ
  1647  	}
  1648  
  1649  	p.syntax_error("")
  1650  	p.advance()
  1651  	return nil
  1652  }
  1653  
  1654  // signature parses a function signature and returns an OTFUNC node.
  1655  //
  1656  // Signature = Parameters [ Result ] .
  1657  func (p *parser) signature(recv *Node) *Node {
  1658  	if trace && Debug['x'] != 0 {
  1659  		defer p.trace("signature")()
  1660  	}
  1661  
  1662  	params := p.param_list(true)
  1663  
  1664  	var result []*Node
  1665  	if p.tok == '(' {
  1666  		result = p.param_list(false)
  1667  	} else if t := p.try_ntype(); t != nil {
  1668  		result = []*Node{Nod(ODCLFIELD, nil, t)}
  1669  	}
  1670  
  1671  	typ := Nod(OTFUNC, recv, nil)
  1672  	typ.List.Set(params)
  1673  	typ.Rlist.Set(result)
  1674  
  1675  	return typ
  1676  }
  1677  
  1678  // try_ntype is like ntype but it returns nil if there was no type
  1679  // instead of reporting an error.
  1680  //
  1681  // Type     = TypeName | TypeLit | "(" Type ")" .
  1682  // TypeName = identifier | QualifiedIdent .
  1683  // TypeLit  = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
  1684  // 	      SliceType | MapType | ChannelType .
  1685  func (p *parser) try_ntype() *Node {
  1686  	if trace && Debug['x'] != 0 {
  1687  		defer p.trace("try_ntype")()
  1688  	}
  1689  
  1690  	switch p.tok {
  1691  	case LCOMM:
  1692  		// recvchantype
  1693  		p.next()
  1694  		p.want(LCHAN)
  1695  		t := Nod(OTCHAN, p.chan_elem(), nil)
  1696  		t.Etype = EType(Crecv)
  1697  		return t
  1698  
  1699  	case LFUNC:
  1700  		// fntype
  1701  		p.next()
  1702  		return p.signature(nil)
  1703  
  1704  	case '[':
  1705  		// '[' oexpr ']' ntype
  1706  		// '[' LDDD ']' ntype
  1707  		p.next()
  1708  		p.xnest++
  1709  		var len *Node
  1710  		if p.tok != ']' {
  1711  			if p.got(LDDD) {
  1712  				len = Nod(ODDD, nil, nil)
  1713  			} else {
  1714  				len = p.expr()
  1715  			}
  1716  		}
  1717  		p.xnest--
  1718  		p.want(']')
  1719  		return Nod(OTARRAY, len, p.ntype())
  1720  
  1721  	case LCHAN:
  1722  		// LCHAN non_recvchantype
  1723  		// LCHAN LCOMM ntype
  1724  		p.next()
  1725  		var dir = EType(Cboth)
  1726  		if p.got(LCOMM) {
  1727  			dir = EType(Csend)
  1728  		}
  1729  		t := Nod(OTCHAN, p.chan_elem(), nil)
  1730  		t.Etype = dir
  1731  		return t
  1732  
  1733  	case LMAP:
  1734  		// LMAP '[' ntype ']' ntype
  1735  		p.next()
  1736  		p.want('[')
  1737  		key := p.ntype()
  1738  		p.want(']')
  1739  		val := p.ntype()
  1740  		return Nod(OTMAP, key, val)
  1741  
  1742  	case LSTRUCT:
  1743  		return p.structtype()
  1744  
  1745  	case LINTERFACE:
  1746  		return p.interfacetype()
  1747  
  1748  	case '*':
  1749  		// ptrtype
  1750  		p.next()
  1751  		return Nod(OIND, p.ntype(), nil)
  1752  
  1753  	case LNAME, '@', '?':
  1754  		return p.dotname()
  1755  
  1756  	case '(':
  1757  		p.next()
  1758  		t := p.ntype()
  1759  		p.want(')')
  1760  		return t
  1761  
  1762  	default:
  1763  		return nil
  1764  	}
  1765  }
  1766  
  1767  func (p *parser) chan_elem() *Node {
  1768  	if trace && Debug['x'] != 0 {
  1769  		defer p.trace("chan_elem")()
  1770  	}
  1771  
  1772  	if typ := p.try_ntype(); typ != nil {
  1773  		return typ
  1774  	}
  1775  
  1776  	p.syntax_error("missing channel element type")
  1777  	// assume element type is simply absent - don't advance
  1778  	return nil
  1779  }
  1780  
  1781  func (p *parser) new_dotname(obj *Node) *Node {
  1782  	if trace && Debug['x'] != 0 {
  1783  		defer p.trace("new_dotname")()
  1784  	}
  1785  
  1786  	sel := p.sym()
  1787  	if obj.Op == OPACK {
  1788  		s := restrictlookup(sel.Name, obj.Name.Pkg)
  1789  		obj.Used = true
  1790  		return oldname(s)
  1791  	}
  1792  	return NodSym(OXDOT, obj, sel)
  1793  }
  1794  
  1795  func (p *parser) dotname() *Node {
  1796  	if trace && Debug['x'] != 0 {
  1797  		defer p.trace("dotname")()
  1798  	}
  1799  
  1800  	name := p.name()
  1801  	if p.got('.') {
  1802  		return p.new_dotname(name)
  1803  	}
  1804  	return name
  1805  }
  1806  
  1807  // StructType = "struct" "{" { FieldDecl ";" } "}" .
  1808  func (p *parser) structtype() *Node {
  1809  	if trace && Debug['x'] != 0 {
  1810  		defer p.trace("structtype")()
  1811  	}
  1812  
  1813  	p.want(LSTRUCT)
  1814  	p.want('{')
  1815  	var l []*Node
  1816  	for p.tok != EOF && p.tok != '}' {
  1817  		l = append(l, p.structdcl()...)
  1818  		if !p.osemi('}') {
  1819  			break
  1820  		}
  1821  	}
  1822  	p.want('}')
  1823  
  1824  	t := Nod(OTSTRUCT, nil, nil)
  1825  	t.List.Set(l)
  1826  	return t
  1827  }
  1828  
  1829  // InterfaceType = "interface" "{" { MethodSpec ";" } "}" .
  1830  func (p *parser) interfacetype() *Node {
  1831  	if trace && Debug['x'] != 0 {
  1832  		defer p.trace("interfacetype")()
  1833  	}
  1834  
  1835  	p.want(LINTERFACE)
  1836  	p.want('{')
  1837  	var l []*Node
  1838  	for p.tok != EOF && p.tok != '}' {
  1839  		l = append(l, p.interfacedcl())
  1840  		if !p.osemi('}') {
  1841  			break
  1842  		}
  1843  	}
  1844  	p.want('}')
  1845  
  1846  	t := Nod(OTINTER, nil, nil)
  1847  	t.List.Set(l)
  1848  	return t
  1849  }
  1850  
  1851  // Function stuff.
  1852  // All in one place to show how crappy it all is.
  1853  
  1854  func (p *parser) xfndcl() *Node {
  1855  	if trace && Debug['x'] != 0 {
  1856  		defer p.trace("xfndcl")()
  1857  	}
  1858  
  1859  	p.want(LFUNC)
  1860  	f := p.fndcl()
  1861  	body := p.fnbody()
  1862  
  1863  	if f == nil {
  1864  		return nil
  1865  	}
  1866  
  1867  	f.Nbody.Set(body)
  1868  	f.Noescape = p.pragma&Noescape != 0
  1869  	if f.Noescape && len(body) != 0 {
  1870  		Yyerror("can only use //go:noescape with external func implementations")
  1871  	}
  1872  	f.Func.Pragma = p.pragma
  1873  	f.Func.Endlineno = lineno
  1874  
  1875  	funcbody(f)
  1876  
  1877  	return f
  1878  }
  1879  
  1880  // FunctionDecl = "func" FunctionName ( Function | Signature ) .
  1881  // FunctionName = identifier .
  1882  // Function     = Signature FunctionBody .
  1883  // MethodDecl   = "func" Receiver MethodName ( Function | Signature ) .
  1884  // Receiver     = Parameters .
  1885  func (p *parser) fndcl() *Node {
  1886  	if trace && Debug['x'] != 0 {
  1887  		defer p.trace("fndcl")()
  1888  	}
  1889  
  1890  	switch p.tok {
  1891  	case LNAME, '@', '?':
  1892  		// FunctionName Signature
  1893  		name := p.sym()
  1894  		t := p.signature(nil)
  1895  
  1896  		if name.Name == "init" {
  1897  			name = renameinit()
  1898  			if t.List.Len() > 0 || t.Rlist.Len() > 0 {
  1899  				Yyerror("func init must have no arguments and no return values")
  1900  			}
  1901  		}
  1902  
  1903  		if localpkg.Name == "main" && name.Name == "main" {
  1904  			if t.List.Len() > 0 || t.Rlist.Len() > 0 {
  1905  				Yyerror("func main must have no arguments and no return values")
  1906  			}
  1907  		}
  1908  
  1909  		f := Nod(ODCLFUNC, nil, nil)
  1910  		f.Func.Nname = newfuncname(name)
  1911  		f.Func.Nname.Name.Defn = f
  1912  		f.Func.Nname.Name.Param.Ntype = t // TODO: check if nname already has an ntype
  1913  		declare(f.Func.Nname, PFUNC)
  1914  
  1915  		funchdr(f)
  1916  		return f
  1917  
  1918  	case '(':
  1919  		// Receiver MethodName Signature
  1920  		rparam := p.param_list(false)
  1921  		var recv *Node
  1922  		if len(rparam) > 0 {
  1923  			recv = rparam[0]
  1924  		}
  1925  		name := p.sym()
  1926  		t := p.signature(recv)
  1927  
  1928  		// check after parsing header for fault-tolerance
  1929  		if recv == nil {
  1930  			Yyerror("method has no receiver")
  1931  			return nil
  1932  		}
  1933  
  1934  		if len(rparam) > 1 {
  1935  			Yyerror("method has multiple receivers")
  1936  			return nil
  1937  		}
  1938  
  1939  		if recv.Op != ODCLFIELD {
  1940  			Yyerror("bad receiver in method")
  1941  			return nil
  1942  		}
  1943  
  1944  		f := Nod(ODCLFUNC, nil, nil)
  1945  		f.Func.Shortname = newfuncname(name)
  1946  		f.Func.Nname = methodname1(f.Func.Shortname, recv.Right)
  1947  		f.Func.Nname.Name.Defn = f
  1948  		f.Func.Nname.Name.Param.Ntype = t
  1949  		declare(f.Func.Nname, PFUNC)
  1950  
  1951  		funchdr(f)
  1952  		return f
  1953  
  1954  	default:
  1955  		p.syntax_error("expecting name or (")
  1956  		p.advance('{', ';')
  1957  		return nil
  1958  	}
  1959  }
  1960  
  1961  func (p *parser) hidden_fndcl() *Node {
  1962  	if trace && Debug['x'] != 0 {
  1963  		defer p.trace("hidden_fndcl")()
  1964  	}
  1965  
  1966  	switch p.tok {
  1967  	default:
  1968  		// hidden_pkg_importsym '(' ohidden_funarg_list ')' ohidden_funres
  1969  		s1 := p.hidden_pkg_importsym()
  1970  		p.want('(')
  1971  		s3 := p.ohidden_funarg_list()
  1972  		p.want(')')
  1973  		s5 := p.ohidden_funres()
  1974  
  1975  		s := s1
  1976  		t := functype(nil, s3, s5)
  1977  
  1978  		importsym(s, ONAME)
  1979  		if s.Def != nil && s.Def.Op == ONAME {
  1980  			if Eqtype(t, s.Def.Type) {
  1981  				dclcontext = PDISCARD // since we skip funchdr below
  1982  				return nil
  1983  			}
  1984  			Yyerror("inconsistent definition for func %v during import\n\t%v\n\t%v", s, s.Def.Type, t)
  1985  		}
  1986  
  1987  		ss := newfuncname(s)
  1988  		ss.Type = t
  1989  		declare(ss, PFUNC)
  1990  
  1991  		funchdr(ss)
  1992  		return ss
  1993  
  1994  	case '(':
  1995  		// '(' hidden_funarg_list ')' sym '(' ohidden_funarg_list ')' ohidden_funres
  1996  		p.next()
  1997  		s2 := p.hidden_funarg_list()
  1998  		p.want(')')
  1999  		s4 := p.sym()
  2000  		p.want('(')
  2001  		s6 := p.ohidden_funarg_list()
  2002  		p.want(')')
  2003  		s8 := p.ohidden_funres()
  2004  
  2005  		ss := methodname1(newname(s4), s2[0].Right)
  2006  		ss.Type = functype(s2[0], s6, s8)
  2007  
  2008  		checkwidth(ss.Type)
  2009  		addmethod(s4, ss.Type, p.structpkg, false, false)
  2010  		funchdr(ss)
  2011  
  2012  		// inl.C's inlnode in on a dotmeth node expects to find the inlineable body as
  2013  		// (dotmeth's type).Nname.Inl, and dotmeth's type has been pulled
  2014  		// out by typecheck's lookdot as this $$.ttype. So by providing
  2015  		// this back link here we avoid special casing there.
  2016  		ss.Type.SetNname(ss)
  2017  		return ss
  2018  	}
  2019  }
  2020  
  2021  // FunctionBody = Block .
  2022  func (p *parser) fnbody() []*Node {
  2023  	if trace && Debug['x'] != 0 {
  2024  		defer p.trace("fnbody")()
  2025  	}
  2026  
  2027  	if p.got('{') {
  2028  		p.fnest++
  2029  		body := p.stmt_list()
  2030  		p.fnest--
  2031  		p.want('}')
  2032  		if body == nil {
  2033  			body = []*Node{Nod(OEMPTY, nil, nil)}
  2034  		}
  2035  		return body
  2036  	}
  2037  
  2038  	return nil
  2039  }
  2040  
  2041  // Declaration  = ConstDecl | TypeDecl | VarDecl .
  2042  // TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
  2043  func (p *parser) xdcl_list() (l []*Node) {
  2044  	if trace && Debug['x'] != 0 {
  2045  		defer p.trace("xdcl_list")()
  2046  	}
  2047  
  2048  	for p.tok != EOF {
  2049  		switch p.tok {
  2050  		case LVAR, LCONST, LTYPE:
  2051  			l = append(l, p.common_dcl()...)
  2052  
  2053  		case LFUNC:
  2054  			l = append(l, p.xfndcl())
  2055  
  2056  		default:
  2057  			if p.tok == '{' && len(l) != 0 && l[len(l)-1].Op == ODCLFUNC && l[len(l)-1].Nbody.Len() == 0 {
  2058  				// opening { of function declaration on next line
  2059  				p.syntax_error("unexpected semicolon or newline before {")
  2060  			} else {
  2061  				p.syntax_error("non-declaration statement outside function body")
  2062  			}
  2063  			p.advance(LVAR, LCONST, LTYPE, LFUNC)
  2064  			continue
  2065  		}
  2066  
  2067  		// Reset p.pragma BEFORE advancing to the next token (consuming ';')
  2068  		// since comments before may set pragmas for the next function decl.
  2069  		p.pragma = 0
  2070  
  2071  		if p.tok != EOF && !p.got(';') {
  2072  			p.syntax_error("after top level declaration")
  2073  			p.advance(LVAR, LCONST, LTYPE, LFUNC)
  2074  		}
  2075  	}
  2076  
  2077  	if nsyntaxerrors == 0 {
  2078  		testdclstack()
  2079  	}
  2080  	return
  2081  }
  2082  
  2083  // FieldDecl      = (IdentifierList Type | AnonymousField) [ Tag ] .
  2084  // AnonymousField = [ "*" ] TypeName .
  2085  // Tag            = string_lit .
  2086  func (p *parser) structdcl() []*Node {
  2087  	if trace && Debug['x'] != 0 {
  2088  		defer p.trace("structdcl")()
  2089  	}
  2090  
  2091  	var sym *Sym
  2092  	switch p.tok {
  2093  	case LNAME:
  2094  		sym = p.sym_
  2095  		p.next()
  2096  		if sym == nil {
  2097  			panic("unreachable") // we must have a sym for LNAME
  2098  		}
  2099  		if p.tok == '.' || p.tok == LLITERAL || p.tok == ';' || p.tok == '}' {
  2100  			// embed oliteral
  2101  			field := p.embed(sym)
  2102  			tag := p.oliteral()
  2103  
  2104  			field.SetVal(tag)
  2105  			return []*Node{field}
  2106  		}
  2107  
  2108  		// LNAME belongs to first *Sym of new_name_list
  2109  		//
  2110  		// during imports, unqualified non-exported identifiers are from builtinpkg
  2111  		if importpkg != nil && !exportname(sym.Name) {
  2112  			sym = Pkglookup(sym.Name, builtinpkg)
  2113  			if sym == nil {
  2114  				p.import_error()
  2115  			}
  2116  		}
  2117  		fallthrough
  2118  
  2119  	case '@', '?':
  2120  		// new_name_list ntype oliteral
  2121  		fields := p.new_name_list(sym)
  2122  		typ := p.ntype()
  2123  		tag := p.oliteral()
  2124  
  2125  		if len(fields) == 0 || fields[0].Sym.Name == "?" {
  2126  			// ? symbol, during import
  2127  			n := typ
  2128  			if n.Op == OIND {
  2129  				n = n.Left
  2130  			}
  2131  			n = embedded(n.Sym, importpkg)
  2132  			n.Right = typ
  2133  			n.SetVal(tag)
  2134  			return []*Node{n}
  2135  		}
  2136  
  2137  		for i, n := range fields {
  2138  			fields[i] = Nod(ODCLFIELD, n, typ)
  2139  			fields[i].SetVal(tag)
  2140  		}
  2141  		return fields
  2142  
  2143  	case '(':
  2144  		p.next()
  2145  		if p.got('*') {
  2146  			// '(' '*' embed ')' oliteral
  2147  			field := p.embed(nil)
  2148  			p.want(')')
  2149  			tag := p.oliteral()
  2150  
  2151  			field.Right = Nod(OIND, field.Right, nil)
  2152  			field.SetVal(tag)
  2153  			Yyerror("cannot parenthesize embedded type")
  2154  			return []*Node{field}
  2155  
  2156  		} else {
  2157  			// '(' embed ')' oliteral
  2158  			field := p.embed(nil)
  2159  			p.want(')')
  2160  			tag := p.oliteral()
  2161  
  2162  			field.SetVal(tag)
  2163  			Yyerror("cannot parenthesize embedded type")
  2164  			return []*Node{field}
  2165  		}
  2166  
  2167  	case '*':
  2168  		p.next()
  2169  		if p.got('(') {
  2170  			// '*' '(' embed ')' oliteral
  2171  			field := p.embed(nil)
  2172  			p.want(')')
  2173  			tag := p.oliteral()
  2174  
  2175  			field.Right = Nod(OIND, field.Right, nil)
  2176  			field.SetVal(tag)
  2177  			Yyerror("cannot parenthesize embedded type")
  2178  			return []*Node{field}
  2179  
  2180  		} else {
  2181  			// '*' embed oliteral
  2182  			field := p.embed(nil)
  2183  			tag := p.oliteral()
  2184  
  2185  			field.Right = Nod(OIND, field.Right, nil)
  2186  			field.SetVal(tag)
  2187  			return []*Node{field}
  2188  		}
  2189  
  2190  	default:
  2191  		p.syntax_error("expecting field name or embedded type")
  2192  		p.advance(';', '}')
  2193  		return nil
  2194  	}
  2195  }
  2196  
  2197  func (p *parser) oliteral() (v Val) {
  2198  	if p.tok == LLITERAL {
  2199  		v = p.val
  2200  		p.next()
  2201  	}
  2202  	return
  2203  }
  2204  
  2205  func (p *parser) packname(name *Sym) *Sym {
  2206  	if trace && Debug['x'] != 0 {
  2207  		defer p.trace("embed")()
  2208  	}
  2209  
  2210  	if name != nil {
  2211  		// LNAME was already consumed and is coming in as name
  2212  	} else if p.tok == LNAME {
  2213  		name = p.sym_
  2214  		p.next()
  2215  	} else {
  2216  		p.syntax_error("expecting name")
  2217  		p.advance('.', ';', '}')
  2218  		name = new(Sym)
  2219  	}
  2220  
  2221  	if p.got('.') {
  2222  		// LNAME '.' sym
  2223  		s := p.sym()
  2224  
  2225  		var pkg *Pkg
  2226  		if name.Def == nil || name.Def.Op != OPACK {
  2227  			Yyerror("%v is not a package", name)
  2228  			pkg = localpkg
  2229  		} else {
  2230  			name.Def.Used = true
  2231  			pkg = name.Def.Name.Pkg
  2232  		}
  2233  		return restrictlookup(s.Name, pkg)
  2234  	}
  2235  
  2236  	// LNAME
  2237  	if n := oldname(name); n.Name != nil && n.Name.Pack != nil {
  2238  		n.Name.Pack.Used = true
  2239  	}
  2240  	return name
  2241  }
  2242  
  2243  func (p *parser) embed(sym *Sym) *Node {
  2244  	if trace && Debug['x'] != 0 {
  2245  		defer p.trace("embed")()
  2246  	}
  2247  
  2248  	pkgname := p.packname(sym)
  2249  	return embedded(pkgname, localpkg)
  2250  }
  2251  
  2252  // MethodSpec        = MethodName Signature | InterfaceTypeName .
  2253  // MethodName        = identifier .
  2254  // InterfaceTypeName = TypeName .
  2255  func (p *parser) interfacedcl() *Node {
  2256  	if trace && Debug['x'] != 0 {
  2257  		defer p.trace("interfacedcl")()
  2258  	}
  2259  
  2260  	switch p.tok {
  2261  	case LNAME:
  2262  		sym := p.sym_
  2263  		p.next()
  2264  
  2265  		// accept potential name list but complain
  2266  		hasNameList := false
  2267  		for p.got(',') {
  2268  			p.sym()
  2269  			hasNameList = true
  2270  		}
  2271  		if hasNameList {
  2272  			p.syntax_error("name list not allowed in interface type")
  2273  			// already progressed, no need to advance
  2274  		}
  2275  
  2276  		if p.tok != '(' {
  2277  			// packname
  2278  			pname := p.packname(sym)
  2279  			return Nod(ODCLFIELD, nil, oldname(pname))
  2280  		}
  2281  
  2282  		// MethodName Signature
  2283  		mname := newname(sym)
  2284  		sig := p.signature(fakethis())
  2285  
  2286  		meth := Nod(ODCLFIELD, mname, sig)
  2287  		ifacedcl(meth)
  2288  		return meth
  2289  
  2290  	case '@', '?':
  2291  		// MethodName Signature
  2292  		//
  2293  		// We arrive here when parsing an interface type declared inside
  2294  		// an exported and inlineable function and the interface declares
  2295  		// unexported methods (which are then package-qualified).
  2296  		//
  2297  		// Since the compiler always flattens embedded interfaces, we
  2298  		// will never see an embedded package-qualified interface in export
  2299  		// data; i.e., when we reach here we know it must be a method.
  2300  		//
  2301  		// See also issue 14164.
  2302  		mname := newname(p.sym())
  2303  		sig := p.signature(fakethis())
  2304  
  2305  		meth := Nod(ODCLFIELD, mname, sig)
  2306  		ifacedcl(meth)
  2307  		return meth
  2308  
  2309  	case '(':
  2310  		p.next()
  2311  		pname := p.packname(nil)
  2312  		p.want(')')
  2313  		n := Nod(ODCLFIELD, nil, oldname(pname))
  2314  		Yyerror("cannot parenthesize embedded type")
  2315  		return n
  2316  
  2317  	default:
  2318  		p.syntax_error("")
  2319  		p.advance(';', '}')
  2320  		return nil
  2321  	}
  2322  }
  2323  
  2324  // param parses and returns a function parameter list entry which may be
  2325  // a parameter name and type pair (name, typ), a single type (nil, typ),
  2326  // or a single name (name, nil). In the last case, the name may still be
  2327  // a type name. The result is (nil, nil) in case of a syntax error.
  2328  //
  2329  // [ParameterName] Type
  2330  func (p *parser) param() (name *Sym, typ *Node) {
  2331  	if trace && Debug['x'] != 0 {
  2332  		defer p.trace("param")()
  2333  	}
  2334  
  2335  	switch p.tok {
  2336  	case LNAME, '@', '?':
  2337  		name = p.sym() // nil if p.tok == '?' (importing only)
  2338  		switch p.tok {
  2339  		case LCOMM, LFUNC, '[', LCHAN, LMAP, LSTRUCT, LINTERFACE, '*', LNAME, '@', '?', '(':
  2340  			// sym name_or_type
  2341  			typ = p.ntype()
  2342  
  2343  		case LDDD:
  2344  			// sym dotdotdot
  2345  			typ = p.dotdotdot()
  2346  
  2347  		default:
  2348  			// name_or_type
  2349  			if p.got('.') {
  2350  				// a qualified name cannot be a parameter name
  2351  				typ = p.new_dotname(mkname(name))
  2352  				name = nil
  2353  			}
  2354  		}
  2355  
  2356  	case LDDD:
  2357  		// dotdotdot
  2358  		typ = p.dotdotdot()
  2359  
  2360  	case LCOMM, LFUNC, '[', LCHAN, LMAP, LSTRUCT, LINTERFACE, '*', '(':
  2361  		// name_or_type
  2362  		typ = p.ntype()
  2363  
  2364  	default:
  2365  		p.syntax_error("expecting )")
  2366  		p.advance(',', ')')
  2367  	}
  2368  
  2369  	return
  2370  }
  2371  
  2372  // Parameters    = "(" [ ParameterList [ "," ] ] ")" .
  2373  // ParameterList = ParameterDecl { "," ParameterDecl } .
  2374  // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
  2375  func (p *parser) param_list(dddOk bool) []*Node {
  2376  	if trace && Debug['x'] != 0 {
  2377  		defer p.trace("param_list")()
  2378  	}
  2379  
  2380  	type param struct {
  2381  		name *Sym
  2382  		typ  *Node
  2383  	}
  2384  	var params []param
  2385  	var named int // number of parameters that have a name and type
  2386  
  2387  	p.want('(')
  2388  	for p.tok != EOF && p.tok != ')' {
  2389  		name, typ := p.param()
  2390  		params = append(params, param{name, typ})
  2391  		if name != nil && typ != nil {
  2392  			named++
  2393  		}
  2394  		if !p.ocomma(')') {
  2395  			break
  2396  		}
  2397  	}
  2398  	p.want(')')
  2399  	// 0 <= named <= len(params)
  2400  
  2401  	// There are 3 cases:
  2402  	//
  2403  	// 1) named == 0:
  2404  	//    No parameter list entry has both a name and a type; i.e. there are only
  2405  	//    unnamed parameters. Any name must be a type name; they are "converted"
  2406  	//    to types when creating the final parameter list.
  2407  	//    In case of a syntax error, there is neither a name nor a type.
  2408  	//    Nil checks take care of this.
  2409  	//
  2410  	// 2) named == len(names):
  2411  	//    All parameter list entries have both a name and a type.
  2412  	//
  2413  	// 3) Otherwise:
  2414  	if named != 0 && named != len(params) {
  2415  		// Some parameter list entries have both a name and a type:
  2416  		// Distribute types backwards and check that there are no
  2417  		// mixed named and unnamed parameters.
  2418  		var T *Node // type T in a parameter sequence: a, b, c T
  2419  		for i := len(params) - 1; i >= 0; i-- {
  2420  			p := &params[i]
  2421  			if t := p.typ; t != nil {
  2422  				// explicit type: use type for earlier parameters
  2423  				T = t
  2424  				// an explicitly typed entry must have a name
  2425  				// TODO(gri) remove extra importpkg == nil check below
  2426  				//           after switch to binary eport format
  2427  				// Exported inlined function bodies containing function
  2428  				// literals may print parameter names as '?' resulting
  2429  				// in nil *Sym and thus nil names. Don't report an error
  2430  				// in this case.
  2431  				if p.name == nil && importpkg == nil {
  2432  					T = nil // error
  2433  				}
  2434  			} else {
  2435  				// no explicit type: use type of next parameter
  2436  				p.typ = T
  2437  			}
  2438  			if T == nil {
  2439  				Yyerror("mixed named and unnamed function parameters")
  2440  				break
  2441  			}
  2442  		}
  2443  		// Unless there was an error, now all parameter entries have a type.
  2444  	}
  2445  
  2446  	// create final parameter list
  2447  	list := make([]*Node, len(params))
  2448  	for i, p := range params {
  2449  		// create dcl node
  2450  		var name, typ *Node
  2451  		if p.typ != nil {
  2452  			typ = p.typ
  2453  			if p.name != nil {
  2454  				// name must be a parameter name
  2455  				name = newname(p.name)
  2456  			}
  2457  		} else if p.name != nil {
  2458  			// p.name must be a type name (or nil in case of syntax error)
  2459  			typ = mkname(p.name)
  2460  		}
  2461  		n := Nod(ODCLFIELD, name, typ)
  2462  
  2463  		// rewrite ...T parameter
  2464  		if typ != nil && typ.Op == ODDD {
  2465  			if !dddOk {
  2466  				Yyerror("cannot use ... in receiver or result parameter list")
  2467  			} else if i+1 < len(params) {
  2468  				Yyerror("can only use ... with final parameter in list")
  2469  			}
  2470  			typ.Op = OTARRAY
  2471  			typ.Right = typ.Left
  2472  			typ.Left = nil
  2473  			n.Isddd = true
  2474  			if n.Left != nil {
  2475  				n.Left.Isddd = true
  2476  			}
  2477  		}
  2478  
  2479  		list[i] = n
  2480  	}
  2481  
  2482  	return list
  2483  }
  2484  
  2485  var missing_stmt = Nod(OXXX, nil, nil)
  2486  
  2487  // Statement =
  2488  // 	Declaration | LabeledStmt | SimpleStmt |
  2489  // 	GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
  2490  // 	FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
  2491  // 	DeferStmt .
  2492  //
  2493  // stmt may return missing_stmt.
  2494  func (p *parser) stmt() *Node {
  2495  	if trace && Debug['x'] != 0 {
  2496  		defer p.trace("stmt")()
  2497  	}
  2498  
  2499  	switch p.tok {
  2500  	case '{':
  2501  		return p.compound_stmt()
  2502  
  2503  	case LVAR, LCONST, LTYPE:
  2504  		return liststmt(p.common_dcl())
  2505  
  2506  	case LNAME, '@', '?', LLITERAL, LFUNC, '(', // operands
  2507  		'[', LSTRUCT, LMAP, LCHAN, LINTERFACE, // composite types
  2508  		'+', '-', '*', '&', '^', LCOMM, '!': // unary operators
  2509  		return p.simple_stmt(true, false)
  2510  
  2511  	case LFOR:
  2512  		return p.for_stmt()
  2513  
  2514  	case LSWITCH:
  2515  		return p.switch_stmt()
  2516  
  2517  	case LSELECT:
  2518  		return p.select_stmt()
  2519  
  2520  	case LIF:
  2521  		return p.if_stmt()
  2522  
  2523  	case LFALL:
  2524  		p.next()
  2525  		// will be converted to OFALL
  2526  		stmt := Nod(OXFALL, nil, nil)
  2527  		stmt.Xoffset = int64(block)
  2528  		return stmt
  2529  
  2530  	case LBREAK:
  2531  		p.next()
  2532  		return Nod(OBREAK, p.onew_name(), nil)
  2533  
  2534  	case LCONTINUE:
  2535  		p.next()
  2536  		return Nod(OCONTINUE, p.onew_name(), nil)
  2537  
  2538  	case LGO:
  2539  		p.next()
  2540  		return Nod(OPROC, p.pseudocall(), nil)
  2541  
  2542  	case LDEFER:
  2543  		p.next()
  2544  		return Nod(ODEFER, p.pseudocall(), nil)
  2545  
  2546  	case LGOTO:
  2547  		p.next()
  2548  		stmt := Nod(OGOTO, p.new_name(p.sym()), nil)
  2549  		stmt.Sym = dclstack // context, for goto restrictions
  2550  		return stmt
  2551  
  2552  	case LRETURN:
  2553  		p.next()
  2554  		var results []*Node
  2555  		if p.tok != ';' && p.tok != '}' {
  2556  			results = p.expr_list()
  2557  		}
  2558  
  2559  		stmt := Nod(ORETURN, nil, nil)
  2560  		stmt.List.Set(results)
  2561  		if stmt.List.Len() == 0 && Curfn != nil {
  2562  			for _, ln := range Curfn.Func.Dcl {
  2563  				if ln.Class == PPARAM {
  2564  					continue
  2565  				}
  2566  				if ln.Class != PPARAMOUT {
  2567  					break
  2568  				}
  2569  				if ln.Sym.Def != ln {
  2570  					Yyerror("%s is shadowed during return", ln.Sym.Name)
  2571  				}
  2572  			}
  2573  		}
  2574  
  2575  		return stmt
  2576  
  2577  	case ';':
  2578  		return nil
  2579  
  2580  	default:
  2581  		return missing_stmt
  2582  	}
  2583  }
  2584  
  2585  // StatementList = { Statement ";" } .
  2586  func (p *parser) stmt_list() (l []*Node) {
  2587  	if trace && Debug['x'] != 0 {
  2588  		defer p.trace("stmt_list")()
  2589  	}
  2590  
  2591  	for p.tok != EOF && p.tok != '}' && p.tok != LCASE && p.tok != LDEFAULT {
  2592  		s := p.stmt()
  2593  		if s == missing_stmt {
  2594  			break
  2595  		}
  2596  		if s == nil {
  2597  		} else if s.Op == OBLOCK && s.Ninit.Len() == 0 {
  2598  			l = append(l, s.List.Slice()...)
  2599  		} else {
  2600  			l = append(l, s)
  2601  		}
  2602  		// customized version of osemi:
  2603  		// ';' is optional before a closing ')' or '}'
  2604  		if p.tok == ')' || p.tok == '}' {
  2605  			continue
  2606  		}
  2607  		if !p.got(';') {
  2608  			p.syntax_error("at end of statement")
  2609  			p.advance(';', '}')
  2610  		}
  2611  	}
  2612  	return
  2613  }
  2614  
  2615  // IdentifierList = identifier { "," identifier } .
  2616  //
  2617  // If first != nil we have the first symbol already.
  2618  func (p *parser) new_name_list(first *Sym) []*Node {
  2619  	if trace && Debug['x'] != 0 {
  2620  		defer p.trace("new_name_list")()
  2621  	}
  2622  
  2623  	if first == nil {
  2624  		first = p.sym() // may still be nil
  2625  	}
  2626  	var l []*Node
  2627  	n := p.new_name(first)
  2628  	if n != nil {
  2629  		l = append(l, n)
  2630  	}
  2631  	for p.got(',') {
  2632  		n = p.new_name(p.sym())
  2633  		if n != nil {
  2634  			l = append(l, n)
  2635  		}
  2636  	}
  2637  	return l
  2638  }
  2639  
  2640  // IdentifierList = identifier { "," identifier } .
  2641  func (p *parser) dcl_name_list() []*Node {
  2642  	if trace && Debug['x'] != 0 {
  2643  		defer p.trace("dcl_name_list")()
  2644  	}
  2645  
  2646  	s := []*Node{p.dcl_name()}
  2647  	for p.got(',') {
  2648  		s = append(s, p.dcl_name())
  2649  	}
  2650  	return s
  2651  }
  2652  
  2653  // ExpressionList = Expression { "," Expression } .
  2654  func (p *parser) expr_list() []*Node {
  2655  	if trace && Debug['x'] != 0 {
  2656  		defer p.trace("expr_list")()
  2657  	}
  2658  
  2659  	l := []*Node{p.expr()}
  2660  	for p.got(',') {
  2661  		l = append(l, p.expr())
  2662  	}
  2663  	return l
  2664  }
  2665  
  2666  // Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
  2667  func (p *parser) arg_list() (l []*Node, ddd bool) {
  2668  	if trace && Debug['x'] != 0 {
  2669  		defer p.trace("arg_list")()
  2670  	}
  2671  
  2672  	p.want('(')
  2673  	p.xnest++
  2674  
  2675  	for p.tok != EOF && p.tok != ')' && !ddd {
  2676  		l = append(l, p.expr()) // expr_or_type
  2677  		ddd = p.got(LDDD)
  2678  		if !p.ocomma(')') {
  2679  			break
  2680  		}
  2681  	}
  2682  
  2683  	p.xnest--
  2684  	p.want(')')
  2685  
  2686  	return
  2687  }
  2688  
  2689  // osemi parses an optional semicolon.
  2690  func (p *parser) osemi(follow int32) bool {
  2691  	switch p.tok {
  2692  	case ';':
  2693  		p.next()
  2694  		return true
  2695  
  2696  	case ')', '}':
  2697  		// semicolon is optional before ) or }
  2698  		return true
  2699  	}
  2700  
  2701  	p.syntax_error("expecting semicolon, newline, or " + tokstring(follow))
  2702  	p.advance(follow)
  2703  	return false
  2704  }
  2705  
  2706  // ocomma parses an optional comma.
  2707  func (p *parser) ocomma(follow int32) bool {
  2708  	switch p.tok {
  2709  	case ',':
  2710  		p.next()
  2711  		return true
  2712  
  2713  	case ')', '}':
  2714  		// comma is optional before ) or }
  2715  		return true
  2716  	}
  2717  
  2718  	p.syntax_error("expecting comma or " + tokstring(follow))
  2719  	p.advance(follow)
  2720  	return false
  2721  }
  2722  
  2723  // ----------------------------------------------------------------------------
  2724  // Importing packages
  2725  
  2726  func (p *parser) import_error() {
  2727  	p.syntax_error("in export data of imported package")
  2728  	p.next()
  2729  }
  2730  
  2731  // The methods below reflect a 1:1 translation of the original (and now defunct)
  2732  // go.y yacc productions. They could be simplified significantly and also use better
  2733  // variable names. However, we will be able to delete them once we enable the
  2734  // new export format by default, so it's not worth the effort (issue 13241).
  2735  
  2736  func (p *parser) hidden_importsym() *Sym {
  2737  	if trace && Debug['x'] != 0 {
  2738  		defer p.trace("hidden_importsym")()
  2739  	}
  2740  
  2741  	p.want('@')
  2742  	var s2 Val
  2743  	if p.tok == LLITERAL {
  2744  		s2 = p.val
  2745  		p.next()
  2746  	} else {
  2747  		p.import_error()
  2748  	}
  2749  	p.want('.')
  2750  
  2751  	switch p.tok {
  2752  	case LNAME:
  2753  		s4 := p.sym_
  2754  		p.next()
  2755  
  2756  		var p *Pkg
  2757  
  2758  		if s2.U.(string) == "" {
  2759  			p = importpkg
  2760  		} else {
  2761  			if isbadimport(s2.U.(string)) {
  2762  				errorexit()
  2763  			}
  2764  			p = mkpkg(s2.U.(string))
  2765  		}
  2766  		return Pkglookup(s4.Name, p)
  2767  
  2768  	case '?':
  2769  		p.next()
  2770  
  2771  		var p *Pkg
  2772  
  2773  		if s2.U.(string) == "" {
  2774  			p = importpkg
  2775  		} else {
  2776  			if isbadimport(s2.U.(string)) {
  2777  				errorexit()
  2778  			}
  2779  			p = mkpkg(s2.U.(string))
  2780  		}
  2781  		return Pkglookup("?", p)
  2782  
  2783  	default:
  2784  		p.import_error()
  2785  		return nil
  2786  	}
  2787  }
  2788  
  2789  func (p *parser) ohidden_funarg_list() []*Node {
  2790  	if trace && Debug['x'] != 0 {
  2791  		defer p.trace("ohidden_funarg_list")()
  2792  	}
  2793  
  2794  	var ss []*Node
  2795  	if p.tok != ')' {
  2796  		ss = p.hidden_funarg_list()
  2797  	}
  2798  	return ss
  2799  }
  2800  
  2801  func (p *parser) ohidden_structdcl_list() []*Node {
  2802  	if trace && Debug['x'] != 0 {
  2803  		defer p.trace("ohidden_structdcl_list")()
  2804  	}
  2805  
  2806  	var ss []*Node
  2807  	if p.tok != '}' {
  2808  		ss = p.hidden_structdcl_list()
  2809  	}
  2810  	return ss
  2811  }
  2812  
  2813  func (p *parser) ohidden_interfacedcl_list() []*Node {
  2814  	if trace && Debug['x'] != 0 {
  2815  		defer p.trace("ohidden_interfacedcl_list")()
  2816  	}
  2817  
  2818  	var ss []*Node
  2819  	if p.tok != '}' {
  2820  		ss = p.hidden_interfacedcl_list()
  2821  	}
  2822  	return ss
  2823  }
  2824  
  2825  // import syntax from package header
  2826  func (p *parser) hidden_import() {
  2827  	if trace && Debug['x'] != 0 {
  2828  		defer p.trace("hidden_import")()
  2829  	}
  2830  
  2831  	switch p.tok {
  2832  	case LIMPORT:
  2833  		// LIMPORT LNAME LLITERAL ';'
  2834  		p.next()
  2835  		var s2 *Sym
  2836  		if p.tok == LNAME {
  2837  			s2 = p.sym_
  2838  			p.next()
  2839  		} else {
  2840  			p.import_error()
  2841  		}
  2842  		var s3 Val
  2843  		if p.tok == LLITERAL {
  2844  			s3 = p.val
  2845  			p.next()
  2846  		} else {
  2847  			p.import_error()
  2848  		}
  2849  		p.want(';')
  2850  
  2851  		importimport(s2, s3.U.(string))
  2852  
  2853  	case LVAR:
  2854  		// LVAR hidden_pkg_importsym hidden_type ';'
  2855  		p.next()
  2856  		s2 := p.hidden_pkg_importsym()
  2857  		s3 := p.hidden_type()
  2858  		p.want(';')
  2859  
  2860  		importvar(s2, s3)
  2861  
  2862  	case LCONST:
  2863  		// LCONST hidden_pkg_importsym '=' hidden_constant ';'
  2864  		// LCONST hidden_pkg_importsym hidden_type '=' hidden_constant ';'
  2865  		p.next()
  2866  		s2 := p.hidden_pkg_importsym()
  2867  		var s3 *Type = Types[TIDEAL]
  2868  		if p.tok != '=' {
  2869  			s3 = p.hidden_type()
  2870  		}
  2871  		p.want('=')
  2872  		s4 := p.hidden_constant()
  2873  		p.want(';')
  2874  
  2875  		importconst(s2, s3, s4)
  2876  
  2877  	case LTYPE:
  2878  		// LTYPE hidden_pkgtype hidden_type ';'
  2879  		p.next()
  2880  		s2 := p.hidden_pkgtype()
  2881  		s3 := p.hidden_type()
  2882  		p.want(';')
  2883  
  2884  		importtype(s2, s3)
  2885  
  2886  	case LFUNC:
  2887  		// LFUNC hidden_fndcl fnbody ';'
  2888  		p.next()
  2889  		s2 := p.hidden_fndcl()
  2890  		s3 := p.fnbody()
  2891  		p.want(';')
  2892  
  2893  		if s2 == nil {
  2894  			dclcontext = PEXTERN // since we skip the funcbody below
  2895  			return
  2896  		}
  2897  
  2898  		s2.Func.Inl.Set(s3)
  2899  
  2900  		funcbody(s2)
  2901  		importlist = append(importlist, s2)
  2902  
  2903  		if Debug['E'] > 0 {
  2904  			fmt.Printf("import [%q] func %v \n", importpkg.Path, s2)
  2905  			if Debug['m'] > 2 && s2.Func.Inl.Len() != 0 {
  2906  				fmt.Printf("inl body:%v\n", s2.Func.Inl)
  2907  			}
  2908  		}
  2909  
  2910  	default:
  2911  		p.import_error()
  2912  	}
  2913  }
  2914  
  2915  func (p *parser) hidden_pkg_importsym() *Sym {
  2916  	if trace && Debug['x'] != 0 {
  2917  		defer p.trace("hidden_pkg_importsym")()
  2918  	}
  2919  
  2920  	s := p.hidden_importsym()
  2921  	p.structpkg = s.Pkg
  2922  	return s
  2923  }
  2924  
  2925  func (p *parser) hidden_pkgtype() *Type {
  2926  	if trace && Debug['x'] != 0 {
  2927  		defer p.trace("hidden_pkgtype")()
  2928  	}
  2929  
  2930  	return pkgtype(p.hidden_pkg_importsym())
  2931  }
  2932  
  2933  // ----------------------------------------------------------------------------
  2934  // Importing types
  2935  
  2936  func (p *parser) hidden_type() *Type {
  2937  	if trace && Debug['x'] != 0 {
  2938  		defer p.trace("hidden_type")()
  2939  	}
  2940  
  2941  	switch p.tok {
  2942  	default:
  2943  		return p.hidden_type_misc()
  2944  	case LCOMM:
  2945  		return p.hidden_type_recv_chan()
  2946  	case LFUNC:
  2947  		return p.hidden_type_func()
  2948  	}
  2949  }
  2950  
  2951  func (p *parser) hidden_type_non_recv_chan() *Type {
  2952  	if trace && Debug['x'] != 0 {
  2953  		defer p.trace("hidden_type_non_recv_chan")()
  2954  	}
  2955  
  2956  	switch p.tok {
  2957  	default:
  2958  		return p.hidden_type_misc()
  2959  	case LFUNC:
  2960  		return p.hidden_type_func()
  2961  	}
  2962  }
  2963  
  2964  func (p *parser) hidden_type_misc() *Type {
  2965  	if trace && Debug['x'] != 0 {
  2966  		defer p.trace("hidden_type_misc")()
  2967  	}
  2968  
  2969  	switch p.tok {
  2970  	case '@':
  2971  		// hidden_importsym
  2972  		s1 := p.hidden_importsym()
  2973  		return pkgtype(s1)
  2974  
  2975  	case LNAME:
  2976  		// LNAME
  2977  		s1 := p.sym_
  2978  		p.next()
  2979  
  2980  		// predefined name like uint8
  2981  		s1 = Pkglookup(s1.Name, builtinpkg)
  2982  		if s1.Def == nil || s1.Def.Op != OTYPE {
  2983  			Yyerror("%s is not a type", s1.Name)
  2984  			return nil
  2985  		} else {
  2986  			return s1.Def.Type
  2987  		}
  2988  
  2989  	case '[':
  2990  		// '[' ']' hidden_type
  2991  		// '[' LLITERAL ']' hidden_type
  2992  		p.next()
  2993  		var s2 *Node
  2994  		if p.tok == LLITERAL {
  2995  			s2 = nodlit(p.val)
  2996  			p.next()
  2997  		}
  2998  		p.want(']')
  2999  		s4 := p.hidden_type()
  3000  
  3001  		return aindex(s2, s4)
  3002  
  3003  	case LMAP:
  3004  		// LMAP '[' hidden_type ']' hidden_type
  3005  		p.next()
  3006  		p.want('[')
  3007  		s3 := p.hidden_type()
  3008  		p.want(']')
  3009  		s5 := p.hidden_type()
  3010  
  3011  		return typMap(s3, s5)
  3012  
  3013  	case LSTRUCT:
  3014  		// LSTRUCT '{' ohidden_structdcl_list '}'
  3015  		p.next()
  3016  		p.want('{')
  3017  		s3 := p.ohidden_structdcl_list()
  3018  		p.want('}')
  3019  
  3020  		return tostruct(s3)
  3021  
  3022  	case LINTERFACE:
  3023  		// LINTERFACE '{' ohidden_interfacedcl_list '}'
  3024  		p.next()
  3025  		p.want('{')
  3026  		s3 := p.ohidden_interfacedcl_list()
  3027  		p.want('}')
  3028  
  3029  		return tointerface(s3)
  3030  
  3031  	case '*':
  3032  		// '*' hidden_type
  3033  		p.next()
  3034  		s2 := p.hidden_type()
  3035  		return Ptrto(s2)
  3036  
  3037  	case LCHAN:
  3038  		p.next()
  3039  		switch p.tok {
  3040  		default:
  3041  			// LCHAN hidden_type_non_recv_chan
  3042  			s2 := p.hidden_type_non_recv_chan()
  3043  			ss := typChan(s2, Cboth)
  3044  			return ss
  3045  
  3046  		case '(':
  3047  			// LCHAN '(' hidden_type_recv_chan ')'
  3048  			p.next()
  3049  			s3 := p.hidden_type_recv_chan()
  3050  			p.want(')')
  3051  			ss := typChan(s3, Cboth)
  3052  			return ss
  3053  
  3054  		case LCOMM:
  3055  			// LCHAN hidden_type
  3056  			p.next()
  3057  			s3 := p.hidden_type()
  3058  			ss := typChan(s3, Csend)
  3059  			return ss
  3060  		}
  3061  
  3062  	default:
  3063  		p.import_error()
  3064  		return nil
  3065  	}
  3066  }
  3067  
  3068  func (p *parser) hidden_type_recv_chan() *Type {
  3069  	if trace && Debug['x'] != 0 {
  3070  		defer p.trace("hidden_type_recv_chan")()
  3071  	}
  3072  
  3073  	p.want(LCOMM)
  3074  	p.want(LCHAN)
  3075  	s3 := p.hidden_type()
  3076  
  3077  	ss := typChan(s3, Crecv)
  3078  	return ss
  3079  }
  3080  
  3081  func (p *parser) hidden_type_func() *Type {
  3082  	if trace && Debug['x'] != 0 {
  3083  		defer p.trace("hidden_type_func")()
  3084  	}
  3085  
  3086  	p.want(LFUNC)
  3087  	p.want('(')
  3088  	s3 := p.ohidden_funarg_list()
  3089  	p.want(')')
  3090  	s5 := p.ohidden_funres()
  3091  
  3092  	return functype(nil, s3, s5)
  3093  }
  3094  
  3095  func (p *parser) hidden_funarg() *Node {
  3096  	if trace && Debug['x'] != 0 {
  3097  		defer p.trace("hidden_funarg")()
  3098  	}
  3099  
  3100  	s1 := p.sym()
  3101  	switch p.tok {
  3102  	default:
  3103  		s2 := p.hidden_type()
  3104  		s3 := p.oliteral()
  3105  
  3106  		ss := Nod(ODCLFIELD, nil, typenod(s2))
  3107  		if s1 != nil {
  3108  			ss.Left = newname(s1)
  3109  		}
  3110  		ss.SetVal(s3)
  3111  		return ss
  3112  
  3113  	case LDDD:
  3114  		p.next()
  3115  		s3 := p.hidden_type()
  3116  		s4 := p.oliteral()
  3117  
  3118  		t := typSlice(s3)
  3119  
  3120  		ss := Nod(ODCLFIELD, nil, typenod(t))
  3121  		if s1 != nil {
  3122  			ss.Left = newname(s1)
  3123  		}
  3124  		ss.Isddd = true
  3125  		ss.SetVal(s4)
  3126  
  3127  		return ss
  3128  	}
  3129  }
  3130  
  3131  func (p *parser) hidden_structdcl() *Node {
  3132  	if trace && Debug['x'] != 0 {
  3133  		defer p.trace("hidden_structdcl")()
  3134  	}
  3135  
  3136  	s1 := p.sym()
  3137  	s2 := p.hidden_type()
  3138  	s3 := p.oliteral()
  3139  
  3140  	var ss *Node
  3141  	if s1 != nil && s1.Name != "?" {
  3142  		ss = Nod(ODCLFIELD, newname(s1), typenod(s2))
  3143  		ss.SetVal(s3)
  3144  	} else {
  3145  		s := s2.Sym
  3146  		if s == nil && s2.IsPtr() {
  3147  			s = s2.Elem().Sym
  3148  		}
  3149  		pkg := importpkg
  3150  		if s1 != nil {
  3151  			pkg = s1.Pkg
  3152  		}
  3153  		ss = embedded(s, pkg)
  3154  		ss.Right = typenod(s2)
  3155  		ss.SetVal(s3)
  3156  	}
  3157  
  3158  	return ss
  3159  }
  3160  
  3161  func (p *parser) hidden_interfacedcl() *Node {
  3162  	if trace && Debug['x'] != 0 {
  3163  		defer p.trace("hidden_interfacedcl")()
  3164  	}
  3165  
  3166  	// The original (now defunct) grammar in go.y accepted both a method
  3167  	// or an (embedded) type:
  3168  	//
  3169  	// hidden_interfacedcl:
  3170  	// 	sym '(' ohidden_funarg_list ')' ohidden_funres
  3171  	// 	{
  3172  	// 		$$ = Nod(ODCLFIELD, newname($1), typenod(functype(fakethis(), $3, $5)));
  3173  	// 	}
  3174  	// |	hidden_type
  3175  	// 	{
  3176  	// 		$$ = Nod(ODCLFIELD, nil, typenod($1));
  3177  	// 	}
  3178  	//
  3179  	// But the current textual export code only exports (inlined) methods,
  3180  	// even if the methods came from embedded interfaces. Furthermore, in
  3181  	// the original grammar, hidden_type may also start with a sym (LNAME
  3182  	// or '@'), complicating matters further. Since we never have embedded
  3183  	// types, only parse methods here.
  3184  
  3185  	s1 := p.sym()
  3186  	p.want('(')
  3187  	s3 := p.ohidden_funarg_list()
  3188  	p.want(')')
  3189  	s5 := p.ohidden_funres()
  3190  
  3191  	return Nod(ODCLFIELD, newname(s1), typenod(functype(fakethis(), s3, s5)))
  3192  }
  3193  
  3194  func (p *parser) ohidden_funres() []*Node {
  3195  	if trace && Debug['x'] != 0 {
  3196  		defer p.trace("ohidden_funres")()
  3197  	}
  3198  
  3199  	switch p.tok {
  3200  	default:
  3201  		return nil
  3202  
  3203  	case '(', '@', LNAME, '[', LMAP, LSTRUCT, LINTERFACE, '*', LCHAN, LCOMM, LFUNC:
  3204  		return p.hidden_funres()
  3205  	}
  3206  }
  3207  
  3208  func (p *parser) hidden_funres() []*Node {
  3209  	if trace && Debug['x'] != 0 {
  3210  		defer p.trace("hidden_funres")()
  3211  	}
  3212  
  3213  	switch p.tok {
  3214  	case '(':
  3215  		p.next()
  3216  		s2 := p.ohidden_funarg_list()
  3217  		p.want(')')
  3218  		return s2
  3219  
  3220  	default:
  3221  		s1 := p.hidden_type()
  3222  		return []*Node{Nod(ODCLFIELD, nil, typenod(s1))}
  3223  	}
  3224  }
  3225  
  3226  // ----------------------------------------------------------------------------
  3227  // Importing constants
  3228  
  3229  func (p *parser) hidden_literal() *Node {
  3230  	if trace && Debug['x'] != 0 {
  3231  		defer p.trace("hidden_literal")()
  3232  	}
  3233  
  3234  	switch p.tok {
  3235  	case LLITERAL:
  3236  		ss := nodlit(p.val)
  3237  		p.next()
  3238  		return ss
  3239  
  3240  	case '-':
  3241  		p.next()
  3242  		if p.tok == LLITERAL {
  3243  			ss := nodlit(p.val)
  3244  			p.next()
  3245  			switch u := ss.Val().U.(type) {
  3246  			case *Mpint:
  3247  				u.Neg()
  3248  			case *Mpflt:
  3249  				u.Neg()
  3250  			case *Mpcplx:
  3251  				u.Real.Neg()
  3252  				u.Imag.Neg()
  3253  			default:
  3254  				Yyerror("bad negated constant")
  3255  			}
  3256  			return ss
  3257  		} else {
  3258  			p.import_error()
  3259  			return nil
  3260  		}
  3261  
  3262  	case LNAME, '@', '?':
  3263  		s1 := p.sym()
  3264  		ss := oldname(Pkglookup(s1.Name, builtinpkg))
  3265  		if ss.Op != OLITERAL {
  3266  			Yyerror("bad constant %v", ss.Sym)
  3267  		}
  3268  		return ss
  3269  
  3270  	default:
  3271  		p.import_error()
  3272  		return nil
  3273  	}
  3274  }
  3275  
  3276  func (p *parser) hidden_constant() *Node {
  3277  	if trace && Debug['x'] != 0 {
  3278  		defer p.trace("hidden_constant")()
  3279  	}
  3280  
  3281  	switch p.tok {
  3282  	default:
  3283  		return p.hidden_literal()
  3284  	case '(':
  3285  		p.next()
  3286  		s2 := p.hidden_literal()
  3287  		p.want('+')
  3288  		s4 := p.hidden_literal()
  3289  		p.want(')')
  3290  
  3291  		if s2.Val().Ctype() == CTRUNE && s4.Val().Ctype() == CTINT {
  3292  			ss := s2
  3293  			s2.Val().U.(*Mpint).Add(s4.Val().U.(*Mpint))
  3294  			return ss
  3295  		}
  3296  		s4.Val().U.(*Mpcplx).Real = s4.Val().U.(*Mpcplx).Imag
  3297  		s4.Val().U.(*Mpcplx).Imag.SetFloat64(0.0)
  3298  		return nodcplxlit(s2.Val(), s4.Val())
  3299  	}
  3300  }
  3301  
  3302  func (p *parser) hidden_import_list() {
  3303  	if trace && Debug['x'] != 0 {
  3304  		defer p.trace("hidden_import_list")()
  3305  	}
  3306  
  3307  	for p.tok != '$' {
  3308  		p.hidden_import()
  3309  	}
  3310  }
  3311  
  3312  func (p *parser) hidden_funarg_list() []*Node {
  3313  	if trace && Debug['x'] != 0 {
  3314  		defer p.trace("hidden_funarg_list")()
  3315  	}
  3316  
  3317  	s1 := p.hidden_funarg()
  3318  	ss := []*Node{s1}
  3319  	for p.got(',') {
  3320  		s3 := p.hidden_funarg()
  3321  		ss = append(ss, s3)
  3322  	}
  3323  	return ss
  3324  }
  3325  
  3326  func (p *parser) hidden_structdcl_list() []*Node {
  3327  	if trace && Debug['x'] != 0 {
  3328  		defer p.trace("hidden_structdcl_list")()
  3329  	}
  3330  
  3331  	s1 := p.hidden_structdcl()
  3332  	ss := []*Node{s1}
  3333  	for p.got(';') {
  3334  		s3 := p.hidden_structdcl()
  3335  		ss = append(ss, s3)
  3336  	}
  3337  	return ss
  3338  }
  3339  
  3340  func (p *parser) hidden_interfacedcl_list() []*Node {
  3341  	if trace && Debug['x'] != 0 {
  3342  		defer p.trace("hidden_interfacedcl_list")()
  3343  	}
  3344  
  3345  	s1 := p.hidden_interfacedcl()
  3346  	ss := []*Node{s1}
  3347  	for p.got(';') {
  3348  		s3 := p.hidden_interfacedcl()
  3349  		ss = append(ss, s3)
  3350  	}
  3351  	return ss
  3352  }