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