Home | History | Annotate | Download | only in syntax
      1 // Copyright 2016 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 syntax
      6 
      7 import (
      8 	"fmt"
      9 	"io"
     10 	"strings"
     11 )
     12 
     13 const debug = false
     14 const trace = false
     15 
     16 // The old gc parser assigned line numbers very inconsistently depending
     17 // on when it happened to construct AST nodes. To make transitioning to the
     18 // new AST easier, we try to mimick the behavior as much as possible.
     19 const gcCompat = true
     20 
     21 type parser struct {
     22 	scanner
     23 
     24 	fnest  int    // function nesting level (for error handling)
     25 	xnest  int    // expression nesting level (for complit ambiguity resolution)
     26 	indent []byte // tracing support
     27 }
     28 
     29 func (p *parser) init(src io.Reader, errh ErrorHandler, pragh PragmaHandler) {
     30 	p.scanner.init(src, errh, pragh)
     31 
     32 	p.fnest = 0
     33 	p.xnest = 0
     34 	p.indent = nil
     35 }
     36 
     37 func (p *parser) got(tok token) bool {
     38 	if p.tok == tok {
     39 		p.next()
     40 		return true
     41 	}
     42 	return false
     43 }
     44 
     45 func (p *parser) want(tok token) {
     46 	if !p.got(tok) {
     47 		p.syntax_error("expecting " + tok.String())
     48 		p.advance()
     49 	}
     50 }
     51 
     52 // ----------------------------------------------------------------------------
     53 // Error handling
     54 
     55 // syntax_error reports a syntax error at the current line.
     56 func (p *parser) syntax_error(msg string) {
     57 	p.syntax_error_at(p.pos, p.line, msg)
     58 }
     59 
     60 // Like syntax_error, but reports error at given line rather than current lexer line.
     61 func (p *parser) syntax_error_at(pos, line int, msg string) {
     62 	if trace {
     63 		defer p.trace("syntax_error (" + msg + ")")()
     64 	}
     65 
     66 	if p.tok == _EOF && p.first != nil {
     67 		return // avoid meaningless follow-up errors
     68 	}
     69 
     70 	// add punctuation etc. as needed to msg
     71 	switch {
     72 	case msg == "":
     73 		// nothing to do
     74 	case strings.HasPrefix(msg, "in"), strings.HasPrefix(msg, "at"), strings.HasPrefix(msg, "after"):
     75 		msg = " " + msg
     76 	case strings.HasPrefix(msg, "expecting"):
     77 		msg = ", " + msg
     78 	default:
     79 		// plain error - we don't care about current token
     80 		p.error_at(pos, line, "syntax error: "+msg)
     81 		return
     82 	}
     83 
     84 	// determine token string
     85 	var tok string
     86 	switch p.tok {
     87 	case _Name:
     88 		tok = p.lit
     89 	case _Literal:
     90 		tok = "literal " + p.lit
     91 	case _Operator:
     92 		tok = p.op.String()
     93 	case _AssignOp:
     94 		tok = p.op.String() + "="
     95 	case _IncOp:
     96 		tok = p.op.String()
     97 		tok += tok
     98 	default:
     99 		tok = tokstring(p.tok)
    100 	}
    101 
    102 	p.error_at(pos, line, "syntax error: unexpected "+tok+msg)
    103 }
    104 
    105 // The stopset contains keywords that start a statement.
    106 // They are good synchronization points in case of syntax
    107 // errors and (usually) shouldn't be skipped over.
    108 const stopset uint64 = 1<<_Break |
    109 	1<<_Const |
    110 	1<<_Continue |
    111 	1<<_Defer |
    112 	1<<_Fallthrough |
    113 	1<<_For |
    114 	1<<_Func |
    115 	1<<_Go |
    116 	1<<_Goto |
    117 	1<<_If |
    118 	1<<_Return |
    119 	1<<_Select |
    120 	1<<_Switch |
    121 	1<<_Type |
    122 	1<<_Var
    123 
    124 // Advance consumes tokens until it finds a token of the stopset or followlist.
    125 // The stopset is only considered if we are inside a function (p.fnest > 0).
    126 // The followlist is the list of valid tokens that can follow a production;
    127 // if it is empty, exactly one token is consumed to ensure progress.
    128 func (p *parser) advance(followlist ...token) {
    129 	if len(followlist) == 0 {
    130 		p.next()
    131 		return
    132 	}
    133 
    134 	// compute follow set
    135 	// TODO(gri) the args are constants - do as constant expressions?
    136 	var followset uint64 = 1 << _EOF // never skip over EOF
    137 	for _, tok := range followlist {
    138 		followset |= 1 << tok
    139 	}
    140 
    141 	for !(contains(followset, p.tok) || p.fnest > 0 && contains(stopset, p.tok)) {
    142 		p.next()
    143 	}
    144 }
    145 
    146 func tokstring(tok token) string {
    147 	switch tok {
    148 	case _EOF:
    149 		return "EOF"
    150 	case _Comma:
    151 		return "comma"
    152 	case _Semi:
    153 		return "semicolon or newline"
    154 	}
    155 	return tok.String()
    156 }
    157 
    158 // usage: defer p.trace(msg)()
    159 func (p *parser) trace(msg string) func() {
    160 	fmt.Printf("%5d: %s%s (\n", p.line, p.indent, msg)
    161 	const tab = ". "
    162 	p.indent = append(p.indent, tab...)
    163 	return func() {
    164 		p.indent = p.indent[:len(p.indent)-len(tab)]
    165 		if x := recover(); x != nil {
    166 			panic(x) // skip print_trace
    167 		}
    168 		fmt.Printf("%5d: %s)\n", p.line, p.indent)
    169 	}
    170 }
    171 
    172 // ----------------------------------------------------------------------------
    173 // Package files
    174 //
    175 // Parse methods are annotated with matching Go productions as appropriate.
    176 // The annotations are intended as guidelines only since a single Go grammar
    177 // rule may be covered by multiple parse methods and vice versa.
    178 
    179 // SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
    180 func (p *parser) file() *File {
    181 	if trace {
    182 		defer p.trace("file")()
    183 	}
    184 
    185 	f := new(File)
    186 	f.init(p)
    187 
    188 	// PackageClause
    189 	if !p.got(_Package) {
    190 		p.syntax_error("package statement must be first")
    191 		return nil
    192 	}
    193 	f.PkgName = p.name()
    194 	p.want(_Semi)
    195 
    196 	// don't bother continuing if package clause has errors
    197 	if p.first != nil {
    198 		return nil
    199 	}
    200 
    201 	// { ImportDecl ";" }
    202 	for p.got(_Import) {
    203 		f.DeclList = p.appendGroup(f.DeclList, p.importDecl)
    204 		p.want(_Semi)
    205 	}
    206 
    207 	// { TopLevelDecl ";" }
    208 	for p.tok != _EOF {
    209 		switch p.tok {
    210 		case _Const:
    211 			p.next()
    212 			f.DeclList = p.appendGroup(f.DeclList, p.constDecl)
    213 
    214 		case _Type:
    215 			p.next()
    216 			f.DeclList = p.appendGroup(f.DeclList, p.typeDecl)
    217 
    218 		case _Var:
    219 			p.next()
    220 			f.DeclList = p.appendGroup(f.DeclList, p.varDecl)
    221 
    222 		case _Func:
    223 			p.next()
    224 			f.DeclList = append(f.DeclList, p.funcDecl())
    225 
    226 		default:
    227 			if p.tok == _Lbrace && len(f.DeclList) > 0 && emptyFuncDecl(f.DeclList[len(f.DeclList)-1]) {
    228 				// opening { of function declaration on next line
    229 				p.syntax_error("unexpected semicolon or newline before {")
    230 			} else {
    231 				p.syntax_error("non-declaration statement outside function body")
    232 			}
    233 			p.advance(_Const, _Type, _Var, _Func)
    234 			continue
    235 		}
    236 
    237 		// Reset p.pragma BEFORE advancing to the next token (consuming ';')
    238 		// since comments before may set pragmas for the next function decl.
    239 		p.pragma = 0
    240 
    241 		if p.tok != _EOF && !p.got(_Semi) {
    242 			p.syntax_error("after top level declaration")
    243 			p.advance(_Const, _Type, _Var, _Func)
    244 		}
    245 	}
    246 	// p.tok == _EOF
    247 
    248 	f.Lines = p.source.line
    249 
    250 	return f
    251 }
    252 
    253 func emptyFuncDecl(dcl Decl) bool {
    254 	f, ok := dcl.(*FuncDecl)
    255 	return ok && f.Body == nil
    256 }
    257 
    258 // ----------------------------------------------------------------------------
    259 // Declarations
    260 
    261 // appendGroup(f) = f | "(" { f ";" } ")" .
    262 func (p *parser) appendGroup(list []Decl, f func(*Group) Decl) []Decl {
    263 	if p.got(_Lparen) {
    264 		g := new(Group)
    265 		for p.tok != _EOF && p.tok != _Rparen {
    266 			list = append(list, f(g))
    267 			if !p.osemi(_Rparen) {
    268 				break
    269 			}
    270 		}
    271 		p.want(_Rparen)
    272 		return list
    273 	}
    274 
    275 	return append(list, f(nil))
    276 }
    277 
    278 func (p *parser) importDecl(group *Group) Decl {
    279 	if trace {
    280 		defer p.trace("importDecl")()
    281 	}
    282 
    283 	d := new(ImportDecl)
    284 	d.init(p)
    285 
    286 	switch p.tok {
    287 	case _Name:
    288 		d.LocalPkgName = p.name()
    289 	case _Dot:
    290 		n := new(Name)
    291 		n.init(p)
    292 		n.Value = "."
    293 		d.LocalPkgName = n
    294 		p.next()
    295 	}
    296 	if p.tok == _Literal && (gcCompat || p.kind == StringLit) {
    297 		d.Path = p.oliteral()
    298 	} else {
    299 		p.syntax_error("missing import path; require quoted string")
    300 		p.advance(_Semi, _Rparen)
    301 	}
    302 	d.Group = group
    303 
    304 	return d
    305 }
    306 
    307 // ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
    308 func (p *parser) constDecl(group *Group) Decl {
    309 	if trace {
    310 		defer p.trace("constDecl")()
    311 	}
    312 
    313 	d := new(ConstDecl)
    314 	d.init(p)
    315 
    316 	d.NameList = p.nameList(p.name())
    317 	if p.tok != _EOF && p.tok != _Semi && p.tok != _Rparen {
    318 		d.Type = p.tryType()
    319 		if p.got(_Assign) {
    320 			d.Values = p.exprList()
    321 		}
    322 	}
    323 	d.Group = group
    324 
    325 	return d
    326 }
    327 
    328 // TypeSpec = identifier Type .
    329 func (p *parser) typeDecl(group *Group) Decl {
    330 	if trace {
    331 		defer p.trace("typeDecl")()
    332 	}
    333 
    334 	d := new(TypeDecl)
    335 	d.init(p)
    336 
    337 	d.Name = p.name()
    338 	d.Type = p.tryType()
    339 	if d.Type == nil {
    340 		p.syntax_error("in type declaration")
    341 		p.advance(_Semi, _Rparen)
    342 	}
    343 	d.Group = group
    344 	d.Pragma = p.pragma
    345 
    346 	return d
    347 }
    348 
    349 // VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
    350 func (p *parser) varDecl(group *Group) Decl {
    351 	if trace {
    352 		defer p.trace("varDecl")()
    353 	}
    354 
    355 	d := new(VarDecl)
    356 	d.init(p)
    357 
    358 	d.NameList = p.nameList(p.name())
    359 	if p.got(_Assign) {
    360 		d.Values = p.exprList()
    361 	} else {
    362 		d.Type = p.type_()
    363 		if p.got(_Assign) {
    364 			d.Values = p.exprList()
    365 		}
    366 	}
    367 	d.Group = group
    368 	if gcCompat {
    369 		d.init(p)
    370 	}
    371 
    372 	return d
    373 }
    374 
    375 // FunctionDecl = "func" FunctionName ( Function | Signature ) .
    376 // FunctionName = identifier .
    377 // Function     = Signature FunctionBody .
    378 // MethodDecl   = "func" Receiver MethodName ( Function | Signature ) .
    379 // Receiver     = Parameters .
    380 func (p *parser) funcDecl() *FuncDecl {
    381 	if trace {
    382 		defer p.trace("funcDecl")()
    383 	}
    384 
    385 	f := new(FuncDecl)
    386 	f.init(p)
    387 
    388 	badRecv := false
    389 	if p.tok == _Lparen {
    390 		rcvr := p.paramList()
    391 		switch len(rcvr) {
    392 		case 0:
    393 			p.error("method has no receiver")
    394 			badRecv = true
    395 		case 1:
    396 			f.Recv = rcvr[0]
    397 		default:
    398 			p.error("method has multiple receivers")
    399 			badRecv = true
    400 		}
    401 	}
    402 
    403 	if p.tok != _Name {
    404 		p.syntax_error("expecting name or (")
    405 		p.advance(_Lbrace, _Semi)
    406 		return nil
    407 	}
    408 
    409 	// TODO(gri) check for regular functions only
    410 	// if name.Sym.Name == "init" {
    411 	// 	name = renameinit()
    412 	// 	if params != nil || result != nil {
    413 	// 		p.error("func init must have no arguments and no return values")
    414 	// 	}
    415 	// }
    416 
    417 	// if localpkg.Name == "main" && name.Name == "main" {
    418 	// 	if params != nil || result != nil {
    419 	// 		p.error("func main must have no arguments and no return values")
    420 	// 	}
    421 	// }
    422 
    423 	f.Name = p.name()
    424 	f.Type = p.funcType()
    425 	if gcCompat {
    426 		f.node = f.Type.node
    427 	}
    428 	f.Body = p.funcBody()
    429 
    430 	f.Pragma = p.pragma
    431 	f.EndLine = uint32(p.line)
    432 
    433 	// TODO(gri) deal with function properties
    434 	// if noescape && body != nil {
    435 	// 	p.error("can only use //go:noescape with external func implementations")
    436 	// }
    437 
    438 	if badRecv {
    439 		return nil // TODO(gri) better solution
    440 	}
    441 	return f
    442 }
    443 
    444 // ----------------------------------------------------------------------------
    445 // Expressions
    446 
    447 func (p *parser) expr() Expr {
    448 	if trace {
    449 		defer p.trace("expr")()
    450 	}
    451 
    452 	return p.binaryExpr(0)
    453 }
    454 
    455 // Expression = UnaryExpr | Expression binary_op Expression .
    456 func (p *parser) binaryExpr(prec int) Expr {
    457 	// don't trace binaryExpr - only leads to overly nested trace output
    458 
    459 	x := p.unaryExpr()
    460 	for (p.tok == _Operator || p.tok == _Star) && p.prec > prec {
    461 		t := new(Operation)
    462 		t.init(p)
    463 		t.Op = p.op
    464 		t.X = x
    465 		tprec := p.prec
    466 		p.next()
    467 		t.Y = p.binaryExpr(tprec)
    468 		if gcCompat {
    469 			t.init(p)
    470 		}
    471 		x = t
    472 	}
    473 	return x
    474 }
    475 
    476 // UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
    477 func (p *parser) unaryExpr() Expr {
    478 	if trace {
    479 		defer p.trace("unaryExpr")()
    480 	}
    481 
    482 	switch p.tok {
    483 	case _Operator, _Star:
    484 		switch p.op {
    485 		case Mul, Add, Sub, Not, Xor:
    486 			x := new(Operation)
    487 			x.init(p)
    488 			x.Op = p.op
    489 			p.next()
    490 			x.X = p.unaryExpr()
    491 			if gcCompat {
    492 				x.init(p)
    493 			}
    494 			return x
    495 
    496 		case And:
    497 			p.next()
    498 			x := new(Operation)
    499 			x.init(p)
    500 			x.Op = And
    501 			// unaryExpr may have returned a parenthesized composite literal
    502 			// (see comment in operand) - remove parentheses if any
    503 			x.X = unparen(p.unaryExpr())
    504 			return x
    505 		}
    506 
    507 	case _Arrow:
    508 		// receive op (<-x) or receive-only channel (<-chan E)
    509 		p.next()
    510 
    511 		// If the next token is _Chan we still don't know if it is
    512 		// a channel (<-chan int) or a receive op (<-chan int(ch)).
    513 		// We only know once we have found the end of the unaryExpr.
    514 
    515 		x := p.unaryExpr()
    516 
    517 		// There are two cases:
    518 		//
    519 		//   <-chan...  => <-x is a channel type
    520 		//   <-x        => <-x is a receive operation
    521 		//
    522 		// In the first case, <- must be re-associated with
    523 		// the channel type parsed already:
    524 		//
    525 		//   <-(chan E)   =>  (<-chan E)
    526 		//   <-(chan<-E)  =>  (<-chan (<-E))
    527 
    528 		if _, ok := x.(*ChanType); ok {
    529 			// x is a channel type => re-associate <-
    530 			dir := SendOnly
    531 			t := x
    532 			for dir == SendOnly {
    533 				c, ok := t.(*ChanType)
    534 				if !ok {
    535 					break
    536 				}
    537 				dir = c.Dir
    538 				if dir == RecvOnly {
    539 					// t is type <-chan E but <-<-chan E is not permitted
    540 					// (report same error as for "type _ <-<-chan E")
    541 					p.syntax_error("unexpected <-, expecting chan")
    542 					// already progressed, no need to advance
    543 				}
    544 				c.Dir = RecvOnly
    545 				t = c.Elem
    546 			}
    547 			if dir == SendOnly {
    548 				// channel dir is <- but channel element E is not a channel
    549 				// (report same error as for "type _ <-chan<-E")
    550 				p.syntax_error(fmt.Sprintf("unexpected %s, expecting chan", String(t)))
    551 				// already progressed, no need to advance
    552 			}
    553 			return x
    554 		}
    555 
    556 		// x is not a channel type => we have a receive op
    557 		return &Operation{Op: Recv, X: x}
    558 	}
    559 
    560 	// TODO(mdempsky): We need parens here so we can report an
    561 	// error for "(x) := true". It should be possible to detect
    562 	// and reject that more efficiently though.
    563 	return p.pexpr(true)
    564 }
    565 
    566 // callStmt parses call-like statements that can be preceded by 'defer' and 'go'.
    567 func (p *parser) callStmt() *CallStmt {
    568 	if trace {
    569 		defer p.trace("callStmt")()
    570 	}
    571 
    572 	s := new(CallStmt)
    573 	s.init(p)
    574 	s.Tok = p.tok
    575 	p.next()
    576 
    577 	x := p.pexpr(p.tok == _Lparen) // keep_parens so we can report error below
    578 	switch x := x.(type) {
    579 	case *CallExpr:
    580 		s.Call = x
    581 		if gcCompat {
    582 			s.node = x.node
    583 		}
    584 	case *ParenExpr:
    585 		p.error(fmt.Sprintf("expression in %s must not be parenthesized", s.Tok))
    586 		// already progressed, no need to advance
    587 	default:
    588 		p.error(fmt.Sprintf("expression in %s must be function call", s.Tok))
    589 		// already progressed, no need to advance
    590 	}
    591 
    592 	return s // TODO(gri) should we return nil in case of failure?
    593 }
    594 
    595 // Operand     = Literal | OperandName | MethodExpr | "(" Expression ")" .
    596 // Literal     = BasicLit | CompositeLit | FunctionLit .
    597 // BasicLit    = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
    598 // OperandName = identifier | QualifiedIdent.
    599 func (p *parser) operand(keep_parens bool) Expr {
    600 	if trace {
    601 		defer p.trace("operand " + p.tok.String())()
    602 	}
    603 
    604 	switch p.tok {
    605 	case _Name:
    606 		return p.name()
    607 
    608 	case _Literal:
    609 		return p.oliteral()
    610 
    611 	case _Lparen:
    612 		p.next()
    613 		p.xnest++
    614 		x := p.expr() // expr_or_type
    615 		p.xnest--
    616 		p.want(_Rparen)
    617 
    618 		// Optimization: Record presence of ()'s only where needed
    619 		// for error reporting. Don't bother in other cases; it is
    620 		// just a waste of memory and time.
    621 
    622 		// Parentheses are not permitted on lhs of := .
    623 		// switch x.Op {
    624 		// case ONAME, ONONAME, OPACK, OTYPE, OLITERAL, OTYPESW:
    625 		// 	keep_parens = true
    626 		// }
    627 
    628 		// Parentheses are not permitted around T in a composite
    629 		// literal T{}. If the next token is a {, assume x is a
    630 		// composite literal type T (it may not be, { could be
    631 		// the opening brace of a block, but we don't know yet).
    632 		if p.tok == _Lbrace {
    633 			keep_parens = true
    634 		}
    635 
    636 		// Parentheses are also not permitted around the expression
    637 		// in a go/defer statement. In that case, operand is called
    638 		// with keep_parens set.
    639 		if keep_parens {
    640 			x = &ParenExpr{X: x}
    641 		}
    642 		return x
    643 
    644 	case _Func:
    645 		p.next()
    646 		t := p.funcType()
    647 		if p.tok == _Lbrace {
    648 			p.fnest++
    649 			p.xnest++
    650 			f := new(FuncLit)
    651 			f.init(p)
    652 			f.Type = t
    653 			f.Body = p.funcBody()
    654 			f.EndLine = uint32(p.line)
    655 			p.xnest--
    656 			p.fnest--
    657 			return f
    658 		}
    659 		return t
    660 
    661 	case _Lbrack, _Chan, _Map, _Struct, _Interface:
    662 		return p.type_() // othertype
    663 
    664 	case _Lbrace:
    665 		// common case: p.header is missing simpleStmt before { in if, for, switch
    666 		p.syntax_error("missing operand")
    667 		// '{' will be consumed in pexpr - no need to consume it here
    668 		return nil
    669 
    670 	default:
    671 		p.syntax_error("expecting expression")
    672 		p.advance()
    673 		return nil
    674 	}
    675 
    676 	// Syntactically, composite literals are operands. Because a complit
    677 	// type may be a qualified identifier which is handled by pexpr
    678 	// (together with selector expressions), complits are parsed there
    679 	// as well (operand is only called from pexpr).
    680 }
    681 
    682 // PrimaryExpr =
    683 // 	Operand |
    684 // 	Conversion |
    685 // 	PrimaryExpr Selector |
    686 // 	PrimaryExpr Index |
    687 // 	PrimaryExpr Slice |
    688 // 	PrimaryExpr TypeAssertion |
    689 // 	PrimaryExpr Arguments .
    690 //
    691 // Selector       = "." identifier .
    692 // Index          = "[" Expression "]" .
    693 // Slice          = "[" ( [ Expression ] ":" [ Expression ] ) |
    694 //                      ( [ Expression ] ":" Expression ":" Expression )
    695 //                  "]" .
    696 // TypeAssertion  = "." "(" Type ")" .
    697 // Arguments      = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
    698 func (p *parser) pexpr(keep_parens bool) Expr {
    699 	if trace {
    700 		defer p.trace("pexpr")()
    701 	}
    702 
    703 	x := p.operand(keep_parens)
    704 
    705 loop:
    706 	for {
    707 		switch p.tok {
    708 		case _Dot:
    709 			p.next()
    710 			switch p.tok {
    711 			case _Name:
    712 				// pexpr '.' sym
    713 				t := new(SelectorExpr)
    714 				t.init(p)
    715 				t.X = x
    716 				t.Sel = p.name()
    717 				x = t
    718 
    719 			case _Lparen:
    720 				p.next()
    721 				if p.got(_Type) {
    722 					t := new(TypeSwitchGuard)
    723 					t.init(p)
    724 					t.X = x
    725 					x = t
    726 				} else {
    727 					t := new(AssertExpr)
    728 					t.init(p)
    729 					t.X = x
    730 					t.Type = p.expr()
    731 					x = t
    732 				}
    733 				p.want(_Rparen)
    734 
    735 			default:
    736 				p.syntax_error("expecting name or (")
    737 				p.advance(_Semi, _Rparen)
    738 			}
    739 			if gcCompat {
    740 				x.init(p)
    741 			}
    742 
    743 		case _Lbrack:
    744 			p.next()
    745 			p.xnest++
    746 
    747 			var i Expr
    748 			if p.tok != _Colon {
    749 				i = p.expr()
    750 				if p.got(_Rbrack) {
    751 					// x[i]
    752 					t := new(IndexExpr)
    753 					t.init(p)
    754 					t.X = x
    755 					t.Index = i
    756 					x = t
    757 					p.xnest--
    758 					break
    759 				}
    760 			}
    761 
    762 			// x[i:...
    763 			t := new(SliceExpr)
    764 			t.init(p)
    765 			t.X = x
    766 			t.Index[0] = i
    767 			p.want(_Colon)
    768 			if p.tok != _Colon && p.tok != _Rbrack {
    769 				// x[i:j...
    770 				t.Index[1] = p.expr()
    771 			}
    772 			if p.got(_Colon) {
    773 				t.Full = true
    774 				// x[i:j:...]
    775 				if t.Index[1] == nil {
    776 					p.error("middle index required in 3-index slice")
    777 				}
    778 				if p.tok != _Rbrack {
    779 					// x[i:j:k...
    780 					t.Index[2] = p.expr()
    781 				} else {
    782 					p.error("final index required in 3-index slice")
    783 				}
    784 			}
    785 			p.want(_Rbrack)
    786 
    787 			x = t
    788 			p.xnest--
    789 
    790 		case _Lparen:
    791 			x = p.call(x)
    792 
    793 		case _Lbrace:
    794 			// operand may have returned a parenthesized complit
    795 			// type; accept it but complain if we have a complit
    796 			t := unparen(x)
    797 			// determine if '{' belongs to a complit or a compound_stmt
    798 			complit_ok := false
    799 			switch t.(type) {
    800 			case *Name, *SelectorExpr:
    801 				if p.xnest >= 0 {
    802 					// x is considered a comptype
    803 					complit_ok = true
    804 				}
    805 			case *ArrayType, *SliceType, *StructType, *MapType:
    806 				// x is a comptype
    807 				complit_ok = true
    808 			}
    809 			if !complit_ok {
    810 				break loop
    811 			}
    812 			if t != x {
    813 				p.syntax_error("cannot parenthesize type in composite literal")
    814 				// already progressed, no need to advance
    815 			}
    816 			n := p.complitexpr()
    817 			n.Type = x
    818 			x = n
    819 
    820 		default:
    821 			break loop
    822 		}
    823 	}
    824 
    825 	return x
    826 }
    827 
    828 // Element = Expression | LiteralValue .
    829 func (p *parser) bare_complitexpr() Expr {
    830 	if trace {
    831 		defer p.trace("bare_complitexpr")()
    832 	}
    833 
    834 	if p.tok == _Lbrace {
    835 		// '{' start_complit braced_keyval_list '}'
    836 		return p.complitexpr()
    837 	}
    838 
    839 	return p.expr()
    840 }
    841 
    842 // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
    843 func (p *parser) complitexpr() *CompositeLit {
    844 	if trace {
    845 		defer p.trace("complitexpr")()
    846 	}
    847 
    848 	x := new(CompositeLit)
    849 	x.init(p)
    850 
    851 	p.want(_Lbrace)
    852 	p.xnest++
    853 
    854 	for p.tok != _EOF && p.tok != _Rbrace {
    855 		// value
    856 		e := p.bare_complitexpr()
    857 		if p.got(_Colon) {
    858 			// key ':' value
    859 			l := new(KeyValueExpr)
    860 			l.init(p)
    861 			l.Key = e
    862 			l.Value = p.bare_complitexpr()
    863 			if gcCompat {
    864 				l.init(p)
    865 			}
    866 			e = l
    867 			x.NKeys++
    868 		}
    869 		x.ElemList = append(x.ElemList, e)
    870 		if !p.ocomma(_Rbrace) {
    871 			break
    872 		}
    873 	}
    874 
    875 	x.EndLine = uint32(p.line)
    876 	p.xnest--
    877 	p.want(_Rbrace)
    878 
    879 	return x
    880 }
    881 
    882 // ----------------------------------------------------------------------------
    883 // Types
    884 
    885 func (p *parser) type_() Expr {
    886 	if trace {
    887 		defer p.trace("type_")()
    888 	}
    889 
    890 	if typ := p.tryType(); typ != nil {
    891 		return typ
    892 	}
    893 
    894 	p.syntax_error("")
    895 	p.advance()
    896 	return nil
    897 }
    898 
    899 func indirect(typ Expr) Expr {
    900 	return &Operation{Op: Mul, X: typ}
    901 }
    902 
    903 // tryType is like type_ but it returns nil if there was no type
    904 // instead of reporting an error.
    905 //
    906 // Type     = TypeName | TypeLit | "(" Type ")" .
    907 // TypeName = identifier | QualifiedIdent .
    908 // TypeLit  = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
    909 // 	      SliceType | MapType | Channel_Type .
    910 func (p *parser) tryType() Expr {
    911 	if trace {
    912 		defer p.trace("tryType")()
    913 	}
    914 
    915 	switch p.tok {
    916 	case _Star:
    917 		// ptrtype
    918 		p.next()
    919 		return indirect(p.type_())
    920 
    921 	case _Arrow:
    922 		// recvchantype
    923 		p.next()
    924 		p.want(_Chan)
    925 		t := new(ChanType)
    926 		t.init(p)
    927 		t.Dir = RecvOnly
    928 		t.Elem = p.chanElem()
    929 		return t
    930 
    931 	case _Func:
    932 		// fntype
    933 		p.next()
    934 		return p.funcType()
    935 
    936 	case _Lbrack:
    937 		// '[' oexpr ']' ntype
    938 		// '[' _DotDotDot ']' ntype
    939 		p.next()
    940 		p.xnest++
    941 		if p.got(_Rbrack) {
    942 			// []T
    943 			p.xnest--
    944 			t := new(SliceType)
    945 			t.init(p)
    946 			t.Elem = p.type_()
    947 			return t
    948 		}
    949 
    950 		// [n]T
    951 		t := new(ArrayType)
    952 		t.init(p)
    953 		if !p.got(_DotDotDot) {
    954 			t.Len = p.expr()
    955 		}
    956 		p.want(_Rbrack)
    957 		p.xnest--
    958 		t.Elem = p.type_()
    959 		return t
    960 
    961 	case _Chan:
    962 		// _Chan non_recvchantype
    963 		// _Chan _Comm ntype
    964 		p.next()
    965 		t := new(ChanType)
    966 		t.init(p)
    967 		if p.got(_Arrow) {
    968 			t.Dir = SendOnly
    969 		}
    970 		t.Elem = p.chanElem()
    971 		return t
    972 
    973 	case _Map:
    974 		// _Map '[' ntype ']' ntype
    975 		p.next()
    976 		p.want(_Lbrack)
    977 		t := new(MapType)
    978 		t.init(p)
    979 		t.Key = p.type_()
    980 		p.want(_Rbrack)
    981 		t.Value = p.type_()
    982 		return t
    983 
    984 	case _Struct:
    985 		return p.structType()
    986 
    987 	case _Interface:
    988 		return p.interfaceType()
    989 
    990 	case _Name:
    991 		return p.dotname(p.name())
    992 
    993 	case _Lparen:
    994 		p.next()
    995 		t := p.type_()
    996 		p.want(_Rparen)
    997 		return t
    998 	}
    999 
   1000 	return nil
   1001 }
   1002 
   1003 func (p *parser) funcType() *FuncType {
   1004 	if trace {
   1005 		defer p.trace("funcType")()
   1006 	}
   1007 
   1008 	typ := new(FuncType)
   1009 	typ.init(p)
   1010 	typ.ParamList = p.paramList()
   1011 	typ.ResultList = p.funcResult()
   1012 	if gcCompat {
   1013 		typ.init(p)
   1014 	}
   1015 	return typ
   1016 }
   1017 
   1018 func (p *parser) chanElem() Expr {
   1019 	if trace {
   1020 		defer p.trace("chanElem")()
   1021 	}
   1022 
   1023 	if typ := p.tryType(); typ != nil {
   1024 		return typ
   1025 	}
   1026 
   1027 	p.syntax_error("missing channel element type")
   1028 	// assume element type is simply absent - don't advance
   1029 	return nil
   1030 }
   1031 
   1032 func (p *parser) dotname(name *Name) Expr {
   1033 	if trace {
   1034 		defer p.trace("dotname")()
   1035 	}
   1036 
   1037 	if p.got(_Dot) {
   1038 		s := new(SelectorExpr)
   1039 		s.init(p)
   1040 		s.X = name
   1041 		s.Sel = p.name()
   1042 		return s
   1043 	}
   1044 	return name
   1045 }
   1046 
   1047 // StructType = "struct" "{" { FieldDecl ";" } "}" .
   1048 func (p *parser) structType() *StructType {
   1049 	if trace {
   1050 		defer p.trace("structType")()
   1051 	}
   1052 
   1053 	typ := new(StructType)
   1054 	typ.init(p)
   1055 
   1056 	p.want(_Struct)
   1057 	p.want(_Lbrace)
   1058 	for p.tok != _EOF && p.tok != _Rbrace {
   1059 		p.fieldDecl(typ)
   1060 		if !p.osemi(_Rbrace) {
   1061 			break
   1062 		}
   1063 	}
   1064 	if gcCompat {
   1065 		typ.init(p)
   1066 	}
   1067 	p.want(_Rbrace)
   1068 
   1069 	return typ
   1070 }
   1071 
   1072 // InterfaceType = "interface" "{" { MethodSpec ";" } "}" .
   1073 func (p *parser) interfaceType() *InterfaceType {
   1074 	if trace {
   1075 		defer p.trace("interfaceType")()
   1076 	}
   1077 
   1078 	typ := new(InterfaceType)
   1079 	typ.init(p)
   1080 
   1081 	p.want(_Interface)
   1082 	p.want(_Lbrace)
   1083 	for p.tok != _EOF && p.tok != _Rbrace {
   1084 		if m := p.methodDecl(); m != nil {
   1085 			typ.MethodList = append(typ.MethodList, m)
   1086 		}
   1087 		if !p.osemi(_Rbrace) {
   1088 			break
   1089 		}
   1090 	}
   1091 	if gcCompat {
   1092 		typ.init(p)
   1093 	}
   1094 	p.want(_Rbrace)
   1095 
   1096 	return typ
   1097 }
   1098 
   1099 // FunctionBody = Block .
   1100 func (p *parser) funcBody() []Stmt {
   1101 	if trace {
   1102 		defer p.trace("funcBody")()
   1103 	}
   1104 
   1105 	if p.got(_Lbrace) {
   1106 		p.fnest++
   1107 		body := p.stmtList()
   1108 		p.fnest--
   1109 		p.want(_Rbrace)
   1110 		if body == nil {
   1111 			body = []Stmt{new(EmptyStmt)}
   1112 		}
   1113 		return body
   1114 	}
   1115 
   1116 	return nil
   1117 }
   1118 
   1119 // Result = Parameters | Type .
   1120 func (p *parser) funcResult() []*Field {
   1121 	if trace {
   1122 		defer p.trace("funcResult")()
   1123 	}
   1124 
   1125 	if p.tok == _Lparen {
   1126 		return p.paramList()
   1127 	}
   1128 
   1129 	if result := p.tryType(); result != nil {
   1130 		f := new(Field)
   1131 		f.init(p)
   1132 		f.Type = result
   1133 		return []*Field{f}
   1134 	}
   1135 
   1136 	return nil
   1137 }
   1138 
   1139 func (p *parser) addField(styp *StructType, name *Name, typ Expr, tag *BasicLit) {
   1140 	if tag != nil {
   1141 		for i := len(styp.FieldList) - len(styp.TagList); i > 0; i-- {
   1142 			styp.TagList = append(styp.TagList, nil)
   1143 		}
   1144 		styp.TagList = append(styp.TagList, tag)
   1145 	}
   1146 
   1147 	f := new(Field)
   1148 	f.init(p)
   1149 	f.Name = name
   1150 	f.Type = typ
   1151 	styp.FieldList = append(styp.FieldList, f)
   1152 
   1153 	if gcCompat && name != nil {
   1154 		f.node = name.node
   1155 	}
   1156 
   1157 	if debug && tag != nil && len(styp.FieldList) != len(styp.TagList) {
   1158 		panic("inconsistent struct field list")
   1159 	}
   1160 }
   1161 
   1162 // FieldDecl      = (IdentifierList Type | AnonymousField) [ Tag ] .
   1163 // AnonymousField = [ "*" ] TypeName .
   1164 // Tag            = string_lit .
   1165 func (p *parser) fieldDecl(styp *StructType) {
   1166 	if trace {
   1167 		defer p.trace("fieldDecl")()
   1168 	}
   1169 
   1170 	var name *Name
   1171 	switch p.tok {
   1172 	case _Name:
   1173 		name = p.name()
   1174 		if p.tok == _Dot || p.tok == _Literal || p.tok == _Semi || p.tok == _Rbrace {
   1175 			// embed oliteral
   1176 			typ := p.qualifiedName(name)
   1177 			tag := p.oliteral()
   1178 			p.addField(styp, nil, typ, tag)
   1179 			return
   1180 		}
   1181 
   1182 		// new_name_list ntype oliteral
   1183 		names := p.nameList(name)
   1184 		typ := p.type_()
   1185 		tag := p.oliteral()
   1186 
   1187 		for _, name := range names {
   1188 			p.addField(styp, name, typ, tag)
   1189 		}
   1190 
   1191 	case _Lparen:
   1192 		p.next()
   1193 		if p.tok == _Star {
   1194 			// '(' '*' embed ')' oliteral
   1195 			p.next()
   1196 			typ := indirect(p.qualifiedName(nil))
   1197 			p.want(_Rparen)
   1198 			tag := p.oliteral()
   1199 			p.addField(styp, nil, typ, tag)
   1200 			p.error("cannot parenthesize embedded type")
   1201 
   1202 		} else {
   1203 			// '(' embed ')' oliteral
   1204 			typ := p.qualifiedName(nil)
   1205 			p.want(_Rparen)
   1206 			tag := p.oliteral()
   1207 			p.addField(styp, nil, typ, tag)
   1208 			p.error("cannot parenthesize embedded type")
   1209 		}
   1210 
   1211 	case _Star:
   1212 		p.next()
   1213 		if p.got(_Lparen) {
   1214 			// '*' '(' embed ')' oliteral
   1215 			typ := indirect(p.qualifiedName(nil))
   1216 			p.want(_Rparen)
   1217 			tag := p.oliteral()
   1218 			p.addField(styp, nil, typ, tag)
   1219 			p.error("cannot parenthesize embedded type")
   1220 
   1221 		} else {
   1222 			// '*' embed oliteral
   1223 			typ := indirect(p.qualifiedName(nil))
   1224 			tag := p.oliteral()
   1225 			p.addField(styp, nil, typ, tag)
   1226 		}
   1227 
   1228 	default:
   1229 		p.syntax_error("expecting field name or embedded type")
   1230 		p.advance(_Semi, _Rbrace)
   1231 	}
   1232 }
   1233 
   1234 func (p *parser) oliteral() *BasicLit {
   1235 	if p.tok == _Literal {
   1236 		b := new(BasicLit)
   1237 		b.init(p)
   1238 		b.Value = p.lit
   1239 		b.Kind = p.kind
   1240 		p.next()
   1241 		return b
   1242 	}
   1243 	return nil
   1244 }
   1245 
   1246 // MethodSpec        = MethodName Signature | InterfaceTypeName .
   1247 // MethodName        = identifier .
   1248 // InterfaceTypeName = TypeName .
   1249 func (p *parser) methodDecl() *Field {
   1250 	if trace {
   1251 		defer p.trace("methodDecl")()
   1252 	}
   1253 
   1254 	switch p.tok {
   1255 	case _Name:
   1256 		name := p.name()
   1257 
   1258 		// accept potential name list but complain
   1259 		hasNameList := false
   1260 		for p.got(_Comma) {
   1261 			p.name()
   1262 			hasNameList = true
   1263 		}
   1264 		if hasNameList {
   1265 			p.syntax_error("name list not allowed in interface type")
   1266 			// already progressed, no need to advance
   1267 		}
   1268 
   1269 		f := new(Field)
   1270 		f.init(p)
   1271 		if p.tok != _Lparen {
   1272 			// packname
   1273 			f.Type = p.qualifiedName(name)
   1274 			return f
   1275 		}
   1276 
   1277 		f.Name = name
   1278 		f.Type = p.funcType()
   1279 		return f
   1280 
   1281 	case _Lparen:
   1282 		p.next()
   1283 		f := new(Field)
   1284 		f.init(p)
   1285 		f.Type = p.qualifiedName(nil)
   1286 		p.want(_Rparen)
   1287 		p.error("cannot parenthesize embedded type")
   1288 		return f
   1289 
   1290 	default:
   1291 		p.syntax_error("")
   1292 		p.advance(_Semi, _Rbrace)
   1293 		return nil
   1294 	}
   1295 }
   1296 
   1297 // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
   1298 func (p *parser) paramDecl() *Field {
   1299 	if trace {
   1300 		defer p.trace("paramDecl")()
   1301 	}
   1302 
   1303 	f := new(Field)
   1304 	f.init(p)
   1305 
   1306 	switch p.tok {
   1307 	case _Name:
   1308 		f.Name = p.name()
   1309 		switch p.tok {
   1310 		case _Name, _Star, _Arrow, _Func, _Lbrack, _Chan, _Map, _Struct, _Interface, _Lparen:
   1311 			// sym name_or_type
   1312 			f.Type = p.type_()
   1313 
   1314 		case _DotDotDot:
   1315 			// sym dotdotdot
   1316 			f.Type = p.dotsType()
   1317 
   1318 		case _Dot:
   1319 			// name_or_type
   1320 			// from dotname
   1321 			f.Type = p.dotname(f.Name)
   1322 			f.Name = nil
   1323 		}
   1324 
   1325 	case _Arrow, _Star, _Func, _Lbrack, _Chan, _Map, _Struct, _Interface, _Lparen:
   1326 		// name_or_type
   1327 		f.Type = p.type_()
   1328 
   1329 	case _DotDotDot:
   1330 		// dotdotdot
   1331 		f.Type = p.dotsType()
   1332 
   1333 	default:
   1334 		p.syntax_error("expecting )")
   1335 		p.advance(_Comma, _Rparen)
   1336 		return nil
   1337 	}
   1338 
   1339 	return f
   1340 }
   1341 
   1342 // ...Type
   1343 func (p *parser) dotsType() *DotsType {
   1344 	if trace {
   1345 		defer p.trace("dotsType")()
   1346 	}
   1347 
   1348 	t := new(DotsType)
   1349 	t.init(p)
   1350 
   1351 	p.want(_DotDotDot)
   1352 	t.Elem = p.tryType()
   1353 	if t.Elem == nil {
   1354 		p.error("final argument in variadic function missing type")
   1355 	}
   1356 
   1357 	return t
   1358 }
   1359 
   1360 // Parameters    = "(" [ ParameterList [ "," ] ] ")" .
   1361 // ParameterList = ParameterDecl { "," ParameterDecl } .
   1362 func (p *parser) paramList() (list []*Field) {
   1363 	if trace {
   1364 		defer p.trace("paramList")()
   1365 	}
   1366 
   1367 	p.want(_Lparen)
   1368 
   1369 	var named int // number of parameters that have an explicit name and type
   1370 	for p.tok != _EOF && p.tok != _Rparen {
   1371 		if par := p.paramDecl(); par != nil {
   1372 			if debug && par.Name == nil && par.Type == nil {
   1373 				panic("parameter without name or type")
   1374 			}
   1375 			if par.Name != nil && par.Type != nil {
   1376 				named++
   1377 			}
   1378 			list = append(list, par)
   1379 		}
   1380 		if !p.ocomma(_Rparen) {
   1381 			break
   1382 		}
   1383 	}
   1384 
   1385 	// distribute parameter types
   1386 	if named == 0 {
   1387 		// all unnamed => found names are named types
   1388 		for _, par := range list {
   1389 			if typ := par.Name; typ != nil {
   1390 				par.Type = typ
   1391 				par.Name = nil
   1392 			}
   1393 		}
   1394 	} else if named != len(list) {
   1395 		// some named => all must be named
   1396 		var typ Expr
   1397 		for i := len(list) - 1; i >= 0; i-- {
   1398 			if par := list[i]; par.Type != nil {
   1399 				typ = par.Type
   1400 				if par.Name == nil {
   1401 					typ = nil // error
   1402 				}
   1403 			} else {
   1404 				par.Type = typ
   1405 			}
   1406 			if typ == nil {
   1407 				p.syntax_error("mixed named and unnamed function parameters")
   1408 				break
   1409 			}
   1410 		}
   1411 	}
   1412 
   1413 	p.want(_Rparen)
   1414 	return
   1415 }
   1416 
   1417 // ----------------------------------------------------------------------------
   1418 // Statements
   1419 
   1420 // We represent x++, x-- as assignments x += ImplicitOne, x -= ImplicitOne.
   1421 // ImplicitOne should not be used elsewhere.
   1422 var ImplicitOne = &BasicLit{Value: "1"}
   1423 
   1424 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
   1425 //
   1426 // simpleStmt may return missing_stmt if labelOk is set.
   1427 func (p *parser) simpleStmt(lhs Expr, rangeOk bool) SimpleStmt {
   1428 	if trace {
   1429 		defer p.trace("simpleStmt")()
   1430 	}
   1431 
   1432 	if rangeOk && p.got(_Range) {
   1433 		// _Range expr
   1434 		if debug && lhs != nil {
   1435 			panic("invalid call of simpleStmt")
   1436 		}
   1437 		return p.rangeClause(nil, false)
   1438 	}
   1439 
   1440 	if lhs == nil {
   1441 		lhs = p.exprList()
   1442 	}
   1443 
   1444 	if _, ok := lhs.(*ListExpr); !ok && p.tok != _Assign && p.tok != _Define {
   1445 		// expr
   1446 		switch p.tok {
   1447 		case _AssignOp:
   1448 			// lhs op= rhs
   1449 			op := p.op
   1450 			p.next()
   1451 			return p.newAssignStmt(op, lhs, p.expr())
   1452 
   1453 		case _IncOp:
   1454 			// lhs++ or lhs--
   1455 			op := p.op
   1456 			p.next()
   1457 			return p.newAssignStmt(op, lhs, ImplicitOne)
   1458 
   1459 		case _Arrow:
   1460 			// lhs <- rhs
   1461 			p.next()
   1462 			s := new(SendStmt)
   1463 			s.init(p)
   1464 			s.Chan = lhs
   1465 			s.Value = p.expr()
   1466 			if gcCompat {
   1467 				s.init(p)
   1468 			}
   1469 			return s
   1470 
   1471 		default:
   1472 			// expr
   1473 			return &ExprStmt{X: lhs}
   1474 		}
   1475 	}
   1476 
   1477 	// expr_list
   1478 	switch p.tok {
   1479 	case _Assign:
   1480 		p.next()
   1481 
   1482 		if rangeOk && p.got(_Range) {
   1483 			// expr_list '=' _Range expr
   1484 			return p.rangeClause(lhs, false)
   1485 		}
   1486 
   1487 		// expr_list '=' expr_list
   1488 		return p.newAssignStmt(0, lhs, p.exprList())
   1489 
   1490 	case _Define:
   1491 		var n node
   1492 		n.init(p)
   1493 		p.next()
   1494 
   1495 		if rangeOk && p.got(_Range) {
   1496 			// expr_list ':=' range expr
   1497 			return p.rangeClause(lhs, true)
   1498 		}
   1499 
   1500 		// expr_list ':=' expr_list
   1501 		rhs := p.exprList()
   1502 
   1503 		if x, ok := rhs.(*TypeSwitchGuard); ok {
   1504 			switch lhs := lhs.(type) {
   1505 			case *Name:
   1506 				x.Lhs = lhs
   1507 			case *ListExpr:
   1508 				p.error(fmt.Sprintf("argument count mismatch: %d = %d", len(lhs.ElemList), 1))
   1509 			default:
   1510 				// TODO(mdempsky): Have Expr types implement Stringer?
   1511 				p.error(fmt.Sprintf("invalid variable name %s in type switch", lhs))
   1512 			}
   1513 			return &ExprStmt{X: x}
   1514 		}
   1515 
   1516 		as := p.newAssignStmt(Def, lhs, rhs)
   1517 		if gcCompat {
   1518 			as.node = n
   1519 		}
   1520 		return as
   1521 
   1522 	default:
   1523 		p.syntax_error("expecting := or = or comma")
   1524 		p.advance(_Semi, _Rbrace)
   1525 		return nil
   1526 	}
   1527 }
   1528 
   1529 func (p *parser) rangeClause(lhs Expr, def bool) *RangeClause {
   1530 	r := new(RangeClause)
   1531 	r.init(p)
   1532 	r.Lhs = lhs
   1533 	r.Def = def
   1534 	r.X = p.expr()
   1535 	if gcCompat {
   1536 		r.init(p)
   1537 	}
   1538 	return r
   1539 }
   1540 
   1541 func (p *parser) newAssignStmt(op Operator, lhs, rhs Expr) *AssignStmt {
   1542 	a := new(AssignStmt)
   1543 	a.init(p)
   1544 	a.Op = op
   1545 	a.Lhs = lhs
   1546 	a.Rhs = rhs
   1547 	return a
   1548 }
   1549 
   1550 func (p *parser) labeledStmt(label *Name) Stmt {
   1551 	if trace {
   1552 		defer p.trace("labeledStmt")()
   1553 	}
   1554 
   1555 	s := new(LabeledStmt)
   1556 	s.init(p)
   1557 	s.Label = label
   1558 
   1559 	p.want(_Colon)
   1560 
   1561 	if p.tok != _Rbrace && p.tok != _EOF {
   1562 		s.Stmt = p.stmt()
   1563 		if s.Stmt == missing_stmt {
   1564 			// report error at line of ':' token
   1565 			p.syntax_error_at(int(label.pos), int(label.line), "missing statement after label")
   1566 			// we are already at the end of the labeled statement - no need to advance
   1567 			return missing_stmt
   1568 		}
   1569 	}
   1570 
   1571 	return s
   1572 }
   1573 
   1574 func (p *parser) blockStmt() *BlockStmt {
   1575 	if trace {
   1576 		defer p.trace("blockStmt")()
   1577 	}
   1578 
   1579 	s := new(BlockStmt)
   1580 	s.init(p)
   1581 	p.want(_Lbrace)
   1582 	s.Body = p.stmtList()
   1583 	p.want(_Rbrace)
   1584 
   1585 	return s
   1586 }
   1587 
   1588 func (p *parser) declStmt(f func(*Group) Decl) *DeclStmt {
   1589 	if trace {
   1590 		defer p.trace("declStmt")()
   1591 	}
   1592 
   1593 	s := new(DeclStmt)
   1594 	s.init(p)
   1595 
   1596 	p.next() // _Const, _Type, or _Var
   1597 	s.DeclList = p.appendGroup(nil, f)
   1598 
   1599 	return s
   1600 }
   1601 
   1602 func (p *parser) forStmt() Stmt {
   1603 	if trace {
   1604 		defer p.trace("forStmt")()
   1605 	}
   1606 
   1607 	s := new(ForStmt)
   1608 	s.init(p)
   1609 
   1610 	p.want(_For)
   1611 	s.Init, s.Cond, s.Post = p.header(true)
   1612 	if gcCompat {
   1613 		s.init(p)
   1614 	}
   1615 	s.Body = p.stmtBody("for clause")
   1616 
   1617 	return s
   1618 }
   1619 
   1620 // stmtBody parses if and for statement bodies.
   1621 func (p *parser) stmtBody(context string) []Stmt {
   1622 	if trace {
   1623 		defer p.trace("stmtBody")()
   1624 	}
   1625 
   1626 	if !p.got(_Lbrace) {
   1627 		p.syntax_error("missing { after " + context)
   1628 		p.advance(_Name, _Rbrace)
   1629 	}
   1630 
   1631 	body := p.stmtList()
   1632 	p.want(_Rbrace)
   1633 
   1634 	return body
   1635 }
   1636 
   1637 var dummyCond = &Name{Value: "false"}
   1638 
   1639 func (p *parser) header(forStmt bool) (init SimpleStmt, cond Expr, post SimpleStmt) {
   1640 	if p.tok == _Lbrace {
   1641 		return
   1642 	}
   1643 
   1644 	outer := p.xnest
   1645 	p.xnest = -1
   1646 
   1647 	if p.tok != _Semi {
   1648 		// accept potential varDecl but complain
   1649 		if forStmt && p.got(_Var) {
   1650 			p.error("var declaration not allowed in for initializer")
   1651 		}
   1652 		init = p.simpleStmt(nil, forStmt)
   1653 		// If we have a range clause, we are done.
   1654 		if _, ok := init.(*RangeClause); ok {
   1655 			p.xnest = outer
   1656 			return
   1657 		}
   1658 	}
   1659 
   1660 	var condStmt SimpleStmt
   1661 	if p.got(_Semi) {
   1662 		if forStmt {
   1663 			if p.tok != _Semi {
   1664 				condStmt = p.simpleStmt(nil, false)
   1665 			}
   1666 			p.want(_Semi)
   1667 			if p.tok != _Lbrace {
   1668 				post = p.simpleStmt(nil, false)
   1669 			}
   1670 		} else if p.tok != _Lbrace {
   1671 			condStmt = p.simpleStmt(nil, false)
   1672 		}
   1673 	} else {
   1674 		condStmt = init
   1675 		init = nil
   1676 	}
   1677 
   1678 	// unpack condStmt
   1679 	switch s := condStmt.(type) {
   1680 	case nil:
   1681 		// nothing to do
   1682 	case *ExprStmt:
   1683 		cond = s.X
   1684 	default:
   1685 		p.syntax_error(fmt.Sprintf("%s used as value", String(s)))
   1686 		cond = dummyCond // avoid follow-up error for if statements
   1687 	}
   1688 
   1689 	p.xnest = outer
   1690 	return
   1691 }
   1692 
   1693 func (p *parser) ifStmt() *IfStmt {
   1694 	if trace {
   1695 		defer p.trace("ifStmt")()
   1696 	}
   1697 
   1698 	s := new(IfStmt)
   1699 	s.init(p)
   1700 
   1701 	p.want(_If)
   1702 	s.Init, s.Cond, _ = p.header(false)
   1703 	if s.Cond == nil {
   1704 		p.error("missing condition in if statement")
   1705 	}
   1706 
   1707 	if gcCompat {
   1708 		s.init(p)
   1709 	}
   1710 
   1711 	s.Then = p.stmtBody("if clause")
   1712 
   1713 	if p.got(_Else) {
   1714 		switch p.tok {
   1715 		case _If:
   1716 			s.Else = p.ifStmt()
   1717 		case _Lbrace:
   1718 			s.Else = p.blockStmt()
   1719 		default:
   1720 			p.error("else must be followed by if or statement block")
   1721 			p.advance(_Name, _Rbrace)
   1722 		}
   1723 	}
   1724 
   1725 	return s
   1726 }
   1727 
   1728 func (p *parser) switchStmt() *SwitchStmt {
   1729 	if trace {
   1730 		defer p.trace("switchStmt")()
   1731 	}
   1732 
   1733 	p.want(_Switch)
   1734 	s := new(SwitchStmt)
   1735 	s.init(p)
   1736 
   1737 	s.Init, s.Tag, _ = p.header(false)
   1738 
   1739 	if !p.got(_Lbrace) {
   1740 		p.syntax_error("missing { after switch clause")
   1741 		p.advance(_Case, _Default, _Rbrace)
   1742 	}
   1743 	for p.tok != _EOF && p.tok != _Rbrace {
   1744 		s.Body = append(s.Body, p.caseClause())
   1745 	}
   1746 	p.want(_Rbrace)
   1747 
   1748 	return s
   1749 }
   1750 
   1751 func (p *parser) selectStmt() *SelectStmt {
   1752 	if trace {
   1753 		defer p.trace("selectStmt")()
   1754 	}
   1755 
   1756 	p.want(_Select)
   1757 	s := new(SelectStmt)
   1758 	s.init(p)
   1759 
   1760 	if !p.got(_Lbrace) {
   1761 		p.syntax_error("missing { after select clause")
   1762 		p.advance(_Case, _Default, _Rbrace)
   1763 	}
   1764 	for p.tok != _EOF && p.tok != _Rbrace {
   1765 		s.Body = append(s.Body, p.commClause())
   1766 	}
   1767 	p.want(_Rbrace)
   1768 
   1769 	return s
   1770 }
   1771 
   1772 func (p *parser) caseClause() *CaseClause {
   1773 	if trace {
   1774 		defer p.trace("caseClause")()
   1775 	}
   1776 
   1777 	c := new(CaseClause)
   1778 	c.init(p)
   1779 
   1780 	switch p.tok {
   1781 	case _Case:
   1782 		p.next()
   1783 		c.Cases = p.exprList()
   1784 
   1785 	case _Default:
   1786 		p.next()
   1787 
   1788 	default:
   1789 		p.syntax_error("expecting case or default or }")
   1790 		p.advance(_Case, _Default, _Rbrace)
   1791 	}
   1792 
   1793 	if gcCompat {
   1794 		c.init(p)
   1795 	}
   1796 	p.want(_Colon)
   1797 	c.Body = p.stmtList()
   1798 
   1799 	return c
   1800 }
   1801 
   1802 func (p *parser) commClause() *CommClause {
   1803 	if trace {
   1804 		defer p.trace("commClause")()
   1805 	}
   1806 
   1807 	c := new(CommClause)
   1808 	c.init(p)
   1809 
   1810 	switch p.tok {
   1811 	case _Case:
   1812 		p.next()
   1813 		c.Comm = p.simpleStmt(nil, false)
   1814 
   1815 		// The syntax restricts the possible simple statements here to:
   1816 		//
   1817 		//     lhs <- x (send statement)
   1818 		//     <-x
   1819 		//     lhs = <-x
   1820 		//     lhs := <-x
   1821 		//
   1822 		// All these (and more) are recognized by simpleStmt and invalid
   1823 		// syntax trees are flagged later, during type checking.
   1824 		// TODO(gri) eventually may want to restrict valid syntax trees
   1825 		// here.
   1826 
   1827 	case _Default:
   1828 		p.next()
   1829 
   1830 	default:
   1831 		p.syntax_error("expecting case or default or }")
   1832 		p.advance(_Case, _Default, _Rbrace)
   1833 	}
   1834 
   1835 	if gcCompat {
   1836 		c.init(p)
   1837 	}
   1838 	p.want(_Colon)
   1839 	c.Body = p.stmtList()
   1840 
   1841 	return c
   1842 }
   1843 
   1844 // TODO(gri) find a better solution
   1845 var missing_stmt Stmt = new(EmptyStmt) // = nod(OXXX, nil, nil)
   1846 
   1847 // Statement =
   1848 // 	Declaration | LabeledStmt | SimpleStmt |
   1849 // 	GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
   1850 // 	FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
   1851 // 	DeferStmt .
   1852 //
   1853 // stmt may return missing_stmt.
   1854 func (p *parser) stmt() Stmt {
   1855 	if trace {
   1856 		defer p.trace("stmt " + p.tok.String())()
   1857 	}
   1858 
   1859 	// Most statements (assignments) start with an identifier;
   1860 	// look for it first before doing anything more expensive.
   1861 	if p.tok == _Name {
   1862 		lhs := p.exprList()
   1863 		if label, ok := lhs.(*Name); ok && p.tok == _Colon {
   1864 			return p.labeledStmt(label)
   1865 		}
   1866 		return p.simpleStmt(lhs, false)
   1867 	}
   1868 
   1869 	switch p.tok {
   1870 	case _Lbrace:
   1871 		return p.blockStmt()
   1872 
   1873 	case _Var:
   1874 		return p.declStmt(p.varDecl)
   1875 
   1876 	case _Const:
   1877 		return p.declStmt(p.constDecl)
   1878 
   1879 	case _Type:
   1880 		return p.declStmt(p.typeDecl)
   1881 
   1882 	case _Operator, _Star:
   1883 		switch p.op {
   1884 		case Add, Sub, Mul, And, Xor, Not:
   1885 			return p.simpleStmt(nil, false) // unary operators
   1886 		}
   1887 
   1888 	case _Literal, _Func, _Lparen, // operands
   1889 		_Lbrack, _Struct, _Map, _Chan, _Interface, // composite types
   1890 		_Arrow: // receive operator
   1891 		return p.simpleStmt(nil, false)
   1892 
   1893 	case _For:
   1894 		return p.forStmt()
   1895 
   1896 	case _Switch:
   1897 		return p.switchStmt()
   1898 
   1899 	case _Select:
   1900 		return p.selectStmt()
   1901 
   1902 	case _If:
   1903 		return p.ifStmt()
   1904 
   1905 	case _Fallthrough:
   1906 		p.next()
   1907 		s := new(BranchStmt)
   1908 		s.init(p)
   1909 		s.Tok = _Fallthrough
   1910 		return s
   1911 		// // will be converted to OFALL
   1912 		// stmt := nod(OXFALL, nil, nil)
   1913 		// stmt.Xoffset = int64(block)
   1914 		// return stmt
   1915 
   1916 	case _Break, _Continue:
   1917 		tok := p.tok
   1918 		p.next()
   1919 		s := new(BranchStmt)
   1920 		s.init(p)
   1921 		s.Tok = tok
   1922 		if p.tok == _Name {
   1923 			s.Label = p.name()
   1924 		}
   1925 		return s
   1926 
   1927 	case _Go, _Defer:
   1928 		return p.callStmt()
   1929 
   1930 	case _Goto:
   1931 		p.next()
   1932 		s := new(BranchStmt)
   1933 		s.init(p)
   1934 		s.Tok = _Goto
   1935 		s.Label = p.name()
   1936 		return s
   1937 		// stmt := nod(OGOTO, p.new_name(p.name()), nil)
   1938 		// stmt.Sym = dclstack // context, for goto restrictions
   1939 		// return stmt
   1940 
   1941 	case _Return:
   1942 		p.next()
   1943 		s := new(ReturnStmt)
   1944 		s.init(p)
   1945 		if p.tok != _Semi && p.tok != _Rbrace {
   1946 			s.Results = p.exprList()
   1947 		}
   1948 		if gcCompat {
   1949 			s.init(p)
   1950 		}
   1951 		return s
   1952 
   1953 	case _Semi:
   1954 		s := new(EmptyStmt)
   1955 		s.init(p)
   1956 		return s
   1957 	}
   1958 
   1959 	return missing_stmt
   1960 }
   1961 
   1962 // StatementList = { Statement ";" } .
   1963 func (p *parser) stmtList() (l []Stmt) {
   1964 	if trace {
   1965 		defer p.trace("stmtList")()
   1966 	}
   1967 
   1968 	for p.tok != _EOF && p.tok != _Rbrace && p.tok != _Case && p.tok != _Default {
   1969 		s := p.stmt()
   1970 		if s == missing_stmt {
   1971 			break
   1972 		}
   1973 		l = append(l, s)
   1974 		// customized version of osemi:
   1975 		// ';' is optional before a closing ')' or '}'
   1976 		if p.tok == _Rparen || p.tok == _Rbrace {
   1977 			continue
   1978 		}
   1979 		if !p.got(_Semi) {
   1980 			p.syntax_error("at end of statement")
   1981 			p.advance(_Semi, _Rbrace)
   1982 		}
   1983 	}
   1984 	return
   1985 }
   1986 
   1987 // Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
   1988 func (p *parser) call(fun Expr) *CallExpr {
   1989 	if trace {
   1990 		defer p.trace("call")()
   1991 	}
   1992 
   1993 	// call or conversion
   1994 	// convtype '(' expr ocomma ')'
   1995 	c := new(CallExpr)
   1996 	c.init(p)
   1997 	c.Fun = fun
   1998 
   1999 	p.want(_Lparen)
   2000 	p.xnest++
   2001 
   2002 	for p.tok != _EOF && p.tok != _Rparen {
   2003 		c.ArgList = append(c.ArgList, p.expr()) // expr_or_type
   2004 		c.HasDots = p.got(_DotDotDot)
   2005 		if !p.ocomma(_Rparen) || c.HasDots {
   2006 			break
   2007 		}
   2008 	}
   2009 
   2010 	p.xnest--
   2011 	if gcCompat {
   2012 		c.init(p)
   2013 	}
   2014 	p.want(_Rparen)
   2015 
   2016 	return c
   2017 }
   2018 
   2019 // ----------------------------------------------------------------------------
   2020 // Common productions
   2021 
   2022 func (p *parser) name() *Name {
   2023 	// no tracing to avoid overly verbose output
   2024 
   2025 	n := new(Name)
   2026 	n.init(p)
   2027 
   2028 	if p.tok == _Name {
   2029 		n.Value = p.lit
   2030 		p.next()
   2031 	} else {
   2032 		n.Value = "_"
   2033 		p.syntax_error("expecting name")
   2034 		p.advance()
   2035 	}
   2036 
   2037 	return n
   2038 }
   2039 
   2040 // IdentifierList = identifier { "," identifier } .
   2041 // The first name must be provided.
   2042 func (p *parser) nameList(first *Name) []*Name {
   2043 	if trace {
   2044 		defer p.trace("nameList")()
   2045 	}
   2046 
   2047 	if debug && first == nil {
   2048 		panic("first name not provided")
   2049 	}
   2050 
   2051 	l := []*Name{first}
   2052 	for p.got(_Comma) {
   2053 		l = append(l, p.name())
   2054 	}
   2055 
   2056 	return l
   2057 }
   2058 
   2059 // The first name may be provided, or nil.
   2060 func (p *parser) qualifiedName(name *Name) Expr {
   2061 	if trace {
   2062 		defer p.trace("qualifiedName")()
   2063 	}
   2064 
   2065 	switch {
   2066 	case name != nil:
   2067 		// name is provided
   2068 	case p.tok == _Name:
   2069 		name = p.name()
   2070 	default:
   2071 		name = new(Name)
   2072 		name.init(p)
   2073 		p.syntax_error("expecting name")
   2074 		p.advance(_Dot, _Semi, _Rbrace)
   2075 	}
   2076 
   2077 	return p.dotname(name)
   2078 }
   2079 
   2080 // ExpressionList = Expression { "," Expression } .
   2081 func (p *parser) exprList() Expr {
   2082 	if trace {
   2083 		defer p.trace("exprList")()
   2084 	}
   2085 
   2086 	x := p.expr()
   2087 	if p.got(_Comma) {
   2088 		list := []Expr{x, p.expr()}
   2089 		for p.got(_Comma) {
   2090 			list = append(list, p.expr())
   2091 		}
   2092 		t := new(ListExpr)
   2093 		t.init(p) // TODO(gri) what is the correct thing here?
   2094 		t.ElemList = list
   2095 		x = t
   2096 	}
   2097 	return x
   2098 }
   2099 
   2100 // osemi parses an optional semicolon.
   2101 func (p *parser) osemi(follow token) bool {
   2102 	switch p.tok {
   2103 	case _Semi:
   2104 		p.next()
   2105 		return true
   2106 
   2107 	case _Rparen, _Rbrace:
   2108 		// semicolon is optional before ) or }
   2109 		return true
   2110 	}
   2111 
   2112 	p.syntax_error("expecting semicolon, newline, or " + tokstring(follow))
   2113 	p.advance(follow)
   2114 	return false
   2115 }
   2116 
   2117 // ocomma parses an optional comma.
   2118 func (p *parser) ocomma(follow token) bool {
   2119 	switch p.tok {
   2120 	case _Comma:
   2121 		p.next()
   2122 		return true
   2123 
   2124 	case _Rparen, _Rbrace:
   2125 		// comma is optional before ) or }
   2126 		return true
   2127 	}
   2128 
   2129 	p.syntax_error("expecting comma or " + tokstring(follow))
   2130 	p.advance(follow)
   2131 	return false
   2132 }
   2133 
   2134 // unparen removes all parentheses around an expression.
   2135 func unparen(x Expr) Expr {
   2136 	for {
   2137 		p, ok := x.(*ParenExpr)
   2138 		if !ok {
   2139 			break
   2140 		}
   2141 		x = p.X
   2142 	}
   2143 	return x
   2144 }
   2145