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