github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/go/printer/testdata/parser.go (about) 1 // Copyright 2009 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 parser implements a parser for Go source files. Input may be 6 // provided in a variety of forms (see the various Parse* functions); the 7 // output is an abstract syntax tree (AST) representing the Go source. The 8 // parser is invoked through one of the Parse* functions. 9 10 package parser 11 12 import ( 13 "fmt" 14 "go/ast" 15 "go/scanner" 16 "go/token" 17 ) 18 19 // The mode parameter to the Parse* functions is a set of flags (or 0). 20 // They control the amount of source code parsed and other optional 21 // parser functionality. 22 // 23 const ( 24 PackageClauseOnly uint = 1 << iota // parsing stops after package clause 25 ImportsOnly // parsing stops after import declarations 26 ParseComments // parse comments and add them to AST 27 Trace // print a trace of parsed productions 28 DeclarationErrors // report declaration errors 29 ) 30 31 // The parser structure holds the parser's internal state. 32 type parser struct { 33 file *token.File 34 scanner.ErrorVector 35 scanner scanner.Scanner 36 37 // Tracing/debugging 38 mode uint // parsing mode 39 trace bool // == (mode & Trace != 0) 40 indent uint // indentation used for tracing output 41 42 // Comments 43 comments []*ast.CommentGroup 44 leadComment *ast.CommentGroup // last lead comment 45 lineComment *ast.CommentGroup // last line comment 46 47 // Next token 48 pos token.Pos // token position 49 tok token.Token // one token look-ahead 50 lit string // token literal 51 52 // Non-syntactic parser control 53 exprLev int // < 0: in control clause, >= 0: in expression 54 55 // Ordinary identifier scopes 56 pkgScope *ast.Scope // pkgScope.Outer == nil 57 topScope *ast.Scope // top-most scope; may be pkgScope 58 unresolved []*ast.Ident // unresolved identifiers 59 imports []*ast.ImportSpec // list of imports 60 61 // Label scope 62 // (maintained by open/close LabelScope) 63 labelScope *ast.Scope // label scope for current function 64 targetStack [][]*ast.Ident // stack of unresolved labels 65 } 66 67 // scannerMode returns the scanner mode bits given the parser's mode bits. 68 func scannerMode(mode uint) uint { 69 var m uint = scanner.InsertSemis 70 if mode&ParseComments != 0 { 71 m |= scanner.ScanComments 72 } 73 return m 74 } 75 76 func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode uint) { 77 p.file = fset.AddFile(filename, fset.Base(), len(src)) 78 p.scanner.Init(p.file, src, p, scannerMode(mode)) 79 80 p.mode = mode 81 p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently) 82 83 p.next() 84 85 // set up the pkgScope here (as opposed to in parseFile) because 86 // there are other parser entry points (ParseExpr, etc.) 87 p.openScope() 88 p.pkgScope = p.topScope 89 90 // for the same reason, set up a label scope 91 p.openLabelScope() 92 } 93 94 // ---------------------------------------------------------------------------- 95 // Scoping support 96 97 func (p *parser) openScope() { 98 p.topScope = ast.NewScope(p.topScope) 99 } 100 101 func (p *parser) closeScope() { 102 p.topScope = p.topScope.Outer 103 } 104 105 func (p *parser) openLabelScope() { 106 p.labelScope = ast.NewScope(p.labelScope) 107 p.targetStack = append(p.targetStack, nil) 108 } 109 110 func (p *parser) closeLabelScope() { 111 // resolve labels 112 n := len(p.targetStack) - 1 113 scope := p.labelScope 114 for _, ident := range p.targetStack[n] { 115 ident.Obj = scope.Lookup(ident.Name) 116 if ident.Obj == nil && p.mode&DeclarationErrors != 0 { 117 p.error(ident.Pos(), fmt.Sprintf("label %s undefined", ident.Name)) 118 } 119 } 120 // pop label scope 121 p.targetStack = p.targetStack[0:n] 122 p.labelScope = p.labelScope.Outer 123 } 124 125 func (p *parser) declare(decl interface{}, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) { 126 for _, ident := range idents { 127 assert(ident.Obj == nil, "identifier already declared or resolved") 128 if ident.Name != "_" { 129 obj := ast.NewObj(kind, ident.Name) 130 // remember the corresponding declaration for redeclaration 131 // errors and global variable resolution/typechecking phase 132 obj.Decl = decl 133 if alt := scope.Insert(obj); alt != nil && p.mode&DeclarationErrors != 0 { 134 prevDecl := "" 135 if pos := alt.Pos(); pos.IsValid() { 136 prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", p.file.Position(pos)) 137 } 138 p.error(ident.Pos(), fmt.Sprintf("%s redeclared in this block%s", ident.Name, prevDecl)) 139 } 140 ident.Obj = obj 141 } 142 } 143 } 144 145 func (p *parser) shortVarDecl(idents []*ast.Ident) { 146 // Go spec: A short variable declaration may redeclare variables 147 // provided they were originally declared in the same block with 148 // the same type, and at least one of the non-blank variables is new. 149 n := 0 // number of new variables 150 for _, ident := range idents { 151 assert(ident.Obj == nil, "identifier already declared or resolved") 152 if ident.Name != "_" { 153 obj := ast.NewObj(ast.Var, ident.Name) 154 // short var declarations cannot have redeclaration errors 155 // and are not global => no need to remember the respective 156 // declaration 157 alt := p.topScope.Insert(obj) 158 if alt == nil { 159 n++ // new declaration 160 alt = obj 161 } 162 ident.Obj = alt 163 } 164 } 165 if n == 0 && p.mode&DeclarationErrors != 0 { 166 p.error(idents[0].Pos(), "no new variables on left side of :=") 167 } 168 } 169 170 // The unresolved object is a sentinel to mark identifiers that have been added 171 // to the list of unresolved identifiers. The sentinel is only used for verifying 172 // internal consistency. 173 var unresolved = new(ast.Object) 174 175 func (p *parser) resolve(x ast.Expr) { 176 // nothing to do if x is not an identifier or the blank identifier 177 ident, _ := x.(*ast.Ident) 178 if ident == nil { 179 return 180 } 181 assert(ident.Obj == nil, "identifier already declared or resolved") 182 if ident.Name == "_" { 183 return 184 } 185 // try to resolve the identifier 186 for s := p.topScope; s != nil; s = s.Outer { 187 if obj := s.Lookup(ident.Name); obj != nil { 188 ident.Obj = obj 189 return 190 } 191 } 192 // all local scopes are known, so any unresolved identifier 193 // must be found either in the file scope, package scope 194 // (perhaps in another file), or universe scope --- collect 195 // them so that they can be resolved later 196 ident.Obj = unresolved 197 p.unresolved = append(p.unresolved, ident) 198 } 199 200 // ---------------------------------------------------------------------------- 201 // Parsing support 202 203 func (p *parser) printTrace(a ...interface{}) { 204 const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " + 205 ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " 206 const n = uint(len(dots)) 207 pos := p.file.Position(p.pos) 208 fmt.Printf("%5d:%3d: ", pos.Line, pos.Column) 209 i := 2 * p.indent 210 for ; i > n; i -= n { 211 fmt.Print(dots) 212 } 213 fmt.Print(dots[0:i]) 214 fmt.Println(a...) 215 } 216 217 func trace(p *parser, msg string) *parser { 218 p.printTrace(msg, "(") 219 p.indent++ 220 return p 221 } 222 223 // Usage pattern: defer un(trace(p, "...")); 224 func un(p *parser) { 225 p.indent-- 226 p.printTrace(")") 227 } 228 229 // Advance to the next token. 230 func (p *parser) next0() { 231 // Because of one-token look-ahead, print the previous token 232 // when tracing as it provides a more readable output. The 233 // very first token (!p.pos.IsValid()) is not initialized 234 // (it is token.ILLEGAL), so don't print it . 235 if p.trace && p.pos.IsValid() { 236 s := p.tok.String() 237 switch { 238 case p.tok.IsLiteral(): 239 p.printTrace(s, p.lit) 240 case p.tok.IsOperator(), p.tok.IsKeyword(): 241 p.printTrace("\"" + s + "\"") 242 default: 243 p.printTrace(s) 244 } 245 } 246 247 p.pos, p.tok, p.lit = p.scanner.Scan() 248 } 249 250 // Consume a comment and return it and the line on which it ends. 251 func (p *parser) consumeComment() (comment *ast.Comment, endline int) { 252 // /*-style comments may end on a different line than where they start. 253 // Scan the comment for '\n' chars and adjust endline accordingly. 254 endline = p.file.Line(p.pos) 255 if p.lit[1] == '*' { 256 // don't use range here - no need to decode Unicode code points 257 for i := 0; i < len(p.lit); i++ { 258 if p.lit[i] == '\n' { 259 endline++ 260 } 261 } 262 } 263 264 comment = &ast.Comment{p.pos, p.lit} 265 p.next0() 266 267 return 268 } 269 270 // Consume a group of adjacent comments, add it to the parser's 271 // comments list, and return it together with the line at which 272 // the last comment in the group ends. An empty line or non-comment 273 // token terminates a comment group. 274 // 275 func (p *parser) consumeCommentGroup() (comments *ast.CommentGroup, endline int) { 276 var list []*ast.Comment 277 endline = p.file.Line(p.pos) 278 for p.tok == token.COMMENT && endline+1 >= p.file.Line(p.pos) { 279 var comment *ast.Comment 280 comment, endline = p.consumeComment() 281 list = append(list, comment) 282 } 283 284 // add comment group to the comments list 285 comments = &ast.CommentGroup{list} 286 p.comments = append(p.comments, comments) 287 288 return 289 } 290 291 // Advance to the next non-comment token. In the process, collect 292 // any comment groups encountered, and remember the last lead and 293 // and line comments. 294 // 295 // A lead comment is a comment group that starts and ends in a 296 // line without any other tokens and that is followed by a non-comment 297 // token on the line immediately after the comment group. 298 // 299 // A line comment is a comment group that follows a non-comment 300 // token on the same line, and that has no tokens after it on the line 301 // where it ends. 302 // 303 // Lead and line comments may be considered documentation that is 304 // stored in the AST. 305 // 306 func (p *parser) next() { 307 p.leadComment = nil 308 p.lineComment = nil 309 line := p.file.Line(p.pos) // current line 310 p.next0() 311 312 if p.tok == token.COMMENT { 313 var comment *ast.CommentGroup 314 var endline int 315 316 if p.file.Line(p.pos) == line { 317 // The comment is on same line as the previous token; it 318 // cannot be a lead comment but may be a line comment. 319 comment, endline = p.consumeCommentGroup() 320 if p.file.Line(p.pos) != endline { 321 // The next token is on a different line, thus 322 // the last comment group is a line comment. 323 p.lineComment = comment 324 } 325 } 326 327 // consume successor comments, if any 328 endline = -1 329 for p.tok == token.COMMENT { 330 comment, endline = p.consumeCommentGroup() 331 } 332 333 if endline+1 == p.file.Line(p.pos) { 334 // The next token is following on the line immediately after the 335 // comment group, thus the last comment group is a lead comment. 336 p.leadComment = comment 337 } 338 } 339 } 340 341 func (p *parser) error(pos token.Pos, msg string) { 342 p.Error(p.file.Position(pos), msg) 343 } 344 345 func (p *parser) errorExpected(pos token.Pos, msg string) { 346 msg = "expected " + msg 347 if pos == p.pos { 348 // the error happened at the current position; 349 // make the error message more specific 350 if p.tok == token.SEMICOLON && p.lit[0] == '\n' { 351 msg += ", found newline" 352 } else { 353 msg += ", found '" + p.tok.String() + "'" 354 if p.tok.IsLiteral() { 355 msg += " " + p.lit 356 } 357 } 358 } 359 p.error(pos, msg) 360 } 361 362 func (p *parser) expect(tok token.Token) token.Pos { 363 pos := p.pos 364 if p.tok != tok { 365 p.errorExpected(pos, "'"+tok.String()+"'") 366 } 367 p.next() // make progress 368 return pos 369 } 370 371 func (p *parser) expectSemi() { 372 if p.tok != token.RPAREN && p.tok != token.RBRACE { 373 p.expect(token.SEMICOLON) 374 } 375 } 376 377 func assert(cond bool, msg string) { 378 if !cond { 379 panic("go/parser internal error: " + msg) 380 } 381 } 382 383 // ---------------------------------------------------------------------------- 384 // Identifiers 385 386 func (p *parser) parseIdent() *ast.Ident { 387 pos := p.pos 388 name := "_" 389 if p.tok == token.IDENT { 390 name = p.lit 391 p.next() 392 } else { 393 p.expect(token.IDENT) // use expect() error handling 394 } 395 return &ast.Ident{pos, name, nil} 396 } 397 398 func (p *parser) parseIdentList() (list []*ast.Ident) { 399 if p.trace { 400 defer un(trace(p, "IdentList")) 401 } 402 403 list = append(list, p.parseIdent()) 404 for p.tok == token.COMMA { 405 p.next() 406 list = append(list, p.parseIdent()) 407 } 408 409 return 410 } 411 412 // ---------------------------------------------------------------------------- 413 // Common productions 414 415 // If lhs is set, result list elements which are identifiers are not resolved. 416 func (p *parser) parseExprList(lhs bool) (list []ast.Expr) { 417 if p.trace { 418 defer un(trace(p, "ExpressionList")) 419 } 420 421 list = append(list, p.parseExpr(lhs)) 422 for p.tok == token.COMMA { 423 p.next() 424 list = append(list, p.parseExpr(lhs)) 425 } 426 427 return 428 } 429 430 func (p *parser) parseLhsList() []ast.Expr { 431 list := p.parseExprList(true) 432 switch p.tok { 433 case token.DEFINE: 434 // lhs of a short variable declaration 435 p.shortVarDecl(p.makeIdentList(list)) 436 case token.COLON: 437 // lhs of a label declaration or a communication clause of a select 438 // statement (parseLhsList is not called when parsing the case clause 439 // of a switch statement): 440 // - labels are declared by the caller of parseLhsList 441 // - for communication clauses, if there is a stand-alone identifier 442 // followed by a colon, we have a syntax error; there is no need 443 // to resolve the identifier in that case 444 default: 445 // identifiers must be declared elsewhere 446 for _, x := range list { 447 p.resolve(x) 448 } 449 } 450 return list 451 } 452 453 func (p *parser) parseRhsList() []ast.Expr { 454 return p.parseExprList(false) 455 } 456 457 // ---------------------------------------------------------------------------- 458 // Types 459 460 func (p *parser) parseType() ast.Expr { 461 if p.trace { 462 defer un(trace(p, "Type")) 463 } 464 465 typ := p.tryType() 466 467 if typ == nil { 468 pos := p.pos 469 p.errorExpected(pos, "type") 470 p.next() // make progress 471 return &ast.BadExpr{pos, p.pos} 472 } 473 474 return typ 475 } 476 477 // If the result is an identifier, it is not resolved. 478 func (p *parser) parseTypeName() ast.Expr { 479 if p.trace { 480 defer un(trace(p, "TypeName")) 481 } 482 483 ident := p.parseIdent() 484 // don't resolve ident yet - it may be a parameter or field name 485 486 if p.tok == token.PERIOD { 487 // ident is a package name 488 p.next() 489 p.resolve(ident) 490 sel := p.parseIdent() 491 return &ast.SelectorExpr{ident, sel} 492 } 493 494 return ident 495 } 496 497 func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr { 498 if p.trace { 499 defer un(trace(p, "ArrayType")) 500 } 501 502 lbrack := p.expect(token.LBRACK) 503 var len ast.Expr 504 if ellipsisOk && p.tok == token.ELLIPSIS { 505 len = &ast.Ellipsis{p.pos, nil} 506 p.next() 507 } else if p.tok != token.RBRACK { 508 len = p.parseRhs() 509 } 510 p.expect(token.RBRACK) 511 elt := p.parseType() 512 513 return &ast.ArrayType{lbrack, len, elt} 514 } 515 516 func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident { 517 idents := make([]*ast.Ident, len(list)) 518 for i, x := range list { 519 ident, isIdent := x.(*ast.Ident) 520 if !isIdent { 521 pos := x.(ast.Expr).Pos() 522 p.errorExpected(pos, "identifier") 523 ident = &ast.Ident{pos, "_", nil} 524 } 525 idents[i] = ident 526 } 527 return idents 528 } 529 530 func (p *parser) parseFieldDecl(scope *ast.Scope) *ast.Field { 531 if p.trace { 532 defer un(trace(p, "FieldDecl")) 533 } 534 535 doc := p.leadComment 536 537 // fields 538 list, typ := p.parseVarList(false) 539 540 // optional tag 541 var tag *ast.BasicLit 542 if p.tok == token.STRING { 543 tag = &ast.BasicLit{p.pos, p.tok, p.lit} 544 p.next() 545 } 546 547 // analyze case 548 var idents []*ast.Ident 549 if typ != nil { 550 // IdentifierList Type 551 idents = p.makeIdentList(list) 552 } else { 553 // ["*"] TypeName (AnonymousField) 554 typ = list[0] // we always have at least one element 555 p.resolve(typ) 556 if n := len(list); n > 1 || !isTypeName(deref(typ)) { 557 pos := typ.Pos() 558 p.errorExpected(pos, "anonymous field") 559 typ = &ast.BadExpr{pos, list[n-1].End()} 560 } 561 } 562 563 p.expectSemi() // call before accessing p.linecomment 564 565 field := &ast.Field{doc, idents, typ, tag, p.lineComment} 566 p.declare(field, scope, ast.Var, idents...) 567 568 return field 569 } 570 571 func (p *parser) parseStructType() *ast.StructType { 572 if p.trace { 573 defer un(trace(p, "StructType")) 574 } 575 576 pos := p.expect(token.STRUCT) 577 lbrace := p.expect(token.LBRACE) 578 scope := ast.NewScope(nil) // struct scope 579 var list []*ast.Field 580 for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN { 581 // a field declaration cannot start with a '(' but we accept 582 // it here for more robust parsing and better error messages 583 // (parseFieldDecl will check and complain if necessary) 584 list = append(list, p.parseFieldDecl(scope)) 585 } 586 rbrace := p.expect(token.RBRACE) 587 588 // TODO(gri): store struct scope in AST 589 return &ast.StructType{pos, &ast.FieldList{lbrace, list, rbrace}, false} 590 } 591 592 func (p *parser) parsePointerType() *ast.StarExpr { 593 if p.trace { 594 defer un(trace(p, "PointerType")) 595 } 596 597 star := p.expect(token.MUL) 598 base := p.parseType() 599 600 return &ast.StarExpr{star, base} 601 } 602 603 func (p *parser) tryVarType(isParam bool) ast.Expr { 604 if isParam && p.tok == token.ELLIPSIS { 605 pos := p.pos 606 p.next() 607 typ := p.tryIdentOrType(isParam) // don't use parseType so we can provide better error message 608 if typ == nil { 609 p.error(pos, "'...' parameter is missing type") 610 typ = &ast.BadExpr{pos, p.pos} 611 } 612 if p.tok != token.RPAREN { 613 p.error(pos, "can use '...' with last parameter type only") 614 } 615 return &ast.Ellipsis{pos, typ} 616 } 617 return p.tryIdentOrType(false) 618 } 619 620 func (p *parser) parseVarType(isParam bool) ast.Expr { 621 typ := p.tryVarType(isParam) 622 if typ == nil { 623 pos := p.pos 624 p.errorExpected(pos, "type") 625 p.next() // make progress 626 typ = &ast.BadExpr{pos, p.pos} 627 } 628 return typ 629 } 630 631 func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) { 632 if p.trace { 633 defer un(trace(p, "VarList")) 634 } 635 636 // a list of identifiers looks like a list of type names 637 for { 638 // parseVarType accepts any type (including parenthesized ones) 639 // even though the syntax does not permit them here: we 640 // accept them all for more robust parsing and complain 641 // afterwards 642 list = append(list, p.parseVarType(isParam)) 643 if p.tok != token.COMMA { 644 break 645 } 646 p.next() 647 } 648 649 // if we had a list of identifiers, it must be followed by a type 650 typ = p.tryVarType(isParam) 651 if typ != nil { 652 p.resolve(typ) 653 } 654 655 return 656 } 657 658 func (p *parser) parseParameterList(scope *ast.Scope, ellipsisOk bool) (params []*ast.Field) { 659 if p.trace { 660 defer un(trace(p, "ParameterList")) 661 } 662 663 list, typ := p.parseVarList(ellipsisOk) 664 if typ != nil { 665 // IdentifierList Type 666 idents := p.makeIdentList(list) 667 field := &ast.Field{nil, idents, typ, nil, nil} 668 params = append(params, field) 669 // Go spec: The scope of an identifier denoting a function 670 // parameter or result variable is the function body. 671 p.declare(field, scope, ast.Var, idents...) 672 if p.tok == token.COMMA { 673 p.next() 674 } 675 676 for p.tok != token.RPAREN && p.tok != token.EOF { 677 idents := p.parseIdentList() 678 typ := p.parseVarType(ellipsisOk) 679 field := &ast.Field{nil, idents, typ, nil, nil} 680 params = append(params, field) 681 // Go spec: The scope of an identifier denoting a function 682 // parameter or result variable is the function body. 683 p.declare(field, scope, ast.Var, idents...) 684 if p.tok != token.COMMA { 685 break 686 } 687 p.next() 688 } 689 690 } else { 691 // Type { "," Type } (anonymous parameters) 692 params = make([]*ast.Field, len(list)) 693 for i, x := range list { 694 p.resolve(x) 695 params[i] = &ast.Field{Type: x} 696 } 697 } 698 699 return 700 } 701 702 func (p *parser) parseParameters(scope *ast.Scope, ellipsisOk bool) *ast.FieldList { 703 if p.trace { 704 defer un(trace(p, "Parameters")) 705 } 706 707 var params []*ast.Field 708 lparen := p.expect(token.LPAREN) 709 if p.tok != token.RPAREN { 710 params = p.parseParameterList(scope, ellipsisOk) 711 } 712 rparen := p.expect(token.RPAREN) 713 714 return &ast.FieldList{lparen, params, rparen} 715 } 716 717 func (p *parser) parseResult(scope *ast.Scope) *ast.FieldList { 718 if p.trace { 719 defer un(trace(p, "Result")) 720 } 721 722 if p.tok == token.LPAREN { 723 return p.parseParameters(scope, false) 724 } 725 726 typ := p.tryType() 727 if typ != nil { 728 list := make([]*ast.Field, 1) 729 list[0] = &ast.Field{Type: typ} 730 return &ast.FieldList{List: list} 731 } 732 733 return nil 734 } 735 736 func (p *parser) parseSignature(scope *ast.Scope) (params, results *ast.FieldList) { 737 if p.trace { 738 defer un(trace(p, "Signature")) 739 } 740 741 params = p.parseParameters(scope, true) 742 results = p.parseResult(scope) 743 744 return 745 } 746 747 func (p *parser) parseFuncType() (*ast.FuncType, *ast.Scope) { 748 if p.trace { 749 defer un(trace(p, "FuncType")) 750 } 751 752 pos := p.expect(token.FUNC) 753 scope := ast.NewScope(p.topScope) // function scope 754 params, results := p.parseSignature(scope) 755 756 return &ast.FuncType{pos, params, results}, scope 757 } 758 759 func (p *parser) parseMethodSpec(scope *ast.Scope) *ast.Field { 760 if p.trace { 761 defer un(trace(p, "MethodSpec")) 762 } 763 764 doc := p.leadComment 765 var idents []*ast.Ident 766 var typ ast.Expr 767 x := p.parseTypeName() 768 if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN { 769 // method 770 idents = []*ast.Ident{ident} 771 scope := ast.NewScope(nil) // method scope 772 params, results := p.parseSignature(scope) 773 typ = &ast.FuncType{token.NoPos, params, results} 774 } else { 775 // embedded interface 776 typ = x 777 } 778 p.expectSemi() // call before accessing p.linecomment 779 780 spec := &ast.Field{doc, idents, typ, nil, p.lineComment} 781 p.declare(spec, scope, ast.Fun, idents...) 782 783 return spec 784 } 785 786 func (p *parser) parseInterfaceType() *ast.InterfaceType { 787 if p.trace { 788 defer un(trace(p, "InterfaceType")) 789 } 790 791 pos := p.expect(token.INTERFACE) 792 lbrace := p.expect(token.LBRACE) 793 scope := ast.NewScope(nil) // interface scope 794 var list []*ast.Field 795 for p.tok == token.IDENT { 796 list = append(list, p.parseMethodSpec(scope)) 797 } 798 rbrace := p.expect(token.RBRACE) 799 800 // TODO(gri): store interface scope in AST 801 return &ast.InterfaceType{pos, &ast.FieldList{lbrace, list, rbrace}, false} 802 } 803 804 func (p *parser) parseMapType() *ast.MapType { 805 if p.trace { 806 defer un(trace(p, "MapType")) 807 } 808 809 pos := p.expect(token.MAP) 810 p.expect(token.LBRACK) 811 key := p.parseType() 812 p.expect(token.RBRACK) 813 value := p.parseType() 814 815 return &ast.MapType{pos, key, value} 816 } 817 818 func (p *parser) parseChanType() *ast.ChanType { 819 if p.trace { 820 defer un(trace(p, "ChanType")) 821 } 822 823 pos := p.pos 824 dir := ast.SEND | ast.RECV 825 if p.tok == token.CHAN { 826 p.next() 827 if p.tok == token.ARROW { 828 p.next() 829 dir = ast.SEND 830 } 831 } else { 832 p.expect(token.ARROW) 833 p.expect(token.CHAN) 834 dir = ast.RECV 835 } 836 value := p.parseType() 837 838 return &ast.ChanType{pos, dir, value} 839 } 840 841 // If the result is an identifier, it is not resolved. 842 func (p *parser) tryIdentOrType(ellipsisOk bool) ast.Expr { 843 switch p.tok { 844 case token.IDENT: 845 return p.parseTypeName() 846 case token.LBRACK: 847 return p.parseArrayType(ellipsisOk) 848 case token.STRUCT: 849 return p.parseStructType() 850 case token.MUL: 851 return p.parsePointerType() 852 case token.FUNC: 853 typ, _ := p.parseFuncType() 854 return typ 855 case token.INTERFACE: 856 return p.parseInterfaceType() 857 case token.MAP: 858 return p.parseMapType() 859 case token.CHAN, token.ARROW: 860 return p.parseChanType() 861 case token.LPAREN: 862 lparen := p.pos 863 p.next() 864 typ := p.parseType() 865 rparen := p.expect(token.RPAREN) 866 return &ast.ParenExpr{lparen, typ, rparen} 867 } 868 869 // no type found 870 return nil 871 } 872 873 func (p *parser) tryType() ast.Expr { 874 typ := p.tryIdentOrType(false) 875 if typ != nil { 876 p.resolve(typ) 877 } 878 return typ 879 } 880 881 // ---------------------------------------------------------------------------- 882 // Blocks 883 884 func (p *parser) parseStmtList() (list []ast.Stmt) { 885 if p.trace { 886 defer un(trace(p, "StatementList")) 887 } 888 889 for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF { 890 list = append(list, p.parseStmt()) 891 } 892 893 return 894 } 895 896 func (p *parser) parseBody(scope *ast.Scope) *ast.BlockStmt { 897 if p.trace { 898 defer un(trace(p, "Body")) 899 } 900 901 lbrace := p.expect(token.LBRACE) 902 p.topScope = scope // open function scope 903 p.openLabelScope() 904 list := p.parseStmtList() 905 p.closeLabelScope() 906 p.closeScope() 907 rbrace := p.expect(token.RBRACE) 908 909 return &ast.BlockStmt{lbrace, list, rbrace} 910 } 911 912 func (p *parser) parseBlockStmt() *ast.BlockStmt { 913 if p.trace { 914 defer un(trace(p, "BlockStmt")) 915 } 916 917 lbrace := p.expect(token.LBRACE) 918 p.openScope() 919 list := p.parseStmtList() 920 p.closeScope() 921 rbrace := p.expect(token.RBRACE) 922 923 return &ast.BlockStmt{lbrace, list, rbrace} 924 } 925 926 // ---------------------------------------------------------------------------- 927 // Expressions 928 929 func (p *parser) parseFuncTypeOrLit() ast.Expr { 930 if p.trace { 931 defer un(trace(p, "FuncTypeOrLit")) 932 } 933 934 typ, scope := p.parseFuncType() 935 if p.tok != token.LBRACE { 936 // function type only 937 return typ 938 } 939 940 p.exprLev++ 941 body := p.parseBody(scope) 942 p.exprLev-- 943 944 return &ast.FuncLit{typ, body} 945 } 946 947 // parseOperand may return an expression or a raw type (incl. array 948 // types of the form [...]T. Callers must verify the result. 949 // If lhs is set and the result is an identifier, it is not resolved. 950 // 951 func (p *parser) parseOperand(lhs bool) ast.Expr { 952 if p.trace { 953 defer un(trace(p, "Operand")) 954 } 955 956 switch p.tok { 957 case token.IDENT: 958 x := p.parseIdent() 959 if !lhs { 960 p.resolve(x) 961 } 962 return x 963 964 case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING: 965 x := &ast.BasicLit{p.pos, p.tok, p.lit} 966 p.next() 967 return x 968 969 case token.LPAREN: 970 lparen := p.pos 971 p.next() 972 p.exprLev++ 973 x := p.parseRhs() 974 p.exprLev-- 975 rparen := p.expect(token.RPAREN) 976 return &ast.ParenExpr{lparen, x, rparen} 977 978 case token.FUNC: 979 return p.parseFuncTypeOrLit() 980 981 default: 982 if typ := p.tryIdentOrType(true); typ != nil { 983 // could be type for composite literal or conversion 984 _, isIdent := typ.(*ast.Ident) 985 assert(!isIdent, "type cannot be identifier") 986 return typ 987 } 988 } 989 990 pos := p.pos 991 p.errorExpected(pos, "operand") 992 p.next() // make progress 993 return &ast.BadExpr{pos, p.pos} 994 } 995 996 func (p *parser) parseSelector(x ast.Expr) ast.Expr { 997 if p.trace { 998 defer un(trace(p, "Selector")) 999 } 1000 1001 sel := p.parseIdent() 1002 1003 return &ast.SelectorExpr{x, sel} 1004 } 1005 1006 func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr { 1007 if p.trace { 1008 defer un(trace(p, "TypeAssertion")) 1009 } 1010 1011 p.expect(token.LPAREN) 1012 var typ ast.Expr 1013 if p.tok == token.TYPE { 1014 // type switch: typ == nil 1015 p.next() 1016 } else { 1017 typ = p.parseType() 1018 } 1019 p.expect(token.RPAREN) 1020 1021 return &ast.TypeAssertExpr{x, typ} 1022 } 1023 1024 func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr { 1025 if p.trace { 1026 defer un(trace(p, "IndexOrSlice")) 1027 } 1028 1029 lbrack := p.expect(token.LBRACK) 1030 p.exprLev++ 1031 var low, high ast.Expr 1032 isSlice := false 1033 if p.tok != token.COLON { 1034 low = p.parseRhs() 1035 } 1036 if p.tok == token.COLON { 1037 isSlice = true 1038 p.next() 1039 if p.tok != token.RBRACK { 1040 high = p.parseRhs() 1041 } 1042 } 1043 p.exprLev-- 1044 rbrack := p.expect(token.RBRACK) 1045 1046 if isSlice { 1047 return &ast.SliceExpr{x, lbrack, low, high, rbrack} 1048 } 1049 return &ast.IndexExpr{x, lbrack, low, rbrack} 1050 } 1051 1052 func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr { 1053 if p.trace { 1054 defer un(trace(p, "CallOrConversion")) 1055 } 1056 1057 lparen := p.expect(token.LPAREN) 1058 p.exprLev++ 1059 var list []ast.Expr 1060 var ellipsis token.Pos 1061 for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() { 1062 list = append(list, p.parseRhs()) 1063 if p.tok == token.ELLIPSIS { 1064 ellipsis = p.pos 1065 p.next() 1066 } 1067 if p.tok != token.COMMA { 1068 break 1069 } 1070 p.next() 1071 } 1072 p.exprLev-- 1073 rparen := p.expect(token.RPAREN) 1074 1075 return &ast.CallExpr{fun, lparen, list, ellipsis, rparen} 1076 } 1077 1078 func (p *parser) parseElement(keyOk bool) ast.Expr { 1079 if p.trace { 1080 defer un(trace(p, "Element")) 1081 } 1082 1083 if p.tok == token.LBRACE { 1084 return p.parseLiteralValue(nil) 1085 } 1086 1087 x := p.parseExpr(keyOk) // don't resolve if map key 1088 if keyOk { 1089 if p.tok == token.COLON { 1090 colon := p.pos 1091 p.next() 1092 return &ast.KeyValueExpr{x, colon, p.parseElement(false)} 1093 } 1094 p.resolve(x) // not a map key 1095 } 1096 1097 return x 1098 } 1099 1100 func (p *parser) parseElementList() (list []ast.Expr) { 1101 if p.trace { 1102 defer un(trace(p, "ElementList")) 1103 } 1104 1105 for p.tok != token.RBRACE && p.tok != token.EOF { 1106 list = append(list, p.parseElement(true)) 1107 if p.tok != token.COMMA { 1108 break 1109 } 1110 p.next() 1111 } 1112 1113 return 1114 } 1115 1116 func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr { 1117 if p.trace { 1118 defer un(trace(p, "LiteralValue")) 1119 } 1120 1121 lbrace := p.expect(token.LBRACE) 1122 var elts []ast.Expr 1123 p.exprLev++ 1124 if p.tok != token.RBRACE { 1125 elts = p.parseElementList() 1126 } 1127 p.exprLev-- 1128 rbrace := p.expect(token.RBRACE) 1129 return &ast.CompositeLit{typ, lbrace, elts, rbrace} 1130 } 1131 1132 // checkExpr checks that x is an expression (and not a type). 1133 func (p *parser) checkExpr(x ast.Expr) ast.Expr { 1134 switch t := unparen(x).(type) { 1135 case *ast.BadExpr: 1136 case *ast.Ident: 1137 case *ast.BasicLit: 1138 case *ast.FuncLit: 1139 case *ast.CompositeLit: 1140 case *ast.ParenExpr: 1141 panic("unreachable") 1142 case *ast.SelectorExpr: 1143 case *ast.IndexExpr: 1144 case *ast.SliceExpr: 1145 case *ast.TypeAssertExpr: 1146 if t.Type == nil { 1147 // the form X.(type) is only allowed in type switch expressions 1148 p.errorExpected(x.Pos(), "expression") 1149 x = &ast.BadExpr{x.Pos(), x.End()} 1150 } 1151 case *ast.CallExpr: 1152 case *ast.StarExpr: 1153 case *ast.UnaryExpr: 1154 if t.Op == token.RANGE { 1155 // the range operator is only allowed at the top of a for statement 1156 p.errorExpected(x.Pos(), "expression") 1157 x = &ast.BadExpr{x.Pos(), x.End()} 1158 } 1159 case *ast.BinaryExpr: 1160 default: 1161 // all other nodes are not proper expressions 1162 p.errorExpected(x.Pos(), "expression") 1163 x = &ast.BadExpr{x.Pos(), x.End()} 1164 } 1165 return x 1166 } 1167 1168 // isTypeName returns true iff x is a (qualified) TypeName. 1169 func isTypeName(x ast.Expr) bool { 1170 switch t := x.(type) { 1171 case *ast.BadExpr: 1172 case *ast.Ident: 1173 case *ast.SelectorExpr: 1174 _, isIdent := t.X.(*ast.Ident) 1175 return isIdent 1176 default: 1177 return false // all other nodes are not type names 1178 } 1179 return true 1180 } 1181 1182 // isLiteralType returns true iff x is a legal composite literal type. 1183 func isLiteralType(x ast.Expr) bool { 1184 switch t := x.(type) { 1185 case *ast.BadExpr: 1186 case *ast.Ident: 1187 case *ast.SelectorExpr: 1188 _, isIdent := t.X.(*ast.Ident) 1189 return isIdent 1190 case *ast.ArrayType: 1191 case *ast.StructType: 1192 case *ast.MapType: 1193 default: 1194 return false // all other nodes are not legal composite literal types 1195 } 1196 return true 1197 } 1198 1199 // If x is of the form *T, deref returns T, otherwise it returns x. 1200 func deref(x ast.Expr) ast.Expr { 1201 if p, isPtr := x.(*ast.StarExpr); isPtr { 1202 x = p.X 1203 } 1204 return x 1205 } 1206 1207 // If x is of the form (T), unparen returns unparen(T), otherwise it returns x. 1208 func unparen(x ast.Expr) ast.Expr { 1209 if p, isParen := x.(*ast.ParenExpr); isParen { 1210 x = unparen(p.X) 1211 } 1212 return x 1213 } 1214 1215 // checkExprOrType checks that x is an expression or a type 1216 // (and not a raw type such as [...]T). 1217 // 1218 func (p *parser) checkExprOrType(x ast.Expr) ast.Expr { 1219 switch t := unparen(x).(type) { 1220 case *ast.ParenExpr: 1221 panic("unreachable") 1222 case *ast.UnaryExpr: 1223 if t.Op == token.RANGE { 1224 // the range operator is only allowed at the top of a for statement 1225 p.errorExpected(x.Pos(), "expression") 1226 x = &ast.BadExpr{x.Pos(), x.End()} 1227 } 1228 case *ast.ArrayType: 1229 if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis { 1230 p.error(len.Pos(), "expected array length, found '...'") 1231 x = &ast.BadExpr{x.Pos(), x.End()} 1232 } 1233 } 1234 1235 // all other nodes are expressions or types 1236 return x 1237 } 1238 1239 // If lhs is set and the result is an identifier, it is not resolved. 1240 func (p *parser) parsePrimaryExpr(lhs bool) ast.Expr { 1241 if p.trace { 1242 defer un(trace(p, "PrimaryExpr")) 1243 } 1244 1245 x := p.parseOperand(lhs) 1246 L: 1247 for { 1248 switch p.tok { 1249 case token.PERIOD: 1250 p.next() 1251 if lhs { 1252 p.resolve(x) 1253 } 1254 switch p.tok { 1255 case token.IDENT: 1256 x = p.parseSelector(p.checkExpr(x)) 1257 case token.LPAREN: 1258 x = p.parseTypeAssertion(p.checkExpr(x)) 1259 default: 1260 pos := p.pos 1261 p.next() // make progress 1262 p.errorExpected(pos, "selector or type assertion") 1263 x = &ast.BadExpr{pos, p.pos} 1264 } 1265 case token.LBRACK: 1266 if lhs { 1267 p.resolve(x) 1268 } 1269 x = p.parseIndexOrSlice(p.checkExpr(x)) 1270 case token.LPAREN: 1271 if lhs { 1272 p.resolve(x) 1273 } 1274 x = p.parseCallOrConversion(p.checkExprOrType(x)) 1275 case token.LBRACE: 1276 if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) { 1277 if lhs { 1278 p.resolve(x) 1279 } 1280 x = p.parseLiteralValue(x) 1281 } else { 1282 break L 1283 } 1284 default: 1285 break L 1286 } 1287 lhs = false // no need to try to resolve again 1288 } 1289 1290 return x 1291 } 1292 1293 // If lhs is set and the result is an identifier, it is not resolved. 1294 func (p *parser) parseUnaryExpr(lhs bool) ast.Expr { 1295 if p.trace { 1296 defer un(trace(p, "UnaryExpr")) 1297 } 1298 1299 switch p.tok { 1300 case token.ADD, token.SUB, token.NOT, token.XOR, token.AND, token.RANGE: 1301 pos, op := p.pos, p.tok 1302 p.next() 1303 x := p.parseUnaryExpr(false) 1304 return &ast.UnaryExpr{pos, op, p.checkExpr(x)} 1305 1306 case token.ARROW: 1307 // channel type or receive expression 1308 pos := p.pos 1309 p.next() 1310 if p.tok == token.CHAN { 1311 p.next() 1312 value := p.parseType() 1313 return &ast.ChanType{pos, ast.RECV, value} 1314 } 1315 1316 x := p.parseUnaryExpr(false) 1317 return &ast.UnaryExpr{pos, token.ARROW, p.checkExpr(x)} 1318 1319 case token.MUL: 1320 // pointer type or unary "*" expression 1321 pos := p.pos 1322 p.next() 1323 x := p.parseUnaryExpr(false) 1324 return &ast.StarExpr{pos, p.checkExprOrType(x)} 1325 } 1326 1327 return p.parsePrimaryExpr(lhs) 1328 } 1329 1330 // If lhs is set and the result is an identifier, it is not resolved. 1331 func (p *parser) parseBinaryExpr(lhs bool, prec1 int) ast.Expr { 1332 if p.trace { 1333 defer un(trace(p, "BinaryExpr")) 1334 } 1335 1336 x := p.parseUnaryExpr(lhs) 1337 for prec := p.tok.Precedence(); prec >= prec1; prec-- { 1338 for p.tok.Precedence() == prec { 1339 pos, op := p.pos, p.tok 1340 p.next() 1341 if lhs { 1342 p.resolve(x) 1343 lhs = false 1344 } 1345 y := p.parseBinaryExpr(false, prec+1) 1346 x = &ast.BinaryExpr{p.checkExpr(x), pos, op, p.checkExpr(y)} 1347 } 1348 } 1349 1350 return x 1351 } 1352 1353 // If lhs is set and the result is an identifier, it is not resolved. 1354 // TODO(gri): parseExpr may return a type or even a raw type ([..]int) - 1355 // should reject when a type/raw type is obviously not allowed 1356 func (p *parser) parseExpr(lhs bool) ast.Expr { 1357 if p.trace { 1358 defer un(trace(p, "Expression")) 1359 } 1360 1361 return p.parseBinaryExpr(lhs, token.LowestPrec+1) 1362 } 1363 1364 func (p *parser) parseRhs() ast.Expr { 1365 return p.parseExpr(false) 1366 } 1367 1368 // ---------------------------------------------------------------------------- 1369 // Statements 1370 1371 func (p *parser) parseSimpleStmt(labelOk bool) ast.Stmt { 1372 if p.trace { 1373 defer un(trace(p, "SimpleStmt")) 1374 } 1375 1376 x := p.parseLhsList() 1377 1378 switch p.tok { 1379 case 1380 token.DEFINE, token.ASSIGN, token.ADD_ASSIGN, 1381 token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN, 1382 token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN, 1383 token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN: 1384 // assignment statement 1385 pos, tok := p.pos, p.tok 1386 p.next() 1387 y := p.parseRhsList() 1388 return &ast.AssignStmt{x, pos, tok, y} 1389 } 1390 1391 if len(x) > 1 { 1392 p.errorExpected(x[0].Pos(), "1 expression") 1393 // continue with first expression 1394 } 1395 1396 switch p.tok { 1397 case token.COLON: 1398 // labeled statement 1399 colon := p.pos 1400 p.next() 1401 if label, isIdent := x[0].(*ast.Ident); labelOk && isIdent { 1402 // Go spec: The scope of a label is the body of the function 1403 // in which it is declared and excludes the body of any nested 1404 // function. 1405 stmt := &ast.LabeledStmt{label, colon, p.parseStmt()} 1406 p.declare(stmt, p.labelScope, ast.Lbl, label) 1407 return stmt 1408 } 1409 p.error(x[0].Pos(), "illegal label declaration") 1410 return &ast.BadStmt{x[0].Pos(), colon + 1} 1411 1412 case token.ARROW: 1413 // send statement 1414 arrow := p.pos 1415 p.next() // consume "<-" 1416 y := p.parseRhs() 1417 return &ast.SendStmt{x[0], arrow, y} 1418 1419 case token.INC, token.DEC: 1420 // increment or decrement 1421 s := &ast.IncDecStmt{x[0], p.pos, p.tok} 1422 p.next() // consume "++" or "--" 1423 return s 1424 } 1425 1426 // expression 1427 return &ast.ExprStmt{x[0]} 1428 } 1429 1430 func (p *parser) parseCallExpr() *ast.CallExpr { 1431 x := p.parseRhs() 1432 if call, isCall := x.(*ast.CallExpr); isCall { 1433 return call 1434 } 1435 p.errorExpected(x.Pos(), "function/method call") 1436 return nil 1437 } 1438 1439 func (p *parser) parseGoStmt() ast.Stmt { 1440 if p.trace { 1441 defer un(trace(p, "GoStmt")) 1442 } 1443 1444 pos := p.expect(token.GO) 1445 call := p.parseCallExpr() 1446 p.expectSemi() 1447 if call == nil { 1448 return &ast.BadStmt{pos, pos + 2} // len("go") 1449 } 1450 1451 return &ast.GoStmt{pos, call} 1452 } 1453 1454 func (p *parser) parseDeferStmt() ast.Stmt { 1455 if p.trace { 1456 defer un(trace(p, "DeferStmt")) 1457 } 1458 1459 pos := p.expect(token.DEFER) 1460 call := p.parseCallExpr() 1461 p.expectSemi() 1462 if call == nil { 1463 return &ast.BadStmt{pos, pos + 5} // len("defer") 1464 } 1465 1466 return &ast.DeferStmt{pos, call} 1467 } 1468 1469 func (p *parser) parseReturnStmt() *ast.ReturnStmt { 1470 if p.trace { 1471 defer un(trace(p, "ReturnStmt")) 1472 } 1473 1474 pos := p.pos 1475 p.expect(token.RETURN) 1476 var x []ast.Expr 1477 if p.tok != token.SEMICOLON && p.tok != token.RBRACE { 1478 x = p.parseRhsList() 1479 } 1480 p.expectSemi() 1481 1482 return &ast.ReturnStmt{pos, x} 1483 } 1484 1485 func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt { 1486 if p.trace { 1487 defer un(trace(p, "BranchStmt")) 1488 } 1489 1490 pos := p.expect(tok) 1491 var label *ast.Ident 1492 if tok != token.FALLTHROUGH && p.tok == token.IDENT { 1493 label = p.parseIdent() 1494 // add to list of unresolved targets 1495 n := len(p.targetStack) - 1 1496 p.targetStack[n] = append(p.targetStack[n], label) 1497 } 1498 p.expectSemi() 1499 1500 return &ast.BranchStmt{pos, tok, label} 1501 } 1502 1503 func (p *parser) makeExpr(s ast.Stmt) ast.Expr { 1504 if s == nil { 1505 return nil 1506 } 1507 if es, isExpr := s.(*ast.ExprStmt); isExpr { 1508 return p.checkExpr(es.X) 1509 } 1510 p.error(s.Pos(), "expected condition, found simple statement") 1511 return &ast.BadExpr{s.Pos(), s.End()} 1512 } 1513 1514 func (p *parser) parseIfStmt() *ast.IfStmt { 1515 if p.trace { 1516 defer un(trace(p, "IfStmt")) 1517 } 1518 1519 pos := p.expect(token.IF) 1520 p.openScope() 1521 defer p.closeScope() 1522 1523 var s ast.Stmt 1524 var x ast.Expr 1525 { 1526 prevLev := p.exprLev 1527 p.exprLev = -1 1528 if p.tok == token.SEMICOLON { 1529 p.next() 1530 x = p.parseRhs() 1531 } else { 1532 s = p.parseSimpleStmt(false) 1533 if p.tok == token.SEMICOLON { 1534 p.next() 1535 x = p.parseRhs() 1536 } else { 1537 x = p.makeExpr(s) 1538 s = nil 1539 } 1540 } 1541 p.exprLev = prevLev 1542 } 1543 1544 body := p.parseBlockStmt() 1545 var else_ ast.Stmt 1546 if p.tok == token.ELSE { 1547 p.next() 1548 else_ = p.parseStmt() 1549 } else { 1550 p.expectSemi() 1551 } 1552 1553 return &ast.IfStmt{pos, s, x, body, else_} 1554 } 1555 1556 func (p *parser) parseTypeList() (list []ast.Expr) { 1557 if p.trace { 1558 defer un(trace(p, "TypeList")) 1559 } 1560 1561 list = append(list, p.parseType()) 1562 for p.tok == token.COMMA { 1563 p.next() 1564 list = append(list, p.parseType()) 1565 } 1566 1567 return 1568 } 1569 1570 func (p *parser) parseCaseClause(exprSwitch bool) *ast.CaseClause { 1571 if p.trace { 1572 defer un(trace(p, "CaseClause")) 1573 } 1574 1575 pos := p.pos 1576 var list []ast.Expr 1577 if p.tok == token.CASE { 1578 p.next() 1579 if exprSwitch { 1580 list = p.parseRhsList() 1581 } else { 1582 list = p.parseTypeList() 1583 } 1584 } else { 1585 p.expect(token.DEFAULT) 1586 } 1587 1588 colon := p.expect(token.COLON) 1589 p.openScope() 1590 body := p.parseStmtList() 1591 p.closeScope() 1592 1593 return &ast.CaseClause{pos, list, colon, body} 1594 } 1595 1596 func isExprSwitch(s ast.Stmt) bool { 1597 if s == nil { 1598 return true 1599 } 1600 if e, ok := s.(*ast.ExprStmt); ok { 1601 if a, ok := e.X.(*ast.TypeAssertExpr); ok { 1602 return a.Type != nil // regular type assertion 1603 } 1604 return true 1605 } 1606 return false 1607 } 1608 1609 func (p *parser) parseSwitchStmt() ast.Stmt { 1610 if p.trace { 1611 defer un(trace(p, "SwitchStmt")) 1612 } 1613 1614 pos := p.expect(token.SWITCH) 1615 p.openScope() 1616 defer p.closeScope() 1617 1618 var s1, s2 ast.Stmt 1619 if p.tok != token.LBRACE { 1620 prevLev := p.exprLev 1621 p.exprLev = -1 1622 if p.tok != token.SEMICOLON { 1623 s2 = p.parseSimpleStmt(false) 1624 } 1625 if p.tok == token.SEMICOLON { 1626 p.next() 1627 s1 = s2 1628 s2 = nil 1629 if p.tok != token.LBRACE { 1630 s2 = p.parseSimpleStmt(false) 1631 } 1632 } 1633 p.exprLev = prevLev 1634 } 1635 1636 exprSwitch := isExprSwitch(s2) 1637 lbrace := p.expect(token.LBRACE) 1638 var list []ast.Stmt 1639 for p.tok == token.CASE || p.tok == token.DEFAULT { 1640 list = append(list, p.parseCaseClause(exprSwitch)) 1641 } 1642 rbrace := p.expect(token.RBRACE) 1643 p.expectSemi() 1644 body := &ast.BlockStmt{lbrace, list, rbrace} 1645 1646 if exprSwitch { 1647 return &ast.SwitchStmt{pos, s1, p.makeExpr(s2), body} 1648 } 1649 // type switch 1650 // TODO(gri): do all the checks! 1651 return &ast.TypeSwitchStmt{pos, s1, s2, body} 1652 } 1653 1654 func (p *parser) parseCommClause() *ast.CommClause { 1655 if p.trace { 1656 defer un(trace(p, "CommClause")) 1657 } 1658 1659 p.openScope() 1660 pos := p.pos 1661 var comm ast.Stmt 1662 if p.tok == token.CASE { 1663 p.next() 1664 lhs := p.parseLhsList() 1665 if p.tok == token.ARROW { 1666 // SendStmt 1667 if len(lhs) > 1 { 1668 p.errorExpected(lhs[0].Pos(), "1 expression") 1669 // continue with first expression 1670 } 1671 arrow := p.pos 1672 p.next() 1673 rhs := p.parseRhs() 1674 comm = &ast.SendStmt{lhs[0], arrow, rhs} 1675 } else { 1676 // RecvStmt 1677 pos := p.pos 1678 tok := p.tok 1679 var rhs ast.Expr 1680 if tok == token.ASSIGN || tok == token.DEFINE { 1681 // RecvStmt with assignment 1682 if len(lhs) > 2 { 1683 p.errorExpected(lhs[0].Pos(), "1 or 2 expressions") 1684 // continue with first two expressions 1685 lhs = lhs[0:2] 1686 } 1687 p.next() 1688 rhs = p.parseRhs() 1689 } else { 1690 // rhs must be single receive operation 1691 if len(lhs) > 1 { 1692 p.errorExpected(lhs[0].Pos(), "1 expression") 1693 // continue with first expression 1694 } 1695 rhs = lhs[0] 1696 lhs = nil // there is no lhs 1697 } 1698 if x, isUnary := rhs.(*ast.UnaryExpr); !isUnary || x.Op != token.ARROW { 1699 p.errorExpected(rhs.Pos(), "send or receive operation") 1700 rhs = &ast.BadExpr{rhs.Pos(), rhs.End()} 1701 } 1702 if lhs != nil { 1703 comm = &ast.AssignStmt{lhs, pos, tok, []ast.Expr{rhs}} 1704 } else { 1705 comm = &ast.ExprStmt{rhs} 1706 } 1707 } 1708 } else { 1709 p.expect(token.DEFAULT) 1710 } 1711 1712 colon := p.expect(token.COLON) 1713 body := p.parseStmtList() 1714 p.closeScope() 1715 1716 return &ast.CommClause{pos, comm, colon, body} 1717 } 1718 1719 func (p *parser) parseSelectStmt() *ast.SelectStmt { 1720 if p.trace { 1721 defer un(trace(p, "SelectStmt")) 1722 } 1723 1724 pos := p.expect(token.SELECT) 1725 lbrace := p.expect(token.LBRACE) 1726 var list []ast.Stmt 1727 for p.tok == token.CASE || p.tok == token.DEFAULT { 1728 list = append(list, p.parseCommClause()) 1729 } 1730 rbrace := p.expect(token.RBRACE) 1731 p.expectSemi() 1732 body := &ast.BlockStmt{lbrace, list, rbrace} 1733 1734 return &ast.SelectStmt{pos, body} 1735 } 1736 1737 func (p *parser) parseForStmt() ast.Stmt { 1738 if p.trace { 1739 defer un(trace(p, "ForStmt")) 1740 } 1741 1742 pos := p.expect(token.FOR) 1743 p.openScope() 1744 defer p.closeScope() 1745 1746 var s1, s2, s3 ast.Stmt 1747 if p.tok != token.LBRACE { 1748 prevLev := p.exprLev 1749 p.exprLev = -1 1750 if p.tok != token.SEMICOLON { 1751 s2 = p.parseSimpleStmt(false) 1752 } 1753 if p.tok == token.SEMICOLON { 1754 p.next() 1755 s1 = s2 1756 s2 = nil 1757 if p.tok != token.SEMICOLON { 1758 s2 = p.parseSimpleStmt(false) 1759 } 1760 p.expectSemi() 1761 if p.tok != token.LBRACE { 1762 s3 = p.parseSimpleStmt(false) 1763 } 1764 } 1765 p.exprLev = prevLev 1766 } 1767 1768 body := p.parseBlockStmt() 1769 p.expectSemi() 1770 1771 if as, isAssign := s2.(*ast.AssignStmt); isAssign { 1772 // possibly a for statement with a range clause; check assignment operator 1773 if as.Tok != token.ASSIGN && as.Tok != token.DEFINE { 1774 p.errorExpected(as.TokPos, "'=' or ':='") 1775 return &ast.BadStmt{pos, body.End()} 1776 } 1777 // check lhs 1778 var key, value ast.Expr 1779 switch len(as.Lhs) { 1780 case 2: 1781 key, value = as.Lhs[0], as.Lhs[1] 1782 case 1: 1783 key = as.Lhs[0] 1784 default: 1785 p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions") 1786 return &ast.BadStmt{pos, body.End()} 1787 } 1788 // check rhs 1789 if len(as.Rhs) != 1 { 1790 p.errorExpected(as.Rhs[0].Pos(), "1 expression") 1791 return &ast.BadStmt{pos, body.End()} 1792 } 1793 if rhs, isUnary := as.Rhs[0].(*ast.UnaryExpr); isUnary && rhs.Op == token.RANGE { 1794 // rhs is range expression 1795 // (any short variable declaration was handled by parseSimpleStat above) 1796 return &ast.RangeStmt{pos, key, value, as.TokPos, as.Tok, rhs.X, body} 1797 } 1798 p.errorExpected(s2.Pos(), "range clause") 1799 return &ast.BadStmt{pos, body.End()} 1800 } 1801 1802 // regular for statement 1803 return &ast.ForStmt{pos, s1, p.makeExpr(s2), s3, body} 1804 } 1805 1806 func (p *parser) parseStmt() (s ast.Stmt) { 1807 if p.trace { 1808 defer un(trace(p, "Statement")) 1809 } 1810 1811 switch p.tok { 1812 case token.CONST, token.TYPE, token.VAR: 1813 s = &ast.DeclStmt{p.parseDecl()} 1814 case 1815 // tokens that may start a top-level expression 1816 token.IDENT, token.INT, token.FLOAT, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operand 1817 token.LBRACK, token.STRUCT, // composite type 1818 token.MUL, token.AND, token.ARROW, token.ADD, token.SUB, token.XOR: // unary operators 1819 s = p.parseSimpleStmt(true) 1820 // because of the required look-ahead, labeled statements are 1821 // parsed by parseSimpleStmt - don't expect a semicolon after 1822 // them 1823 if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt { 1824 p.expectSemi() 1825 } 1826 case token.GO: 1827 s = p.parseGoStmt() 1828 case token.DEFER: 1829 s = p.parseDeferStmt() 1830 case token.RETURN: 1831 s = p.parseReturnStmt() 1832 case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH: 1833 s = p.parseBranchStmt(p.tok) 1834 case token.LBRACE: 1835 s = p.parseBlockStmt() 1836 p.expectSemi() 1837 case token.IF: 1838 s = p.parseIfStmt() 1839 case token.SWITCH: 1840 s = p.parseSwitchStmt() 1841 case token.SELECT: 1842 s = p.parseSelectStmt() 1843 case token.FOR: 1844 s = p.parseForStmt() 1845 case token.SEMICOLON: 1846 s = &ast.EmptyStmt{p.pos} 1847 p.next() 1848 case token.RBRACE: 1849 // a semicolon may be omitted before a closing "}" 1850 s = &ast.EmptyStmt{p.pos} 1851 default: 1852 // no statement found 1853 pos := p.pos 1854 p.errorExpected(pos, "statement") 1855 p.next() // make progress 1856 s = &ast.BadStmt{pos, p.pos} 1857 } 1858 1859 return 1860 } 1861 1862 // ---------------------------------------------------------------------------- 1863 // Declarations 1864 1865 type parseSpecFunction func(p *parser, doc *ast.CommentGroup, iota int) ast.Spec 1866 1867 func parseImportSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { 1868 if p.trace { 1869 defer un(trace(p, "ImportSpec")) 1870 } 1871 1872 var ident *ast.Ident 1873 switch p.tok { 1874 case token.PERIOD: 1875 ident = &ast.Ident{p.pos, ".", nil} 1876 p.next() 1877 case token.IDENT: 1878 ident = p.parseIdent() 1879 } 1880 1881 var path *ast.BasicLit 1882 if p.tok == token.STRING { 1883 path = &ast.BasicLit{p.pos, p.tok, p.lit} 1884 p.next() 1885 } else { 1886 p.expect(token.STRING) // use expect() error handling 1887 } 1888 p.expectSemi() // call before accessing p.linecomment 1889 1890 // collect imports 1891 spec := &ast.ImportSpec{doc, ident, path, p.lineComment} 1892 p.imports = append(p.imports, spec) 1893 1894 return spec 1895 } 1896 1897 func parseConstSpec(p *parser, doc *ast.CommentGroup, iota int) ast.Spec { 1898 if p.trace { 1899 defer un(trace(p, "ConstSpec")) 1900 } 1901 1902 idents := p.parseIdentList() 1903 typ := p.tryType() 1904 var values []ast.Expr 1905 if typ != nil || p.tok == token.ASSIGN || iota == 0 { 1906 p.expect(token.ASSIGN) 1907 values = p.parseRhsList() 1908 } 1909 p.expectSemi() // call before accessing p.linecomment 1910 1911 // Go spec: The scope of a constant or variable identifier declared inside 1912 // a function begins at the end of the ConstSpec or VarSpec and ends at 1913 // the end of the innermost containing block. 1914 // (Global identifiers are resolved in a separate phase after parsing.) 1915 spec := &ast.ValueSpec{doc, idents, typ, values, p.lineComment} 1916 p.declare(spec, p.topScope, ast.Con, idents...) 1917 1918 return spec 1919 } 1920 1921 func parseTypeSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { 1922 if p.trace { 1923 defer un(trace(p, "TypeSpec")) 1924 } 1925 1926 ident := p.parseIdent() 1927 1928 // Go spec: The scope of a type identifier declared inside a function begins 1929 // at the identifier in the TypeSpec and ends at the end of the innermost 1930 // containing block. 1931 // (Global identifiers are resolved in a separate phase after parsing.) 1932 spec := &ast.TypeSpec{doc, ident, nil, nil} 1933 p.declare(spec, p.topScope, ast.Typ, ident) 1934 1935 spec.Type = p.parseType() 1936 p.expectSemi() // call before accessing p.linecomment 1937 spec.Comment = p.lineComment 1938 1939 return spec 1940 } 1941 1942 func parseVarSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec { 1943 if p.trace { 1944 defer un(trace(p, "VarSpec")) 1945 } 1946 1947 idents := p.parseIdentList() 1948 typ := p.tryType() 1949 var values []ast.Expr 1950 if typ == nil || p.tok == token.ASSIGN { 1951 p.expect(token.ASSIGN) 1952 values = p.parseRhsList() 1953 } 1954 p.expectSemi() // call before accessing p.linecomment 1955 1956 // Go spec: The scope of a constant or variable identifier declared inside 1957 // a function begins at the end of the ConstSpec or VarSpec and ends at 1958 // the end of the innermost containing block. 1959 // (Global identifiers are resolved in a separate phase after parsing.) 1960 spec := &ast.ValueSpec{doc, idents, typ, values, p.lineComment} 1961 p.declare(spec, p.topScope, ast.Var, idents...) 1962 1963 return spec 1964 } 1965 1966 func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl { 1967 if p.trace { 1968 defer un(trace(p, "GenDecl("+keyword.String()+")")) 1969 } 1970 1971 doc := p.leadComment 1972 pos := p.expect(keyword) 1973 var lparen, rparen token.Pos 1974 var list []ast.Spec 1975 if p.tok == token.LPAREN { 1976 lparen = p.pos 1977 p.next() 1978 for iota := 0; p.tok != token.RPAREN && p.tok != token.EOF; iota++ { 1979 list = append(list, f(p, p.leadComment, iota)) 1980 } 1981 rparen = p.expect(token.RPAREN) 1982 p.expectSemi() 1983 } else { 1984 list = append(list, f(p, nil, 0)) 1985 } 1986 1987 return &ast.GenDecl{doc, pos, keyword, lparen, list, rparen} 1988 } 1989 1990 func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList { 1991 if p.trace { 1992 defer un(trace(p, "Receiver")) 1993 } 1994 1995 pos := p.pos 1996 par := p.parseParameters(scope, false) 1997 1998 // must have exactly one receiver 1999 if par.NumFields() != 1 { 2000 p.errorExpected(pos, "exactly one receiver") 2001 // TODO determine a better range for BadExpr below 2002 par.List = []*ast.Field{{Type: &ast.BadExpr{pos, pos}}} 2003 return par 2004 } 2005 2006 // recv type must be of the form ["*"] identifier 2007 recv := par.List[0] 2008 base := deref(recv.Type) 2009 if _, isIdent := base.(*ast.Ident); !isIdent { 2010 p.errorExpected(base.Pos(), "(unqualified) identifier") 2011 par.List = []*ast.Field{{Type: &ast.BadExpr{recv.Pos(), recv.End()}}} 2012 } 2013 2014 return par 2015 } 2016 2017 func (p *parser) parseFuncDecl() *ast.FuncDecl { 2018 if p.trace { 2019 defer un(trace(p, "FunctionDecl")) 2020 } 2021 2022 doc := p.leadComment 2023 pos := p.expect(token.FUNC) 2024 scope := ast.NewScope(p.topScope) // function scope 2025 2026 var recv *ast.FieldList 2027 if p.tok == token.LPAREN { 2028 recv = p.parseReceiver(scope) 2029 } 2030 2031 ident := p.parseIdent() 2032 2033 params, results := p.parseSignature(scope) 2034 2035 var body *ast.BlockStmt 2036 if p.tok == token.LBRACE { 2037 body = p.parseBody(scope) 2038 } 2039 p.expectSemi() 2040 2041 decl := &ast.FuncDecl{doc, recv, ident, &ast.FuncType{pos, params, results}, body} 2042 if recv == nil { 2043 // Go spec: The scope of an identifier denoting a constant, type, 2044 // variable, or function (but not method) declared at top level 2045 // (outside any function) is the package block. 2046 // 2047 // init() functions cannot be referred to and there may 2048 // be more than one - don't put them in the pkgScope 2049 if ident.Name != "init" { 2050 p.declare(decl, p.pkgScope, ast.Fun, ident) 2051 } 2052 } 2053 2054 return decl 2055 } 2056 2057 func (p *parser) parseDecl() ast.Decl { 2058 if p.trace { 2059 defer un(trace(p, "Declaration")) 2060 } 2061 2062 var f parseSpecFunction 2063 switch p.tok { 2064 case token.CONST: 2065 f = parseConstSpec 2066 2067 case token.TYPE: 2068 f = parseTypeSpec 2069 2070 case token.VAR: 2071 f = parseVarSpec 2072 2073 case token.FUNC: 2074 return p.parseFuncDecl() 2075 2076 default: 2077 pos := p.pos 2078 p.errorExpected(pos, "declaration") 2079 p.next() // make progress 2080 decl := &ast.BadDecl{pos, p.pos} 2081 return decl 2082 } 2083 2084 return p.parseGenDecl(p.tok, f) 2085 } 2086 2087 func (p *parser) parseDeclList() (list []ast.Decl) { 2088 if p.trace { 2089 defer un(trace(p, "DeclList")) 2090 } 2091 2092 for p.tok != token.EOF { 2093 list = append(list, p.parseDecl()) 2094 } 2095 2096 return 2097 } 2098 2099 // ---------------------------------------------------------------------------- 2100 // Source files 2101 2102 func (p *parser) parseFile() *ast.File { 2103 if p.trace { 2104 defer un(trace(p, "File")) 2105 } 2106 2107 // package clause 2108 doc := p.leadComment 2109 pos := p.expect(token.PACKAGE) 2110 // Go spec: The package clause is not a declaration; 2111 // the package name does not appear in any scope. 2112 ident := p.parseIdent() 2113 if ident.Name == "_" { 2114 p.error(p.pos, "invalid package name _") 2115 } 2116 p.expectSemi() 2117 2118 var decls []ast.Decl 2119 2120 // Don't bother parsing the rest if we had errors already. 2121 // Likely not a Go source file at all. 2122 2123 if p.ErrorCount() == 0 && p.mode&PackageClauseOnly == 0 { 2124 // import decls 2125 for p.tok == token.IMPORT { 2126 decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec)) 2127 } 2128 2129 if p.mode&ImportsOnly == 0 { 2130 // rest of package body 2131 for p.tok != token.EOF { 2132 decls = append(decls, p.parseDecl()) 2133 } 2134 } 2135 } 2136 2137 assert(p.topScope == p.pkgScope, "imbalanced scopes") 2138 2139 // resolve global identifiers within the same file 2140 i := 0 2141 for _, ident := range p.unresolved { 2142 // i <= index for current ident 2143 assert(ident.Obj == unresolved, "object already resolved") 2144 ident.Obj = p.pkgScope.Lookup(ident.Name) // also removes unresolved sentinel 2145 if ident.Obj == nil { 2146 p.unresolved[i] = ident 2147 i++ 2148 } 2149 } 2150 2151 // TODO(gri): store p.imports in AST 2152 return &ast.File{doc, pos, ident, decls, p.pkgScope, p.imports, p.unresolved[0:i], p.comments} 2153 }