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.
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
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
37 func (p *parser) init(file *PosBase, r io.Reader, errh ErrorHandler, pragh PragmaHandler, mode Mode) {
45 // Error and directive handler for scanner.
46 // Because the (line, col) positions passed to the
47 // handler is always at or after the current reading
48 // position, it is safe to use the most recent position
49 // base to compute the corresponding Pos value.
50 func(line, col uint, msg string) {
52 p.errorAt(p.posAt(line, col), msg)
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
63 // line comment (newline is part of the comment)
64 pos = MakePos(p.file, line+1, colbase)
67 // (if the comment spans multiple lines it's not
68 // a valid line directive and will be discarded
70 pos = MakePos(p.file, line, col+uint(len(msg)))
72 p.updateBase(pos, line, col+2+5, text[5:]) // +2 to skip over // or /*
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)
84 p.pragma = pragh(p.posAt(line, col+2), p.scanner.blank, text, p.pragma) // +2 to skip over // or /*
101 // takePragma returns the current parsed pragmas
102 // and clears them from the parser state.
103 func (p *parser) takePragma() Pragma {
109 // clearPragma is called at the end of a statement or
110 // other Go form that does NOT accept a pragma.
111 // It sends the pragma back to the pragma handler
112 // to be reported as unused.
113 func (p *parser) clearPragma() {
115 p.pragh(p.pos(), p.scanner.blank, "", p.pragma)
120 // updateBase sets the current position base to a new line base at pos.
121 // The base's filename, line, and column values are extracted from text
122 // which is positioned at (tline, tcol) (only needed for error messages).
123 func (p *parser) updateBase(pos Pos, tline, tcol uint, text string) {
124 i, n, ok := trailingDigits(text)
126 return // ignore (not a line directive)
131 // text has a suffix :xxx but xxx is not a number
132 p.errorAt(p.posAt(tline, tcol+i), "invalid line number: "+text[i:])
137 i2, n2, ok2 := trailingDigits(text[:i-1])
139 //line filename:line:col
142 if col == 0 || col > PosMax {
143 p.errorAt(p.posAt(tline, tcol+i2), "invalid column number: "+text[i2:])
146 text = text[:i2-1] // lop off ":col"
152 if line == 0 || line > PosMax {
153 p.errorAt(p.posAt(tline, tcol+i), "invalid line number: "+text[i:])
157 // If we have a column (//line filename:line:col form),
158 // an empty filename means to use the previous filename.
159 filename := text[:i-1] // lop off ":line"
161 if filename == "" && ok2 {
162 filename = p.base.Filename()
163 trimmed = p.base.Trimmed()
166 p.base = NewLineBase(pos, filename, trimmed, line, col)
169 func commentText(s string) string {
171 return s[2 : len(s)-2] // lop off /* and */
174 // line comment (does not include newline)
175 // (on Windows, the line comment may end in \r\n)
180 return s[2:i] // lop off //, and \r at end, if any
183 func trailingDigits(text string) (uint, uint, bool) {
184 i := strings.LastIndexByte(text, ':') // look from right (Windows filenames may contain ':')
186 return 0, 0, false // no ':'
189 n, err := strconv.ParseUint(text[i+1:], 10, 0)
190 return uint(i + 1), uint(n), err == nil
193 func (p *parser) got(tok token) bool {
201 func (p *parser) want(tok token) {
203 p.syntaxError("expected " + tokstring(tok))
208 // gotAssign is like got(_Assign) but it also accepts ":="
209 // (and reports an error) for better parser error recovery.
210 func (p *parser) gotAssign() bool {
213 p.syntaxError("expected =")
222 // ----------------------------------------------------------------------------
225 // posAt returns the Pos value for (line, col) and the current position base.
226 func (p *parser) posAt(line, col uint) Pos {
227 return MakePos(p.base, line, col)
230 // errorAt reports an error at the given position.
231 func (p *parser) errorAt(pos Pos, msg string) {
232 err := Error{pos, msg}
243 // syntaxErrorAt reports a syntax error at the given position.
244 func (p *parser) syntaxErrorAt(pos Pos, msg string) {
246 p.print("syntax error: " + msg)
249 if p.tok == _EOF && p.first != nil {
250 return // avoid meaningless follow-up errors
253 // add punctuation etc. as needed to msg
257 case strings.HasPrefix(msg, "in "), strings.HasPrefix(msg, "at "), strings.HasPrefix(msg, "after "):
259 case strings.HasPrefix(msg, "expected "):
262 // plain error - we don't care about current token
263 p.errorAt(pos, "syntax error: "+msg)
267 // determine token string
273 tok = "literal " + p.lit
277 tok = p.op.String() + "="
282 tok = tokstring(p.tok)
285 // TODO(gri) This may print "unexpected X, expected Y".
286 // Consider "got X, expected Y" in this case.
287 p.errorAt(pos, "syntax error: unexpected "+tok+msg)
290 // tokstring returns the English word for selected punctuation tokens
291 // for more readable error messages. Use tokstring (not tok.String())
292 // for user-facing (error) messages; use tok.String() for debugging
294 func tokstring(tok token) string {
299 return "semicolon or newline"
304 // Convenience methods using the current token position.
305 func (p *parser) pos() Pos { return p.posAt(p.line, p.col) }
306 func (p *parser) error(msg string) { p.errorAt(p.pos(), msg) }
307 func (p *parser) syntaxError(msg string) { p.syntaxErrorAt(p.pos(), msg) }
309 // The stopset contains keywords that start a statement.
310 // They are good synchronization points in case of syntax
311 // errors and (usually) shouldn't be skipped over.
312 const stopset uint64 = 1<<_Break |
327 // advance consumes tokens until it finds a token of the stopset or followlist.
328 // The stopset is only considered if we are inside a function (p.fnest > 0).
329 // The followlist is the list of valid tokens that can follow a production;
330 // if it is empty, exactly one (non-EOF) token is consumed to ensure progress.
331 func (p *parser) advance(followlist ...token) {
333 p.print(fmt.Sprintf("advance %s", followlist))
336 // compute follow set
337 // (not speed critical, advance is only called in error situations)
338 var followset uint64 = 1 << _EOF // don't skip over EOF
339 if len(followlist) > 0 {
343 for _, tok := range followlist {
344 followset |= 1 << tok
348 for !contains(followset, p.tok) {
350 p.print("skip " + p.tok.String())
353 if len(followlist) == 0 {
359 p.print("next " + p.tok.String())
363 // usage: defer p.trace(msg)()
364 func (p *parser) trace(msg string) func() {
367 p.indent = append(p.indent, tab...)
369 p.indent = p.indent[:len(p.indent)-len(tab)]
370 if x := recover(); x != nil {
371 panic(x) // skip print_trace
377 func (p *parser) print(msg string) {
378 fmt.Printf("%5d: %s%s\n", p.line, p.indent, msg)
381 // ----------------------------------------------------------------------------
384 // Parse methods are annotated with matching Go productions as appropriate.
385 // The annotations are intended as guidelines only since a single Go grammar
386 // rule may be covered by multiple parse methods and vice versa.
388 // Excluding methods returning slices, parse methods named xOrNil may return
389 // nil; all others are expected to return a valid non-nil node.
391 // SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
392 func (p *parser) fileOrNil() *File {
394 defer p.trace("file")()
401 f.GoVersion = p.goVersion
403 if !p.got(_Package) {
404 p.syntaxError("package statement must be first")
407 f.Pragma = p.takePragma()
411 // don't bother continuing if package clause has errors
416 // Accept import declarations anywhere for error tolerance, but complain.
417 // { ( ImportDecl | TopLevelDecl ) ";" }
420 if p.tok == _Import && prev != _Import {
421 p.syntaxError("imports must appear before other declarations")
428 f.DeclList = p.appendGroup(f.DeclList, p.importDecl)
432 f.DeclList = p.appendGroup(f.DeclList, p.constDecl)
436 f.DeclList = p.appendGroup(f.DeclList, p.typeDecl)
440 f.DeclList = p.appendGroup(f.DeclList, p.varDecl)
444 if d := p.funcDeclOrNil(); d != nil {
445 f.DeclList = append(f.DeclList, d)
449 if p.tok == _Lbrace && len(f.DeclList) > 0 && isEmptyFuncDecl(f.DeclList[len(f.DeclList)-1]) {
450 // opening { of function declaration on next line
451 p.syntaxError("unexpected semicolon or newline before {")
453 p.syntaxError("non-declaration statement outside function body")
455 p.advance(_Import, _Const, _Type, _Var, _Func)
459 // Reset p.pragma BEFORE advancing to the next token (consuming ';')
460 // since comments before may set pragmas for the next function decl.
463 if p.tok != _EOF && !p.got(_Semi) {
464 p.syntaxError("after top level declaration")
465 p.advance(_Import, _Const, _Type, _Var, _Func)
476 func isEmptyFuncDecl(dcl Decl) bool {
477 f, ok := dcl.(*FuncDecl)
478 return ok && f.Body == nil
481 // ----------------------------------------------------------------------------
484 // list parses a possibly empty, sep-separated list of elements, optionally
485 // followed by sep, and closed by close (or EOF). sep must be one of _Comma
486 // or _Semi, and close must be one of _Rparen, _Rbrace, or _Rbrack.
488 // For each list element, f is called. Specifically, unless we're at close
489 // (or EOF), f is called at least once. After f returns true, no more list
490 // elements are accepted. list returns the position of the closing token.
492 // list = [ f { sep f } [sep] ] close .
493 func (p *parser) list(context string, sep, close token, f func() bool) Pos {
494 if debug && (sep != _Comma && sep != _Semi || close != _Rparen && close != _Rbrace && close != _Rbrack) {
495 panic("invalid sep or close argument for list")
499 for p.tok != _EOF && p.tok != close && !done {
501 // sep is optional before close
502 if !p.got(sep) && p.tok != close {
503 p.syntaxError(fmt.Sprintf("in %s; possibly missing %s or %s", context, tokstring(sep), tokstring(close)))
504 p.advance(_Rparen, _Rbrack, _Rbrace)
506 // position could be better but we had an error so we don't care
517 // appendGroup(f) = f | "(" { f ";" } ")" . // ";" is optional before ")"
518 func (p *parser) appendGroup(list []Decl, f func(*Group) Decl) []Decl {
519 if p.tok == _Lparen {
522 p.next() // must consume "(" after calling clearPragma!
523 p.list("grouped declaration", _Semi, _Rparen, func() bool {
524 if x := f(g); x != nil {
525 list = append(list, x)
530 if x := f(nil); x != nil {
531 list = append(list, x)
537 // ImportSpec = [ "." | PackageName ] ImportPath .
538 // ImportPath = string_lit .
539 func (p *parser) importDecl(group *Group) Decl {
541 defer p.trace("importDecl")()
547 d.Pragma = p.takePragma()
551 d.LocalPkgName = p.name()
553 d.LocalPkgName = NewName(p.pos(), ".")
556 d.Path = p.oliteral()
558 p.syntaxError("missing import path")
559 p.advance(_Semi, _Rparen)
562 if !d.Path.Bad && d.Path.Kind != StringLit {
563 p.syntaxErrorAt(d.Path.Pos(), "import path must be a string")
566 // d.Path.Bad || d.Path.Kind == StringLit
571 // ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
572 func (p *parser) constDecl(group *Group) Decl {
574 defer p.trace("constDecl")()
580 d.Pragma = p.takePragma()
582 d.NameList = p.nameList(p.name())
583 if p.tok != _EOF && p.tok != _Semi && p.tok != _Rparen {
584 d.Type = p.typeOrNil()
586 d.Values = p.exprList()
593 // TypeSpec = identifier [ TypeParams ] [ "=" ] Type .
594 func (p *parser) typeDecl(group *Group) Decl {
596 defer p.trace("typeDecl")()
602 d.Pragma = p.takePragma()
605 if p.tok == _Lbrack {
607 // array/slice type or type parameter list
612 // We may have an array type or a type parameter list.
613 // In either case we expect an expression x (which may
614 // just be a name, or a more complex expression) which
615 // we can analyze further.
617 // A type parameter list may have a type bound starting
618 // with a "[" as in: P []E. In that case, simply parsing
619 // an expression would lead to an error: P[] is invalid.
620 // But since index or slice expressions are never constant
621 // and thus invalid array length expressions, if the name
622 // is followed by "[" it must be the start of an array or
623 // slice constraint. Only if we don't see a "[" do we
624 // need to parse a full expression. Notably, name <- x
625 // is not a concern because name <- x is a statement and
626 // not an expression.
627 var x Expr = p.name()
628 if p.tok != _Lbrack {
629 // To parse the expression starting with name, expand
630 // the call sequence we would get by passing in name
631 // to parser.expr, and pass in name to parser.pexpr.
633 x = p.binaryExpr(p.pexpr(x, false), 0)
636 // Analyze expression x. If we can split x into a type parameter
637 // name, possibly followed by a type parameter type, we consider
638 // this the start of a type parameter list, with some caveats:
639 // a single name followed by "]" tilts the decision towards an
640 // array declaration; a type parameter type that could also be
641 // an ordinary expression but which is followed by a comma tilts
642 // the decision towards a type parameter list.
643 if pname, ptype := extractName(x, p.tok == _Comma); pname != nil && (ptype != nil || p.tok != _Rbrack) {
644 // d.Name "[" pname ...
645 // d.Name "[" pname ptype ...
646 // d.Name "[" pname ptype "," ...
647 d.TParamList = p.paramList(pname, ptype, _Rbrack, true) // ptype may be nil
648 d.Alias = p.gotAssign()
649 d.Type = p.typeOrNil()
651 // d.Name "[" pname "]" ...
653 d.Type = p.arrayType(pos, x)
656 // d.Name "[" "]" ...
658 d.Type = p.sliceType(pos)
661 d.Type = p.arrayType(pos, nil)
664 d.Alias = p.gotAssign()
665 d.Type = p.typeOrNil()
670 p.syntaxError("in type declaration")
671 p.advance(_Semi, _Rparen)
677 // extractName splits the expression x into (name, expr) if syntactically
678 // x can be written as name expr. The split only happens if expr is a type
679 // element (per the isTypeElem predicate) or if force is set.
680 // If x is just a name, the result is (name, nil). If the split succeeds,
681 // the result is (name, expr). Otherwise the result is (nil, x).
685 // ------------------------------------
686 // P*[]int T/F P *[]int
689 // P([]int) T/F P []int
692 // P*E|F|~G T/F P *E|F|~G
693 // P*E|F|G T P *E|F|G
694 // P*E|F|G F nil P*E|F|G
695 func extractName(x Expr, force bool) (*Name, Expr) {
696 switch x := x.(type) {
705 if name, _ := x.X.(*Name); name != nil && (force || isTypeElem(x.Y)) {
708 op.X, op.Y = op.Y, nil // change op into unary *op.Y
712 if name, lhs := extractName(x.X, force || isTypeElem(x.Y)); name != nil && lhs != nil {
720 if name, _ := x.Fun.(*Name); name != nil {
721 if len(x.ArgList) == 1 && !x.HasDots && (force || isTypeElem(x.ArgList[0])) {
722 // x = name "(" x.ArgList[0] ")"
723 return name, x.ArgList[0]
730 // isTypeElem reports whether x is a (possibly parenthesized) type element expression.
731 // The result is false if x could be a type element OR an ordinary (value) expression.
732 func isTypeElem(x Expr) bool {
733 switch x := x.(type) {
734 case *ArrayType, *StructType, *FuncType, *InterfaceType, *SliceType, *MapType, *ChanType:
737 return isTypeElem(x.X) || (x.Y != nil && isTypeElem(x.Y)) || x.Op == Tilde
739 return isTypeElem(x.X)
744 // VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
745 func (p *parser) varDecl(group *Group) Decl {
747 defer p.trace("varDecl")()
753 d.Pragma = p.takePragma()
755 d.NameList = p.nameList(p.name())
757 d.Values = p.exprList()
761 d.Values = p.exprList()
768 // FunctionDecl = "func" FunctionName [ TypeParams ] ( Function | Signature ) .
769 // FunctionName = identifier .
770 // Function = Signature FunctionBody .
771 // MethodDecl = "func" Receiver MethodName ( Function | Signature ) .
772 // Receiver = Parameters .
773 func (p *parser) funcDeclOrNil() *FuncDecl {
775 defer p.trace("funcDecl")()
780 f.Pragma = p.takePragma()
785 rcvr := p.paramList(nil, nil, _Rparen, false)
788 p.error("method has no receiver")
790 p.error("method has multiple receivers")
799 f.TParamList, f.Type = p.funcType(context)
801 f.Name = NewName(p.pos(), "_")
802 f.Type = new(FuncType)
804 msg := "expected name or ("
806 msg = "expected name"
809 p.advance(_Lbrace, _Semi)
812 if p.tok == _Lbrace {
813 f.Body = p.funcBody()
819 func (p *parser) funcBody() *BlockStmt {
822 body := p.blockStmt("")
825 // Don't check branches if there were syntax errors in the function
826 // as it may lead to spurious errors (e.g., see test/switch2.go) or
827 // possibly crashes due to incomplete syntax trees.
828 if p.mode&CheckBranches != 0 && errcnt == p.errcnt {
829 checkBranches(body, p.errh)
835 // ----------------------------------------------------------------------------
838 func (p *parser) expr() Expr {
840 defer p.trace("expr")()
843 return p.binaryExpr(nil, 0)
846 // Expression = UnaryExpr | Expression binary_op Expression .
847 func (p *parser) binaryExpr(x Expr, prec int) Expr {
848 // don't trace binaryExpr - only leads to overly nested trace output
853 for (p.tok == _Operator || p.tok == _Star) && p.prec > prec {
860 t.Y = p.binaryExpr(nil, tprec)
866 // UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
867 func (p *parser) unaryExpr() Expr {
869 defer p.trace("unaryExpr")()
873 case _Operator, _Star:
875 case Mul, Add, Sub, Not, Xor, Tilde:
888 // unaryExpr may have returned a parenthesized composite literal
889 // (see comment in operand) - remove parentheses if any
890 x.X = Unparen(p.unaryExpr())
895 // receive op (<-x) or receive-only channel (<-chan E)
899 // If the next token is _Chan we still don't know if it is
900 // a channel (<-chan int) or a receive op (<-chan int(ch)).
901 // We only know once we have found the end of the unaryExpr.
905 // There are two cases:
907 // <-chan... => <-x is a channel type
908 // <-x => <-x is a receive operation
910 // In the first case, <- must be re-associated with
911 // the channel type parsed already:
913 // <-(chan E) => (<-chan E)
914 // <-(chan<-E) => (<-chan (<-E))
916 if _, ok := x.(*ChanType); ok {
917 // x is a channel type => re-associate <-
920 for dir == SendOnly {
921 c, ok := t.(*ChanType)
927 // t is type <-chan E but <-<-chan E is not permitted
928 // (report same error as for "type _ <-<-chan E")
929 p.syntaxError("unexpected <-, expected chan")
930 // already progressed, no need to advance
936 // channel dir is <- but channel element E is not a channel
937 // (report same error as for "type _ <-chan<-E")
938 p.syntaxError(fmt.Sprintf("unexpected %s, expected chan", String(t)))
939 // already progressed, no need to advance
944 // x is not a channel type => we have a receive op
952 // TODO(mdempsky): We need parens here so we can report an
953 // error for "(x) := true". It should be possible to detect
954 // and reject that more efficiently though.
955 return p.pexpr(nil, true)
958 // callStmt parses call-like statements that can be preceded by 'defer' and 'go'.
959 func (p *parser) callStmt() *CallStmt {
961 defer p.trace("callStmt")()
966 s.Tok = p.tok // _Defer or _Go
969 x := p.pexpr(nil, p.tok == _Lparen) // keep_parens so we can report error below
970 if t := Unparen(x); t != x {
971 p.errorAt(x.Pos(), fmt.Sprintf("expression in %s must not be parenthesized", s.Tok))
972 // already progressed, no need to advance
980 // Operand = Literal | OperandName | MethodExpr | "(" Expression ")" .
981 // Literal = BasicLit | CompositeLit | FunctionLit .
982 // BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
983 // OperandName = identifier | QualifiedIdent.
984 func (p *parser) operand(keep_parens bool) Expr {
986 defer p.trace("operand " + p.tok.String())()
1004 // Optimization: Record presence of ()'s only where needed
1005 // for error reporting. Don't bother in other cases; it is
1006 // just a waste of memory and time.
1008 // Parentheses are not permitted around T in a composite
1009 // literal T{}. If the next token is a {, assume x is a
1010 // composite literal type T (it may not be, { could be
1011 // the opening brace of a block, but we don't know yet).
1012 if p.tok == _Lbrace {
1016 // Parentheses are also not permitted around the expression
1017 // in a go/defer statement. In that case, operand is called
1018 // with keep_parens set.
1020 px := new(ParenExpr)
1030 _, ftyp := p.funcType("function type")
1031 if p.tok == _Lbrace {
1037 f.Body = p.funcBody()
1044 case _Lbrack, _Chan, _Map, _Struct, _Interface:
1045 return p.type_() // othertype
1049 p.syntaxError("expected expression")
1050 p.advance(_Rparen, _Rbrack, _Rbrace)
1054 // Syntactically, composite literals are operands. Because a complit
1055 // type may be a qualified identifier which is handled by pexpr
1056 // (together with selector expressions), complits are parsed there
1057 // as well (operand is only called from pexpr).
1060 // pexpr parses a PrimaryExpr.
1065 // PrimaryExpr Selector |
1066 // PrimaryExpr Index |
1067 // PrimaryExpr Slice |
1068 // PrimaryExpr TypeAssertion |
1069 // PrimaryExpr Arguments .
1071 // Selector = "." identifier .
1072 // Index = "[" Expression "]" .
1073 // Slice = "[" ( [ Expression ] ":" [ Expression ] ) |
1074 // ( [ Expression ] ":" Expression ":" Expression )
1076 // TypeAssertion = "." "(" Type ")" .
1077 // Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
1078 func (p *parser) pexpr(x Expr, keep_parens bool) Expr {
1080 defer p.trace("pexpr")()
1084 x = p.operand(keep_parens)
1096 t := new(SelectorExpr)
1105 t := new(TypeSwitchGuard)
1106 // t.Lhs is filled in by parser.simpleStmt
1111 t := new(AssertExpr)
1120 p.syntaxError("expected name or (")
1121 p.advance(_Semi, _Rparen)
1128 if p.tok != _Colon {
1130 if p.tok == _Rbrack {
1131 // invalid empty instance, slice or index expression; accept but complain
1132 p.syntaxError("expected operand")
1135 i, comma = p.typeList(false)
1137 if comma || p.tok == _Rbrack {
1139 // x[], x[i,] or x[i, j, ...]
1150 // For better error message, don't simply use p.want(_Colon) here (issue #47704).
1152 p.syntaxError("expected comma, : or ]")
1153 p.advance(_Comma, _Colon, _Rbrack)
1160 if p.tok != _Colon && p.tok != _Rbrack {
1162 t.Index[1] = p.expr()
1164 if p.tok == _Colon {
1167 if t.Index[1] == nil {
1168 p.error("middle index required in 3-index slice")
1169 t.Index[1] = p.badExpr()
1172 if p.tok != _Rbrack {
1174 t.Index[2] = p.expr()
1176 p.error("final index required in 3-index slice")
1177 t.Index[2] = p.badExpr()
1189 t.ArgList, t.HasDots = p.argList()
1193 // operand may have returned a parenthesized complit
1194 // type; accept it but complain if we have a complit
1196 // determine if '{' belongs to a composite literal or a block statement
1199 case *Name, *SelectorExpr:
1201 // x is possibly a composite literal type
1205 if p.xnest >= 0 && !isValue(t) {
1206 // x is possibly a composite literal type
1209 case *ArrayType, *SliceType, *StructType, *MapType:
1217 p.syntaxError("cannot parenthesize type in composite literal")
1218 // already progressed, no need to advance
1220 n := p.complitexpr()
1232 // isValue reports whether x syntactically must be a value (and not a type) expression.
1233 func isValue(x Expr) bool {
1234 switch x := x.(type) {
1235 case *BasicLit, *CompositeLit, *FuncLit, *SliceExpr, *AssertExpr, *TypeSwitchGuard, *CallExpr:
1238 return x.Op != Mul || x.Y != nil // *T may be a type
1242 return isValue(x.X) || isValue(x.Index)
1247 // Element = Expression | LiteralValue .
1248 func (p *parser) bare_complitexpr() Expr {
1250 defer p.trace("bare_complitexpr")()
1253 if p.tok == _Lbrace {
1254 // '{' start_complit braced_keyval_list '}'
1255 return p.complitexpr()
1261 // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
1262 func (p *parser) complitexpr() *CompositeLit {
1264 defer p.trace("complitexpr")()
1267 x := new(CompositeLit)
1272 x.Rbrace = p.list("composite literal", _Comma, _Rbrace, func() bool {
1274 e := p.bare_complitexpr()
1275 if p.tok == _Colon {
1277 l := new(KeyValueExpr)
1281 l.Value = p.bare_complitexpr()
1285 x.ElemList = append(x.ElemList, e)
1293 // ----------------------------------------------------------------------------
1296 func (p *parser) type_() Expr {
1298 defer p.trace("type_")()
1301 typ := p.typeOrNil()
1304 p.syntaxError("expected type")
1305 p.advance(_Comma, _Colon, _Semi, _Rparen, _Rbrack, _Rbrace)
1311 func newIndirect(pos Pos, typ Expr) Expr {
1319 // typeOrNil is like type_ but it returns nil if there was no type
1320 // instead of reporting an error.
1322 // Type = TypeName | TypeLit | "(" Type ")" .
1323 // TypeName = identifier | QualifiedIdent .
1324 // TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
1325 // SliceType | MapType | Channel_Type .
1326 func (p *parser) typeOrNil() Expr {
1328 defer p.trace("typeOrNil")()
1336 return newIndirect(pos, p.type_())
1345 t.Elem = p.chanElem()
1351 _, t := p.funcType("function type")
1355 // '[' oexpr ']' ntype
1356 // '[' _DotDotDot ']' ntype
1359 return p.sliceType(pos)
1361 return p.arrayType(pos, nil)
1364 // _Chan non_recvchantype
1365 // _Chan _Comm ntype
1372 t.Elem = p.chanElem()
1376 // _Map '[' ntype ']' ntype
1387 return p.structType()
1390 return p.interfaceType()
1393 return p.qualifiedName(nil)
1405 func (p *parser) typeInstance(typ Expr) Expr {
1407 defer p.trace("typeInstance")()
1415 if p.tok == _Rbrack {
1416 p.syntaxError("expected type argument list")
1417 x.Index = p.badExpr()
1419 x.Index, _ = p.typeList(true)
1425 // If context != "", type parameters are not permitted.
1426 func (p *parser) funcType(context string) ([]*Field, *FuncType) {
1428 defer p.trace("funcType")()
1431 typ := new(FuncType)
1434 var tparamList []*Field
1437 // accept but complain
1438 p.syntaxErrorAt(typ.pos, context+" must have no type parameters")
1440 if p.tok == _Rbrack {
1441 p.syntaxError("empty type parameter list")
1444 tparamList = p.paramList(nil, nil, _Rbrack, true)
1449 typ.ParamList = p.paramList(nil, nil, _Rparen, false)
1450 typ.ResultList = p.funcResult()
1452 return tparamList, typ
1455 // "[" has already been consumed, and pos is its position.
1456 // If len != nil it is the already consumed array length.
1457 func (p *parser) arrayType(pos Pos, len Expr) Expr {
1459 defer p.trace("arrayType")()
1462 if len == nil && !p.got(_DotDotDot) {
1467 if p.tok == _Comma {
1468 // Trailing commas are accepted in type parameter
1469 // lists but not in array type declarations.
1470 // Accept for better error handling but complain.
1471 p.syntaxError("unexpected comma; expected ]")
1482 // "[" and "]" have already been consumed, and pos is the position of "[".
1483 func (p *parser) sliceType(pos Pos) Expr {
1490 func (p *parser) chanElem() Expr {
1492 defer p.trace("chanElem")()
1495 typ := p.typeOrNil()
1498 p.syntaxError("missing channel element type")
1499 // assume element type is simply absent - don't advance
1505 // StructType = "struct" "{" { FieldDecl ";" } "}" .
1506 func (p *parser) structType() *StructType {
1508 defer p.trace("structType")()
1511 typ := new(StructType)
1516 p.list("struct type", _Semi, _Rbrace, func() bool {
1524 // InterfaceType = "interface" "{" { ( MethodDecl | EmbeddedElem ) ";" } "}" .
1525 func (p *parser) interfaceType() *InterfaceType {
1527 defer p.trace("interfaceType")()
1530 typ := new(InterfaceType)
1535 p.list("interface type", _Semi, _Rbrace, func() bool {
1540 if f == nil || f.Name == nil {
1541 f = p.embeddedElem(f)
1543 typ.MethodList = append(typ.MethodList, f)
1550 // Result = Parameters | Type .
1551 func (p *parser) funcResult() []*Field {
1553 defer p.trace("funcResult")()
1557 return p.paramList(nil, nil, _Rparen, false)
1561 if typ := p.typeOrNil(); typ != nil {
1571 func (p *parser) addField(styp *StructType, pos Pos, name *Name, typ Expr, tag *BasicLit) {
1573 for i := len(styp.FieldList) - len(styp.TagList); i > 0; i-- {
1574 styp.TagList = append(styp.TagList, nil)
1576 styp.TagList = append(styp.TagList, tag)
1583 styp.FieldList = append(styp.FieldList, f)
1585 if debug && tag != nil && len(styp.FieldList) != len(styp.TagList) {
1586 panic("inconsistent struct field list")
1590 // FieldDecl = (IdentifierList Type | AnonymousField) [ Tag ] .
1591 // AnonymousField = [ "*" ] TypeName .
1592 // Tag = string_lit .
1593 func (p *parser) fieldDecl(styp *StructType) {
1595 defer p.trace("fieldDecl")()
1602 if p.tok == _Dot || p.tok == _Literal || p.tok == _Semi || p.tok == _Rbrace {
1604 typ := p.qualifiedName(name)
1606 p.addField(styp, pos, nil, typ, tag)
1610 // name1, name2, ... Type [ tag ]
1611 names := p.nameList(name)
1614 // Careful dance: We don't know if we have an embedded instantiated
1615 // type T[P1, P2, ...] or a field T of array/slice type [P]E or []E.
1616 if len(names) == 1 && p.tok == _Lbrack {
1617 typ = p.arrayOrTArgs()
1618 if typ, ok := typ.(*IndexExpr); ok {
1619 // embedded type T[P1, P2, ...]
1620 typ.X = name // name == names[0]
1622 p.addField(styp, pos, nil, typ, tag)
1632 for _, name := range names {
1633 p.addField(styp, name.Pos(), name, typ, tag)
1639 if p.tok == _Lparen {
1641 p.syntaxError("cannot parenthesize embedded type")
1643 typ = p.qualifiedName(nil)
1644 p.got(_Rparen) // no need to complain if missing
1647 typ = p.qualifiedName(nil)
1650 p.addField(styp, pos, nil, newIndirect(pos, typ), tag)
1653 p.syntaxError("cannot parenthesize embedded type")
1660 typ = newIndirect(pos, p.qualifiedName(nil))
1663 typ = p.qualifiedName(nil)
1665 p.got(_Rparen) // no need to complain if missing
1667 p.addField(styp, pos, nil, typ, tag)
1670 p.syntaxError("expected field name or embedded type")
1671 p.advance(_Semi, _Rbrace)
1675 func (p *parser) arrayOrTArgs() Expr {
1677 defer p.trace("arrayOrTArgs")()
1683 return p.sliceType(pos)
1686 // x [n]E or x[n,], x[n1, n2], ...
1687 n, comma := p.typeList(false)
1690 if elem := p.typeOrNil(); elem != nil {
1700 // x[n,], x[n1, n2], ...
1703 // t.X will be filled in by caller
1708 func (p *parser) oliteral() *BasicLit {
1709 if p.tok == _Literal {
1721 // MethodSpec = MethodName Signature | InterfaceTypeName .
1722 // MethodName = identifier .
1723 // InterfaceTypeName = TypeName .
1724 func (p *parser) methodDecl() *Field {
1726 defer p.trace("methodDecl")()
1733 const context = "interface method"
1739 _, f.Type = p.funcType(context)
1742 // Careful dance: We don't know if we have a generic method m[T C](x T)
1743 // or an embedded instantiated type T[P1, P2] (we accept generic methods
1744 // for generality and robustness of parsing but complain with an error).
1748 // Empty type parameter or argument lists are not permitted.
1749 // Treat as if [] were absent.
1750 if p.tok == _Rbrack {
1754 if p.tok == _Lparen {
1756 p.errorAt(pos, "empty type parameter list")
1758 _, f.Type = p.funcType(context)
1760 p.errorAt(pos, "empty type argument list")
1766 // A type argument list looks like a parameter list with only
1767 // types. Parse a parameter list and decide afterwards.
1768 list := p.paramList(nil, nil, _Rbrack, false)
1770 // The type parameter list is not [] but we got nothing
1771 // due to other errors (reported by paramList). Treat
1772 // as if [] were absent.
1773 if p.tok == _Lparen {
1775 _, f.Type = p.funcType(context)
1783 if list[0].Name != nil {
1786 _, f.Type = p.funcType(context)
1787 p.errorAt(pos, "interface method must have no type parameters")
1791 // embedded instantiated type
1796 t.Index = list[0].Type
1800 l.pos = list[0].Pos()
1801 l.ElemList = make([]Expr, len(list))
1802 for i := range list {
1803 l.ElemList[i] = list[i].Type
1811 f.Type = p.qualifiedName(name)
1817 // EmbeddedElem = MethodSpec | EmbeddedTerm { "|" EmbeddedTerm } .
1818 func (p *parser) embeddedElem(f *Field) *Field {
1820 defer p.trace("embeddedElem")()
1826 f.Type = p.embeddedTerm()
1829 for p.tok == _Operator && p.op == Or {
1835 t.Y = p.embeddedTerm()
1842 // EmbeddedTerm = [ "~" ] Type .
1843 func (p *parser) embeddedTerm() Expr {
1845 defer p.trace("embeddedTerm")()
1848 if p.tok == _Operator && p.op == Tilde {
1860 p.syntaxError("expected ~ term or type")
1861 p.advance(_Operator, _Semi, _Rparen, _Rbrack, _Rbrace)
1867 // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
1868 func (p *parser) paramDeclOrNil(name *Name, follow token) *Field {
1870 defer p.trace("paramDeclOrNil")()
1873 // type set notation is ok in type parameter lists
1874 typeSetsOk := follow == _Rbrack
1879 } else if typeSetsOk && p.tok == _Operator && p.op == Tilde {
1881 return p.embeddedElem(nil)
1887 if p.tok == _Name || name != nil {
1893 if p.tok == _Lbrack {
1895 f.Type = p.arrayOrTArgs()
1896 if typ, ok := f.Type.(*IndexExpr); ok {
1903 if typeSetsOk && p.tok == _Operator && p.op == Or {
1904 // name "[" ... "]" "|" ...
1905 // name "[" n "]" E "|" ...
1906 f = p.embeddedElem(f)
1913 f.Type = p.qualifiedName(name)
1914 if typeSetsOk && p.tok == _Operator && p.op == Or {
1915 // name "." name "|" ...
1916 f = p.embeddedElem(f)
1921 if typeSetsOk && p.tok == _Operator && p.op == Or {
1924 return p.embeddedElem(f)
1930 if p.tok == _DotDotDot {
1935 t.Elem = p.typeOrNil()
1937 t.Elem = p.badExpr()
1938 p.syntaxError("... is missing type")
1944 if typeSetsOk && p.tok == _Operator && p.op == Tilde {
1946 f.Type = p.embeddedElem(nil).Type
1950 f.Type = p.typeOrNil()
1951 if typeSetsOk && p.tok == _Operator && p.op == Or && f.Type != nil {
1953 f = p.embeddedElem(f)
1955 if f.Name != nil || f.Type != nil {
1959 p.syntaxError("expected " + tokstring(follow))
1960 p.advance(_Comma, follow)
1964 // Parameters = "(" [ ParameterList [ "," ] ] ")" .
1965 // ParameterList = ParameterDecl { "," ParameterDecl } .
1966 // "(" or "[" has already been consumed.
1967 // If name != nil, it is the first name after "(" or "[".
1968 // If typ != nil, name must be != nil, and (name, typ) is the first field in the list.
1969 // In the result list, either all fields have a name, or no field has a name.
1970 func (p *parser) paramList(name *Name, typ Expr, close token, requireNames bool) (list []*Field) {
1972 defer p.trace("paramList")()
1975 // p.list won't invoke its function argument if we're at the end of the
1976 // parameter list. If we have a complete field, handle this case here.
1977 if name != nil && typ != nil && p.tok == close {
1983 return []*Field{par}
1986 var named int // number of parameters that have an explicit name and type
1987 var typed int // number of parameters that have an explicit type
1988 end := p.list("parameter list", _Comma, close, func() bool {
1991 if debug && name == nil {
1992 panic("initial type provided without name")
1999 par = p.paramDeclOrNil(name, close)
2001 name = nil // 1st name was consumed if present
2002 typ = nil // 1st type was consumed if present
2004 if debug && par.Name == nil && par.Type == nil {
2005 panic("parameter without name or type")
2007 if par.Name != nil && par.Type != nil {
2010 if par.Type != nil {
2013 list = append(list, par)
2022 // distribute parameter types (len(list) > 0)
2023 if named == 0 && !requireNames {
2024 // all unnamed => found names are named types
2025 for _, par := range list {
2026 if typ := par.Name; typ != nil {
2031 } else if named != len(list) {
2032 // some named => all must have names and types
2033 var pos Pos // left-most error position (or unknown)
2034 var typ Expr // current type (from right to left)
2035 for i := len(list) - 1; i >= 0; i-- {
2037 if par.Type != nil {
2039 if par.Name == nil {
2041 par.Name = NewName(pos, "_")
2043 } else if typ != nil {
2046 // par.Type == nil && typ == nil => we only have a par.Name
2047 pos = par.Name.Pos()
2049 t.pos = pos // correct position
2057 pos = end // position error at closing ]
2058 msg = "missing type constraint"
2060 msg = "type parameters must be named"
2063 msg = "mixed named and unnamed parameters"
2065 p.syntaxErrorAt(pos, msg)
2072 func (p *parser) badExpr() *BadExpr {
2078 // ----------------------------------------------------------------------------
2081 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
2082 func (p *parser) simpleStmt(lhs Expr, keyword token) SimpleStmt {
2084 defer p.trace("simpleStmt")()
2087 if keyword == _For && p.tok == _Range {
2089 if debug && lhs != nil {
2090 panic("invalid call of simpleStmt")
2092 return p.newRangeClause(nil, false)
2099 if _, ok := lhs.(*ListExpr); !ok && p.tok != _Assign && p.tok != _Define {
2107 return p.newAssignStmt(pos, op, lhs, p.expr())
2113 return p.newAssignStmt(pos, op, lhs, nil)
2135 case _Assign, _Define:
2138 if p.tok == _Define {
2143 if keyword == _For && p.tok == _Range {
2144 // expr_list op= _Range expr
2145 return p.newRangeClause(lhs, op == Def)
2148 // expr_list op= expr_list
2151 if x, ok := rhs.(*TypeSwitchGuard); ok && keyword == _Switch && op == Def {
2152 if lhs, ok := lhs.(*Name); ok {
2153 // switch … lhs := rhs.(type)
2162 return p.newAssignStmt(pos, op, lhs, rhs)
2165 p.syntaxError("expected := or = or comma")
2166 p.advance(_Semi, _Rbrace)
2167 // make the best of what we have
2168 if x, ok := lhs.(*ListExpr); ok {
2178 func (p *parser) newRangeClause(lhs Expr, def bool) *RangeClause {
2179 r := new(RangeClause)
2181 p.next() // consume _Range
2188 func (p *parser) newAssignStmt(pos Pos, op Operator, lhs, rhs Expr) *AssignStmt {
2189 a := new(AssignStmt)
2197 func (p *parser) labeledStmtOrNil(label *Name) Stmt {
2199 defer p.trace("labeledStmt")()
2202 s := new(LabeledStmt)
2208 if p.tok == _Rbrace {
2209 // We expect a statement (incl. an empty statement), which must be
2210 // terminated by a semicolon. Because semicolons may be omitted before
2211 // an _Rbrace, seeing an _Rbrace implies an empty statement.
2218 s.Stmt = p.stmtOrNil()
2223 // report error at line of ':' token
2224 p.syntaxErrorAt(s.pos, "missing statement after label")
2225 // we are already at the end of the labeled statement - no need to advance
2226 return nil // avoids follow-on errors (see e.g., fixedbugs/bug274.go)
2229 // context must be a non-empty string unless we know that p.tok == _Lbrace.
2230 func (p *parser) blockStmt(context string) *BlockStmt {
2232 defer p.trace("blockStmt")()
2238 // people coming from C may forget that braces are mandatory in Go
2239 if !p.got(_Lbrace) {
2240 p.syntaxError("expected { after " + context)
2241 p.advance(_Name, _Rbrace)
2242 s.Rbrace = p.pos() // in case we found "}"
2248 s.List = p.stmtList()
2255 func (p *parser) declStmt(f func(*Group) Decl) *DeclStmt {
2257 defer p.trace("declStmt")()
2263 p.next() // _Const, _Type, or _Var
2264 s.DeclList = p.appendGroup(nil, f)
2269 func (p *parser) forStmt() Stmt {
2271 defer p.trace("forStmt")()
2277 s.Init, s.Cond, s.Post = p.header(_For)
2278 s.Body = p.blockStmt("for clause")
2283 func (p *parser) header(keyword token) (init SimpleStmt, cond Expr, post SimpleStmt) {
2286 if p.tok == _Lbrace {
2288 p.syntaxError("missing condition in if statement")
2299 // accept potential varDecl but complain
2301 p.syntaxError(fmt.Sprintf("var declaration not allowed in %s initializer", tokstring(keyword)))
2303 init = p.simpleStmt(nil, keyword)
2304 // If we have a range clause, we are done (can only happen for keyword == _For).
2305 if _, ok := init.(*RangeClause); ok {
2311 var condStmt SimpleStmt
2314 lit string // valid if pos.IsKnown()
2316 if p.tok != _Lbrace {
2322 // asking for a '{' rather than a ';' here leads to a better error message
2324 if p.tok != _Lbrace {
2325 p.advance(_Lbrace, _Rbrace) // for better synchronization (e.g., issue #22581)
2328 if keyword == _For {
2330 if p.tok == _Lbrace {
2331 p.syntaxError("expected for loop condition")
2334 condStmt = p.simpleStmt(nil, 0 /* range not permitted */)
2337 if p.tok != _Lbrace {
2338 post = p.simpleStmt(nil, 0 /* range not permitted */)
2339 if a, _ := post.(*AssignStmt); a != nil && a.Op == Def {
2340 p.syntaxErrorAt(a.Pos(), "cannot declare in post statement of for loop")
2343 } else if p.tok != _Lbrace {
2344 condStmt = p.simpleStmt(nil, keyword)
2353 switch s := condStmt.(type) {
2355 if keyword == _If && semi.pos.IsKnown() {
2356 if semi.lit != "semicolon" {
2357 p.syntaxErrorAt(semi.pos, fmt.Sprintf("unexpected %s, expected { after if clause", semi.lit))
2359 p.syntaxErrorAt(semi.pos, "missing condition in if statement")
2368 // A common syntax error is to write '=' instead of '==',
2369 // which turns an expression into an assignment. Provide
2370 // a more explicit error message in that case to prevent
2371 // further confusion.
2373 if as, ok := s.(*AssignStmt); ok && as.Op == 0 {
2374 // Emphasize complex Lhs and Rhs of assignment with parentheses to highlight '='.
2375 str = "assignment " + emphasize(as.Lhs) + " = " + emphasize(as.Rhs)
2379 p.syntaxErrorAt(s.Pos(), fmt.Sprintf("cannot use %s as value", str))
2386 // emphasize returns a string representation of x, with (top-level)
2387 // binary expressions emphasized by enclosing them in parentheses.
2388 func emphasize(x Expr) string {
2390 if op, _ := x.(*Operation); op != nil && op.Y != nil {
2391 // binary expression
2392 return "(" + s + ")"
2397 func (p *parser) ifStmt() *IfStmt {
2399 defer p.trace("ifStmt")()
2405 s.Init, s.Cond, _ = p.header(_If)
2406 s.Then = p.blockStmt("if clause")
2413 s.Else = p.blockStmt("")
2415 p.syntaxError("else must be followed by if or statement block")
2416 p.advance(_Name, _Rbrace)
2423 func (p *parser) switchStmt() *SwitchStmt {
2425 defer p.trace("switchStmt")()
2428 s := new(SwitchStmt)
2431 s.Init, s.Tag, _ = p.header(_Switch)
2433 if !p.got(_Lbrace) {
2434 p.syntaxError("missing { after switch clause")
2435 p.advance(_Case, _Default, _Rbrace)
2437 for p.tok != _EOF && p.tok != _Rbrace {
2438 s.Body = append(s.Body, p.caseClause())
2446 func (p *parser) selectStmt() *SelectStmt {
2448 defer p.trace("selectStmt")()
2451 s := new(SelectStmt)
2455 if !p.got(_Lbrace) {
2456 p.syntaxError("missing { after select clause")
2457 p.advance(_Case, _Default, _Rbrace)
2459 for p.tok != _EOF && p.tok != _Rbrace {
2460 s.Body = append(s.Body, p.commClause())
2468 func (p *parser) caseClause() *CaseClause {
2470 defer p.trace("caseClause")()
2473 c := new(CaseClause)
2479 c.Cases = p.exprList()
2485 p.syntaxError("expected case or default or }")
2486 p.advance(_Colon, _Case, _Default, _Rbrace)
2491 c.Body = p.stmtList()
2496 func (p *parser) commClause() *CommClause {
2498 defer p.trace("commClause")()
2501 c := new(CommClause)
2507 c.Comm = p.simpleStmt(nil, 0)
2509 // The syntax restricts the possible simple statements here to:
2511 // lhs <- x (send statement)
2516 // All these (and more) are recognized by simpleStmt and invalid
2517 // syntax trees are flagged later, during type checking.
2523 p.syntaxError("expected case or default or }")
2524 p.advance(_Colon, _Case, _Default, _Rbrace)
2529 c.Body = p.stmtList()
2534 // stmtOrNil parses a statement if one is present, or else returns nil.
2537 // Declaration | LabeledStmt | SimpleStmt |
2538 // GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
2539 // FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
2541 func (p *parser) stmtOrNil() Stmt {
2543 defer p.trace("stmt " + p.tok.String())()
2546 // Most statements (assignments) start with an identifier;
2547 // look for it first before doing anything more expensive.
2551 if label, ok := lhs.(*Name); ok && p.tok == _Colon {
2552 return p.labeledStmtOrNil(label)
2554 return p.simpleStmt(lhs, 0)
2559 return p.declStmt(p.varDecl)
2562 return p.declStmt(p.constDecl)
2565 return p.declStmt(p.typeDecl)
2572 return p.blockStmt("")
2574 case _Operator, _Star:
2576 case Add, Sub, Mul, And, Xor, Not:
2577 return p.simpleStmt(nil, 0) // unary operators
2580 case _Literal, _Func, _Lparen, // operands
2581 _Lbrack, _Struct, _Map, _Chan, _Interface, // composite types
2582 _Arrow: // receive operator
2583 return p.simpleStmt(nil, 0)
2589 return p.switchStmt()
2592 return p.selectStmt()
2598 s := new(BranchStmt)
2601 s.Tok = _Fallthrough
2604 case _Break, _Continue:
2605 s := new(BranchStmt)
2618 s := new(BranchStmt)
2626 s := new(ReturnStmt)
2629 if p.tok != _Semi && p.tok != _Rbrace {
2630 s.Results = p.exprList()
2643 // StatementList = { Statement ";" } .
2644 func (p *parser) stmtList() (l []Stmt) {
2646 defer p.trace("stmtList")()
2649 for p.tok != _EOF && p.tok != _Rbrace && p.tok != _Case && p.tok != _Default {
2656 // ";" is optional before "}"
2657 if !p.got(_Semi) && p.tok != _Rbrace {
2658 p.syntaxError("at end of statement")
2659 p.advance(_Semi, _Rbrace, _Case, _Default)
2660 p.got(_Semi) // avoid spurious empty statement
2666 // argList parses a possibly empty, comma-separated list of arguments,
2667 // optionally followed by a comma (if not empty), and closed by ")".
2668 // The last argument may be followed by "...".
2670 // argList = [ arg { "," arg } [ "..." ] [ "," ] ] ")" .
2671 func (p *parser) argList() (list []Expr, hasDots bool) {
2673 defer p.trace("argList")()
2677 p.list("argument list", _Comma, _Rparen, func() bool {
2678 list = append(list, p.expr())
2679 hasDots = p.got(_DotDotDot)
2687 // ----------------------------------------------------------------------------
2688 // Common productions
2690 func (p *parser) name() *Name {
2691 // no tracing to avoid overly verbose output
2694 n := NewName(p.pos(), p.lit)
2699 n := NewName(p.pos(), "_")
2700 p.syntaxError("expected name")
2705 // IdentifierList = identifier { "," identifier } .
2706 // The first name must be provided.
2707 func (p *parser) nameList(first *Name) []*Name {
2709 defer p.trace("nameList")()
2712 if debug && first == nil {
2713 panic("first name not provided")
2718 l = append(l, p.name())
2724 // The first name may be provided, or nil.
2725 func (p *parser) qualifiedName(name *Name) Expr {
2727 defer p.trace("qualifiedName")()
2734 case p.tok == _Name:
2737 x = NewName(p.pos(), "_")
2738 p.syntaxError("expected name")
2739 p.advance(_Dot, _Semi, _Rbrace)
2743 s := new(SelectorExpr)
2751 if p.tok == _Lbrack {
2752 x = p.typeInstance(x)
2758 // ExpressionList = Expression { "," Expression } .
2759 func (p *parser) exprList() Expr {
2761 defer p.trace("exprList")()
2766 list := []Expr{x, p.expr()}
2768 list = append(list, p.expr())
2778 // typeList parses a non-empty, comma-separated list of types,
2779 // optionally followed by a comma. If strict is set to false,
2780 // the first element may also be a (non-type) expression.
2781 // If there is more than one argument, the result is a *ListExpr.
2782 // The comma result indicates whether there was a (separating or
2785 // typeList = arg { "," arg } [ "," ] .
2786 func (p *parser) typeList(strict bool) (x Expr, comma bool) {
2788 defer p.trace("typeList")()
2799 if t := p.typeOrNil(); t != nil {
2800 list := []Expr{x, t}
2802 if t = p.typeOrNil(); t == nil {
2805 list = append(list, t)
2808 l.pos = x.Pos() // == list[0].Pos()
2817 // Unparen returns e with any enclosing parentheses stripped.
2818 func Unparen(x Expr) Expr {
2820 p, ok := x.(*ParenExpr)
2829 // UnpackListExpr unpacks a *ListExpr into a []Expr.
2830 func UnpackListExpr(x Expr) []Expr {
2831 switch x := x.(type) {