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