ast
import "go/ast"
Package ast declares the types used to represent syntax trees for Go packages.
Index
- func FileExports(src *File) bool
- func FilterDecl(decl Decl, f Filter) bool
- func FilterFile(src *File, f Filter) bool
- func FilterPackage(pkg *Package, f Filter) bool
- func Fprint(w io.Writer, fset *token.FileSet, x interface{}, f FieldFilter) error
- func Inspect(node Node, f func(Node) bool)
- func IsExported(name string) bool
- func NotNilFilter(_ string, v reflect.Value) bool
- func PackageExports(pkg *Package) bool
- func Print(fset *token.FileSet, x interface{}) error
- func SortImports(fset *token.FileSet, f *File)
- func Walk(v Visitor, node Node)
- type ArrayType
- type AssignStmt
- type BadDecl
- type BadExpr
- type BadStmt
- type BasicLit
- type BinaryExpr
- type BlockStmt
- type BranchStmt
- type CallExpr
- type CaseClause
- type ChanDir
- type ChanType
- type CommClause
- type Comment
- type CommentGroup
- func (g *CommentGroup) End() token.Pos
- func (g *CommentGroup) Pos() token.Pos
- func (g *CommentGroup) Text() string
- type CommentMap
- func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap
- func (cmap CommentMap) Comments() []*CommentGroup
- func (cmap CommentMap) Filter(node Node) CommentMap
- func (cmap CommentMap) String() string
- func (cmap CommentMap) Update(old, new Node) Node
- type CompositeLit
- type Decl
- type DeclStmt
- type DeferStmt
- type Ellipsis
- type EmptyStmt
- type Expr
- type ExprStmt
- type Field
- type FieldFilter
- type FieldList
- func (f *FieldList) End() token.Pos
- func (f *FieldList) NumFields() int
- func (f *FieldList) Pos() token.Pos
- type File
- func MergePackageFiles(pkg *Package, mode MergeMode) *File
- func (f *File) End() token.Pos
- func (f *File) Pos() token.Pos
- type Filter
- type ForStmt
- type FuncDecl
- type FuncLit
- type FuncType
- type GenDecl
- type GoStmt
- type Ident
- func NewIdent(name string) *Ident
- func (x *Ident) End() token.Pos
- func (id *Ident) IsExported() bool
- func (x *Ident) Pos() token.Pos
- func (id *Ident) String() string
- type IfStmt
- type ImportSpec
- type Importer
- type IncDecStmt
- type IndexExpr
- type InterfaceType
- type KeyValueExpr
- type LabeledStmt
- type MapType
- type MergeMode
- type Node
- type ObjKind
- type Object
- type Package
- func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error)
- func (p *Package) End() token.Pos
- func (p *Package) Pos() token.Pos
- type ParenExpr
- type RangeStmt
- type ReturnStmt
- type Scope
- func NewScope(outer *Scope) *Scope
- func (s *Scope) Insert(obj *Object) (alt *Object)
- func (s *Scope) Lookup(name string) *Object
- func (s *Scope) String() string
- type SelectStmt
- type SelectorExpr
- type SendStmt
- type SliceExpr
- type Spec
- type StarExpr
- type Stmt
- type StructType
- type SwitchStmt
- type TypeAssertExpr
- type TypeSpec
- type TypeSwitchStmt
- type UnaryExpr
- type ValueSpec
- type Visitor
Examples ¶
Package Files ¶
ast.go commentmap.go filter.go import.go print.go resolve.go scope.go walk.go
func FileExports ¶ Uses
❖func FileExports(src *File) bool
FileExports trims the AST for a Go source file in place such that only exported nodes remain: all top-level identifiers which are not exported and their associated information (such as type, initial value, or function body) are removed. Non-exported fields and methods of exported types are stripped. The File.Comments list is not changed.
FileExports reports whether there are exported declarations.
func FilterDecl ¶ Uses
❖func FilterDecl(decl Decl, f Filter) bool
FilterDecl trims the AST for a Go declaration in place by removing all names (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f.
FilterDecl reports whether there are any declared names left after filtering.
func FilterFile ¶ Uses
❖func FilterFile(src *File, f Filter) bool
FilterFile trims the AST for a Go file in place by removing all names from top-level declarations (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f. If the declaration is empty afterwards, the declaration is removed from the AST. Import declarations are always removed. The File.Comments list is not changed.
FilterFile reports whether there are any top-level declarations left after filtering.
func FilterPackage ¶ Uses
❖func FilterPackage(pkg *Package, f Filter) bool
FilterPackage trims the AST for a Go package in place by removing all names from top-level declarations (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f. If the declaration is empty afterwards, the declaration is removed from the AST. The pkg.Files list is not changed, so that file names and top-level package comments don't get lost.
FilterPackage reports whether there are any top-level declarations left after filtering.
func Fprint ¶ Uses
❖func Fprint(w io.Writer, fset *token.FileSet, x interface{}, f FieldFilter) error
Fprint prints the (sub-)tree starting at AST node x to w. If fset != nil, position information is interpreted relative to that file set. Otherwise positions are printed as integer values (file set specific offsets).
A non-nil FieldFilter f may be provided to control the output: struct fields for which f(fieldname, fieldvalue) is true are printed; all others are filtered from the output. Unexported struct fields are never printed.
func Inspect ¶ Uses
❖func Inspect(node Node, f func(Node) bool)
Inspect traverses an AST in depth-first order: It starts by calling f(node); node must not be nil. If f returns true, Inspect invokes f recursively for each of the non-nil children of node, followed by a call of f(nil).
ExampleThis example demonstrates how to inspect the AST of a Go program.
Code:play
// src is the input for which we want to inspect the AST. src := ` package p const c = 1.0 var X = f(3.14)*2 + c ` // Create the AST by parsing src. fset := token.NewFileSet() // positions are relative to fset f, err := parser.ParseFile(fset, "src.go", src, 0) if err != nil { panic(err) } // Inspect the AST and print all identifiers and literals. ast.Inspect(f, func(n ast.Node) bool { var s string switch x := n.(type) { case *ast.BasicLit: s = x.Value case *ast.Ident: s = x.Name } if s != "" { fmt.Printf("%s:\t%s\n", fset.Position(n.Pos()), s) } return true })
Output:
src.go:2:9: p src.go:3:7: c src.go:3:11: 1.0 src.go:4:5: X src.go:4:9: f src.go:4:11: 3.14 src.go:4:17: 2 src.go:4:21: c
func IsExported ¶ Uses
❖func IsExported(name string) bool
IsExported reports whether name is an exported Go symbol (that is, whether it begins with an upper-case letter).
func NotNilFilter ¶ Uses
❖func NotNilFilter(_ string, v reflect.Value) bool
NotNilFilter returns true for field values that are not nil; it returns false otherwise.
func PackageExports ¶ Uses
❖func PackageExports(pkg *Package) bool
PackageExports trims the AST for a Go package in place such that only exported nodes remain. The pkg.Files list is not changed, so that file names and top-level package comments don't get lost.
PackageExports reports whether there are exported declarations; it returns false otherwise.
func Print ¶ Uses
❖func Print(fset *token.FileSet, x interface{}) error
Print prints x to standard output, skipping nil fields. Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter).
ExampleThis example shows what an AST looks like when printed for debugging.
Code:play
// src is the input for which we want to print the AST. src := ` package main func main() { println("Hello, World!") } ` // Create the AST by parsing src. fset := token.NewFileSet() // positions are relative to fset f, err := parser.ParseFile(fset, "", src, 0) if err != nil { panic(err) } // Print the AST. ast.Print(fset, f)
Output:
0 *ast.File { 1 . Package: 2:1 2 . Name: *ast.Ident { 3 . . NamePos: 2:9 4 . . Name: "main" 5 . } 6 . Decls: []ast.Decl (len = 1) { 7 . . 0: *ast.FuncDecl { 8 . . . Name: *ast.Ident { 9 . . . . NamePos: 3:6 10 . . . . Name: "main" 11 . . . . Obj: *ast.Object { 12 . . . . . Kind: func 13 . . . . . Name: "main" 14 . . . . . Decl: *(obj @ 7) 15 . . . . } 16 . . . } 17 . . . Type: *ast.FuncType { 18 . . . . Func: 3:1 19 . . . . Params: *ast.FieldList { 20 . . . . . Opening: 3:10 21 . . . . . Closing: 3:11 22 . . . . } 23 . . . } 24 . . . Body: *ast.BlockStmt { 25 . . . . Lbrace: 3:13 26 . . . . List: []ast.Stmt (len = 1) { 27 . . . . . 0: *ast.ExprStmt { 28 . . . . . . X: *ast.CallExpr { 29 . . . . . . . Fun: *ast.Ident { 30 . . . . . . . . NamePos: 4:2 31 . . . . . . . . Name: "println" 32 . . . . . . . } 33 . . . . . . . Lparen: 4:9 34 . . . . . . . Args: []ast.Expr (len = 1) { 35 . . . . . . . . 0: *ast.BasicLit { 36 . . . . . . . . . ValuePos: 4:10 37 . . . . . . . . . Kind: STRING 38 . . . . . . . . . Value: "\"Hello, World!\"" 39 . . . . . . . . } 40 . . . . . . . } 41 . . . . . . . Ellipsis: - 42 . . . . . . . Rparen: 4:25 43 . . . . . . } 44 . . . . . } 45 . . . . } 46 . . . . Rbrace: 5:1 47 . . . } 48 . . } 49 . } 50 . Scope: *ast.Scope { 51 . . Objects: map[string]*ast.Object (len = 1) { 52 . . . "main": *(obj @ 11) 53 . . } 54 . } 55 . Unresolved: []*ast.Ident (len = 1) { 56 . . 0: *(obj @ 29) 57 . } 58 }
func SortImports ¶ Uses
❖func SortImports(fset *token.FileSet, f *File)
SortImports sorts runs of consecutive import lines in import blocks in f. It also removes duplicate imports when it is possible to do so without data loss.
func Walk ¶ Uses
❖func Walk(v Visitor, node Node)
Walk traverses an AST in depth-first order: It starts by calling v.Visit(node); node must not be nil. If the visitor w returned by v.Visit(node) is not nil, Walk is invoked recursively with visitor w for each of the non-nil children of node, followed by a call of w.Visit(nil).
type ArrayType ¶ Uses
❖type ArrayType struct { Lbrack token.Pos // position of "[" Len Expr // Ellipsis node for [...]T array types, nil for slice types Elt Expr // element type }
An ArrayType node represents an array or slice type.
func (*ArrayType) End ¶ Uses
❖func (x *ArrayType) End() token.Pos
func (*ArrayType) Pos ¶ Uses
❖func (x *ArrayType) Pos() token.Pos
type AssignStmt ¶ Uses
❖type AssignStmt struct { Lhs []Expr TokPos token.Pos // position of Tok Tok token.Token // assignment token, DEFINE Rhs []Expr }
An AssignStmt node represents an assignment or a short variable declaration.
func (*AssignStmt) End ¶ Uses
❖func (s *AssignStmt) End() token.Pos
func (*AssignStmt) Pos ¶ Uses
❖func (s *AssignStmt) Pos() token.Pos
type BadDecl ¶ Uses
❖type BadDecl struct { From, To token.Pos // position range of bad declaration }
A BadDecl node is a placeholder for declarations containing syntax errors for which no correct declaration nodes can be created.
func (*BadDecl) End ¶ Uses
❖func (d *BadDecl) End() token.Pos
func (*BadDecl) Pos ¶ Uses
❖func (d *BadDecl) Pos() token.Pos
type BadExpr ¶ Uses
❖type BadExpr struct { From, To token.Pos // position range of bad expression }
A BadExpr node is a placeholder for expressions containing syntax errors for which no correct expression nodes can be created.
func (*BadExpr) End ¶ Uses
❖func (x *BadExpr) End() token.Pos
func (*BadExpr) Pos ¶ Uses
❖func (x *BadExpr) Pos() token.Pos
type BadStmt ¶ Uses
❖type BadStmt struct { From, To token.Pos // position range of bad statement }
A BadStmt node is a placeholder for statements containing syntax errors for which no correct statement nodes can be created.
func (*BadStmt) End ¶ Uses
❖func (s *BadStmt) End() token.Pos
func (*BadStmt) Pos ¶ Uses
❖func (s *BadStmt) Pos() token.Pos
type BasicLit ¶ Uses
❖type BasicLit struct { ValuePos token.Pos // literal position Kind token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING Value string // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o` }
A BasicLit node represents a literal of basic type.
func (*BasicLit) End ¶ Uses
❖func (x *BasicLit) End() token.Pos
func (*BasicLit) Pos ¶ Uses
❖func (x *BasicLit) Pos() token.Pos
type BinaryExpr ¶ Uses
❖type BinaryExpr struct { X Expr // left operand OpPos token.Pos // position of Op Op token.Token // operator Y Expr // right operand }
A BinaryExpr node represents a binary expression.
func (*BinaryExpr) End ¶ Uses
❖func (x *BinaryExpr) End() token.Pos
func (*BinaryExpr) Pos ¶ Uses
❖func (x *BinaryExpr) Pos() token.Pos
type BlockStmt ¶ Uses
❖type BlockStmt struct { Lbrace token.Pos // position of "{" List []Stmt Rbrace token.Pos // position of "}" }
A BlockStmt node represents a braced statement list.
func (*BlockStmt) End ¶ Uses
❖func (s *BlockStmt) End() token.Pos
func (*BlockStmt) Pos ¶ Uses
❖func (s *BlockStmt) Pos() token.Pos
type BranchStmt ¶ Uses
❖type BranchStmt struct { TokPos token.Pos // position of Tok Tok token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH) Label *Ident // label name; or nil }
A BranchStmt node represents a break, continue, goto, or fallthrough statement.
func (*BranchStmt) End ¶ Uses
❖func (s *BranchStmt) End() token.Pos
func (*BranchStmt) Pos ¶ Uses
❖func (s *BranchStmt) Pos() token.Pos
type CallExpr ¶ Uses
❖type CallExpr struct { Fun Expr // function expression Lparen token.Pos // position of "(" Args []Expr // function arguments; or nil Ellipsis token.Pos // position of "..." (token.NoPos if there is no "...") Rparen token.Pos // position of ")" }
A CallExpr node represents an expression followed by an argument list.
func (*CallExpr) End ¶ Uses
❖func (x *CallExpr) End() token.Pos
func (*CallExpr) Pos ¶ Uses
❖func (x *CallExpr) Pos() token.Pos
type CaseClause ¶ Uses
❖type CaseClause struct { Case token.Pos // position of "case" or "default" keyword List []Expr // list of expressions or types; nil means default case Colon token.Pos // position of ":" Body []Stmt // statement list; or nil }
A CaseClause represents a case of an expression or type switch statement.
func (*CaseClause) End ¶ Uses
❖func (s *CaseClause) End() token.Pos
func (*CaseClause) Pos ¶ Uses
❖func (s *CaseClause) Pos() token.Pos
type ChanDir ¶ Uses
❖type ChanDir int
The direction of a channel type is indicated by one of the following constants.
❖const ( SEND ChanDir = 1 << iota RECV )
type ChanType ¶ Uses
❖type ChanType struct { Begin token.Pos // position of "chan" keyword or "<-" (whichever comes first) Arrow token.Pos // position of "<-" (token.NoPos if there is no "<-") Dir ChanDir // channel direction Value Expr // value type }
A ChanType node represents a channel type.
func (*ChanType) End ¶ Uses
❖func (x *ChanType) End() token.Pos
func (*ChanType) Pos ¶ Uses
❖func (x *ChanType) Pos() token.Pos
type CommClause ¶ Uses
❖type CommClause struct { Case token.Pos // position of "case" or "default" keyword Comm Stmt // send or receive statement; nil means default case Colon token.Pos // position of ":" Body []Stmt // statement list; or nil }
A CommClause node represents a case of a select statement.
func (*CommClause) End ¶ Uses
❖func (s *CommClause) End() token.Pos
func (*CommClause) Pos ¶ Uses
❖func (s *CommClause) Pos() token.Pos
type Comment ¶ Uses
❖type Comment struct { Slash token.Pos // position of "/" starting the comment Text string // comment text (excluding '\n' for //-style comments) }
A Comment node represents a single //-style or /*-style comment.
func (*Comment) End ¶ Uses
❖func (c *Comment) End() token.Pos
func (*Comment) Pos ¶ Uses
❖func (c *Comment) Pos() token.Pos
type CommentGroup ¶ Uses
❖type CommentGroup struct { List []*Comment // len(List) > 0 }
A CommentGroup represents a sequence of comments with no other tokens and no empty lines between.
func (*CommentGroup) End ¶ Uses
❖func (g *CommentGroup) End() token.Pos
func (*CommentGroup) Pos ¶ Uses
❖func (g *CommentGroup) Pos() token.Pos
func (*CommentGroup) Text ¶ Uses
❖func (g *CommentGroup) Text() string
Text returns the text of the comment. Comment markers (//, /*, and */), the first space of a line comment, and leading and trailing empty lines are removed. Multiple empty lines are reduced to one, and trailing space on lines is trimmed. Unless the result is empty, it is newline-terminated.
type CommentMap ¶ Uses
❖type CommentMap map[Node][]*CommentGroup
A CommentMap maps an AST node to a list of comment groups associated with it. See NewCommentMap for a description of the association.
ExampleThis example illustrates how to remove a variable declaration in a Go program while maintaining correct comment association using an ast.CommentMap.
Code:
// src is the input for which we create the AST that we // are going to manipulate. src := ` // This is the package comment. package main // This comment is associated with the hello constant. const hello = "Hello, World!" // line comment 1 // This comment is associated with the foo variable. var foo = hello // line comment 2 // This comment is associated with the main function. func main() { fmt.Println(hello) // line comment 3 } ` // Create the AST by parsing src. fset := token.NewFileSet() // positions are relative to fset f, err := parser.ParseFile(fset, "src.go", src, parser.ParseComments) if err != nil { panic(err) } // Create an ast.CommentMap from the ast.File's comments. // This helps keeping the association between comments // and AST nodes. cmap := ast.NewCommentMap(fset, f, f.Comments) // Remove the first variable declaration from the list of declarations. f.Decls = removeFirstVarDecl(f.Decls) // Use the comment map to filter comments that don't belong anymore // (the comments associated with the variable declaration), and create // the new comments list. f.Comments = cmap.Filter(f).Comments() // Print the modified AST. var buf bytes.Buffer if err := format.Node(&buf, fset, f); err != nil { panic(err) } fmt.Printf("%s", buf.Bytes())
Output:
// This is the package comment. package main // This comment is associated with the hello constant. const hello = "Hello, World!" // line comment 1 // This comment is associated with the main function. func main() { fmt.Println(hello) // line comment 3 }
func NewCommentMap ¶ Uses
❖func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap
NewCommentMap creates a new comment map by associating comment groups of the comments list with the nodes of the AST specified by node.
A comment group g is associated with a node n if:
- g starts on the same line as n ends - g starts on the line immediately following n, and there is at least one empty line after g and before the next node - g starts before n and is not associated to the node before n via the previous rules
NewCommentMap tries to associate a comment group to the "largest" node possible: For instance, if the comment is a line comment trailing an assignment, the comment is associated with the entire assignment rather than just the last operand in the assignment.
func (CommentMap) Comments ¶ Uses
❖func (cmap CommentMap) Comments() []*CommentGroup
Comments returns the list of comment groups in the comment map. The result is sorted in source order.
func (CommentMap) Filter ¶ Uses
❖func (cmap CommentMap) Filter(node Node) CommentMap
Filter returns a new comment map consisting of only those entries of cmap for which a corresponding node exists in the AST specified by node.
func (CommentMap) String ¶ Uses
❖func (cmap CommentMap) String() string
func (CommentMap) Update ¶ Uses
❖func (cmap CommentMap) Update(old, new Node) Node
Update replaces an old node in the comment map with the new node and returns the new node. Comments that were associated with the old node are associated with the new node.
type CompositeLit ¶ Uses
❖type CompositeLit struct { Type Expr // literal type; or nil Lbrace token.Pos // position of "{" Elts []Expr // list of composite elements; or nil Rbrace token.Pos // position of "}" }
A CompositeLit node represents a composite literal.
func (*CompositeLit) End ¶ Uses
❖func (x *CompositeLit) End() token.Pos
func (*CompositeLit) Pos ¶ Uses
❖func (x *CompositeLit) Pos() token.Pos
type Decl ¶ Uses
❖type Decl interface { Node // contains filtered or unexported methods }
All declaration nodes implement the Decl interface.
type DeclStmt ¶ Uses
❖type DeclStmt struct { Decl Decl // *GenDecl with CONST, TYPE, or VAR token }
A DeclStmt node represents a declaration in a statement list.
func (*DeclStmt) End ¶ Uses
❖func (s *DeclStmt) End() token.Pos
func (*DeclStmt) Pos ¶ Uses
❖func (s *DeclStmt) Pos() token.Pos
type DeferStmt ¶ Uses
❖type DeferStmt struct { Defer token.Pos // position of "defer" keyword Call *CallExpr }
A DeferStmt node represents a defer statement.
func (*DeferStmt) End ¶ Uses
❖func (s *DeferStmt) End() token.Pos
func (*DeferStmt) Pos ¶ Uses
❖func (s *DeferStmt) Pos() token.Pos
type Ellipsis ¶ Uses
❖type Ellipsis struct { Ellipsis token.Pos // position of "..." Elt Expr // ellipsis element type (parameter lists only); or nil }
An Ellipsis node stands for the "..." type in a parameter list or the "..." length in an array type.
func (*Ellipsis) End ¶ Uses
❖func (x *Ellipsis) End() token.Pos
func (*Ellipsis) Pos ¶ Uses
❖func (x *Ellipsis) Pos() token.Pos
type EmptyStmt ¶ Uses
❖type EmptyStmt struct { Semicolon token.Pos // position of following ";" Implicit bool // if set, ";" was omitted in the source }
An EmptyStmt node represents an empty statement. The "position" of the empty statement is the position of the immediately following (explicit or implicit) semicolon.
func (*EmptyStmt) End ¶ Uses
❖func (s *EmptyStmt) End() token.Pos
func (*EmptyStmt) Pos ¶ Uses
❖func (s *EmptyStmt) Pos() token.Pos
type Expr ¶ Uses
❖type Expr interface { Node // contains filtered or unexported methods }
All expression nodes implement the Expr interface.
type ExprStmt ¶ Uses
❖type ExprStmt struct { X Expr // expression }
An ExprStmt node represents a (stand-alone) expression in a statement list.
func (*ExprStmt) End ¶ Uses
❖func (s *ExprStmt) End() token.Pos
func (*ExprStmt) Pos ¶ Uses
❖func (s *ExprStmt) Pos() token.Pos
type Field ¶ Uses
❖type Field struct { Doc *CommentGroup // associated documentation; or nil Names []*Ident // field/method/parameter names; or nil if anonymous field Type Expr // field/method/parameter type Tag *BasicLit // field tag; or nil Comment *CommentGroup // line comments; or nil }
A Field represents a Field declaration list in a struct type, a method list in an interface type, or a parameter/result declaration in a signature.
func (*Field) End ¶ Uses
❖func (f *Field) End() token.Pos
func (*Field) Pos ¶ Uses
❖func (f *Field) Pos() token.Pos
type FieldFilter ¶ Uses
❖type FieldFilter func(name string, value reflect.Value) bool
A FieldFilter may be provided to Fprint to control the output.
type FieldList ¶ Uses
❖type FieldList struct { Opening token.Pos // position of opening parenthesis/brace, if any List []*Field // field list; or nil Closing token.Pos // position of closing parenthesis/brace, if any }
A FieldList represents a list of Fields, enclosed by parentheses or braces.
func (*FieldList) End ¶ Uses
❖func (f *FieldList) End() token.Pos
func (*FieldList) NumFields ¶ Uses
❖func (f *FieldList) NumFields() int
NumFields returns the number of (named and anonymous fields) in a FieldList.
func (*FieldList) Pos ¶ Uses
❖func (f *FieldList) Pos() token.Pos
type File ¶ Uses
❖type File struct { Doc *CommentGroup // associated documentation; or nil Package token.Pos // position of "package" keyword Name *Ident // package name Decls []Decl // top-level declarations; or nil Scope *Scope // package scope (this file only) Imports []*ImportSpec // imports in this file Unresolved []*Ident // unresolved identifiers in this file Comments []*CommentGroup // list of all comments in the source file }
A File node represents a Go source file.
The Comments list contains all comments in the source file in order of appearance, including the comments that are pointed to from other nodes via Doc and Comment fields.
func MergePackageFiles ¶ Uses
❖func MergePackageFiles(pkg *Package, mode MergeMode) *File
MergePackageFiles creates a file AST by merging the ASTs of the files belonging to a package. The mode flags control merging behavior.
func (*File) End ¶ Uses
❖func (f *File) End() token.Pos
func (*File) Pos ¶ Uses
❖func (f *File) Pos() token.Pos
type Filter ¶ Uses
❖type Filter func(string) bool
type ForStmt ¶ Uses
❖type ForStmt struct { For token.Pos // position of "for" keyword Init Stmt // initialization statement; or nil Cond Expr // condition; or nil Post Stmt // post iteration statement; or nil Body *BlockStmt }
A ForStmt represents a for statement.
func (*ForStmt) End ¶ Uses
❖func (s *ForStmt) End() token.Pos
func (*ForStmt) Pos ¶ Uses
❖func (s *ForStmt) Pos() token.Pos
type FuncDecl ¶ Uses
❖type FuncDecl struct { Doc *CommentGroup // associated documentation; or nil Recv *FieldList // receiver (methods); or nil (functions) Name *Ident // function/method name Type *FuncType // function signature: parameters, results, and position of "func" keyword Body *BlockStmt // function body; or nil (forward declaration) }
A FuncDecl node represents a function declaration.
func (*FuncDecl) End ¶ Uses
❖func (d *FuncDecl) End() token.Pos
func (*FuncDecl) Pos ¶ Uses
❖func (d *FuncDecl) Pos() token.Pos
type FuncLit ¶ Uses
❖type FuncLit struct { Type *FuncType // function type Body *BlockStmt // function body }
A FuncLit node represents a function literal.
func (*FuncLit) End ¶ Uses
❖func (x *FuncLit) End() token.Pos
func (*FuncLit) Pos ¶ Uses
❖func (x *FuncLit) Pos() token.Pos
type FuncType ¶ Uses
❖type FuncType struct { Func token.Pos // position of "func" keyword (token.NoPos if there is no "func") Params *FieldList // (incoming) parameters; non-nil Results *FieldList // (outgoing) results; or nil }
A FuncType node represents a function type.
func (*FuncType) End ¶ Uses
❖func (x *FuncType) End() token.Pos
func (*FuncType) Pos ¶ Uses
❖func (x *FuncType) Pos() token.Pos
type GenDecl ¶ Uses
❖type GenDecl struct { Doc *CommentGroup // associated documentation; or nil TokPos token.Pos // position of Tok Tok token.Token // IMPORT, CONST, TYPE, VAR Lparen token.Pos // position of '(', if any Specs []Spec Rparen token.Pos // position of ')', if any }
A GenDecl node (generic declaration node) represents an import, constant, type or variable declaration. A valid Lparen position (Lparen.IsValid()) indicates a parenthesized declaration.
Relationship between Tok value and Specs element type:
token.IMPORT *ImportSpec token.CONST *ValueSpec token.TYPE *TypeSpec token.VAR *ValueSpec
func (*GenDecl) End ¶ Uses
❖func (d *GenDecl) End() token.Pos
func (*GenDecl) Pos ¶ Uses
❖func (d *GenDecl) Pos() token.Pos
type GoStmt ¶ Uses
❖type GoStmt struct { Go token.Pos // position of "go" keyword Call *CallExpr }
A GoStmt node represents a go statement.
func (*GoStmt) End ¶ Uses
❖func (s *GoStmt) End() token.Pos
func (*GoStmt) Pos ¶ Uses
❖func (s *GoStmt) Pos() token.Pos
type Ident ¶ Uses
❖type Ident struct { NamePos token.Pos // identifier position Name string // identifier name Obj *Object // denoted object; or nil }
An Ident node represents an identifier.
func NewIdent ¶ Uses
❖func NewIdent(name string) *Ident
NewIdent creates a new Ident without position. Useful for ASTs generated by code other than the Go parser.
func (*Ident) End ¶ Uses
❖func (x *Ident) End() token.Pos
func (*Ident) IsExported ¶ Uses
❖func (id *Ident) IsExported() bool
IsExported reports whether id is an exported Go symbol (that is, whether it begins with an uppercase letter).
func (*Ident) Pos ¶ Uses
❖func (x *Ident) Pos() token.Pos
func (*Ident) String ¶ Uses
❖func (id *Ident) String() string
type IfStmt ¶ Uses
❖type IfStmt struct { If token.Pos // position of "if" keyword Init Stmt // initialization statement; or nil Cond Expr // condition Body *BlockStmt Else Stmt // else branch; or nil }
An IfStmt node represents an if statement.
func (*IfStmt) End ¶ Uses
❖func (s *IfStmt) End() token.Pos
func (*IfStmt) Pos ¶ Uses
❖func (s *IfStmt) Pos() token.Pos
type ImportSpec ¶ Uses
❖type ImportSpec struct { Doc *CommentGroup // associated documentation; or nil Name *Ident // local package name (including "."); or nil Path *BasicLit // import path Comment *CommentGroup // line comments; or nil EndPos token.Pos // end of spec (overrides Path.Pos if nonzero) }
An ImportSpec node represents a single package import.
func (*ImportSpec) End ¶ Uses
❖func (s *ImportSpec) End() token.Pos
func (*ImportSpec) Pos ¶ Uses
❖func (s *ImportSpec) Pos() token.Pos
type Importer ¶ Uses
❖type Importer func(imports map[string]*Object, path string) (pkg *Object, err error)
An Importer resolves import paths to package Objects. The imports map records the packages already imported, indexed by package id (canonical import path). An Importer must determine the canonical import path and check the map to see if it is already present in the imports map. If so, the Importer can return the map entry. Otherwise, the Importer should load the package data for the given path into a new *Object (pkg), record pkg in the imports map, and then return pkg.
type IncDecStmt ¶ Uses
❖type IncDecStmt struct { X Expr TokPos token.Pos // position of Tok Tok token.Token // INC or DEC }
An IncDecStmt node represents an increment or decrement statement.
func (*IncDecStmt) End ¶ Uses
❖func (s *IncDecStmt) End() token.Pos
func (*IncDecStmt) Pos ¶ Uses
❖func (s *IncDecStmt) Pos() token.Pos
type IndexExpr ¶ Uses
❖type IndexExpr struct { X Expr // expression Lbrack token.Pos // position of "[" Index Expr // index expression Rbrack token.Pos // position of "]" }
An IndexExpr node represents an expression followed by an index.
func (*IndexExpr) End ¶ Uses
❖func (x *IndexExpr) End() token.Pos
func (*IndexExpr) Pos ¶ Uses
❖func (x *IndexExpr) Pos() token.Pos
type InterfaceType ¶ Uses
❖type InterfaceType struct { Interface token.Pos // position of "interface" keyword Methods *FieldList // list of methods Incomplete bool // true if (source) methods are missing in the Methods list }
An InterfaceType node represents an interface type.
func (*InterfaceType) End ¶ Uses
❖func (x *InterfaceType) End() token.Pos
func (*InterfaceType) Pos ¶ Uses
❖func (x *InterfaceType) Pos() token.Pos
type KeyValueExpr ¶ Uses
❖type KeyValueExpr struct { Key Expr Colon token.Pos // position of ":" Value Expr }
A KeyValueExpr node represents (key : value) pairs in composite literals.
func (*KeyValueExpr) End ¶ Uses
❖func (x *KeyValueExpr) End() token.Pos
func (*KeyValueExpr) Pos ¶ Uses
❖func (x *KeyValueExpr) Pos() token.Pos
type LabeledStmt ¶ Uses
❖type LabeledStmt struct { Label *Ident Colon token.Pos // position of ":" Stmt Stmt }
A LabeledStmt node represents a labeled statement.
func (*LabeledStmt) End ¶ Uses
❖func (s *LabeledStmt) End() token.Pos
func (*LabeledStmt) Pos ¶ Uses
❖func (s *LabeledStmt) Pos() token.Pos
type MapType ¶ Uses
❖type MapType struct { Map token.Pos // position of "map" keyword Key Expr Value Expr }
A MapType node represents a map type.
func (*MapType) End ¶ Uses
❖func (x *MapType) End() token.Pos
func (*MapType) Pos ¶ Uses
❖func (x *MapType) Pos() token.Pos
type MergeMode ¶ Uses
❖type MergeMode uint
The MergeMode flags control the behavior of MergePackageFiles.
❖const ( // If set, duplicate function declarations are excluded. FilterFuncDuplicates MergeMode = 1 << iota // If set, comments that are not associated with a specific // AST node (as Doc or Comment) are excluded. FilterUnassociatedComments // If set, duplicate import declarations are excluded. FilterImportDuplicates )
type Node ¶ Uses
❖type Node interface { Pos() token.Pos // position of first character belonging to the node End() token.Pos // position of first character immediately after the node }
All node types implement the Node interface.
type ObjKind ¶ Uses
❖type ObjKind int
ObjKind describes what an object represents.
❖const ( Bad ObjKind = iota // for error handling Pkg // package Con // constant Typ // type Var // variable Fun // function or method Lbl // label )
The list of possible Object kinds.
func (ObjKind) String ¶ Uses
❖func (kind ObjKind) String() string
type Object ¶ Uses
❖type Object struct { Kind ObjKind Name string // declared name Decl interface{} // corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil Data interface{} // object-specific data; or nil Type interface{} // placeholder for type information; may be nil }
An Object describes a named language entity such as a package, constant, type, variable, function (incl. methods), or label.
The Data fields contains object-specific data:
Kind Data type Data value Pkg *Scope package scope Con int iota for the respective declaration
func NewObj ¶ Uses
❖func NewObj(kind ObjKind, name string) *Object
NewObj creates a new object of a given kind and name.
func (*Object) Pos ¶ Uses
❖func (obj *Object) Pos() token.Pos
Pos computes the source position of the declaration of an object name. The result may be an invalid position if it cannot be computed (obj.Decl may be nil or not correct).
type Package ¶ Uses
❖type Package struct { Name string // package name Scope *Scope // package scope across all files Imports map[string]*Object // map of package id -> package object Files map[string]*File // Go source files by filename }
A Package node represents a set of source files collectively building a Go package.
func NewPackage ¶ Uses
❖func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error)
NewPackage creates a new Package node from a set of File nodes. It resolves unresolved identifiers across files and updates each file's Unresolved list accordingly. If a non-nil importer and universe scope are provided, they are used to resolve identifiers not declared in any of the package files. Any remaining unresolved identifiers are reported as undeclared. If the files belong to different packages, one package name is selected and files with different package names are reported and then ignored. The result is a package node and a scanner.ErrorList if there were errors.
func (*Package) End ¶ Uses
❖func (p *Package) End() token.Pos
func (*Package) Pos ¶ Uses
❖func (p *Package) Pos() token.Pos
type ParenExpr ¶ Uses
❖type ParenExpr struct { Lparen token.Pos // position of "(" X Expr // parenthesized expression Rparen token.Pos // position of ")" }
A ParenExpr node represents a parenthesized expression.
func (*ParenExpr) End ¶ Uses
❖func (x *ParenExpr) End() token.Pos
func (*ParenExpr) Pos ¶ Uses
❖func (x *ParenExpr) Pos() token.Pos
type RangeStmt ¶ Uses
❖type RangeStmt struct { For token.Pos // position of "for" keyword Key, Value Expr // Key, Value may be nil TokPos token.Pos // position of Tok; invalid if Key == nil Tok token.Token // ILLEGAL if Key == nil, ASSIGN, DEFINE X Expr // value to range over Body *BlockStmt }
A RangeStmt represents a for statement with a range clause.
func (*RangeStmt) End ¶ Uses
❖func (s *RangeStmt) End() token.Pos
func (*RangeStmt) Pos ¶ Uses
❖func (s *RangeStmt) Pos() token.Pos
type ReturnStmt ¶ Uses
❖type ReturnStmt struct { Return token.Pos // position of "return" keyword Results []Expr // result expressions; or nil }
A ReturnStmt node represents a return statement.
func (*ReturnStmt) End ¶ Uses
❖func (s *ReturnStmt) End() token.Pos
func (*ReturnStmt) Pos ¶ Uses
❖func (s *ReturnStmt) Pos() token.Pos
type Scope ¶ Uses
❖type Scope struct { Outer *Scope Objects map[string]*Object }
A Scope maintains the set of named language entities declared in the scope and a link to the immediately surrounding (outer) scope.
func NewScope ¶ Uses
❖func NewScope(outer *Scope) *Scope
NewScope creates a new scope nested in the outer scope.
func (*Scope) Insert ¶ Uses
❖func (s *Scope) Insert(obj *Object) (alt *Object)
Insert attempts to insert a named object obj into the scope s. If the scope already contains an object alt with the same name, Insert leaves the scope unchanged and returns alt. Otherwise it inserts obj and returns nil.
func (*Scope) Lookup ¶ Uses
❖func (s *Scope) Lookup(name string) *Object
Lookup returns the object with the given name if it is found in scope s, otherwise it returns nil. Outer scopes are ignored.
func (*Scope) String ¶ Uses
❖func (s *Scope) String() string
Debugging support
type SelectStmt ¶ Uses
❖type SelectStmt struct { Select token.Pos // position of "select" keyword Body *BlockStmt // CommClauses only }
An SelectStmt node represents a select statement.
func (*SelectStmt) End ¶ Uses
❖func (s *SelectStmt) End() token.Pos
func (*SelectStmt) Pos ¶ Uses
❖func (s *SelectStmt) Pos() token.Pos
type SelectorExpr ¶ Uses
❖type SelectorExpr struct { X Expr // expression Sel *Ident // field selector }
A SelectorExpr node represents an expression followed by a selector.
func (*SelectorExpr) End ¶ Uses
❖func (x *SelectorExpr) End() token.Pos
func (*SelectorExpr) Pos ¶ Uses
❖func (x *SelectorExpr) Pos() token.Pos
type SendStmt ¶ Uses
❖type SendStmt struct { Chan Expr Arrow token.Pos // position of "<-" Value Expr }
A SendStmt node represents a send statement.
func (*SendStmt) End ¶ Uses
❖func (s *SendStmt) End() token.Pos
func (*SendStmt) Pos ¶ Uses
❖func (s *SendStmt) Pos() token.Pos
type SliceExpr ¶ Uses
❖type SliceExpr struct { X Expr // expression Lbrack token.Pos // position of "[" Low Expr // begin of slice range; or nil High Expr // end of slice range; or nil Max Expr // maximum capacity of slice; or nil Slice3 bool // true if 3-index slice (2 colons present) Rbrack token.Pos // position of "]" }
An SliceExpr node represents an expression followed by slice indices.
func (*SliceExpr) End ¶ Uses
❖func (x *SliceExpr) End() token.Pos
func (*SliceExpr) Pos ¶ Uses
❖func (x *SliceExpr) Pos() token.Pos
type Spec ¶ Uses
❖type Spec interface { Node // contains filtered or unexported methods }
The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec.
type StarExpr ¶ Uses
❖type StarExpr struct { Star token.Pos // position of "*" X Expr // operand }
A StarExpr node represents an expression of the form "*" Expression. Semantically it could be a unary "*" expression, or a pointer type.
func (*StarExpr) End ¶ Uses
❖func (x *StarExpr) End() token.Pos
func (*StarExpr) Pos ¶ Uses
❖func (x *StarExpr) Pos() token.Pos
type Stmt ¶ Uses
❖type Stmt interface { Node // contains filtered or unexported methods }
All statement nodes implement the Stmt interface.
type StructType ¶ Uses
❖type StructType struct { Struct token.Pos // position of "struct" keyword Fields *FieldList // list of field declarations Incomplete bool // true if (source) fields are missing in the Fields list }
A StructType node represents a struct type.
func (*StructType) End ¶ Uses
❖func (x *StructType) End() token.Pos
func (*StructType) Pos ¶ Uses
❖func (x *StructType) Pos() token.Pos
type SwitchStmt ¶ Uses
❖type SwitchStmt struct { Switch token.Pos // position of "switch" keyword Init Stmt // initialization statement; or nil Tag Expr // tag expression; or nil Body *BlockStmt // CaseClauses only }
A SwitchStmt node represents an expression switch statement.
func (*SwitchStmt) End ¶ Uses
❖func (s *SwitchStmt) End() token.Pos
func (*SwitchStmt) Pos ¶ Uses
❖func (s *SwitchStmt) Pos() token.Pos
type TypeAssertExpr ¶ Uses
❖type TypeAssertExpr struct { X Expr // expression Lparen token.Pos // position of "(" Type Expr // asserted type; nil means type switch X.(type) Rparen token.Pos // position of ")" }
A TypeAssertExpr node represents an expression followed by a type assertion.
func (*TypeAssertExpr) End ¶ Uses
❖func (x *TypeAssertExpr) End() token.Pos
func (*TypeAssertExpr) Pos ¶ Uses
❖func (x *TypeAssertExpr) Pos() token.Pos
type TypeSpec ¶ Uses
❖type TypeSpec struct { Doc *CommentGroup // associated documentation; or nil Name *Ident // type name Type Expr // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes Comment *CommentGroup // line comments; or nil }
A TypeSpec node represents a type declaration (TypeSpec production).
func (*TypeSpec) End ¶ Uses
❖func (s *TypeSpec) End() token.Pos
func (*TypeSpec) Pos ¶ Uses
❖func (s *TypeSpec) Pos() token.Pos
type TypeSwitchStmt ¶ Uses
❖type TypeSwitchStmt struct { Switch token.Pos // position of "switch" keyword Init Stmt // initialization statement; or nil Assign Stmt // x := y.(type) or y.(type) Body *BlockStmt // CaseClauses only }
An TypeSwitchStmt node represents a type switch statement.
func (*TypeSwitchStmt) End ¶ Uses
❖func (s *TypeSwitchStmt) End() token.Pos
func (*TypeSwitchStmt) Pos ¶ Uses
❖func (s *TypeSwitchStmt) Pos() token.Pos
type UnaryExpr ¶ Uses
❖type UnaryExpr struct { OpPos token.Pos // position of Op Op token.Token // operator X Expr // operand }
A UnaryExpr node represents a unary expression. Unary "*" expressions are represented via StarExpr nodes.
func (*UnaryExpr) End ¶ Uses
❖func (x *UnaryExpr) End() token.Pos
func (*UnaryExpr) Pos ¶ Uses
❖func (x *UnaryExpr) Pos() token.Pos
type ValueSpec ¶ Uses
❖type ValueSpec struct { Doc *CommentGroup // associated documentation; or nil Names []*Ident // value names (len(Names) > 0) Type Expr // value type; or nil Values []Expr // initial values; or nil Comment *CommentGroup // line comments; or nil }
A ValueSpec node represents a constant or variable declaration (ConstSpec or VarSpec production).
func (*ValueSpec) End ¶ Uses
❖func (s *ValueSpec) End() token.Pos
func (*ValueSpec) Pos ¶ Uses
❖func (s *ValueSpec) Pos() token.Pos
type Visitor ¶ Uses
❖type Visitor interface { Visit(node Node) (w Visitor) }
A Visitor's Visit method is invoked for each node encountered by Walk. If the result visitor w is not nil, Walk visits each of the children of node with the visitor w, followed by a call of w.Visit(nil).