github.com/miolini/go@v0.0.0-20160405192216-fca68c8cb408/src/cmd/compile/internal/gc/parser.go (about)

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