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