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