Source file src/pkg/go/ast/ast.go
1 // 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 ast declares the types used to represent syntax trees for Go
6 // packages.
7 //
8 package ast
9
10 import (
11 "go/token"
12 "strings"
13 "unicode"
14 "unicode/utf8"
15 )
16
17 // ----------------------------------------------------------------------------
18 // Interfaces
19 //
20 // There are 3 main classes of nodes: Expressions and type nodes,
21 // statement nodes, and declaration nodes. The node names usually
22 // match the corresponding Go spec production names to which they
23 // correspond. The node fields correspond to the individual parts
24 // of the respective productions.
25 //
26 // All nodes contain position information marking the beginning of
27 // the corresponding source text segment; it is accessible via the
28 // Pos accessor method. Nodes may contain additional position info
29 // for language constructs where comments may be found between parts
30 // of the construct (typically any larger, parenthesized subpart).
31 // That position information is needed to properly position comments
32 // when printing the construct.
33
34 // All node types implement the Node interface.
35 type Node interface {
36 Pos() token.Pos // position of first character belonging to the node
37 End() token.Pos // position of first character immediately after the node
38 }
39
40 // All expression nodes implement the Expr interface.
41 type Expr interface {
42 Node
43 exprNode()
44 }
45
46 // All statement nodes implement the Stmt interface.
47 type Stmt interface {
48 Node
49 stmtNode()
50 }
51
52 // All declaration nodes implement the Decl interface.
53 type Decl interface {
54 Node
55 declNode()
56 }
57
58 // ----------------------------------------------------------------------------
59 // Comments
60
61 // A Comment node represents a single //-style or /*-style comment.
62 type Comment struct {
63 Slash token.Pos // position of "/" starting the comment
64 Text string // comment text (excluding '\n' for //-style comments)
65 }
66
67 func (c *Comment) Pos() token.Pos { return c.Slash }
68 func (c *Comment) End() token.Pos { return token.Pos(int(c.Slash) + len(c.Text)) }
69
70 // A CommentGroup represents a sequence of comments
71 // with no other tokens and no empty lines between.
72 //
73 type CommentGroup struct {
74 List []*Comment // len(List) > 0
75 }
76
77 func (g *CommentGroup) Pos() token.Pos { return g.List[0].Pos() }
78 func (g *CommentGroup) End() token.Pos { return g.List[len(g.List)-1].End() }
79
80 func isWhitespace(ch byte) bool { return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' }
81
82 func stripTrailingWhitespace(s string) string {
83 i := len(s)
84 for i > 0 && isWhitespace(s[i-1]) {
85 i--
86 }
87 return s[0:i]
88 }
89
90 // Text returns the text of the comment,
91 // with the comment markers - //, /*, and */ - removed.
92 func (g *CommentGroup) Text() string {
93 if g == nil {
94 return ""
95 }
96 comments := make([]string, len(g.List))
97 for i, c := range g.List {
98 comments[i] = string(c.Text)
99 }
100
101 lines := make([]string, 0, 10) // most comments are less than 10 lines
102 for _, c := range comments {
103 // Remove comment markers.
104 // The parser has given us exactly the comment text.
105 switch c[1] {
106 case '/':
107 //-style comment
108 c = c[2:]
109 // Remove leading space after //, if there is one.
110 // TODO(gri) This appears to be necessary in isolated
111 // cases (bignum.RatFromString) - why?
112 if len(c) > 0 && c[0] == ' ' {
113 c = c[1:]
114 }
115 case '*':
116 /*-style comment */
117 c = c[2 : len(c)-2]
118 }
119
120 // Split on newlines.
121 cl := strings.Split(c, "\n")
122
123 // Walk lines, stripping trailing white space and adding to list.
124 for _, l := range cl {
125 lines = append(lines, stripTrailingWhitespace(l))
126 }
127 }
128
129 // Remove leading blank lines; convert runs of
130 // interior blank lines to a single blank line.
131 n := 0
132 for _, line := range lines {
133 if line != "" || n > 0 && lines[n-1] != "" {
134 lines[n] = line
135 n++
136 }
137 }
138 lines = lines[0:n]
139
140 // Add final "" entry to get trailing newline from Join.
141 if n > 0 && lines[n-1] != "" {
142 lines = append(lines, "")
143 }
144
145 return strings.Join(lines, "\n")
146 }
147
148 // ----------------------------------------------------------------------------
149 // Expressions and types
150
151 // A Field represents a Field declaration list in a struct type,
152 // a method list in an interface type, or a parameter/result declaration
153 // in a signature.
154 //
155 type Field struct {
156 Doc *CommentGroup // associated documentation; or nil
157 Names []*Ident // field/method/parameter names; or nil if anonymous field
158 Type Expr // field/method/parameter type
159 Tag *BasicLit // field tag; or nil
160 Comment *CommentGroup // line comments; or nil
161 }
162
163 func (f *Field) Pos() token.Pos {
164 if len(f.Names) > 0 {
165 return f.Names[0].Pos()
166 }
167 return f.Type.Pos()
168 }
169
170 func (f *Field) End() token.Pos {
171 if f.Tag != nil {
172 return f.Tag.End()
173 }
174 return f.Type.End()
175 }
176
177 // A FieldList represents a list of Fields, enclosed by parentheses or braces.
178 type FieldList struct {
179 Opening token.Pos // position of opening parenthesis/brace, if any
180 List []*Field // field list; or nil
181 Closing token.Pos // position of closing parenthesis/brace, if any
182 }
183
184 func (f *FieldList) Pos() token.Pos {
185 if f.Opening.IsValid() {
186 return f.Opening
187 }
188 // the list should not be empty in this case;
189 // be conservative and guard against bad ASTs
190 if len(f.List) > 0 {
191 return f.List[0].Pos()
192 }
193 return token.NoPos
194 }
195
196 func (f *FieldList) End() token.Pos {
197 if f.Closing.IsValid() {
198 return f.Closing + 1
199 }
200 // the list should not be empty in this case;
201 // be conservative and guard against bad ASTs
202 if n := len(f.List); n > 0 {
203 return f.List[n-1].End()
204 }
205 return token.NoPos
206 }
207
208 // NumFields returns the number of (named and anonymous fields) in a FieldList.
209 func (f *FieldList) NumFields() int {
210 n := 0
211 if f != nil {
212 for _, g := range f.List {
213 m := len(g.Names)
214 if m == 0 {
215 m = 1 // anonymous field
216 }
217 n += m
218 }
219 }
220 return n
221 }
222
223 // An expression is represented by a tree consisting of one
224 // or more of the following concrete expression nodes.
225 //
226 type (
227 // A BadExpr node is a placeholder for expressions containing
228 // syntax errors for which no correct expression nodes can be
229 // created.
230 //
231 BadExpr struct {
232 From, To token.Pos // position range of bad expression
233 }
234
235 // An Ident node represents an identifier.
236 Ident struct {
237 NamePos token.Pos // identifier position
238 Name string // identifier name
239 Obj *Object // denoted object; or nil
240 }
241
242 // An Ellipsis node stands for the "..." type in a
243 // parameter list or the "..." length in an array type.
244 //
245 Ellipsis struct {
246 Ellipsis token.Pos // position of "..."
247 Elt Expr // ellipsis element type (parameter lists only); or nil
248 }
249
250 // A BasicLit node represents a literal of basic type.
251 BasicLit struct {
252 ValuePos token.Pos // literal position
253 Kind token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING
254 Value string // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o`
255 }
256
257 // A FuncLit node represents a function literal.
258 FuncLit struct {
259 Type *FuncType // function type
260 Body *BlockStmt // function body
261 }
262
263 // A CompositeLit node represents a composite literal.
264 CompositeLit struct {
265 Type Expr // literal type; or nil
266 Lbrace token.Pos // position of "{"
267 Elts []Expr // list of composite elements; or nil
268 Rbrace token.Pos // position of "}"
269 }
270
271 // A ParenExpr node represents a parenthesized expression.
272 ParenExpr struct {
273 Lparen token.Pos // position of "("
274 X Expr // parenthesized expression
275 Rparen token.Pos // position of ")"
276 }
277
278 // A SelectorExpr node represents an expression followed by a selector.
279 SelectorExpr struct {
280 X Expr // expression
281 Sel *Ident // field selector
282 }
283
284 // An IndexExpr node represents an expression followed by an index.
285 IndexExpr struct {
286 X Expr // expression
287 Lbrack token.Pos // position of "["
288 Index Expr // index expression
289 Rbrack token.Pos // position of "]"
290 }
291
292 // An SliceExpr node represents an expression followed by slice indices.
293 SliceExpr struct {
294 X Expr // expression
295 Lbrack token.Pos // position of "["
296 Low Expr // begin of slice range; or nil
297 High Expr // end of slice range; or nil
298 Rbrack token.Pos // position of "]"
299 }
300
301 // A TypeAssertExpr node represents an expression followed by a
302 // type assertion.
303 //
304 TypeAssertExpr struct {
305 X Expr // expression
306 Type Expr // asserted type; nil means type switch X.(type)
307 }
308
309 // A CallExpr node represents an expression followed by an argument list.
310 CallExpr struct {
311 Fun Expr // function expression
312 Lparen token.Pos // position of "("
313 Args []Expr // function arguments; or nil
314 Ellipsis token.Pos // position of "...", if any
315 Rparen token.Pos // position of ")"
316 }
317
318 // A StarExpr node represents an expression of the form "*" Expression.
319 // Semantically it could be a unary "*" expression, or a pointer type.
320 //
321 StarExpr struct {
322 Star token.Pos // position of "*"
323 X Expr // operand
324 }
325
326 // A UnaryExpr node represents a unary expression.
327 // Unary "*" expressions are represented via StarExpr nodes.
328 //
329 UnaryExpr struct {
330 OpPos token.Pos // position of Op
331 Op token.Token // operator
332 X Expr // operand
333 }
334
335 // A BinaryExpr node represents a binary expression.
336 BinaryExpr struct {
337 X Expr // left operand
338 OpPos token.Pos // position of Op
339 Op token.Token // operator
340 Y Expr // right operand
341 }
342
343 // A KeyValueExpr node represents (key : value) pairs
344 // in composite literals.
345 //
346 KeyValueExpr struct {
347 Key Expr
348 Colon token.Pos // position of ":"
349 Value Expr
350 }
351 )
352
353 // The direction of a channel type is indicated by one
354 // of the following constants.
355 //
356 type ChanDir int
357
358 const (
359 SEND ChanDir = 1 << iota
360 RECV
361 )
362
363 // A type is represented by a tree consisting of one
364 // or more of the following type-specific expression
365 // nodes.
366 //
367 type (
368 // An ArrayType node represents an array or slice type.
369 ArrayType struct {
370 Lbrack token.Pos // position of "["
371 Len Expr // Ellipsis node for [...]T array types, nil for slice types
372 Elt Expr // element type
373 }
374
375 // A StructType node represents a struct type.
376 StructType struct {
377 Struct token.Pos // position of "struct" keyword
378 Fields *FieldList // list of field declarations
379 Incomplete bool // true if (source) fields are missing in the Fields list
380 }
381
382 // Pointer types are represented via StarExpr nodes.
383
384 // A FuncType node represents a function type.
385 FuncType struct {
386 Func token.Pos // position of "func" keyword
387 Params *FieldList // (incoming) parameters; or nil
388 Results *FieldList // (outgoing) results; or nil
389 }
390
391 // An InterfaceType node represents an interface type.
392 InterfaceType struct {
393 Interface token.Pos // position of "interface" keyword
394 Methods *FieldList // list of methods
395 Incomplete bool // true if (source) methods are missing in the Methods list
396 }
397
398 // A MapType node represents a map type.
399 MapType struct {
400 Map token.Pos // position of "map" keyword
401 Key Expr
402 Value Expr
403 }
404
405 // A ChanType node represents a channel type.
406 ChanType struct {
407 Begin token.Pos // position of "chan" keyword or "<-" (whichever comes first)
408 Dir ChanDir // channel direction
409 Value Expr // value type
410 }
411 )
412
413 // Pos and End implementations for expression/type nodes.
414 //
415 func (x *BadExpr) Pos() token.Pos { return x.From }
416 func (x *Ident) Pos() token.Pos { return x.NamePos }
417 func (x *Ellipsis) Pos() token.Pos { return x.Ellipsis }
418 func (x *BasicLit) Pos() token.Pos { return x.ValuePos }
419 func (x *FuncLit) Pos() token.Pos { return x.Type.Pos() }
420 func (x *CompositeLit) Pos() token.Pos {
421 if x.Type != nil {
422 return x.Type.Pos()
423 }
424 return x.Lbrace
425 }
426 func (x *ParenExpr) Pos() token.Pos { return x.Lparen }
427 func (x *SelectorExpr) Pos() token.Pos { return x.X.Pos() }
428 func (x *IndexExpr) Pos() token.Pos { return x.X.Pos() }
429 func (x *SliceExpr) Pos() token.Pos { return x.X.Pos() }
430 func (x *TypeAssertExpr) Pos() token.Pos { return x.X.Pos() }
431 func (x *CallExpr) Pos() token.Pos { return x.Fun.Pos() }
432 func (x *StarExpr) Pos() token.Pos { return x.Star }
433 func (x *UnaryExpr) Pos() token.Pos { return x.OpPos }
434 func (x *BinaryExpr) Pos() token.Pos { return x.X.Pos() }
435 func (x *KeyValueExpr) Pos() token.Pos { return x.Key.Pos() }
436 func (x *ArrayType) Pos() token.Pos { return x.Lbrack }
437 func (x *StructType) Pos() token.Pos { return x.Struct }
438 func (x *FuncType) Pos() token.Pos { return x.Func }
439 func (x *InterfaceType) Pos() token.Pos { return x.Interface }
440 func (x *MapType) Pos() token.Pos { return x.Map }
441 func (x *ChanType) Pos() token.Pos { return x.Begin }
442
443 func (x *BadExpr) End() token.Pos { return x.To }
444 func (x *Ident) End() token.Pos { return token.Pos(int(x.NamePos) + len(x.Name)) }
445 func (x *Ellipsis) End() token.Pos {
446 if x.Elt != nil {
447 return x.Elt.End()
448 }
449 return x.Ellipsis + 3 // len("...")
450 }
451 func (x *BasicLit) End() token.Pos { return token.Pos(int(x.ValuePos) + len(x.Value)) }
452 func (x *FuncLit) End() token.Pos { return x.Body.End() }
453 func (x *CompositeLit) End() token.Pos { return x.Rbrace + 1 }
454 func (x *ParenExpr) End() token.Pos { return x.Rparen + 1 }
455 func (x *SelectorExpr) End() token.Pos { return x.Sel.End() }
456 func (x *IndexExpr) End() token.Pos { return x.Rbrack + 1 }
457 func (x *SliceExpr) End() token.Pos { return x.Rbrack + 1 }
458 func (x *TypeAssertExpr) End() token.Pos {
459 if x.Type != nil {
460 return x.Type.End()
461 }
462 return x.X.End()
463 }
464 func (x *CallExpr) End() token.Pos { return x.Rparen + 1 }
465 func (x *StarExpr) End() token.Pos { return x.X.End() }
466 func (x *UnaryExpr) End() token.Pos { return x.X.End() }
467 func (x *BinaryExpr) End() token.Pos { return x.Y.End() }
468 func (x *KeyValueExpr) End() token.Pos { return x.Value.End() }
469 func (x *ArrayType) End() token.Pos { return x.Elt.End() }
470 func (x *StructType) End() token.Pos { return x.Fields.End() }
471 func (x *FuncType) End() token.Pos {
472 if x.Results != nil {
473 return x.Results.End()
474 }
475 return x.Params.End()
476 }
477 func (x *InterfaceType) End() token.Pos { return x.Methods.End() }
478 func (x *MapType) End() token.Pos { return x.Value.End() }
479 func (x *ChanType) End() token.Pos { return x.Value.End() }
480
481 // exprNode() ensures that only expression/type nodes can be
482 // assigned to an ExprNode.
483 //
484 func (*BadExpr) exprNode() {}
485 func (*Ident) exprNode() {}
486 func (*Ellipsis) exprNode() {}
487 func (*BasicLit) exprNode() {}
488 func (*FuncLit) exprNode() {}
489 func (*CompositeLit) exprNode() {}
490 func (*ParenExpr) exprNode() {}
491 func (*SelectorExpr) exprNode() {}
492 func (*IndexExpr) exprNode() {}
493 func (*SliceExpr) exprNode() {}
494 func (*TypeAssertExpr) exprNode() {}
495 func (*CallExpr) exprNode() {}
496 func (*StarExpr) exprNode() {}
497 func (*UnaryExpr) exprNode() {}
498 func (*BinaryExpr) exprNode() {}
499 func (*KeyValueExpr) exprNode() {}
500
501 func (*ArrayType) exprNode() {}
502 func (*StructType) exprNode() {}
503 func (*FuncType) exprNode() {}
504 func (*InterfaceType) exprNode() {}
505 func (*MapType) exprNode() {}
506 func (*ChanType) exprNode() {}
507
508 // ----------------------------------------------------------------------------
509 // Convenience functions for Idents
510
511 var noPos token.Pos
512
513 // NewIdent creates a new Ident without position.
514 // Useful for ASTs generated by code other than the Go parser.
515 //
516 func NewIdent(name string) *Ident { return &Ident{noPos, name, nil} }
517
518 // IsExported returns whether name is an exported Go symbol
519 // (i.e., whether it begins with an uppercase letter).
520 //
521 func IsExported(name string) bool {
522 ch, _ := utf8.DecodeRuneInString(name)
523 return unicode.IsUpper(ch)
524 }
525
526 // IsExported returns whether id is an exported Go symbol
527 // (i.e., whether it begins with an uppercase letter).
528 //
529 func (id *Ident) IsExported() bool { return IsExported(id.Name) }
530
531 func (id *Ident) String() string {
532 if id != nil {
533 return id.Name
534 }
535 return "<nil>"
536 }
537
538 // ----------------------------------------------------------------------------
539 // Statements
540
541 // A statement is represented by a tree consisting of one
542 // or more of the following concrete statement nodes.
543 //
544 type (
545 // A BadStmt node is a placeholder for statements containing
546 // syntax errors for which no correct statement nodes can be
547 // created.
548 //
549 BadStmt struct {
550 From, To token.Pos // position range of bad statement
551 }
552
553 // A DeclStmt node represents a declaration in a statement list.
554 DeclStmt struct {
555 Decl Decl
556 }
557
558 // An EmptyStmt node represents an empty statement.
559 // The "position" of the empty statement is the position
560 // of the immediately preceding semicolon.
561 //
562 EmptyStmt struct {
563 Semicolon token.Pos // position of preceding ";"
564 }
565
566 // A LabeledStmt node represents a labeled statement.
567 LabeledStmt struct {
568 Label *Ident
569 Colon token.Pos // position of ":"
570 Stmt Stmt
571 }
572
573 // An ExprStmt node represents a (stand-alone) expression
574 // in a statement list.
575 //
576 ExprStmt struct {
577 X Expr // expression
578 }
579
580 // A SendStmt node represents a send statement.
581 SendStmt struct {
582 Chan Expr
583 Arrow token.Pos // position of "<-"
584 Value Expr
585 }
586
587 // An IncDecStmt node represents an increment or decrement statement.
588 IncDecStmt struct {
589 X Expr
590 TokPos token.Pos // position of Tok
591 Tok token.Token // INC or DEC
592 }
593
594 // An AssignStmt node represents an assignment or
595 // a short variable declaration.
596 //
597 AssignStmt struct {
598 Lhs []Expr
599 TokPos token.Pos // position of Tok
600 Tok token.Token // assignment token, DEFINE
601 Rhs []Expr
602 }
603
604 // A GoStmt node represents a go statement.
605 GoStmt struct {
606 Go token.Pos // position of "go" keyword
607 Call *CallExpr
608 }
609
610 // A DeferStmt node represents a defer statement.
611 DeferStmt struct {
612 Defer token.Pos // position of "defer" keyword
613 Call *CallExpr
614 }
615
616 // A ReturnStmt node represents a return statement.
617 ReturnStmt struct {
618 Return token.Pos // position of "return" keyword
619 Results []Expr // result expressions; or nil
620 }
621
622 // A BranchStmt node represents a break, continue, goto,
623 // or fallthrough statement.
624 //
625 BranchStmt struct {
626 TokPos token.Pos // position of Tok
627 Tok token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH)
628 Label *Ident // label name; or nil
629 }
630
631 // A BlockStmt node represents a braced statement list.
632 BlockStmt struct {
633 Lbrace token.Pos // position of "{"
634 List []Stmt
635 Rbrace token.Pos // position of "}"
636 }
637
638 // An IfStmt node represents an if statement.
639 IfStmt struct {
640 If token.Pos // position of "if" keyword
641 Init Stmt // initialization statement; or nil
642 Cond Expr // condition
643 Body *BlockStmt
644 Else Stmt // else branch; or nil
645 }
646
647 // A CaseClause represents a case of an expression or type switch statement.
648 CaseClause struct {
649 Case token.Pos // position of "case" or "default" keyword
650 List []Expr // list of expressions or types; nil means default case
651 Colon token.Pos // position of ":"
652 Body []Stmt // statement list; or nil
653 }
654
655 // A SwitchStmt node represents an expression switch statement.
656 SwitchStmt struct {
657 Switch token.Pos // position of "switch" keyword
658 Init Stmt // initialization statement; or nil
659 Tag Expr // tag expression; or nil
660 Body *BlockStmt // CaseClauses only
661 }
662
663 // An TypeSwitchStmt node represents a type switch statement.
664 TypeSwitchStmt struct {
665 Switch token.Pos // position of "switch" keyword
666 Init Stmt // initialization statement; or nil
667 Assign Stmt // x := y.(type) or y.(type)
668 Body *BlockStmt // CaseClauses only
669 }
670
671 // A CommClause node represents a case of a select statement.
672 CommClause struct {
673 Case token.Pos // position of "case" or "default" keyword
674 Comm Stmt // send or receive statement; nil means default case
675 Colon token.Pos // position of ":"
676 Body []Stmt // statement list; or nil
677 }
678
679 // An SelectStmt node represents a select statement.
680 SelectStmt struct {
681 Select token.Pos // position of "select" keyword
682 Body *BlockStmt // CommClauses only
683 }
684
685 // A ForStmt represents a for statement.
686 ForStmt struct {
687 For token.Pos // position of "for" keyword
688 Init Stmt // initialization statement; or nil
689 Cond Expr // condition; or nil
690 Post Stmt // post iteration statement; or nil
691 Body *BlockStmt
692 }
693
694 // A RangeStmt represents a for statement with a range clause.
695 RangeStmt struct {
696 For token.Pos // position of "for" keyword
697 Key, Value Expr // Value may be nil
698 TokPos token.Pos // position of Tok
699 Tok token.Token // ASSIGN, DEFINE
700 X Expr // value to range over
701 Body *BlockStmt
702 }
703 )
704
705 // Pos and End implementations for statement nodes.
706 //
707 func (s *BadStmt) Pos() token.Pos { return s.From }
708 func (s *DeclStmt) Pos() token.Pos { return s.Decl.Pos() }
709 func (s *EmptyStmt) Pos() token.Pos { return s.Semicolon }
710 func (s *LabeledStmt) Pos() token.Pos { return s.Label.Pos() }
711 func (s *ExprStmt) Pos() token.Pos { return s.X.Pos() }
712 func (s *SendStmt) Pos() token.Pos { return s.Chan.Pos() }
713 func (s *IncDecStmt) Pos() token.Pos { return s.X.Pos() }
714 func (s *AssignStmt) Pos() token.Pos { return s.Lhs[0].Pos() }
715 func (s *GoStmt) Pos() token.Pos { return s.Go }
716 func (s *DeferStmt) Pos() token.Pos { return s.Defer }
717 func (s *ReturnStmt) Pos() token.Pos { return s.Return }
718 func (s *BranchStmt) Pos() token.Pos { return s.TokPos }
719 func (s *BlockStmt) Pos() token.Pos { return s.Lbrace }
720 func (s *IfStmt) Pos() token.Pos { return s.If }
721 func (s *CaseClause) Pos() token.Pos { return s.Case }
722 func (s *SwitchStmt) Pos() token.Pos { return s.Switch }
723 func (s *TypeSwitchStmt) Pos() token.Pos { return s.Switch }
724 func (s *CommClause) Pos() token.Pos { return s.Case }
725 func (s *SelectStmt) Pos() token.Pos { return s.Select }
726 func (s *ForStmt) Pos() token.Pos { return s.For }
727 func (s *RangeStmt) Pos() token.Pos { return s.For }
728
729 func (s *BadStmt) End() token.Pos { return s.To }
730 func (s *DeclStmt) End() token.Pos { return s.Decl.End() }
731 func (s *EmptyStmt) End() token.Pos {
732 return s.Semicolon + 1 /* len(";") */
733 }
734 func (s *LabeledStmt) End() token.Pos { return s.Stmt.End() }
735 func (s *ExprStmt) End() token.Pos { return s.X.End() }
736 func (s *SendStmt) End() token.Pos { return s.Value.End() }
737 func (s *IncDecStmt) End() token.Pos {
738 return s.TokPos + 2 /* len("++") */
739 }
740 func (s *AssignStmt) End() token.Pos { return s.Rhs[len(s.Rhs)-1].End() }
741 func (s *GoStmt) End() token.Pos { return s.Call.End() }
742 func (s *DeferStmt) End() token.Pos { return s.Call.End() }
743 func (s *ReturnStmt) End() token.Pos {
744 if n := len(s.Results); n > 0 {
745 return s.Results[n-1].End()
746 }
747 return s.Return + 6 // len("return")
748 }
749 func (s *BranchStmt) End() token.Pos {
750 if s.Label != nil {
751 return s.Label.End()
752 }
753 return token.Pos(int(s.TokPos) + len(s.Tok.String()))
754 }
755 func (s *BlockStmt) End() token.Pos { return s.Rbrace + 1 }
756 func (s *IfStmt) End() token.Pos {
757 if s.Else != nil {
758 return s.Else.End()
759 }
760 return s.Body.End()
761 }
762 func (s *CaseClause) End() token.Pos {
763 if n := len(s.Body); n > 0 {
764 return s.Body[n-1].End()
765 }
766 return s.Colon + 1
767 }
768 func (s *SwitchStmt) End() token.Pos { return s.Body.End() }
769 func (s *TypeSwitchStmt) End() token.Pos { return s.Body.End() }
770 func (s *CommClause) End() token.Pos {
771 if n := len(s.Body); n > 0 {
772 return s.Body[n-1].End()
773 }
774 return s.Colon + 1
775 }
776 func (s *SelectStmt) End() token.Pos { return s.Body.End() }
777 func (s *ForStmt) End() token.Pos { return s.Body.End() }
778 func (s *RangeStmt) End() token.Pos { return s.Body.End() }
779
780 // stmtNode() ensures that only statement nodes can be
781 // assigned to a StmtNode.
782 //
783 func (*BadStmt) stmtNode() {}
784 func (*DeclStmt) stmtNode() {}
785 func (*EmptyStmt) stmtNode() {}
786 func (*LabeledStmt) stmtNode() {}
787 func (*ExprStmt) stmtNode() {}
788 func (*SendStmt) stmtNode() {}
789 func (*IncDecStmt) stmtNode() {}
790 func (*AssignStmt) stmtNode() {}
791 func (*GoStmt) stmtNode() {}
792 func (*DeferStmt) stmtNode() {}
793 func (*ReturnStmt) stmtNode() {}
794 func (*BranchStmt) stmtNode() {}
795 func (*BlockStmt) stmtNode() {}
796 func (*IfStmt) stmtNode() {}
797 func (*CaseClause) stmtNode() {}
798 func (*SwitchStmt) stmtNode() {}
799 func (*TypeSwitchStmt) stmtNode() {}
800 func (*CommClause) stmtNode() {}
801 func (*SelectStmt) stmtNode() {}
802 func (*ForStmt) stmtNode() {}
803 func (*RangeStmt) stmtNode() {}
804
805 // ----------------------------------------------------------------------------
806 // Declarations
807
808 // A Spec node represents a single (non-parenthesized) import,
809 // constant, type, or variable declaration.
810 //
811 type (
812 // The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec.
813 Spec interface {
814 Node
815 specNode()
816 }
817
818 // An ImportSpec node represents a single package import.
819 ImportSpec struct {
820 Doc *CommentGroup // associated documentation; or nil
821 Name *Ident // local package name (including "."); or nil
822 Path *BasicLit // import path
823 Comment *CommentGroup // line comments; or nil
824 EndPos token.Pos // end of spec (overrides Path.Pos if nonzero)
825 }
826
827 // A ValueSpec node represents a constant or variable declaration
828 // (ConstSpec or VarSpec production).
829 //
830 ValueSpec struct {
831 Doc *CommentGroup // associated documentation; or nil
832 Names []*Ident // value names (len(Names) > 0)
833 Type Expr // value type; or nil
834 Values []Expr // initial values; or nil
835 Comment *CommentGroup // line comments; or nil
836 }
837
838 // A TypeSpec node represents a type declaration (TypeSpec production).
839 TypeSpec struct {
840 Doc *CommentGroup // associated documentation; or nil
841 Name *Ident // type name
842 Type Expr // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes
843 Comment *CommentGroup // line comments; or nil
844 }
845 )
846
847 // Pos and End implementations for spec nodes.
848 //
849 func (s *ImportSpec) Pos() token.Pos {
850 if s.Name != nil {
851 return s.Name.Pos()
852 }
853 return s.Path.Pos()
854 }
855 func (s *ValueSpec) Pos() token.Pos { return s.Names[0].Pos() }
856 func (s *TypeSpec) Pos() token.Pos { return s.Name.Pos() }
857
858 func (s *ImportSpec) End() token.Pos {
859 if s.EndPos != 0 {
860 return s.EndPos
861 }
862 return s.Path.End()
863 }
864
865 func (s *ValueSpec) End() token.Pos {
866 if n := len(s.Values); n > 0 {
867 return s.Values[n-1].End()
868 }
869 if s.Type != nil {
870 return s.Type.End()
871 }
872 return s.Names[len(s.Names)-1].End()
873 }
874 func (s *TypeSpec) End() token.Pos { return s.Type.End() }
875
876 // specNode() ensures that only spec nodes can be
877 // assigned to a Spec.
878 //
879 func (*ImportSpec) specNode() {}
880 func (*ValueSpec) specNode() {}
881 func (*TypeSpec) specNode() {}
882
883 // A declaration is represented by one of the following declaration nodes.
884 //
885 type (
886 // A BadDecl node is a placeholder for declarations containing
887 // syntax errors for which no correct declaration nodes can be
888 // created.
889 //
890 BadDecl struct {
891 From, To token.Pos // position range of bad declaration
892 }
893
894 // A GenDecl node (generic declaration node) represents an import,
895 // constant, type or variable declaration. A valid Lparen position
896 // (Lparen.Line > 0) indicates a parenthesized declaration.
897 //
898 // Relationship between Tok value and Specs element type:
899 //
900 // token.IMPORT *ImportSpec
901 // token.CONST *ValueSpec
902 // token.TYPE *TypeSpec
903 // token.VAR *ValueSpec
904 //
905 GenDecl struct {
906 Doc *CommentGroup // associated documentation; or nil
907 TokPos token.Pos // position of Tok
908 Tok token.Token // IMPORT, CONST, TYPE, VAR
909 Lparen token.Pos // position of '(', if any
910 Specs []Spec
911 Rparen token.Pos // position of ')', if any
912 }
913
914 // A FuncDecl node represents a function declaration.
915 FuncDecl struct {
916 Doc *CommentGroup // associated documentation; or nil
917 Recv *FieldList // receiver (methods); or nil (functions)
918 Name *Ident // function/method name
919 Type *FuncType // position of Func keyword, parameters and results
920 Body *BlockStmt // function body; or nil (forward declaration)
921 }
922 )
923
924 // Pos and End implementations for declaration nodes.
925 //
926 func (d *BadDecl) Pos() token.Pos { return d.From }
927 func (d *GenDecl) Pos() token.Pos { return d.TokPos }
928 func (d *FuncDecl) Pos() token.Pos { return d.Type.Pos() }
929
930 func (d *BadDecl) End() token.Pos { return d.To }
931 func (d *GenDecl) End() token.Pos {
932 if d.Rparen.IsValid() {
933 return d.Rparen + 1
934 }
935 return d.Specs[0].End()
936 }
937 func (d *FuncDecl) End() token.Pos {
938 if d.Body != nil {
939 return d.Body.End()
940 }
941 return d.Type.End()
942 }
943
944 // declNode() ensures that only declaration nodes can be
945 // assigned to a DeclNode.
946 //
947 func (*BadDecl) declNode() {}
948 func (*GenDecl) declNode() {}
949 func (*FuncDecl) declNode() {}
950
951 // ----------------------------------------------------------------------------
952 // Files and packages
953
954 // A File node represents a Go source file.
955 //
956 // The Comments list contains all comments in the source file in order of
957 // appearance, including the comments that are pointed to from other nodes
958 // via Doc and Comment fields.
959 //
960 type File struct {
961 Doc *CommentGroup // associated documentation; or nil
962 Package token.Pos // position of "package" keyword
963 Name *Ident // package name
964 Decls []Decl // top-level declarations; or nil
965 Scope *Scope // package scope (this file only)
966 Imports []*ImportSpec // imports in this file
967 Unresolved []*Ident // unresolved identifiers in this file
968 Comments []*CommentGroup // list of all comments in the source file
969 }
970
971 func (f *File) Pos() token.Pos { return f.Package }
972 func (f *File) End() token.Pos {
973 if n := len(f.Decls); n > 0 {
974 return f.Decls[n-1].End()
975 }
976 return f.Name.End()
977 }
978
979 // A Package node represents a set of source files
980 // collectively building a Go package.
981 //
982 type Package struct {
983 Name string // package name
984 Scope *Scope // package scope across all files
985 Imports map[string]*Object // map of package id -> package object
986 Files map[string]*File // Go source files by filename
987 }
988
989 func (p *Package) Pos() token.Pos { return token.NoPos }
990 func (p *Package) End() token.Pos { return token.NoPos }