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