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 5package syntax 6 7import ( 8 "fmt" 9 "go/build/constraint" 10 "io" 11 "strconv" 12 "strings" 13) 14 15const debug = false 16const trace = false 17 18type parser struct { 19 file *PosBase 20 errh ErrorHandler 21 mode Mode 22 pragh PragmaHandler 23 scanner 24 25 base *PosBase // current position base 26 first error // first error encountered 27 errcnt int // number of errors encountered 28 pragma Pragma // pragmas 29 goVersion string // Go version from //go:build line 30 31 top bool // in top of file (before package clause) 32 fnest int // function nesting level (for error handling) 33 xnest int // expression nesting level (for complit ambiguity resolution) 34 indent []byte // tracing support 35} 36 37func (p *parser) init(file *PosBase, r io.Reader, errh ErrorHandler, pragh PragmaHandler, mode Mode) { 38 p.top = true 39 p.file = file 40 p.errh = errh 41 p.mode = mode 42 p.pragh = pragh 43 p.scanner.init( 44 r, 45 // Error and directive handler for scanner. 46 // Because the (line, col) positions passed to the 47 // handler is always at or after the current reading 48 // position, it is safe to use the most recent position 49 // base to compute the corresponding Pos value. 50 func(line, col uint, msg string) { 51 if msg[0] != '/' { 52 p.errorAt(p.posAt(line, col), msg) 53 return 54 } 55 56 // otherwise it must be a comment containing a line or go: directive. 57 // //line directives must be at the start of the line (column colbase). 58 // /*line*/ directives can be anywhere in the line. 59 text := commentText(msg) 60 if (col == colbase || msg[1] == '*') && strings.HasPrefix(text, "line ") { 61 var pos Pos // position immediately following the comment 62 if msg[1] == '/' { 63 // line comment (newline is part of the comment) 64 pos = MakePos(p.file, line+1, colbase) 65 } else { 66 // regular comment 67 // (if the comment spans multiple lines it's not 68 // a valid line directive and will be discarded 69 // by updateBase) 70 pos = MakePos(p.file, line, col+uint(len(msg))) 71 } 72 p.updateBase(pos, line, col+2+5, text[5:]) // +2 to skip over // or /* 73 return 74 } 75 76 // go: directive (but be conservative and test) 77 if strings.HasPrefix(text, "go:") { 78 if p.top && strings.HasPrefix(msg, "//go:build") { 79 if x, err := constraint.Parse(msg); err == nil { 80 p.goVersion = constraint.GoVersion(x) 81 } 82 } 83 if pragh != nil { 84 p.pragma = pragh(p.posAt(line, col+2), p.scanner.blank, text, p.pragma) // +2 to skip over // or /* 85 } 86 } 87 }, 88 directives, 89 ) 90 91 p.base = file 92 p.first = nil 93 p.errcnt = 0 94 p.pragma = nil 95 96 p.fnest = 0 97 p.xnest = 0 98 p.indent = nil 99} 100 101// takePragma returns the current parsed pragmas 102// and clears them from the parser state. 103func (p *parser) takePragma() Pragma { 104 prag := p.pragma 105 p.pragma = nil 106 return prag 107} 108 109// clearPragma is called at the end of a statement or 110// other Go form that does NOT accept a pragma. 111// It sends the pragma back to the pragma handler 112// to be reported as unused. 113func (p *parser) clearPragma() { 114 if p.pragma != nil { 115 p.pragh(p.pos(), p.scanner.blank, "", p.pragma) 116 p.pragma = nil 117 } 118} 119 120// updateBase sets the current position base to a new line base at pos. 121// The base's filename, line, and column values are extracted from text 122// which is positioned at (tline, tcol) (only needed for error messages). 123func (p *parser) updateBase(pos Pos, tline, tcol uint, text string) { 124 i, n, ok := trailingDigits(text) 125 if i == 0 { 126 return // ignore (not a line directive) 127 } 128 // i > 0 129 130 if !ok { 131 // text has a suffix :xxx but xxx is not a number 132 p.errorAt(p.posAt(tline, tcol+i), "invalid line number: "+text[i:]) 133 return 134 } 135 136 var line, col uint 137 i2, n2, ok2 := trailingDigits(text[:i-1]) 138 if ok2 { 139 //line filename:line:col 140 i, i2 = i2, i 141 line, col = n2, n 142 if col == 0 || col > PosMax { 143 p.errorAt(p.posAt(tline, tcol+i2), "invalid column number: "+text[i2:]) 144 return 145 } 146 text = text[:i2-1] // lop off ":col" 147 } else { 148 //line filename:line 149 line = n 150 } 151 152 if line == 0 || line > PosMax { 153 p.errorAt(p.posAt(tline, tcol+i), "invalid line number: "+text[i:]) 154 return 155 } 156 157 // If we have a column (//line filename:line:col form), 158 // an empty filename means to use the previous filename. 159 filename := text[:i-1] // lop off ":line" 160 trimmed := false 161 if filename == "" && ok2 { 162 filename = p.base.Filename() 163 trimmed = p.base.Trimmed() 164 } 165 166 p.base = NewLineBase(pos, filename, trimmed, line, col) 167} 168 169func commentText(s string) string { 170 if s[:2] == "/*" { 171 return s[2 : len(s)-2] // lop off /* and */ 172 } 173 174 // line comment (does not include newline) 175 // (on Windows, the line comment may end in \r\n) 176 i := len(s) 177 if s[i-1] == '\r' { 178 i-- 179 } 180 return s[2:i] // lop off //, and \r at end, if any 181} 182 183func trailingDigits(text string) (uint, uint, bool) { 184 i := strings.LastIndexByte(text, ':') // look from right (Windows filenames may contain ':') 185 if i < 0 { 186 return 0, 0, false // no ':' 187 } 188 // i >= 0 189 n, err := strconv.ParseUint(text[i+1:], 10, 0) 190 return uint(i + 1), uint(n), err == nil 191} 192 193func (p *parser) got(tok token) bool { 194 if p.tok == tok { 195 p.next() 196 return true 197 } 198 return false 199} 200 201func (p *parser) want(tok token) { 202 if !p.got(tok) { 203 p.syntaxError("expected " + tokstring(tok)) 204 p.advance() 205 } 206} 207 208// gotAssign is like got(_Assign) but it also accepts ":=" 209// (and reports an error) for better parser error recovery. 210func (p *parser) gotAssign() bool { 211 switch p.tok { 212 case _Define: 213 p.syntaxError("expected =") 214 fallthrough 215 case _Assign: 216 p.next() 217 return true 218 } 219 return false 220} 221 222// ---------------------------------------------------------------------------- 223// Error handling 224 225// posAt returns the Pos value for (line, col) and the current position base. 226func (p *parser) posAt(line, col uint) Pos { 227 return MakePos(p.base, line, col) 228} 229 230// errorAt reports an error at the given position. 231func (p *parser) errorAt(pos Pos, msg string) { 232 err := Error{pos, msg} 233 if p.first == nil { 234 p.first = err 235 } 236 p.errcnt++ 237 if p.errh == nil { 238 panic(p.first) 239 } 240 p.errh(err) 241} 242 243// syntaxErrorAt reports a syntax error at the given position. 244func (p *parser) syntaxErrorAt(pos Pos, msg string) { 245 if trace { 246 p.print("syntax error: " + msg) 247 } 248 249 if p.tok == _EOF && p.first != nil { 250 return // avoid meaningless follow-up errors 251 } 252 253 // add punctuation etc. as needed to msg 254 switch { 255 case msg == "": 256 // nothing to do 257 case strings.HasPrefix(msg, "in "), strings.HasPrefix(msg, "at "), strings.HasPrefix(msg, "after "): 258 msg = " " + msg 259 case strings.HasPrefix(msg, "expected "): 260 msg = ", " + msg 261 default: 262 // plain error - we don't care about current token 263 p.errorAt(pos, "syntax error: "+msg) 264 return 265 } 266 267 // determine token string 268 var tok string 269 switch p.tok { 270 case _Name: 271 tok = "name " + p.lit 272 case _Semi: 273 tok = p.lit 274 case _Literal: 275 tok = "literal " + p.lit 276 case _Operator: 277 tok = p.op.String() 278 case _AssignOp: 279 tok = p.op.String() + "=" 280 case _IncOp: 281 tok = p.op.String() 282 tok += tok 283 default: 284 tok = tokstring(p.tok) 285 } 286 287 // TODO(gri) This may print "unexpected X, expected Y". 288 // Consider "got X, expected Y" in this case. 289 p.errorAt(pos, "syntax error: unexpected "+tok+msg) 290} 291 292// tokstring returns the English word for selected punctuation tokens 293// for more readable error messages. Use tokstring (not tok.String()) 294// for user-facing (error) messages; use tok.String() for debugging 295// output. 296func tokstring(tok token) string { 297 switch tok { 298 case _Comma: 299 return "comma" 300 case _Semi: 301 return "semicolon or newline" 302 } 303 return tok.String() 304} 305 306// Convenience methods using the current token position. 307func (p *parser) pos() Pos { return p.posAt(p.line, p.col) } 308func (p *parser) error(msg string) { p.errorAt(p.pos(), msg) } 309func (p *parser) syntaxError(msg string) { p.syntaxErrorAt(p.pos(), msg) } 310 311// The stopset contains keywords that start a statement. 312// They are good synchronization points in case of syntax 313// errors and (usually) shouldn't be skipped over. 314const stopset uint64 = 1<<_Break | 315 1<<_Const | 316 1<<_Continue | 317 1<<_Defer | 318 1<<_Fallthrough | 319 1<<_For | 320 1<<_Go | 321 1<<_Goto | 322 1<<_If | 323 1<<_Return | 324 1<<_Select | 325 1<<_Switch | 326 1<<_Type | 327 1<<_Var 328 329// advance consumes tokens until it finds a token of the stopset or followlist. 330// The stopset is only considered if we are inside a function (p.fnest > 0). 331// The followlist is the list of valid tokens that can follow a production; 332// if it is empty, exactly one (non-EOF) token is consumed to ensure progress. 333func (p *parser) advance(followlist ...token) { 334 if trace { 335 p.print(fmt.Sprintf("advance %s", followlist)) 336 } 337 338 // compute follow set 339 // (not speed critical, advance is only called in error situations) 340 var followset uint64 = 1 << _EOF // don't skip over EOF 341 if len(followlist) > 0 { 342 if p.fnest > 0 { 343 followset |= stopset 344 } 345 for _, tok := range followlist { 346 followset |= 1 << tok 347 } 348 } 349 350 for !contains(followset, p.tok) { 351 if trace { 352 p.print("skip " + p.tok.String()) 353 } 354 p.next() 355 if len(followlist) == 0 { 356 break 357 } 358 } 359 360 if trace { 361 p.print("next " + p.tok.String()) 362 } 363} 364 365// usage: defer p.trace(msg)() 366func (p *parser) trace(msg string) func() { 367 p.print(msg + " (") 368 const tab = ". " 369 p.indent = append(p.indent, tab...) 370 return func() { 371 p.indent = p.indent[:len(p.indent)-len(tab)] 372 if x := recover(); x != nil { 373 panic(x) // skip print_trace 374 } 375 p.print(")") 376 } 377} 378 379func (p *parser) print(msg string) { 380 fmt.Printf("%5d: %s%s\n", p.line, p.indent, msg) 381} 382 383// ---------------------------------------------------------------------------- 384// Package files 385// 386// Parse methods are annotated with matching Go productions as appropriate. 387// The annotations are intended as guidelines only since a single Go grammar 388// rule may be covered by multiple parse methods and vice versa. 389// 390// Excluding methods returning slices, parse methods named xOrNil may return 391// nil; all others are expected to return a valid non-nil node. 392 393// SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } . 394func (p *parser) fileOrNil() *File { 395 if trace { 396 defer p.trace("file")() 397 } 398 399 f := new(File) 400 f.pos = p.pos() 401 402 // PackageClause 403 f.GoVersion = p.goVersion 404 p.top = false 405 if !p.got(_Package) { 406 p.syntaxError("package statement must be first") 407 return nil 408 } 409 f.Pragma = p.takePragma() 410 f.PkgName = p.name() 411 p.want(_Semi) 412 413 // don't bother continuing if package clause has errors 414 if p.first != nil { 415 return nil 416 } 417 418 // Accept import declarations anywhere for error tolerance, but complain. 419 // { ( ImportDecl | TopLevelDecl ) ";" } 420 prev := _Import 421 for p.tok != _EOF { 422 if p.tok == _Import && prev != _Import { 423 p.syntaxError("imports must appear before other declarations") 424 } 425 prev = p.tok 426 427 switch p.tok { 428 case _Import: 429 p.next() 430 f.DeclList = p.appendGroup(f.DeclList, p.importDecl) 431 432 case _Const: 433 p.next() 434 f.DeclList = p.appendGroup(f.DeclList, p.constDecl) 435 436 case _Type: 437 p.next() 438 f.DeclList = p.appendGroup(f.DeclList, p.typeDecl) 439 440 case _Var: 441 p.next() 442 f.DeclList = p.appendGroup(f.DeclList, p.varDecl) 443 444 case _Func: 445 p.next() 446 if d := p.funcDeclOrNil(); d != nil { 447 f.DeclList = append(f.DeclList, d) 448 } 449 450 default: 451 if p.tok == _Lbrace && len(f.DeclList) > 0 && isEmptyFuncDecl(f.DeclList[len(f.DeclList)-1]) { 452 // opening { of function declaration on next line 453 p.syntaxError("unexpected semicolon or newline before {") 454 } else { 455 p.syntaxError("non-declaration statement outside function body") 456 } 457 p.advance(_Import, _Const, _Type, _Var, _Func) 458 continue 459 } 460 461 // Reset p.pragma BEFORE advancing to the next token (consuming ';') 462 // since comments before may set pragmas for the next function decl. 463 p.clearPragma() 464 465 if p.tok != _EOF && !p.got(_Semi) { 466 p.syntaxError("after top level declaration") 467 p.advance(_Import, _Const, _Type, _Var, _Func) 468 } 469 } 470 // p.tok == _EOF 471 472 p.clearPragma() 473 f.EOF = p.pos() 474 475 return f 476} 477 478func isEmptyFuncDecl(dcl Decl) bool { 479 f, ok := dcl.(*FuncDecl) 480 return ok && f.Body == nil 481} 482 483// ---------------------------------------------------------------------------- 484// Declarations 485 486// list parses a possibly empty, sep-separated list of elements, optionally 487// followed by sep, and closed by close (or EOF). sep must be one of _Comma 488// or _Semi, and close must be one of _Rparen, _Rbrace, or _Rbrack. 489// 490// For each list element, f is called. Specifically, unless we're at close 491// (or EOF), f is called at least once. After f returns true, no more list 492// elements are accepted. list returns the position of the closing token. 493// 494// list = [ f { sep f } [sep] ] close . 495func (p *parser) list(context string, sep, close token, f func() bool) Pos { 496 if debug && (sep != _Comma && sep != _Semi || close != _Rparen && close != _Rbrace && close != _Rbrack) { 497 panic("invalid sep or close argument for list") 498 } 499 500 done := false 501 for p.tok != _EOF && p.tok != close && !done { 502 done = f() 503 // sep is optional before close 504 if !p.got(sep) && p.tok != close { 505 p.syntaxError(fmt.Sprintf("in %s; possibly missing %s or %s", context, tokstring(sep), tokstring(close))) 506 p.advance(_Rparen, _Rbrack, _Rbrace) 507 if p.tok != close { 508 // position could be better but we had an error so we don't care 509 return p.pos() 510 } 511 } 512 } 513 514 pos := p.pos() 515 p.want(close) 516 return pos 517} 518 519// appendGroup(f) = f | "(" { f ";" } ")" . // ";" is optional before ")" 520func (p *parser) appendGroup(list []Decl, f func(*Group) Decl) []Decl { 521 if p.tok == _Lparen { 522 g := new(Group) 523 p.clearPragma() 524 p.next() // must consume "(" after calling clearPragma! 525 p.list("grouped declaration", _Semi, _Rparen, func() bool { 526 if x := f(g); x != nil { 527 list = append(list, x) 528 } 529 return false 530 }) 531 } else { 532 if x := f(nil); x != nil { 533 list = append(list, x) 534 } 535 } 536 return list 537} 538 539// ImportSpec = [ "." | PackageName ] ImportPath . 540// ImportPath = string_lit . 541func (p *parser) importDecl(group *Group) Decl { 542 if trace { 543 defer p.trace("importDecl")() 544 } 545 546 d := new(ImportDecl) 547 d.pos = p.pos() 548 d.Group = group 549 d.Pragma = p.takePragma() 550 551 switch p.tok { 552 case _Name: 553 d.LocalPkgName = p.name() 554 case _Dot: 555 d.LocalPkgName = NewName(p.pos(), ".") 556 p.next() 557 } 558 d.Path = p.oliteral() 559 if d.Path == nil { 560 p.syntaxError("missing import path") 561 p.advance(_Semi, _Rparen) 562 return d 563 } 564 if !d.Path.Bad && d.Path.Kind != StringLit { 565 p.syntaxErrorAt(d.Path.Pos(), "import path must be a string") 566 d.Path.Bad = true 567 } 568 // d.Path.Bad || d.Path.Kind == StringLit 569 570 return d 571} 572 573// ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] . 574func (p *parser) constDecl(group *Group) Decl { 575 if trace { 576 defer p.trace("constDecl")() 577 } 578 579 d := new(ConstDecl) 580 d.pos = p.pos() 581 d.Group = group 582 d.Pragma = p.takePragma() 583 584 d.NameList = p.nameList(p.name()) 585 if p.tok != _EOF && p.tok != _Semi && p.tok != _Rparen { 586 d.Type = p.typeOrNil() 587 if p.gotAssign() { 588 d.Values = p.exprList() 589 } 590 } 591 592 return d 593} 594 595// TypeSpec = identifier [ TypeParams ] [ "=" ] Type . 596func (p *parser) typeDecl(group *Group) Decl { 597 if trace { 598 defer p.trace("typeDecl")() 599 } 600 601 d := new(TypeDecl) 602 d.pos = p.pos() 603 d.Group = group 604 d.Pragma = p.takePragma() 605 606 d.Name = p.name() 607 if p.tok == _Lbrack { 608 // d.Name "[" ... 609 // array/slice type or type parameter list 610 pos := p.pos() 611 p.next() 612 switch p.tok { 613 case _Name: 614 // We may have an array type or a type parameter list. 615 // In either case we expect an expression x (which may 616 // just be a name, or a more complex expression) which 617 // we can analyze further. 618 // 619 // A type parameter list may have a type bound starting 620 // with a "[" as in: P []E. In that case, simply parsing 621 // an expression would lead to an error: P[] is invalid. 622 // But since index or slice expressions are never constant 623 // and thus invalid array length expressions, if the name 624 // is followed by "[" it must be the start of an array or 625 // slice constraint. Only if we don't see a "[" do we 626 // need to parse a full expression. Notably, name <- x 627 // is not a concern because name <- x is a statement and 628 // not an expression. 629 var x Expr = p.name() 630 if p.tok != _Lbrack { 631 // To parse the expression starting with name, expand 632 // the call sequence we would get by passing in name 633 // to parser.expr, and pass in name to parser.pexpr. 634 p.xnest++ 635 x = p.binaryExpr(p.pexpr(x, false), 0) 636 p.xnest-- 637 } 638 // Analyze expression x. If we can split x into a type parameter 639 // name, possibly followed by a type parameter type, we consider 640 // this the start of a type parameter list, with some caveats: 641 // a single name followed by "]" tilts the decision towards an 642 // array declaration; a type parameter type that could also be 643 // an ordinary expression but which is followed by a comma tilts 644 // the decision towards a type parameter list. 645 if pname, ptype := extractName(x, p.tok == _Comma); pname != nil && (ptype != nil || p.tok != _Rbrack) { 646 // d.Name "[" pname ... 647 // d.Name "[" pname ptype ... 648 // d.Name "[" pname ptype "," ... 649 d.TParamList = p.paramList(pname, ptype, _Rbrack, true) // ptype may be nil 650 d.Alias = p.gotAssign() 651 d.Type = p.typeOrNil() 652 } else { 653 // d.Name "[" pname "]" ... 654 // d.Name "[" x ... 655 d.Type = p.arrayType(pos, x) 656 } 657 case _Rbrack: 658 // d.Name "[" "]" ... 659 p.next() 660 d.Type = p.sliceType(pos) 661 default: 662 // d.Name "[" ... 663 d.Type = p.arrayType(pos, nil) 664 } 665 } else { 666 d.Alias = p.gotAssign() 667 d.Type = p.typeOrNil() 668 } 669 670 if d.Type == nil { 671 d.Type = p.badExpr() 672 p.syntaxError("in type declaration") 673 p.advance(_Semi, _Rparen) 674 } 675 676 return d 677} 678 679// extractName splits the expression x into (name, expr) if syntactically 680// x can be written as name expr. The split only happens if expr is a type 681// element (per the isTypeElem predicate) or if force is set. 682// If x is just a name, the result is (name, nil). If the split succeeds, 683// the result is (name, expr). Otherwise the result is (nil, x). 684// Examples: 685// 686// x force name expr 687// ------------------------------------ 688// P*[]int T/F P *[]int 689// P*E T P *E 690// P*E F nil P*E 691// P([]int) T/F P []int 692// P(E) T P E 693// P(E) F nil P(E) 694// P*E|F|~G T/F P *E|F|~G 695// P*E|F|G T P *E|F|G 696// P*E|F|G F nil P*E|F|G 697func extractName(x Expr, force bool) (*Name, Expr) { 698 switch x := x.(type) { 699 case *Name: 700 return x, nil 701 case *Operation: 702 if x.Y == nil { 703 break // unary expr 704 } 705 switch x.Op { 706 case Mul: 707 if name, _ := x.X.(*Name); name != nil && (force || isTypeElem(x.Y)) { 708 // x = name *x.Y 709 op := *x 710 op.X, op.Y = op.Y, nil // change op into unary *op.Y 711 return name, &op 712 } 713 case Or: 714 if name, lhs := extractName(x.X, force || isTypeElem(x.Y)); name != nil && lhs != nil { 715 // x = name lhs|x.Y 716 op := *x 717 op.X = lhs 718 return name, &op 719 } 720 } 721 case *CallExpr: 722 if name, _ := x.Fun.(*Name); name != nil { 723 if len(x.ArgList) == 1 && !x.HasDots && (force || isTypeElem(x.ArgList[0])) { 724 // x = name "(" x.ArgList[0] ")" 725 return name, x.ArgList[0] 726 } 727 } 728 } 729 return nil, x 730} 731 732// isTypeElem reports whether x is a (possibly parenthesized) type element expression. 733// The result is false if x could be a type element OR an ordinary (value) expression. 734func isTypeElem(x Expr) bool { 735 switch x := x.(type) { 736 case *ArrayType, *StructType, *FuncType, *InterfaceType, *SliceType, *MapType, *ChanType: 737 return true 738 case *Operation: 739 return isTypeElem(x.X) || (x.Y != nil && isTypeElem(x.Y)) || x.Op == Tilde 740 case *ParenExpr: 741 return isTypeElem(x.X) 742 } 743 return false 744} 745 746// VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) . 747func (p *parser) varDecl(group *Group) Decl { 748 if trace { 749 defer p.trace("varDecl")() 750 } 751 752 d := new(VarDecl) 753 d.pos = p.pos() 754 d.Group = group 755 d.Pragma = p.takePragma() 756 757 d.NameList = p.nameList(p.name()) 758 if p.gotAssign() { 759 d.Values = p.exprList() 760 } else { 761 d.Type = p.type_() 762 if p.gotAssign() { 763 d.Values = p.exprList() 764 } 765 } 766 767 return d 768} 769 770// FunctionDecl = "func" FunctionName [ TypeParams ] ( Function | Signature ) . 771// FunctionName = identifier . 772// Function = Signature FunctionBody . 773// MethodDecl = "func" Receiver MethodName ( Function | Signature ) . 774// Receiver = Parameters . 775func (p *parser) funcDeclOrNil() *FuncDecl { 776 if trace { 777 defer p.trace("funcDecl")() 778 } 779 780 f := new(FuncDecl) 781 f.pos = p.pos() 782 f.Pragma = p.takePragma() 783 784 var context string 785 if p.got(_Lparen) { 786 context = "method" 787 rcvr := p.paramList(nil, nil, _Rparen, false) 788 switch len(rcvr) { 789 case 0: 790 p.error("method has no receiver") 791 default: 792 p.error("method has multiple receivers") 793 fallthrough 794 case 1: 795 f.Recv = rcvr[0] 796 } 797 } 798 799 if p.tok == _Name { 800 f.Name = p.name() 801 f.TParamList, f.Type = p.funcType(context) 802 } else { 803 f.Name = NewName(p.pos(), "_") 804 f.Type = new(FuncType) 805 f.Type.pos = p.pos() 806 msg := "expected name or (" 807 if context != "" { 808 msg = "expected name" 809 } 810 p.syntaxError(msg) 811 p.advance(_Lbrace, _Semi) 812 } 813 814 if p.tok == _Lbrace { 815 f.Body = p.funcBody() 816 } 817 818 return f 819} 820 821func (p *parser) funcBody() *BlockStmt { 822 p.fnest++ 823 errcnt := p.errcnt 824 body := p.blockStmt("") 825 p.fnest-- 826 827 // Don't check branches if there were syntax errors in the function 828 // as it may lead to spurious errors (e.g., see test/switch2.go) or 829 // possibly crashes due to incomplete syntax trees. 830 if p.mode&CheckBranches != 0 && errcnt == p.errcnt { 831 checkBranches(body, p.errh) 832 } 833 834 return body 835} 836 837// ---------------------------------------------------------------------------- 838// Expressions 839 840func (p *parser) expr() Expr { 841 if trace { 842 defer p.trace("expr")() 843 } 844 845 return p.binaryExpr(nil, 0) 846} 847 848// Expression = UnaryExpr | Expression binary_op Expression . 849func (p *parser) binaryExpr(x Expr, prec int) Expr { 850 // don't trace binaryExpr - only leads to overly nested trace output 851 852 if x == nil { 853 x = p.unaryExpr() 854 } 855 for (p.tok == _Operator || p.tok == _Star) && p.prec > prec { 856 t := new(Operation) 857 t.pos = p.pos() 858 t.Op = p.op 859 tprec := p.prec 860 p.next() 861 t.X = x 862 t.Y = p.binaryExpr(nil, tprec) 863 x = t 864 } 865 return x 866} 867 868// UnaryExpr = PrimaryExpr | unary_op UnaryExpr . 869func (p *parser) unaryExpr() Expr { 870 if trace { 871 defer p.trace("unaryExpr")() 872 } 873 874 switch p.tok { 875 case _Operator, _Star: 876 switch p.op { 877 case Mul, Add, Sub, Not, Xor, Tilde: 878 x := new(Operation) 879 x.pos = p.pos() 880 x.Op = p.op 881 p.next() 882 x.X = p.unaryExpr() 883 return x 884 885 case And: 886 x := new(Operation) 887 x.pos = p.pos() 888 x.Op = And 889 p.next() 890 // unaryExpr may have returned a parenthesized composite literal 891 // (see comment in operand) - remove parentheses if any 892 x.X = Unparen(p.unaryExpr()) 893 return x 894 } 895 896 case _Arrow: 897 // receive op (<-x) or receive-only channel (<-chan E) 898 pos := p.pos() 899 p.next() 900 901 // If the next token is _Chan we still don't know if it is 902 // a channel (<-chan int) or a receive op (<-chan int(ch)). 903 // We only know once we have found the end of the unaryExpr. 904 905 x := p.unaryExpr() 906 907 // There are two cases: 908 // 909 // <-chan... => <-x is a channel type 910 // <-x => <-x is a receive operation 911 // 912 // In the first case, <- must be re-associated with 913 // the channel type parsed already: 914 // 915 // <-(chan E) => (<-chan E) 916 // <-(chan<-E) => (<-chan (<-E)) 917 918 if _, ok := x.(*ChanType); ok { 919 // x is a channel type => re-associate <- 920 dir := SendOnly 921 t := x 922 for dir == SendOnly { 923 c, ok := t.(*ChanType) 924 if !ok { 925 break 926 } 927 dir = c.Dir 928 if dir == RecvOnly { 929 // t is type <-chan E but <-<-chan E is not permitted 930 // (report same error as for "type _ <-<-chan E") 931 p.syntaxError("unexpected <-, expected chan") 932 // already progressed, no need to advance 933 } 934 c.Dir = RecvOnly 935 t = c.Elem 936 } 937 if dir == SendOnly { 938 // channel dir is <- but channel element E is not a channel 939 // (report same error as for "type _ <-chan<-E") 940 p.syntaxError(fmt.Sprintf("unexpected %s, expected chan", String(t))) 941 // already progressed, no need to advance 942 } 943 return x 944 } 945 946 // x is not a channel type => we have a receive op 947 o := new(Operation) 948 o.pos = pos 949 o.Op = Recv 950 o.X = x 951 return o 952 } 953 954 // TODO(mdempsky): We need parens here so we can report an 955 // error for "(x) := true". It should be possible to detect 956 // and reject that more efficiently though. 957 return p.pexpr(nil, true) 958} 959 960// callStmt parses call-like statements that can be preceded by 'defer' and 'go'. 961func (p *parser) callStmt() *CallStmt { 962 if trace { 963 defer p.trace("callStmt")() 964 } 965 966 s := new(CallStmt) 967 s.pos = p.pos() 968 s.Tok = p.tok // _Defer or _Go 969 p.next() 970 971 x := p.pexpr(nil, p.tok == _Lparen) // keep_parens so we can report error below 972 if t := Unparen(x); t != x { 973 p.errorAt(x.Pos(), fmt.Sprintf("expression in %s must not be parenthesized", s.Tok)) 974 // already progressed, no need to advance 975 x = t 976 } 977 978 s.Call = x 979 return s 980} 981 982// Operand = Literal | OperandName | MethodExpr | "(" Expression ")" . 983// Literal = BasicLit | CompositeLit | FunctionLit . 984// BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit . 985// OperandName = identifier | QualifiedIdent. 986func (p *parser) operand(keep_parens bool) Expr { 987 if trace { 988 defer p.trace("operand " + p.tok.String())() 989 } 990 991 switch p.tok { 992 case _Name: 993 return p.name() 994 995 case _Literal: 996 return p.oliteral() 997 998 case _Lparen: 999 pos := p.pos() 1000 p.next() 1001 p.xnest++ 1002 x := p.expr() 1003 p.xnest-- 1004 p.want(_Rparen) 1005 1006 // Optimization: Record presence of ()'s only where needed 1007 // for error reporting. Don't bother in other cases; it is 1008 // just a waste of memory and time. 1009 // 1010 // Parentheses are not permitted around T in a composite 1011 // literal T{}. If the next token is a {, assume x is a 1012 // composite literal type T (it may not be, { could be 1013 // the opening brace of a block, but we don't know yet). 1014 if p.tok == _Lbrace { 1015 keep_parens = true 1016 } 1017 1018 // Parentheses are also not permitted around the expression 1019 // in a go/defer statement. In that case, operand is called 1020 // with keep_parens set. 1021 if keep_parens { 1022 px := new(ParenExpr) 1023 px.pos = pos 1024 px.X = x 1025 x = px 1026 } 1027 return x 1028 1029 case _Func: 1030 pos := p.pos() 1031 p.next() 1032 _, ftyp := p.funcType("function type") 1033 if p.tok == _Lbrace { 1034 p.xnest++ 1035 1036 f := new(FuncLit) 1037 f.pos = pos 1038 f.Type = ftyp 1039 f.Body = p.funcBody() 1040 1041 p.xnest-- 1042 return f 1043 } 1044 return ftyp 1045 1046 case _Lbrack, _Chan, _Map, _Struct, _Interface: 1047 return p.type_() // othertype 1048 1049 default: 1050 x := p.badExpr() 1051 p.syntaxError("expected expression") 1052 p.advance(_Rparen, _Rbrack, _Rbrace) 1053 return x 1054 } 1055 1056 // Syntactically, composite literals are operands. Because a complit 1057 // type may be a qualified identifier which is handled by pexpr 1058 // (together with selector expressions), complits are parsed there 1059 // as well (operand is only called from pexpr). 1060} 1061 1062// pexpr parses a PrimaryExpr. 1063// 1064// PrimaryExpr = 1065// Operand | 1066// Conversion | 1067// PrimaryExpr Selector | 1068// PrimaryExpr Index | 1069// PrimaryExpr Slice | 1070// PrimaryExpr TypeAssertion | 1071// PrimaryExpr Arguments . 1072// 1073// Selector = "." identifier . 1074// Index = "[" Expression "]" . 1075// Slice = "[" ( [ Expression ] ":" [ Expression ] ) | 1076// ( [ Expression ] ":" Expression ":" Expression ) 1077// "]" . 1078// TypeAssertion = "." "(" Type ")" . 1079// Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" . 1080func (p *parser) pexpr(x Expr, keep_parens bool) Expr { 1081 if trace { 1082 defer p.trace("pexpr")() 1083 } 1084 1085 if x == nil { 1086 x = p.operand(keep_parens) 1087 } 1088 1089loop: 1090 for { 1091 pos := p.pos() 1092 switch p.tok { 1093 case _Dot: 1094 p.next() 1095 switch p.tok { 1096 case _Name: 1097 // pexpr '.' sym 1098 t := new(SelectorExpr) 1099 t.pos = pos 1100 t.X = x 1101 t.Sel = p.name() 1102 x = t 1103 1104 case _Lparen: 1105 p.next() 1106 if p.got(_Type) { 1107 t := new(TypeSwitchGuard) 1108 // t.Lhs is filled in by parser.simpleStmt 1109 t.pos = pos 1110 t.X = x 1111 x = t 1112 } else { 1113 t := new(AssertExpr) 1114 t.pos = pos 1115 t.X = x 1116 t.Type = p.type_() 1117 x = t 1118 } 1119 p.want(_Rparen) 1120 1121 default: 1122 p.syntaxError("expected name or (") 1123 p.advance(_Semi, _Rparen) 1124 } 1125 1126 case _Lbrack: 1127 p.next() 1128 1129 var i Expr 1130 if p.tok != _Colon { 1131 var comma bool 1132 if p.tok == _Rbrack { 1133 // invalid empty instance, slice or index expression; accept but complain 1134 p.syntaxError("expected operand") 1135 i = p.badExpr() 1136 } else { 1137 i, comma = p.typeList(false) 1138 } 1139 if comma || p.tok == _Rbrack { 1140 p.want(_Rbrack) 1141 // x[], x[i,] or x[i, j, ...] 1142 t := new(IndexExpr) 1143 t.pos = pos 1144 t.X = x 1145 t.Index = i 1146 x = t 1147 break 1148 } 1149 } 1150 1151 // x[i:... 1152 // For better error message, don't simply use p.want(_Colon) here (go.dev/issue/47704). 1153 if !p.got(_Colon) { 1154 p.syntaxError("expected comma, : or ]") 1155 p.advance(_Comma, _Colon, _Rbrack) 1156 } 1157 p.xnest++ 1158 t := new(SliceExpr) 1159 t.pos = pos 1160 t.X = x 1161 t.Index[0] = i 1162 if p.tok != _Colon && p.tok != _Rbrack { 1163 // x[i:j... 1164 t.Index[1] = p.expr() 1165 } 1166 if p.tok == _Colon { 1167 t.Full = true 1168 // x[i:j:...] 1169 if t.Index[1] == nil { 1170 p.error("middle index required in 3-index slice") 1171 t.Index[1] = p.badExpr() 1172 } 1173 p.next() 1174 if p.tok != _Rbrack { 1175 // x[i:j:k... 1176 t.Index[2] = p.expr() 1177 } else { 1178 p.error("final index required in 3-index slice") 1179 t.Index[2] = p.badExpr() 1180 } 1181 } 1182 p.xnest-- 1183 p.want(_Rbrack) 1184 x = t 1185 1186 case _Lparen: 1187 t := new(CallExpr) 1188 t.pos = pos 1189 p.next() 1190 t.Fun = x 1191 t.ArgList, t.HasDots = p.argList() 1192 x = t 1193 1194 case _Lbrace: 1195 // operand may have returned a parenthesized complit 1196 // type; accept it but complain if we have a complit 1197 t := Unparen(x) 1198 // determine if '{' belongs to a composite literal or a block statement 1199 complit_ok := false 1200 switch t.(type) { 1201 case *Name, *SelectorExpr: 1202 if p.xnest >= 0 { 1203 // x is possibly a composite literal type 1204 complit_ok = true 1205 } 1206 case *IndexExpr: 1207 if p.xnest >= 0 && !isValue(t) { 1208 // x is possibly a composite literal type 1209 complit_ok = true 1210 } 1211 case *ArrayType, *SliceType, *StructType, *MapType: 1212 // x is a comptype 1213 complit_ok = true 1214 } 1215 if !complit_ok { 1216 break loop 1217 } 1218 if t != x { 1219 p.syntaxError("cannot parenthesize type in composite literal") 1220 // already progressed, no need to advance 1221 } 1222 n := p.complitexpr() 1223 n.Type = x 1224 x = n 1225 1226 default: 1227 break loop 1228 } 1229 } 1230 1231 return x 1232} 1233 1234// isValue reports whether x syntactically must be a value (and not a type) expression. 1235func isValue(x Expr) bool { 1236 switch x := x.(type) { 1237 case *BasicLit, *CompositeLit, *FuncLit, *SliceExpr, *AssertExpr, *TypeSwitchGuard, *CallExpr: 1238 return true 1239 case *Operation: 1240 return x.Op != Mul || x.Y != nil // *T may be a type 1241 case *ParenExpr: 1242 return isValue(x.X) 1243 case *IndexExpr: 1244 return isValue(x.X) || isValue(x.Index) 1245 } 1246 return false 1247} 1248 1249// Element = Expression | LiteralValue . 1250func (p *parser) bare_complitexpr() Expr { 1251 if trace { 1252 defer p.trace("bare_complitexpr")() 1253 } 1254 1255 if p.tok == _Lbrace { 1256 // '{' start_complit braced_keyval_list '}' 1257 return p.complitexpr() 1258 } 1259 1260 return p.expr() 1261} 1262 1263// LiteralValue = "{" [ ElementList [ "," ] ] "}" . 1264func (p *parser) complitexpr() *CompositeLit { 1265 if trace { 1266 defer p.trace("complitexpr")() 1267 } 1268 1269 x := new(CompositeLit) 1270 x.pos = p.pos() 1271 1272 p.xnest++ 1273 p.want(_Lbrace) 1274 x.Rbrace = p.list("composite literal", _Comma, _Rbrace, func() bool { 1275 // value 1276 e := p.bare_complitexpr() 1277 if p.tok == _Colon { 1278 // key ':' value 1279 l := new(KeyValueExpr) 1280 l.pos = p.pos() 1281 p.next() 1282 l.Key = e 1283 l.Value = p.bare_complitexpr() 1284 e = l 1285 x.NKeys++ 1286 } 1287 x.ElemList = append(x.ElemList, e) 1288 return false 1289 }) 1290 p.xnest-- 1291 1292 return x 1293} 1294 1295// ---------------------------------------------------------------------------- 1296// Types 1297 1298func (p *parser) type_() Expr { 1299 if trace { 1300 defer p.trace("type_")() 1301 } 1302 1303 typ := p.typeOrNil() 1304 if typ == nil { 1305 typ = p.badExpr() 1306 p.syntaxError("expected type") 1307 p.advance(_Comma, _Colon, _Semi, _Rparen, _Rbrack, _Rbrace) 1308 } 1309 1310 return typ 1311} 1312 1313func newIndirect(pos Pos, typ Expr) Expr { 1314 o := new(Operation) 1315 o.pos = pos 1316 o.Op = Mul 1317 o.X = typ 1318 return o 1319} 1320 1321// typeOrNil is like type_ but it returns nil if there was no type 1322// instead of reporting an error. 1323// 1324// Type = TypeName | TypeLit | "(" Type ")" . 1325// TypeName = identifier | QualifiedIdent . 1326// TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType | 1327// SliceType | MapType | Channel_Type . 1328func (p *parser) typeOrNil() Expr { 1329 if trace { 1330 defer p.trace("typeOrNil")() 1331 } 1332 1333 pos := p.pos() 1334 switch p.tok { 1335 case _Star: 1336 // ptrtype 1337 p.next() 1338 return newIndirect(pos, p.type_()) 1339 1340 case _Arrow: 1341 // recvchantype 1342 p.next() 1343 p.want(_Chan) 1344 t := new(ChanType) 1345 t.pos = pos 1346 t.Dir = RecvOnly 1347 t.Elem = p.chanElem() 1348 return t 1349 1350 case _Func: 1351 // fntype 1352 p.next() 1353 _, t := p.funcType("function type") 1354 return t 1355 1356 case _Lbrack: 1357 // '[' oexpr ']' ntype 1358 // '[' _DotDotDot ']' ntype 1359 p.next() 1360 if p.got(_Rbrack) { 1361 return p.sliceType(pos) 1362 } 1363 return p.arrayType(pos, nil) 1364 1365 case _Chan: 1366 // _Chan non_recvchantype 1367 // _Chan _Comm ntype 1368 p.next() 1369 t := new(ChanType) 1370 t.pos = pos 1371 if p.got(_Arrow) { 1372 t.Dir = SendOnly 1373 } 1374 t.Elem = p.chanElem() 1375 return t 1376 1377 case _Map: 1378 // _Map '[' ntype ']' ntype 1379 p.next() 1380 p.want(_Lbrack) 1381 t := new(MapType) 1382 t.pos = pos 1383 t.Key = p.type_() 1384 p.want(_Rbrack) 1385 t.Value = p.type_() 1386 return t 1387 1388 case _Struct: 1389 return p.structType() 1390 1391 case _Interface: 1392 return p.interfaceType() 1393 1394 case _Name: 1395 return p.qualifiedName(nil) 1396 1397 case _Lparen: 1398 p.next() 1399 t := p.type_() 1400 p.want(_Rparen) 1401 return t 1402 } 1403 1404 return nil 1405} 1406 1407func (p *parser) typeInstance(typ Expr) Expr { 1408 if trace { 1409 defer p.trace("typeInstance")() 1410 } 1411 1412 pos := p.pos() 1413 p.want(_Lbrack) 1414 x := new(IndexExpr) 1415 x.pos = pos 1416 x.X = typ 1417 if p.tok == _Rbrack { 1418 p.syntaxError("expected type argument list") 1419 x.Index = p.badExpr() 1420 } else { 1421 x.Index, _ = p.typeList(true) 1422 } 1423 p.want(_Rbrack) 1424 return x 1425} 1426 1427// If context != "", type parameters are not permitted. 1428func (p *parser) funcType(context string) ([]*Field, *FuncType) { 1429 if trace { 1430 defer p.trace("funcType")() 1431 } 1432 1433 typ := new(FuncType) 1434 typ.pos = p.pos() 1435 1436 var tparamList []*Field 1437 if p.got(_Lbrack) { 1438 if context != "" { 1439 // accept but complain 1440 p.syntaxErrorAt(typ.pos, context+" must have no type parameters") 1441 } 1442 if p.tok == _Rbrack { 1443 p.syntaxError("empty type parameter list") 1444 p.next() 1445 } else { 1446 tparamList = p.paramList(nil, nil, _Rbrack, true) 1447 } 1448 } 1449 1450 p.want(_Lparen) 1451 typ.ParamList = p.paramList(nil, nil, _Rparen, false) 1452 typ.ResultList = p.funcResult() 1453 1454 return tparamList, typ 1455} 1456 1457// "[" has already been consumed, and pos is its position. 1458// If len != nil it is the already consumed array length. 1459func (p *parser) arrayType(pos Pos, len Expr) Expr { 1460 if trace { 1461 defer p.trace("arrayType")() 1462 } 1463 1464 if len == nil && !p.got(_DotDotDot) { 1465 p.xnest++ 1466 len = p.expr() 1467 p.xnest-- 1468 } 1469 if p.tok == _Comma { 1470 // Trailing commas are accepted in type parameter 1471 // lists but not in array type declarations. 1472 // Accept for better error handling but complain. 1473 p.syntaxError("unexpected comma; expected ]") 1474 p.next() 1475 } 1476 p.want(_Rbrack) 1477 t := new(ArrayType) 1478 t.pos = pos 1479 t.Len = len 1480 t.Elem = p.type_() 1481 return t 1482} 1483 1484// "[" and "]" have already been consumed, and pos is the position of "[". 1485func (p *parser) sliceType(pos Pos) Expr { 1486 t := new(SliceType) 1487 t.pos = pos 1488 t.Elem = p.type_() 1489 return t 1490} 1491 1492func (p *parser) chanElem() Expr { 1493 if trace { 1494 defer p.trace("chanElem")() 1495 } 1496 1497 typ := p.typeOrNil() 1498 if typ == nil { 1499 typ = p.badExpr() 1500 p.syntaxError("missing channel element type") 1501 // assume element type is simply absent - don't advance 1502 } 1503 1504 return typ 1505} 1506 1507// StructType = "struct" "{" { FieldDecl ";" } "}" . 1508func (p *parser) structType() *StructType { 1509 if trace { 1510 defer p.trace("structType")() 1511 } 1512 1513 typ := new(StructType) 1514 typ.pos = p.pos() 1515 1516 p.want(_Struct) 1517 p.want(_Lbrace) 1518 p.list("struct type", _Semi, _Rbrace, func() bool { 1519 p.fieldDecl(typ) 1520 return false 1521 }) 1522 1523 return typ 1524} 1525 1526// InterfaceType = "interface" "{" { ( MethodDecl | EmbeddedElem ) ";" } "}" . 1527func (p *parser) interfaceType() *InterfaceType { 1528 if trace { 1529 defer p.trace("interfaceType")() 1530 } 1531 1532 typ := new(InterfaceType) 1533 typ.pos = p.pos() 1534 1535 p.want(_Interface) 1536 p.want(_Lbrace) 1537 p.list("interface type", _Semi, _Rbrace, func() bool { 1538 var f *Field 1539 if p.tok == _Name { 1540 f = p.methodDecl() 1541 } 1542 if f == nil || f.Name == nil { 1543 f = p.embeddedElem(f) 1544 } 1545 typ.MethodList = append(typ.MethodList, f) 1546 return false 1547 }) 1548 1549 return typ 1550} 1551 1552// Result = Parameters | Type . 1553func (p *parser) funcResult() []*Field { 1554 if trace { 1555 defer p.trace("funcResult")() 1556 } 1557 1558 if p.got(_Lparen) { 1559 return p.paramList(nil, nil, _Rparen, false) 1560 } 1561 1562 pos := p.pos() 1563 if typ := p.typeOrNil(); typ != nil { 1564 f := new(Field) 1565 f.pos = pos 1566 f.Type = typ 1567 return []*Field{f} 1568 } 1569 1570 return nil 1571} 1572 1573func (p *parser) addField(styp *StructType, pos Pos, name *Name, typ Expr, tag *BasicLit) { 1574 if tag != nil { 1575 for i := len(styp.FieldList) - len(styp.TagList); i > 0; i-- { 1576 styp.TagList = append(styp.TagList, nil) 1577 } 1578 styp.TagList = append(styp.TagList, tag) 1579 } 1580 1581 f := new(Field) 1582 f.pos = pos 1583 f.Name = name 1584 f.Type = typ 1585 styp.FieldList = append(styp.FieldList, f) 1586 1587 if debug && tag != nil && len(styp.FieldList) != len(styp.TagList) { 1588 panic("inconsistent struct field list") 1589 } 1590} 1591 1592// FieldDecl = (IdentifierList Type | AnonymousField) [ Tag ] . 1593// AnonymousField = [ "*" ] TypeName . 1594// Tag = string_lit . 1595func (p *parser) fieldDecl(styp *StructType) { 1596 if trace { 1597 defer p.trace("fieldDecl")() 1598 } 1599 1600 pos := p.pos() 1601 switch p.tok { 1602 case _Name: 1603 name := p.name() 1604 if p.tok == _Dot || p.tok == _Literal || p.tok == _Semi || p.tok == _Rbrace { 1605 // embedded type 1606 typ := p.qualifiedName(name) 1607 tag := p.oliteral() 1608 p.addField(styp, pos, nil, typ, tag) 1609 break 1610 } 1611 1612 // name1, name2, ... Type [ tag ] 1613 names := p.nameList(name) 1614 var typ Expr 1615 1616 // Careful dance: We don't know if we have an embedded instantiated 1617 // type T[P1, P2, ...] or a field T of array/slice type [P]E or []E. 1618 if len(names) == 1 && p.tok == _Lbrack { 1619 typ = p.arrayOrTArgs() 1620 if typ, ok := typ.(*IndexExpr); ok { 1621 // embedded type T[P1, P2, ...] 1622 typ.X = name // name == names[0] 1623 tag := p.oliteral() 1624 p.addField(styp, pos, nil, typ, tag) 1625 break 1626 } 1627 } else { 1628 // T P 1629 typ = p.type_() 1630 } 1631 1632 tag := p.oliteral() 1633 1634 for _, name := range names { 1635 p.addField(styp, name.Pos(), name, typ, tag) 1636 } 1637 1638 case _Star: 1639 p.next() 1640 var typ Expr 1641 if p.tok == _Lparen { 1642 // *(T) 1643 p.syntaxError("cannot parenthesize embedded type") 1644 p.next() 1645 typ = p.qualifiedName(nil) 1646 p.got(_Rparen) // no need to complain if missing 1647 } else { 1648 // *T 1649 typ = p.qualifiedName(nil) 1650 } 1651 tag := p.oliteral() 1652 p.addField(styp, pos, nil, newIndirect(pos, typ), tag) 1653 1654 case _Lparen: 1655 p.syntaxError("cannot parenthesize embedded type") 1656 p.next() 1657 var typ Expr 1658 if p.tok == _Star { 1659 // (*T) 1660 pos := p.pos() 1661 p.next() 1662 typ = newIndirect(pos, p.qualifiedName(nil)) 1663 } else { 1664 // (T) 1665 typ = p.qualifiedName(nil) 1666 } 1667 p.got(_Rparen) // no need to complain if missing 1668 tag := p.oliteral() 1669 p.addField(styp, pos, nil, typ, tag) 1670 1671 default: 1672 p.syntaxError("expected field name or embedded type") 1673 p.advance(_Semi, _Rbrace) 1674 } 1675} 1676 1677func (p *parser) arrayOrTArgs() Expr { 1678 if trace { 1679 defer p.trace("arrayOrTArgs")() 1680 } 1681 1682 pos := p.pos() 1683 p.want(_Lbrack) 1684 if p.got(_Rbrack) { 1685 return p.sliceType(pos) 1686 } 1687 1688 // x [n]E or x[n,], x[n1, n2], ... 1689 n, comma := p.typeList(false) 1690 p.want(_Rbrack) 1691 if !comma { 1692 if elem := p.typeOrNil(); elem != nil { 1693 // x [n]E 1694 t := new(ArrayType) 1695 t.pos = pos 1696 t.Len = n 1697 t.Elem = elem 1698 return t 1699 } 1700 } 1701 1702 // x[n,], x[n1, n2], ... 1703 t := new(IndexExpr) 1704 t.pos = pos 1705 // t.X will be filled in by caller 1706 t.Index = n 1707 return t 1708} 1709 1710func (p *parser) oliteral() *BasicLit { 1711 if p.tok == _Literal { 1712 b := new(BasicLit) 1713 b.pos = p.pos() 1714 b.Value = p.lit 1715 b.Kind = p.kind 1716 b.Bad = p.bad 1717 p.next() 1718 return b 1719 } 1720 return nil 1721} 1722 1723// MethodSpec = MethodName Signature | InterfaceTypeName . 1724// MethodName = identifier . 1725// InterfaceTypeName = TypeName . 1726func (p *parser) methodDecl() *Field { 1727 if trace { 1728 defer p.trace("methodDecl")() 1729 } 1730 1731 f := new(Field) 1732 f.pos = p.pos() 1733 name := p.name() 1734 1735 const context = "interface method" 1736 1737 switch p.tok { 1738 case _Lparen: 1739 // method 1740 f.Name = name 1741 _, f.Type = p.funcType(context) 1742 1743 case _Lbrack: 1744 // Careful dance: We don't know if we have a generic method m[T C](x T) 1745 // or an embedded instantiated type T[P1, P2] (we accept generic methods 1746 // for generality and robustness of parsing but complain with an error). 1747 pos := p.pos() 1748 p.next() 1749 1750 // Empty type parameter or argument lists are not permitted. 1751 // Treat as if [] were absent. 1752 if p.tok == _Rbrack { 1753 // name[] 1754 pos := p.pos() 1755 p.next() 1756 if p.tok == _Lparen { 1757 // name[]( 1758 p.errorAt(pos, "empty type parameter list") 1759 f.Name = name 1760 _, f.Type = p.funcType(context) 1761 } else { 1762 p.errorAt(pos, "empty type argument list") 1763 f.Type = name 1764 } 1765 break 1766 } 1767 1768 // A type argument list looks like a parameter list with only 1769 // types. Parse a parameter list and decide afterwards. 1770 list := p.paramList(nil, nil, _Rbrack, false) 1771 if len(list) == 0 { 1772 // The type parameter list is not [] but we got nothing 1773 // due to other errors (reported by paramList). Treat 1774 // as if [] were absent. 1775 if p.tok == _Lparen { 1776 f.Name = name 1777 _, f.Type = p.funcType(context) 1778 } else { 1779 f.Type = name 1780 } 1781 break 1782 } 1783 1784 // len(list) > 0 1785 if list[0].Name != nil { 1786 // generic method 1787 f.Name = name 1788 _, f.Type = p.funcType(context) 1789 p.errorAt(pos, "interface method must have no type parameters") 1790 break 1791 } 1792 1793 // embedded instantiated type 1794 t := new(IndexExpr) 1795 t.pos = pos 1796 t.X = name 1797 if len(list) == 1 { 1798 t.Index = list[0].Type 1799 } else { 1800 // len(list) > 1 1801 l := new(ListExpr) 1802 l.pos = list[0].Pos() 1803 l.ElemList = make([]Expr, len(list)) 1804 for i := range list { 1805 l.ElemList[i] = list[i].Type 1806 } 1807 t.Index = l 1808 } 1809 f.Type = t 1810 1811 default: 1812 // embedded type 1813 f.Type = p.qualifiedName(name) 1814 } 1815 1816 return f 1817} 1818 1819// EmbeddedElem = MethodSpec | EmbeddedTerm { "|" EmbeddedTerm } . 1820func (p *parser) embeddedElem(f *Field) *Field { 1821 if trace { 1822 defer p.trace("embeddedElem")() 1823 } 1824 1825 if f == nil { 1826 f = new(Field) 1827 f.pos = p.pos() 1828 f.Type = p.embeddedTerm() 1829 } 1830 1831 for p.tok == _Operator && p.op == Or { 1832 t := new(Operation) 1833 t.pos = p.pos() 1834 t.Op = Or 1835 p.next() 1836 t.X = f.Type 1837 t.Y = p.embeddedTerm() 1838 f.Type = t 1839 } 1840 1841 return f 1842} 1843 1844// EmbeddedTerm = [ "~" ] Type . 1845func (p *parser) embeddedTerm() Expr { 1846 if trace { 1847 defer p.trace("embeddedTerm")() 1848 } 1849 1850 if p.tok == _Operator && p.op == Tilde { 1851 t := new(Operation) 1852 t.pos = p.pos() 1853 t.Op = Tilde 1854 p.next() 1855 t.X = p.type_() 1856 return t 1857 } 1858 1859 t := p.typeOrNil() 1860 if t == nil { 1861 t = p.badExpr() 1862 p.syntaxError("expected ~ term or type") 1863 p.advance(_Operator, _Semi, _Rparen, _Rbrack, _Rbrace) 1864 } 1865 1866 return t 1867} 1868 1869// ParameterDecl = [ IdentifierList ] [ "..." ] Type . 1870func (p *parser) paramDeclOrNil(name *Name, follow token) *Field { 1871 if trace { 1872 defer p.trace("paramDeclOrNil")() 1873 } 1874 1875 // type set notation is ok in type parameter lists 1876 typeSetsOk := follow == _Rbrack 1877 1878 pos := p.pos() 1879 if name != nil { 1880 pos = name.pos 1881 } else if typeSetsOk && p.tok == _Operator && p.op == Tilde { 1882 // "~" ... 1883 return p.embeddedElem(nil) 1884 } 1885 1886 f := new(Field) 1887 f.pos = pos 1888 1889 if p.tok == _Name || name != nil { 1890 // name 1891 if name == nil { 1892 name = p.name() 1893 } 1894 1895 if p.tok == _Lbrack { 1896 // name "[" ... 1897 f.Type = p.arrayOrTArgs() 1898 if typ, ok := f.Type.(*IndexExpr); ok { 1899 // name "[" ... "]" 1900 typ.X = name 1901 } else { 1902 // name "[" n "]" E 1903 f.Name = name 1904 } 1905 if typeSetsOk && p.tok == _Operator && p.op == Or { 1906 // name "[" ... "]" "|" ... 1907 // name "[" n "]" E "|" ... 1908 f = p.embeddedElem(f) 1909 } 1910 return f 1911 } 1912 1913 if p.tok == _Dot { 1914 // name "." ... 1915 f.Type = p.qualifiedName(name) 1916 if typeSetsOk && p.tok == _Operator && p.op == Or { 1917 // name "." name "|" ... 1918 f = p.embeddedElem(f) 1919 } 1920 return f 1921 } 1922 1923 if typeSetsOk && p.tok == _Operator && p.op == Or { 1924 // name "|" ... 1925 f.Type = name 1926 return p.embeddedElem(f) 1927 } 1928 1929 f.Name = name 1930 } 1931 1932 if p.tok == _DotDotDot { 1933 // [name] "..." ... 1934 t := new(DotsType) 1935 t.pos = p.pos() 1936 p.next() 1937 t.Elem = p.typeOrNil() 1938 if t.Elem == nil { 1939 t.Elem = p.badExpr() 1940 p.syntaxError("... is missing type") 1941 } 1942 f.Type = t 1943 return f 1944 } 1945 1946 if typeSetsOk && p.tok == _Operator && p.op == Tilde { 1947 // [name] "~" ... 1948 f.Type = p.embeddedElem(nil).Type 1949 return f 1950 } 1951 1952 f.Type = p.typeOrNil() 1953 if typeSetsOk && p.tok == _Operator && p.op == Or && f.Type != nil { 1954 // [name] type "|" 1955 f = p.embeddedElem(f) 1956 } 1957 if f.Name != nil || f.Type != nil { 1958 return f 1959 } 1960 1961 p.syntaxError("expected " + tokstring(follow)) 1962 p.advance(_Comma, follow) 1963 return nil 1964} 1965 1966// Parameters = "(" [ ParameterList [ "," ] ] ")" . 1967// ParameterList = ParameterDecl { "," ParameterDecl } . 1968// "(" or "[" has already been consumed. 1969// If name != nil, it is the first name after "(" or "[". 1970// If typ != nil, name must be != nil, and (name, typ) is the first field in the list. 1971// In the result list, either all fields have a name, or no field has a name. 1972func (p *parser) paramList(name *Name, typ Expr, close token, requireNames bool) (list []*Field) { 1973 if trace { 1974 defer p.trace("paramList")() 1975 } 1976 1977 // p.list won't invoke its function argument if we're at the end of the 1978 // parameter list. If we have a complete field, handle this case here. 1979 if name != nil && typ != nil && p.tok == close { 1980 p.next() 1981 par := new(Field) 1982 par.pos = name.pos 1983 par.Name = name 1984 par.Type = typ 1985 return []*Field{par} 1986 } 1987 1988 var named int // number of parameters that have an explicit name and type 1989 var typed int // number of parameters that have an explicit type 1990 end := p.list("parameter list", _Comma, close, func() bool { 1991 var par *Field 1992 if typ != nil { 1993 if debug && name == nil { 1994 panic("initial type provided without name") 1995 } 1996 par = new(Field) 1997 par.pos = name.pos 1998 par.Name = name 1999 par.Type = typ 2000 } else { 2001 par = p.paramDeclOrNil(name, close) 2002 } 2003 name = nil // 1st name was consumed if present 2004 typ = nil // 1st type was consumed if present 2005 if par != nil { 2006 if debug && par.Name == nil && par.Type == nil { 2007 panic("parameter without name or type") 2008 } 2009 if par.Name != nil && par.Type != nil { 2010 named++ 2011 } 2012 if par.Type != nil { 2013 typed++ 2014 } 2015 list = append(list, par) 2016 } 2017 return false 2018 }) 2019 2020 if len(list) == 0 { 2021 return 2022 } 2023 2024 // distribute parameter types (len(list) > 0) 2025 if named == 0 && !requireNames { 2026 // all unnamed and we're not in a type parameter list => found names are named types 2027 for _, par := range list { 2028 if typ := par.Name; typ != nil { 2029 par.Type = typ 2030 par.Name = nil 2031 } 2032 } 2033 } else if named != len(list) { 2034 // some named or we're in a type parameter list => all must be named 2035 var errPos Pos // left-most error position (or unknown) 2036 var typ Expr // current type (from right to left) 2037 for i := len(list) - 1; i >= 0; i-- { 2038 par := list[i] 2039 if par.Type != nil { 2040 typ = par.Type 2041 if par.Name == nil { 2042 errPos = StartPos(typ) 2043 par.Name = NewName(errPos, "_") 2044 } 2045 } else if typ != nil { 2046 par.Type = typ 2047 } else { 2048 // par.Type == nil && typ == nil => we only have a par.Name 2049 errPos = par.Name.Pos() 2050 t := p.badExpr() 2051 t.pos = errPos // correct position 2052 par.Type = t 2053 } 2054 } 2055 if errPos.IsKnown() { 2056 var msg string 2057 if requireNames { 2058 // Not all parameters are named because named != len(list). 2059 // If named == typed we must have parameters that have no types, 2060 // and they must be at the end of the parameter list, otherwise 2061 // the types would have been filled in by the right-to-left sweep 2062 // above and we wouldn't have an error. Since we are in a type 2063 // parameter list, the missing types are constraints. 2064 if named == typed { 2065 errPos = end // position error at closing ] 2066 msg = "missing type constraint" 2067 } else { 2068 msg = "missing type parameter name" 2069 // go.dev/issue/60812 2070 if len(list) == 1 { 2071 msg += " or invalid array length" 2072 } 2073 } 2074 } else { 2075 msg = "mixed named and unnamed parameters" 2076 } 2077 p.syntaxErrorAt(errPos, msg) 2078 } 2079 } 2080 2081 return 2082} 2083 2084func (p *parser) badExpr() *BadExpr { 2085 b := new(BadExpr) 2086 b.pos = p.pos() 2087 return b 2088} 2089 2090// ---------------------------------------------------------------------------- 2091// Statements 2092 2093// SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl . 2094func (p *parser) simpleStmt(lhs Expr, keyword token) SimpleStmt { 2095 if trace { 2096 defer p.trace("simpleStmt")() 2097 } 2098 2099 if keyword == _For && p.tok == _Range { 2100 // _Range expr 2101 if debug && lhs != nil { 2102 panic("invalid call of simpleStmt") 2103 } 2104 return p.newRangeClause(nil, false) 2105 } 2106 2107 if lhs == nil { 2108 lhs = p.exprList() 2109 } 2110 2111 if _, ok := lhs.(*ListExpr); !ok && p.tok != _Assign && p.tok != _Define { 2112 // expr 2113 pos := p.pos() 2114 switch p.tok { 2115 case _AssignOp: 2116 // lhs op= rhs 2117 op := p.op 2118 p.next() 2119 return p.newAssignStmt(pos, op, lhs, p.expr()) 2120 2121 case _IncOp: 2122 // lhs++ or lhs-- 2123 op := p.op 2124 p.next() 2125 return p.newAssignStmt(pos, op, lhs, nil) 2126 2127 case _Arrow: 2128 // lhs <- rhs 2129 s := new(SendStmt) 2130 s.pos = pos 2131 p.next() 2132 s.Chan = lhs 2133 s.Value = p.expr() 2134 return s 2135 2136 default: 2137 // expr 2138 s := new(ExprStmt) 2139 s.pos = lhs.Pos() 2140 s.X = lhs 2141 return s 2142 } 2143 } 2144 2145 // expr_list 2146 switch p.tok { 2147 case _Assign, _Define: 2148 pos := p.pos() 2149 var op Operator 2150 if p.tok == _Define { 2151 op = Def 2152 } 2153 p.next() 2154 2155 if keyword == _For && p.tok == _Range { 2156 // expr_list op= _Range expr 2157 return p.newRangeClause(lhs, op == Def) 2158 } 2159 2160 // expr_list op= expr_list 2161 rhs := p.exprList() 2162 2163 if x, ok := rhs.(*TypeSwitchGuard); ok && keyword == _Switch && op == Def { 2164 if lhs, ok := lhs.(*Name); ok { 2165 // switch … lhs := rhs.(type) 2166 x.Lhs = lhs 2167 s := new(ExprStmt) 2168 s.pos = x.Pos() 2169 s.X = x 2170 return s 2171 } 2172 } 2173 2174 return p.newAssignStmt(pos, op, lhs, rhs) 2175 2176 default: 2177 p.syntaxError("expected := or = or comma") 2178 p.advance(_Semi, _Rbrace) 2179 // make the best of what we have 2180 if x, ok := lhs.(*ListExpr); ok { 2181 lhs = x.ElemList[0] 2182 } 2183 s := new(ExprStmt) 2184 s.pos = lhs.Pos() 2185 s.X = lhs 2186 return s 2187 } 2188} 2189 2190func (p *parser) newRangeClause(lhs Expr, def bool) *RangeClause { 2191 r := new(RangeClause) 2192 r.pos = p.pos() 2193 p.next() // consume _Range 2194 r.Lhs = lhs 2195 r.Def = def 2196 r.X = p.expr() 2197 return r 2198} 2199 2200func (p *parser) newAssignStmt(pos Pos, op Operator, lhs, rhs Expr) *AssignStmt { 2201 a := new(AssignStmt) 2202 a.pos = pos 2203 a.Op = op 2204 a.Lhs = lhs 2205 a.Rhs = rhs 2206 return a 2207} 2208 2209func (p *parser) labeledStmtOrNil(label *Name) Stmt { 2210 if trace { 2211 defer p.trace("labeledStmt")() 2212 } 2213 2214 s := new(LabeledStmt) 2215 s.pos = p.pos() 2216 s.Label = label 2217 2218 p.want(_Colon) 2219 2220 if p.tok == _Rbrace { 2221 // We expect a statement (incl. an empty statement), which must be 2222 // terminated by a semicolon. Because semicolons may be omitted before 2223 // an _Rbrace, seeing an _Rbrace implies an empty statement. 2224 e := new(EmptyStmt) 2225 e.pos = p.pos() 2226 s.Stmt = e 2227 return s 2228 } 2229 2230 s.Stmt = p.stmtOrNil() 2231 if s.Stmt != nil { 2232 return s 2233 } 2234 2235 // report error at line of ':' token 2236 p.syntaxErrorAt(s.pos, "missing statement after label") 2237 // we are already at the end of the labeled statement - no need to advance 2238 return nil // avoids follow-on errors (see e.g., fixedbugs/bug274.go) 2239} 2240 2241// context must be a non-empty string unless we know that p.tok == _Lbrace. 2242func (p *parser) blockStmt(context string) *BlockStmt { 2243 if trace { 2244 defer p.trace("blockStmt")() 2245 } 2246 2247 s := new(BlockStmt) 2248 s.pos = p.pos() 2249 2250 // people coming from C may forget that braces are mandatory in Go 2251 if !p.got(_Lbrace) { 2252 p.syntaxError("expected { after " + context) 2253 p.advance(_Name, _Rbrace) 2254 s.Rbrace = p.pos() // in case we found "}" 2255 if p.got(_Rbrace) { 2256 return s 2257 } 2258 } 2259 2260 s.List = p.stmtList() 2261 s.Rbrace = p.pos() 2262 p.want(_Rbrace) 2263 2264 return s 2265} 2266 2267func (p *parser) declStmt(f func(*Group) Decl) *DeclStmt { 2268 if trace { 2269 defer p.trace("declStmt")() 2270 } 2271 2272 s := new(DeclStmt) 2273 s.pos = p.pos() 2274 2275 p.next() // _Const, _Type, or _Var 2276 s.DeclList = p.appendGroup(nil, f) 2277 2278 return s 2279} 2280 2281func (p *parser) forStmt() Stmt { 2282 if trace { 2283 defer p.trace("forStmt")() 2284 } 2285 2286 s := new(ForStmt) 2287 s.pos = p.pos() 2288 2289 s.Init, s.Cond, s.Post = p.header(_For) 2290 s.Body = p.blockStmt("for clause") 2291 2292 return s 2293} 2294 2295func (p *parser) header(keyword token) (init SimpleStmt, cond Expr, post SimpleStmt) { 2296 p.want(keyword) 2297 2298 if p.tok == _Lbrace { 2299 if keyword == _If { 2300 p.syntaxError("missing condition in if statement") 2301 cond = p.badExpr() 2302 } 2303 return 2304 } 2305 // p.tok != _Lbrace 2306 2307 outer := p.xnest 2308 p.xnest = -1 2309 2310 if p.tok != _Semi { 2311 // accept potential varDecl but complain 2312 if p.got(_Var) { 2313 p.syntaxError(fmt.Sprintf("var declaration not allowed in %s initializer", tokstring(keyword))) 2314 } 2315 init = p.simpleStmt(nil, keyword) 2316 // If we have a range clause, we are done (can only happen for keyword == _For). 2317 if _, ok := init.(*RangeClause); ok { 2318 p.xnest = outer 2319 return 2320 } 2321 } 2322 2323 var condStmt SimpleStmt 2324 var semi struct { 2325 pos Pos 2326 lit string // valid if pos.IsKnown() 2327 } 2328 if p.tok != _Lbrace { 2329 if p.tok == _Semi { 2330 semi.pos = p.pos() 2331 semi.lit = p.lit 2332 p.next() 2333 } else { 2334 // asking for a '{' rather than a ';' here leads to a better error message 2335 p.want(_Lbrace) 2336 if p.tok != _Lbrace { 2337 p.advance(_Lbrace, _Rbrace) // for better synchronization (e.g., go.dev/issue/22581) 2338 } 2339 } 2340 if keyword == _For { 2341 if p.tok != _Semi { 2342 if p.tok == _Lbrace { 2343 p.syntaxError("expected for loop condition") 2344 goto done 2345 } 2346 condStmt = p.simpleStmt(nil, 0 /* range not permitted */) 2347 } 2348 p.want(_Semi) 2349 if p.tok != _Lbrace { 2350 post = p.simpleStmt(nil, 0 /* range not permitted */) 2351 if a, _ := post.(*AssignStmt); a != nil && a.Op == Def { 2352 p.syntaxErrorAt(a.Pos(), "cannot declare in post statement of for loop") 2353 } 2354 } 2355 } else if p.tok != _Lbrace { 2356 condStmt = p.simpleStmt(nil, keyword) 2357 } 2358 } else { 2359 condStmt = init 2360 init = nil 2361 } 2362 2363done: 2364 // unpack condStmt 2365 switch s := condStmt.(type) { 2366 case nil: 2367 if keyword == _If && semi.pos.IsKnown() { 2368 if semi.lit != "semicolon" { 2369 p.syntaxErrorAt(semi.pos, fmt.Sprintf("unexpected %s, expected { after if clause", semi.lit)) 2370 } else { 2371 p.syntaxErrorAt(semi.pos, "missing condition in if statement") 2372 } 2373 b := new(BadExpr) 2374 b.pos = semi.pos 2375 cond = b 2376 } 2377 case *ExprStmt: 2378 cond = s.X 2379 default: 2380 // A common syntax error is to write '=' instead of '==', 2381 // which turns an expression into an assignment. Provide 2382 // a more explicit error message in that case to prevent 2383 // further confusion. 2384 var str string 2385 if as, ok := s.(*AssignStmt); ok && as.Op == 0 { 2386 // Emphasize complex Lhs and Rhs of assignment with parentheses to highlight '='. 2387 str = "assignment " + emphasize(as.Lhs) + " = " + emphasize(as.Rhs) 2388 } else { 2389 str = String(s) 2390 } 2391 p.syntaxErrorAt(s.Pos(), fmt.Sprintf("cannot use %s as value", str)) 2392 } 2393 2394 p.xnest = outer 2395 return 2396} 2397 2398// emphasize returns a string representation of x, with (top-level) 2399// binary expressions emphasized by enclosing them in parentheses. 2400func emphasize(x Expr) string { 2401 s := String(x) 2402 if op, _ := x.(*Operation); op != nil && op.Y != nil { 2403 // binary expression 2404 return "(" + s + ")" 2405 } 2406 return s 2407} 2408 2409func (p *parser) ifStmt() *IfStmt { 2410 if trace { 2411 defer p.trace("ifStmt")() 2412 } 2413 2414 s := new(IfStmt) 2415 s.pos = p.pos() 2416 2417 s.Init, s.Cond, _ = p.header(_If) 2418 s.Then = p.blockStmt("if clause") 2419 2420 if p.got(_Else) { 2421 switch p.tok { 2422 case _If: 2423 s.Else = p.ifStmt() 2424 case _Lbrace: 2425 s.Else = p.blockStmt("") 2426 default: 2427 p.syntaxError("else must be followed by if or statement block") 2428 p.advance(_Name, _Rbrace) 2429 } 2430 } 2431 2432 return s 2433} 2434 2435func (p *parser) switchStmt() *SwitchStmt { 2436 if trace { 2437 defer p.trace("switchStmt")() 2438 } 2439 2440 s := new(SwitchStmt) 2441 s.pos = p.pos() 2442 2443 s.Init, s.Tag, _ = p.header(_Switch) 2444 2445 if !p.got(_Lbrace) { 2446 p.syntaxError("missing { after switch clause") 2447 p.advance(_Case, _Default, _Rbrace) 2448 } 2449 for p.tok != _EOF && p.tok != _Rbrace { 2450 s.Body = append(s.Body, p.caseClause()) 2451 } 2452 s.Rbrace = p.pos() 2453 p.want(_Rbrace) 2454 2455 return s 2456} 2457 2458func (p *parser) selectStmt() *SelectStmt { 2459 if trace { 2460 defer p.trace("selectStmt")() 2461 } 2462 2463 s := new(SelectStmt) 2464 s.pos = p.pos() 2465 2466 p.want(_Select) 2467 if !p.got(_Lbrace) { 2468 p.syntaxError("missing { after select clause") 2469 p.advance(_Case, _Default, _Rbrace) 2470 } 2471 for p.tok != _EOF && p.tok != _Rbrace { 2472 s.Body = append(s.Body, p.commClause()) 2473 } 2474 s.Rbrace = p.pos() 2475 p.want(_Rbrace) 2476 2477 return s 2478} 2479 2480func (p *parser) caseClause() *CaseClause { 2481 if trace { 2482 defer p.trace("caseClause")() 2483 } 2484 2485 c := new(CaseClause) 2486 c.pos = p.pos() 2487 2488 switch p.tok { 2489 case _Case: 2490 p.next() 2491 c.Cases = p.exprList() 2492 2493 case _Default: 2494 p.next() 2495 2496 default: 2497 p.syntaxError("expected case or default or }") 2498 p.advance(_Colon, _Case, _Default, _Rbrace) 2499 } 2500 2501 c.Colon = p.pos() 2502 p.want(_Colon) 2503 c.Body = p.stmtList() 2504 2505 return c 2506} 2507 2508func (p *parser) commClause() *CommClause { 2509 if trace { 2510 defer p.trace("commClause")() 2511 } 2512 2513 c := new(CommClause) 2514 c.pos = p.pos() 2515 2516 switch p.tok { 2517 case _Case: 2518 p.next() 2519 c.Comm = p.simpleStmt(nil, 0) 2520 2521 // The syntax restricts the possible simple statements here to: 2522 // 2523 // lhs <- x (send statement) 2524 // <-x 2525 // lhs = <-x 2526 // lhs := <-x 2527 // 2528 // All these (and more) are recognized by simpleStmt and invalid 2529 // syntax trees are flagged later, during type checking. 2530 2531 case _Default: 2532 p.next() 2533 2534 default: 2535 p.syntaxError("expected case or default or }") 2536 p.advance(_Colon, _Case, _Default, _Rbrace) 2537 } 2538 2539 c.Colon = p.pos() 2540 p.want(_Colon) 2541 c.Body = p.stmtList() 2542 2543 return c 2544} 2545 2546// stmtOrNil parses a statement if one is present, or else returns nil. 2547// 2548// Statement = 2549// Declaration | LabeledStmt | SimpleStmt | 2550// GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt | 2551// FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt | 2552// DeferStmt . 2553func (p *parser) stmtOrNil() Stmt { 2554 if trace { 2555 defer p.trace("stmt " + p.tok.String())() 2556 } 2557 2558 // Most statements (assignments) start with an identifier; 2559 // look for it first before doing anything more expensive. 2560 if p.tok == _Name { 2561 p.clearPragma() 2562 lhs := p.exprList() 2563 if label, ok := lhs.(*Name); ok && p.tok == _Colon { 2564 return p.labeledStmtOrNil(label) 2565 } 2566 return p.simpleStmt(lhs, 0) 2567 } 2568 2569 switch p.tok { 2570 case _Var: 2571 return p.declStmt(p.varDecl) 2572 2573 case _Const: 2574 return p.declStmt(p.constDecl) 2575 2576 case _Type: 2577 return p.declStmt(p.typeDecl) 2578 } 2579 2580 p.clearPragma() 2581 2582 switch p.tok { 2583 case _Lbrace: 2584 return p.blockStmt("") 2585 2586 case _Operator, _Star: 2587 switch p.op { 2588 case Add, Sub, Mul, And, Xor, Not: 2589 return p.simpleStmt(nil, 0) // unary operators 2590 } 2591 2592 case _Literal, _Func, _Lparen, // operands 2593 _Lbrack, _Struct, _Map, _Chan, _Interface, // composite types 2594 _Arrow: // receive operator 2595 return p.simpleStmt(nil, 0) 2596 2597 case _For: 2598 return p.forStmt() 2599 2600 case _Switch: 2601 return p.switchStmt() 2602 2603 case _Select: 2604 return p.selectStmt() 2605 2606 case _If: 2607 return p.ifStmt() 2608 2609 case _Fallthrough: 2610 s := new(BranchStmt) 2611 s.pos = p.pos() 2612 p.next() 2613 s.Tok = _Fallthrough 2614 return s 2615 2616 case _Break, _Continue: 2617 s := new(BranchStmt) 2618 s.pos = p.pos() 2619 s.Tok = p.tok 2620 p.next() 2621 if p.tok == _Name { 2622 s.Label = p.name() 2623 } 2624 return s 2625 2626 case _Go, _Defer: 2627 return p.callStmt() 2628 2629 case _Goto: 2630 s := new(BranchStmt) 2631 s.pos = p.pos() 2632 s.Tok = _Goto 2633 p.next() 2634 s.Label = p.name() 2635 return s 2636 2637 case _Return: 2638 s := new(ReturnStmt) 2639 s.pos = p.pos() 2640 p.next() 2641 if p.tok != _Semi && p.tok != _Rbrace { 2642 s.Results = p.exprList() 2643 } 2644 return s 2645 2646 case _Semi: 2647 s := new(EmptyStmt) 2648 s.pos = p.pos() 2649 return s 2650 } 2651 2652 return nil 2653} 2654 2655// StatementList = { Statement ";" } . 2656func (p *parser) stmtList() (l []Stmt) { 2657 if trace { 2658 defer p.trace("stmtList")() 2659 } 2660 2661 for p.tok != _EOF && p.tok != _Rbrace && p.tok != _Case && p.tok != _Default { 2662 s := p.stmtOrNil() 2663 p.clearPragma() 2664 if s == nil { 2665 break 2666 } 2667 l = append(l, s) 2668 // ";" is optional before "}" 2669 if !p.got(_Semi) && p.tok != _Rbrace { 2670 p.syntaxError("at end of statement") 2671 p.advance(_Semi, _Rbrace, _Case, _Default) 2672 p.got(_Semi) // avoid spurious empty statement 2673 } 2674 } 2675 return 2676} 2677 2678// argList parses a possibly empty, comma-separated list of arguments, 2679// optionally followed by a comma (if not empty), and closed by ")". 2680// The last argument may be followed by "...". 2681// 2682// argList = [ arg { "," arg } [ "..." ] [ "," ] ] ")" . 2683func (p *parser) argList() (list []Expr, hasDots bool) { 2684 if trace { 2685 defer p.trace("argList")() 2686 } 2687 2688 p.xnest++ 2689 p.list("argument list", _Comma, _Rparen, func() bool { 2690 list = append(list, p.expr()) 2691 hasDots = p.got(_DotDotDot) 2692 return hasDots 2693 }) 2694 p.xnest-- 2695 2696 return 2697} 2698 2699// ---------------------------------------------------------------------------- 2700// Common productions 2701 2702func (p *parser) name() *Name { 2703 // no tracing to avoid overly verbose output 2704 2705 if p.tok == _Name { 2706 n := NewName(p.pos(), p.lit) 2707 p.next() 2708 return n 2709 } 2710 2711 n := NewName(p.pos(), "_") 2712 p.syntaxError("expected name") 2713 p.advance() 2714 return n 2715} 2716 2717// IdentifierList = identifier { "," identifier } . 2718// The first name must be provided. 2719func (p *parser) nameList(first *Name) []*Name { 2720 if trace { 2721 defer p.trace("nameList")() 2722 } 2723 2724 if debug && first == nil { 2725 panic("first name not provided") 2726 } 2727 2728 l := []*Name{first} 2729 for p.got(_Comma) { 2730 l = append(l, p.name()) 2731 } 2732 2733 return l 2734} 2735 2736// The first name may be provided, or nil. 2737func (p *parser) qualifiedName(name *Name) Expr { 2738 if trace { 2739 defer p.trace("qualifiedName")() 2740 } 2741 2742 var x Expr 2743 switch { 2744 case name != nil: 2745 x = name 2746 case p.tok == _Name: 2747 x = p.name() 2748 default: 2749 x = NewName(p.pos(), "_") 2750 p.syntaxError("expected name") 2751 p.advance(_Dot, _Semi, _Rbrace) 2752 } 2753 2754 if p.tok == _Dot { 2755 s := new(SelectorExpr) 2756 s.pos = p.pos() 2757 p.next() 2758 s.X = x 2759 s.Sel = p.name() 2760 x = s 2761 } 2762 2763 if p.tok == _Lbrack { 2764 x = p.typeInstance(x) 2765 } 2766 2767 return x 2768} 2769 2770// ExpressionList = Expression { "," Expression } . 2771func (p *parser) exprList() Expr { 2772 if trace { 2773 defer p.trace("exprList")() 2774 } 2775 2776 x := p.expr() 2777 if p.got(_Comma) { 2778 list := []Expr{x, p.expr()} 2779 for p.got(_Comma) { 2780 list = append(list, p.expr()) 2781 } 2782 t := new(ListExpr) 2783 t.pos = x.Pos() 2784 t.ElemList = list 2785 x = t 2786 } 2787 return x 2788} 2789 2790// typeList parses a non-empty, comma-separated list of types, 2791// optionally followed by a comma. If strict is set to false, 2792// the first element may also be a (non-type) expression. 2793// If there is more than one argument, the result is a *ListExpr. 2794// The comma result indicates whether there was a (separating or 2795// trailing) comma. 2796// 2797// typeList = arg { "," arg } [ "," ] . 2798func (p *parser) typeList(strict bool) (x Expr, comma bool) { 2799 if trace { 2800 defer p.trace("typeList")() 2801 } 2802 2803 p.xnest++ 2804 if strict { 2805 x = p.type_() 2806 } else { 2807 x = p.expr() 2808 } 2809 if p.got(_Comma) { 2810 comma = true 2811 if t := p.typeOrNil(); t != nil { 2812 list := []Expr{x, t} 2813 for p.got(_Comma) { 2814 if t = p.typeOrNil(); t == nil { 2815 break 2816 } 2817 list = append(list, t) 2818 } 2819 l := new(ListExpr) 2820 l.pos = x.Pos() // == list[0].Pos() 2821 l.ElemList = list 2822 x = l 2823 } 2824 } 2825 p.xnest-- 2826 return 2827} 2828 2829// Unparen returns e with any enclosing parentheses stripped. 2830func Unparen(x Expr) Expr { 2831 for { 2832 p, ok := x.(*ParenExpr) 2833 if !ok { 2834 break 2835 } 2836 x = p.X 2837 } 2838 return x 2839} 2840 2841// UnpackListExpr unpacks a *ListExpr into a []Expr. 2842func UnpackListExpr(x Expr) []Expr { 2843 switch x := x.(type) { 2844 case nil: 2845 return nil 2846 case *ListExpr: 2847 return x.ElemList 2848 default: 2849 return []Expr{x} 2850 } 2851} 2852