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