OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [go/] [parser/] [parser.go] - Blame information for rev 747

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.