version: 1.10

package ast

import "go/ast"

Overview

Package ast declares the types used to represent syntax trees for Go packages.

Index

Examples

Package files

ast.go commentmap.go filter.go import.go print.go resolve.go scope.go walk.go

func FileExports

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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

  1. 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).


Example:

  1. // src is the input for which we want to inspect the AST.
  2. src := `
  3. package p
  4. const c = 1.0
  5. var X = f(3.14)*2 + c
  6. `
  7. // Create the AST by parsing src.
  8. fset := token.NewFileSet() // positions are relative to fset
  9. f, err := parser.ParseFile(fset, "src.go", src, 0)
  10. if err != nil {
  11. panic(err)
  12. }
  13. // Inspect the AST and print all identifiers and literals.
  14. ast.Inspect(f, func(n ast.Node) bool {
  15. var s string
  16. switch x := n.(type) {
  17. case *ast.BasicLit:
  18. s = x.Value
  19. case *ast.Ident:
  20. s = x.Name
  21. }
  22. if s != "" {
  23. fmt.Printf("%s:\t%s\n", fset.Position(n.Pos()), s)
  24. }
  25. return true
  26. })
  27. // Output:
  28. // src.go:2:9: p
  29. // src.go:3:7: c
  30. // src.go:3:11: 1.0
  31. // src.go:4:5: X
  32. // src.go:4:9: f
  33. // src.go:4:11: 3.14
  34. // src.go:4:17: 2
  35. // src.go:4:21: c

func IsExported

  1. 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

  1. func NotNilFilter(_ string, v reflect.Value) bool

NotNilFilter returns true for field values that are not nil; it returns false
otherwise.

func PackageExports

  1. 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

  1. 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).


Example:

  1. // src is the input for which we want to print the AST.
  2. src := `
  3. package main
  4. func main() {
  5. println("Hello, World!")
  6. }
  7. `
  8. // Create the AST by parsing src.
  9. fset := token.NewFileSet() // positions are relative to fset
  10. f, err := parser.ParseFile(fset, "", src, 0)
  11. if err != nil {
  12. panic(err)
  13. }
  14. // Print the AST.
  15. ast.Print(fset, f)
  16. // Output:
  17. // 0 *ast.File {
  18. // 1 . Package: 2:1
  19. // 2 . Name: *ast.Ident {
  20. // 3 . . NamePos: 2:9
  21. // 4 . . Name: "main"
  22. // 5 . }
  23. // 6 . Decls: []ast.Decl (len = 1) {
  24. // 7 . . 0: *ast.FuncDecl {
  25. // 8 . . . Name: *ast.Ident {
  26. // 9 . . . . NamePos: 3:6
  27. // 10 . . . . Name: "main"
  28. // 11 . . . . Obj: *ast.Object {
  29. // 12 . . . . . Kind: func
  30. // 13 . . . . . Name: "main"
  31. // 14 . . . . . Decl: *(obj @ 7)
  32. // 15 . . . . }
  33. // 16 . . . }
  34. // 17 . . . Type: *ast.FuncType {
  35. // 18 . . . . Func: 3:1
  36. // 19 . . . . Params: *ast.FieldList {
  37. // 20 . . . . . Opening: 3:10
  38. // 21 . . . . . Closing: 3:11
  39. // 22 . . . . }
  40. // 23 . . . }
  41. // 24 . . . Body: *ast.BlockStmt {
  42. // 25 . . . . Lbrace: 3:13
  43. // 26 . . . . List: []ast.Stmt (len = 1) {
  44. // 27 . . . . . 0: *ast.ExprStmt {
  45. // 28 . . . . . . X: *ast.CallExpr {
  46. // 29 . . . . . . . Fun: *ast.Ident {
  47. // 30 . . . . . . . . NamePos: 4:2
  48. // 31 . . . . . . . . Name: "println"
  49. // 32 . . . . . . . }
  50. // 33 . . . . . . . Lparen: 4:9
  51. // 34 . . . . . . . Args: []ast.Expr (len = 1) {
  52. // 35 . . . . . . . . 0: *ast.BasicLit {
  53. // 36 . . . . . . . . . ValuePos: 4:10
  54. // 37 . . . . . . . . . Kind: STRING
  55. // 38 . . . . . . . . . Value: "\"Hello, World!\""
  56. // 39 . . . . . . . . }
  57. // 40 . . . . . . . }
  58. // 41 . . . . . . . Ellipsis: -
  59. // 42 . . . . . . . Rparen: 4:25
  60. // 43 . . . . . . }
  61. // 44 . . . . . }
  62. // 45 . . . . }
  63. // 46 . . . . Rbrace: 5:1
  64. // 47 . . . }
  65. // 48 . . }
  66. // 49 . }
  67. // 50 . Scope: *ast.Scope {
  68. // 51 . . Objects: map[string]*ast.Object (len = 1) {
  69. // 52 . . . "main": *(obj @ 11)
  70. // 53 . . }
  71. // 54 . }
  72. // 55 . Unresolved: []*ast.Ident (len = 1) {
  73. // 56 . . 0: *(obj @ 29)
  74. // 57 . }
  75. // 58 }

func SortImports

  1. 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

  1. 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

  1. type ArrayType struct {
  2. Lbrack token.Pos // position of "["
  3. Len Expr // Ellipsis node for [...]T array types, nil for slice types
  4. Elt Expr // element type
  5. }

An ArrayType node represents an array or slice type.

func (*ArrayType) End

  1. func (x *ArrayType) End() token.Pos

func (*ArrayType) Pos

  1. func (x *ArrayType) Pos() token.Pos

type AssignStmt

  1. type AssignStmt struct {
  2. Lhs []Expr
  3. TokPos token.Pos // position of Tok
  4. Tok token.Token // assignment token, DEFINE
  5. Rhs []Expr
  6. }

An AssignStmt node represents an assignment or a short variable declaration.

func (*AssignStmt) End

  1. func (s *AssignStmt) End() token.Pos

func (*AssignStmt) Pos

  1. func (s *AssignStmt) Pos() token.Pos

type BadDecl

  1. type BadDecl struct {
  2. From, To token.Pos // position range of bad declaration
  3. }

A BadDecl node is a placeholder for declarations containing syntax errors for
which no correct declaration nodes can be created.

func (*BadDecl) End

  1. func (d *BadDecl) End() token.Pos

func (*BadDecl) Pos

  1. func (d *BadDecl) Pos() token.Pos

type BadExpr

  1. type BadExpr struct {
  2. From, To token.Pos // position range of bad expression
  3. }

A BadExpr node is a placeholder for expressions containing syntax errors for
which no correct expression nodes can be created.

func (*BadExpr) End

  1. func (x *BadExpr) End() token.Pos

func (*BadExpr) Pos

  1. func (x *BadExpr) Pos() token.Pos

type BadStmt

  1. type BadStmt struct {
  2. From, To token.Pos // position range of bad statement
  3. }

A BadStmt node is a placeholder for statements containing syntax errors for
which no correct statement nodes can be created.

func (*BadStmt) End

  1. func (s *BadStmt) End() token.Pos

func (*BadStmt) Pos

  1. func (s *BadStmt) Pos() token.Pos

type BasicLit

  1. type BasicLit struct {
  2. ValuePos token.Pos // literal position
  3. Kind token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING
  4. Value string // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o`
  5. }

A BasicLit node represents a literal of basic type.

func (*BasicLit) End

  1. func (x *BasicLit) End() token.Pos

func (*BasicLit) Pos

  1. func (x *BasicLit) Pos() token.Pos

type BinaryExpr

  1. type BinaryExpr struct {
  2. X Expr // left operand
  3. OpPos token.Pos // position of Op
  4. Op token.Token // operator
  5. Y Expr // right operand
  6. }

A BinaryExpr node represents a binary expression.

func (*BinaryExpr) End

  1. func (x *BinaryExpr) End() token.Pos

func (*BinaryExpr) Pos

  1. func (x *BinaryExpr) Pos() token.Pos

type BlockStmt

  1. type BlockStmt struct {
  2. Lbrace token.Pos // position of "{"
  3. List []Stmt
  4. Rbrace token.Pos // position of "}"
  5. }

A BlockStmt node represents a braced statement list.

func (*BlockStmt) End

  1. func (s *BlockStmt) End() token.Pos

func (*BlockStmt) Pos

  1. func (s *BlockStmt) Pos() token.Pos

type BranchStmt

  1. type BranchStmt struct {
  2. TokPos token.Pos // position of Tok
  3. Tok token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH)
  4. Label *Ident // label name; or nil
  5. }

A BranchStmt node represents a break, continue, goto, or fallthrough statement.

func (*BranchStmt) End

  1. func (s *BranchStmt) End() token.Pos

func (*BranchStmt) Pos

  1. func (s *BranchStmt) Pos() token.Pos

type CallExpr

  1. type CallExpr struct {
  2. Fun Expr // function expression
  3. Lparen token.Pos // position of "("
  4. Args []Expr // function arguments; or nil
  5. Ellipsis token.Pos // position of "..." (token.NoPos if there is no "...")
  6. Rparen token.Pos // position of ")"
  7. }

A CallExpr node represents an expression followed by an argument list.

func (*CallExpr) End

  1. func (x *CallExpr) End() token.Pos

func (*CallExpr) Pos

  1. func (x *CallExpr) Pos() token.Pos

type CaseClause

  1. type CaseClause struct {
  2. Case token.Pos // position of "case" or "default" keyword
  3. List []Expr // list of expressions or types; nil means default case
  4. Colon token.Pos // position of ":"
  5. Body []Stmt // statement list; or nil
  6. }

A CaseClause represents a case of an expression or type switch statement.

func (*CaseClause) End

  1. func (s *CaseClause) End() token.Pos

func (*CaseClause) Pos

  1. func (s *CaseClause) Pos() token.Pos

type ChanDir

  1. type ChanDir int

The direction of a channel type is indicated by a bit mask including one or both
of the following constants.

  1. const (
  2. SEND ChanDir = 1 << iota
  3. RECV
  4. )

type ChanType

  1. type ChanType struct {
  2. Begin token.Pos // position of "chan" keyword or "<-" (whichever comes first)
  3. Arrow token.Pos // position of "<-" (token.NoPos if there is no "<-")
  4. Dir ChanDir // channel direction
  5. Value Expr // value type
  6. }

A ChanType node represents a channel type.

func (*ChanType) End

  1. func (x *ChanType) End() token.Pos

func (*ChanType) Pos

  1. func (x *ChanType) Pos() token.Pos

type CommClause

  1. type CommClause struct {
  2. Case token.Pos // position of "case" or "default" keyword
  3. Comm Stmt // send or receive statement; nil means default case
  4. Colon token.Pos // position of ":"
  5. Body []Stmt // statement list; or nil
  6. }

A CommClause node represents a case of a select statement.

func (*CommClause) End

  1. func (s *CommClause) End() token.Pos

func (*CommClause) Pos

  1. func (s *CommClause) Pos() token.Pos

type Comment

  1. type Comment struct {
  2. Slash token.Pos // position of "/" starting the comment
  3. Text string // comment text (excluding '\n' for //-style comments)
  4. }

A Comment node represents a single //-style or /*-style comment.

func (*Comment) End

  1. func (c *Comment) End() token.Pos

func (*Comment) Pos

  1. func (c *Comment) Pos() token.Pos

type CommentGroup

  1. type CommentGroup struct {
  2. List []*Comment // len(List) > 0
  3. }

A CommentGroup represents a sequence of comments with no other tokens and no
empty lines between.

func (*CommentGroup) End

  1. func (g *CommentGroup) End() token.Pos

func (*CommentGroup) Pos

  1. func (g *CommentGroup) Pos() token.Pos

func (*CommentGroup) Text

  1. 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

  1. 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.


Example:

  1. // src is the input for which we create the AST that we
  2. // are going to manipulate.
  3. src := `
  4. // This is the package comment.
  5. package main
  6. // This comment is associated with the hello constant.
  7. const hello = "Hello, World!" // line comment 1
  8. // This comment is associated with the foo variable.
  9. var foo = hello // line comment 2
  10. // This comment is associated with the main function.
  11. func main() {
  12. fmt.Println(hello) // line comment 3
  13. }
  14. `
  15. // Create the AST by parsing src.
  16. fset := token.NewFileSet() // positions are relative to fset
  17. f, err := parser.ParseFile(fset, "src.go", src, parser.ParseComments)
  18. if err != nil {
  19. panic(err)
  20. }
  21. // Create an ast.CommentMap from the ast.File's comments.
  22. // This helps keeping the association between comments
  23. // and AST nodes.
  24. cmap := ast.NewCommentMap(fset, f, f.Comments)
  25. // Remove the first variable declaration from the list of declarations.
  26. for i, decl := range f.Decls {
  27. if gen, ok := decl.(*ast.GenDecl); ok && gen.Tok == token.VAR {
  28. copy(f.Decls[i:], f.Decls[i+1:])
  29. f.Decls = f.Decls[:len(f.Decls)-1]
  30. }
  31. }
  32. // Use the comment map to filter comments that don't belong anymore
  33. // (the comments associated with the variable declaration), and create
  34. // the new comments list.
  35. f.Comments = cmap.Filter(f).Comments()
  36. // Print the modified AST.
  37. var buf bytes.Buffer
  38. if err := format.Node(&buf, fset, f); err != nil {
  39. panic(err)
  40. }
  41. fmt.Printf("%s", buf.Bytes())
  42. // Output:
  43. // // This is the package comment.
  44. // package main
  45. //
  46. // // This comment is associated with the hello constant.
  47. // const hello = "Hello, World!" // line comment 1
  48. //
  49. // // This comment is associated with the main function.
  50. // func main() {
  51. // fmt.Println(hello) // line comment 3
  52. // }

func NewCommentMap

  1. 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:

  1. - g starts on the same line as n ends
  2. - g starts on the line immediately following n, and there is
  3. at least one empty line after g and before the next node
  4. - g starts before n and is not associated to the node before n
  5. 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

  1. 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

  1. 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

  1. func (cmap CommentMap) String() string

func (CommentMap) Update

  1. 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

  1. type CompositeLit struct {
  2. Type Expr // literal type; or nil
  3. Lbrace token.Pos // position of "{"
  4. Elts []Expr // list of composite elements; or nil
  5. Rbrace token.Pos // position of "}"
  6. }

A CompositeLit node represents a composite literal.

func (*CompositeLit) End

  1. func (x *CompositeLit) End() token.Pos

func (*CompositeLit) Pos

  1. func (x *CompositeLit) Pos() token.Pos

type Decl

  1. type Decl interface {
  2. Node
  3. // contains filtered or unexported methods
  4. }

All declaration nodes implement the Decl interface.

type DeclStmt

  1. type DeclStmt struct {
  2. Decl Decl // *GenDecl with CONST, TYPE, or VAR token
  3. }

A DeclStmt node represents a declaration in a statement list.

func (*DeclStmt) End

  1. func (s *DeclStmt) End() token.Pos

func (*DeclStmt) Pos

  1. func (s *DeclStmt) Pos() token.Pos

type DeferStmt

  1. type DeferStmt struct {
  2. Defer token.Pos // position of "defer" keyword
  3. Call *CallExpr
  4. }

A DeferStmt node represents a defer statement.

func (*DeferStmt) End

  1. func (s *DeferStmt) End() token.Pos

func (*DeferStmt) Pos

  1. func (s *DeferStmt) Pos() token.Pos

type Ellipsis

  1. type Ellipsis struct {
  2. Ellipsis token.Pos // position of "..."
  3. Elt Expr // ellipsis element type (parameter lists only); or nil
  4. }

An Ellipsis node stands for the “…” type in a parameter list or the “…”
length in an array type.

func (*Ellipsis) End

  1. func (x *Ellipsis) End() token.Pos

func (*Ellipsis) Pos

  1. func (x *Ellipsis) Pos() token.Pos

type EmptyStmt

  1. type EmptyStmt struct {
  2. Semicolon token.Pos // position of following ";"
  3. Implicit bool // if set, ";" was omitted in the source
  4. }

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

  1. func (s *EmptyStmt) End() token.Pos

func (*EmptyStmt) Pos

  1. func (s *EmptyStmt) Pos() token.Pos

type Expr

  1. type Expr interface {
  2. Node
  3. // contains filtered or unexported methods
  4. }

All expression nodes implement the Expr interface.

type ExprStmt

  1. type ExprStmt struct {
  2. X Expr // expression
  3. }

An ExprStmt node represents a (stand-alone) expression in a statement list.

func (*ExprStmt) End

  1. func (s *ExprStmt) End() token.Pos

func (*ExprStmt) Pos

  1. func (s *ExprStmt) Pos() token.Pos

type Field

  1. type Field struct {
  2. Doc *CommentGroup // associated documentation; or nil
  3. Names []*Ident // field/method/parameter names; or nil if anonymous field
  4. Type Expr // field/method/parameter type
  5. Tag *BasicLit // field tag; or nil
  6. Comment *CommentGroup // line comments; or nil
  7. }

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

  1. func (f *Field) End() token.Pos

func (*Field) Pos

  1. func (f *Field) Pos() token.Pos

type FieldFilter

  1. type FieldFilter func(name string, value reflect.Value) bool

A FieldFilter may be provided to Fprint to control the output.

type FieldList

  1. type FieldList struct {
  2. Opening token.Pos // position of opening parenthesis/brace, if any
  3. List []*Field // field list; or nil
  4. Closing token.Pos // position of closing parenthesis/brace, if any
  5. }

A FieldList represents a list of Fields, enclosed by parentheses or braces.

func (*FieldList) End

  1. func (f *FieldList) End() token.Pos

func (*FieldList) NumFields

  1. func (f *FieldList) NumFields() int

NumFields returns the number of (named and anonymous fields) in a FieldList.

func (*FieldList) Pos

  1. func (f *FieldList) Pos() token.Pos

type File

  1. type File struct {
  2. Doc *CommentGroup // associated documentation; or nil
  3. Package token.Pos // position of "package" keyword
  4. Name *Ident // package name
  5. Decls []Decl // top-level declarations; or nil
  6. Scope *Scope // package scope (this file only)
  7. Imports []*ImportSpec // imports in this file
  8. Unresolved []*Ident // unresolved identifiers in this file
  9. Comments []*CommentGroup // list of all comments in the source file
  10. }

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.

For correct printing of source code containing comments (using packages
go/format and go/printer), special care must be taken to update comments when a
File’s syntax tree is modified: For printing, comments are interspersed between
tokens based on their position. If syntax tree nodes are removed or moved,
relevant comments in their vicinity must also be removed (from the File.Comments
list) or moved accordingly (by updating their positions). A CommentMap may be
used to facilitate some of these operations.

Whether and how a comment is associated with a node depends on the
interpretation of the syntax tree by the manipulating program: Except for Doc
and Comment comments directly associated with nodes, the remaining comments are
“free-floating” (see also issues #18593, #20744).

func MergePackageFiles

  1. 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

  1. func (f *File) End() token.Pos

func (*File) Pos

  1. func (f *File) Pos() token.Pos

type Filter

  1. type Filter func(string) bool

type ForStmt

  1. type ForStmt struct {
  2. For token.Pos // position of "for" keyword
  3. Init Stmt // initialization statement; or nil
  4. Cond Expr // condition; or nil
  5. Post Stmt // post iteration statement; or nil
  6. Body *BlockStmt
  7. }

A ForStmt represents a for statement.

func (*ForStmt) End

  1. func (s *ForStmt) End() token.Pos

func (*ForStmt) Pos

  1. func (s *ForStmt) Pos() token.Pos

type FuncDecl

  1. type FuncDecl struct {
  2. Doc *CommentGroup // associated documentation; or nil
  3. Recv *FieldList // receiver (methods); or nil (functions)
  4. Name *Ident // function/method name
  5. Type *FuncType // function signature: parameters, results, and position of "func" keyword
  6. Body *BlockStmt // function body; or nil for external (non-Go) function
  7. }

A FuncDecl node represents a function declaration.

func (*FuncDecl) End

  1. func (d *FuncDecl) End() token.Pos

func (*FuncDecl) Pos

  1. func (d *FuncDecl) Pos() token.Pos

type FuncLit

  1. type FuncLit struct {
  2. Type *FuncType // function type
  3. Body *BlockStmt // function body
  4. }

A FuncLit node represents a function literal.

func (*FuncLit) End

  1. func (x *FuncLit) End() token.Pos

func (*FuncLit) Pos

  1. func (x *FuncLit) Pos() token.Pos

type FuncType

  1. type FuncType struct {
  2. Func token.Pos // position of "func" keyword (token.NoPos if there is no "func")
  3. Params *FieldList // (incoming) parameters; non-nil
  4. Results *FieldList // (outgoing) results; or nil
  5. }

A FuncType node represents a function type.

func (*FuncType) End

  1. func (x *FuncType) End() token.Pos

func (*FuncType) Pos

  1. func (x *FuncType) Pos() token.Pos

type GenDecl

  1. type GenDecl struct {
  2. Doc *CommentGroup // associated documentation; or nil
  3. TokPos token.Pos // position of Tok
  4. Tok token.Token // IMPORT, CONST, TYPE, VAR
  5. Lparen token.Pos // position of '(', if any
  6. Specs []Spec
  7. Rparen token.Pos // position of ')', if any
  8. }

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:

  1. token.IMPORT *ImportSpec
  2. token.CONST *ValueSpec
  3. token.TYPE *TypeSpec
  4. token.VAR *ValueSpec

func (*GenDecl) End

  1. func (d *GenDecl) End() token.Pos

func (*GenDecl) Pos

  1. func (d *GenDecl) Pos() token.Pos

type GoStmt

  1. type GoStmt struct {
  2. Go token.Pos // position of "go" keyword
  3. Call *CallExpr
  4. }

A GoStmt node represents a go statement.

func (*GoStmt) End

  1. func (s *GoStmt) End() token.Pos

func (*GoStmt) Pos

  1. func (s *GoStmt) Pos() token.Pos

type Ident

  1. type Ident struct {
  2. NamePos token.Pos // identifier position
  3. Name string // identifier name
  4. Obj *Object // denoted object; or nil
  5. }

An Ident node represents an identifier.

func NewIdent

  1. 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

  1. func (x *Ident) End() token.Pos

func (*Ident) IsExported

  1. 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

  1. func (x *Ident) Pos() token.Pos

func (*Ident) String

  1. func (id *Ident) String() string

type IfStmt

  1. type IfStmt struct {
  2. If token.Pos // position of "if" keyword
  3. Init Stmt // initialization statement; or nil
  4. Cond Expr // condition
  5. Body *BlockStmt
  6. Else Stmt // else branch; or nil
  7. }

An IfStmt node represents an if statement.

func (*IfStmt) End

  1. func (s *IfStmt) End() token.Pos

func (*IfStmt) Pos

  1. func (s *IfStmt) Pos() token.Pos

type ImportSpec

  1. type ImportSpec struct {
  2. Doc *CommentGroup // associated documentation; or nil
  3. Name *Ident // local package name (including "."); or nil
  4. Path *BasicLit // import path
  5. Comment *CommentGroup // line comments; or nil
  6. EndPos token.Pos // end of spec (overrides Path.Pos if nonzero)
  7. }

An ImportSpec node represents a single package import.

func (*ImportSpec) End

  1. func (s *ImportSpec) End() token.Pos

func (*ImportSpec) Pos

  1. func (s *ImportSpec) Pos() token.Pos

type Importer

  1. 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

  1. type IncDecStmt struct {
  2. X Expr
  3. TokPos token.Pos // position of Tok
  4. Tok token.Token // INC or DEC
  5. }

An IncDecStmt node represents an increment or decrement statement.

func (*IncDecStmt) End

  1. func (s *IncDecStmt) End() token.Pos

func (*IncDecStmt) Pos

  1. func (s *IncDecStmt) Pos() token.Pos

type IndexExpr

  1. type IndexExpr struct {
  2. X Expr // expression
  3. Lbrack token.Pos // position of "["
  4. Index Expr // index expression
  5. Rbrack token.Pos // position of "]"
  6. }

An IndexExpr node represents an expression followed by an index.

func (*IndexExpr) End

  1. func (x *IndexExpr) End() token.Pos

func (*IndexExpr) Pos

  1. func (x *IndexExpr) Pos() token.Pos

type InterfaceType

  1. type InterfaceType struct {
  2. Interface token.Pos // position of "interface" keyword
  3. Methods *FieldList // list of methods
  4. Incomplete bool // true if (source) methods are missing in the Methods list
  5. }

An InterfaceType node represents an interface type.

func (*InterfaceType) End

  1. func (x *InterfaceType) End() token.Pos

func (*InterfaceType) Pos

  1. func (x *InterfaceType) Pos() token.Pos

type KeyValueExpr

  1. type KeyValueExpr struct {
  2. Key Expr
  3. Colon token.Pos // position of ":"
  4. Value Expr
  5. }

A KeyValueExpr node represents (key : value) pairs in composite literals.

func (*KeyValueExpr) End

  1. func (x *KeyValueExpr) End() token.Pos

func (*KeyValueExpr) Pos

  1. func (x *KeyValueExpr) Pos() token.Pos

type LabeledStmt

  1. type LabeledStmt struct {
  2. Label *Ident
  3. Colon token.Pos // position of ":"
  4. Stmt Stmt
  5. }

A LabeledStmt node represents a labeled statement.

func (*LabeledStmt) End

  1. func (s *LabeledStmt) End() token.Pos

func (*LabeledStmt) Pos

  1. func (s *LabeledStmt) Pos() token.Pos

type MapType

  1. type MapType struct {
  2. Map token.Pos // position of "map" keyword
  3. Key Expr
  4. Value Expr
  5. }

A MapType node represents a map type.

func (*MapType) End

  1. func (x *MapType) End() token.Pos

func (*MapType) Pos

  1. func (x *MapType) Pos() token.Pos

type MergeMode

  1. type MergeMode uint

The MergeMode flags control the behavior of MergePackageFiles.

  1. const (
  2. // If set, duplicate function declarations are excluded.
  3. FilterFuncDuplicates MergeMode = 1 << iota
  4. // If set, comments that are not associated with a specific
  5. // AST node (as Doc or Comment) are excluded.
  6. FilterUnassociatedComments
  7. // If set, duplicate import declarations are excluded.
  8. FilterImportDuplicates
  9. )

type Node

  1. type Node interface {
  2. Pos() token.Pos // position of first character belonging to the node
  3. End() token.Pos // position of first character immediately after the node
  4. }

All node types implement the Node interface.

type ObjKind

  1. type ObjKind int

ObjKind describes what an object represents.

  1. const (
  2. Bad ObjKind = iota // for error handling
  3. Pkg // package
  4. Con // constant
  5. Typ // type
  6. Var // variable
  7. Fun // function or method
  8. Lbl // label
  9. )

The list of possible Object kinds.

func (ObjKind) String

  1. func (kind ObjKind) String() string

type Object

  1. type Object struct {
  2. Kind ObjKind
  3. Name string // declared name
  4. Decl interface{} // corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil
  5. Data interface{} // object-specific data; or nil
  6. Type interface{} // placeholder for type information; may be nil
  7. }

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:

  1. Kind Data type Data value
  2. Pkg *Scope package scope
  3. Con int iota for the respective declaration

func NewObj

  1. func NewObj(kind ObjKind, name string) *Object

NewObj creates a new object of a given kind and name.

func (*Object) Pos

  1. 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

  1. type Package struct {
  2. Name string // package name
  3. Scope *Scope // package scope across all files
  4. Imports map[string]*Object // map of package id -> package object
  5. Files map[string]*File // Go source files by filename
  6. }

A Package node represents a set of source files collectively building a Go
package.

func NewPackage

  1. 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

  1. func (p *Package) End() token.Pos

func (*Package) Pos

  1. func (p *Package) Pos() token.Pos

type ParenExpr

  1. type ParenExpr struct {
  2. Lparen token.Pos // position of "("
  3. X Expr // parenthesized expression
  4. Rparen token.Pos // position of ")"
  5. }

A ParenExpr node represents a parenthesized expression.

func (*ParenExpr) End

  1. func (x *ParenExpr) End() token.Pos

func (*ParenExpr) Pos

  1. func (x *ParenExpr) Pos() token.Pos

type RangeStmt

  1. type RangeStmt struct {
  2. For token.Pos // position of "for" keyword
  3. Key, Value Expr // Key, Value may be nil
  4. TokPos token.Pos // position of Tok; invalid if Key == nil
  5. Tok token.Token // ILLEGAL if Key == nil, ASSIGN, DEFINE
  6. X Expr // value to range over
  7. Body *BlockStmt
  8. }

A RangeStmt represents a for statement with a range clause.

func (*RangeStmt) End

  1. func (s *RangeStmt) End() token.Pos

func (*RangeStmt) Pos

  1. func (s *RangeStmt) Pos() token.Pos

type ReturnStmt

  1. type ReturnStmt struct {
  2. Return token.Pos // position of "return" keyword
  3. Results []Expr // result expressions; or nil
  4. }

A ReturnStmt node represents a return statement.

func (*ReturnStmt) End

  1. func (s *ReturnStmt) End() token.Pos

func (*ReturnStmt) Pos

  1. func (s *ReturnStmt) Pos() token.Pos

type Scope

  1. type Scope struct {
  2. Outer *Scope
  3. Objects map[string]*Object
  4. }

A Scope maintains the set of named language entities declared in the scope and a
link to the immediately surrounding (outer) scope.

func NewScope

  1. func NewScope(outer *Scope) *Scope

NewScope creates a new scope nested in the outer scope.

func (*Scope) Insert

  1. 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

  1. 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

  1. func (s *Scope) String() string

Debugging support

type SelectStmt

  1. type SelectStmt struct {
  2. Select token.Pos // position of "select" keyword
  3. Body *BlockStmt // CommClauses only
  4. }

An SelectStmt node represents a select statement.

func (*SelectStmt) End

  1. func (s *SelectStmt) End() token.Pos

func (*SelectStmt) Pos

  1. func (s *SelectStmt) Pos() token.Pos

type SelectorExpr

  1. type SelectorExpr struct {
  2. X Expr // expression
  3. Sel *Ident // field selector
  4. }

A SelectorExpr node represents an expression followed by a selector.

func (*SelectorExpr) End

  1. func (x *SelectorExpr) End() token.Pos

func (*SelectorExpr) Pos

  1. func (x *SelectorExpr) Pos() token.Pos

type SendStmt

  1. type SendStmt struct {
  2. Chan Expr
  3. Arrow token.Pos // position of "<-"
  4. Value Expr
  5. }

A SendStmt node represents a send statement.

func (*SendStmt) End

  1. func (s *SendStmt) End() token.Pos

func (*SendStmt) Pos

  1. func (s *SendStmt) Pos() token.Pos

type SliceExpr

  1. type SliceExpr struct {
  2. X Expr // expression
  3. Lbrack token.Pos // position of "["
  4. Low Expr // begin of slice range; or nil
  5. High Expr // end of slice range; or nil
  6. Max Expr // maximum capacity of slice; or nil
  7. Slice3 bool // true if 3-index slice (2 colons present)
  8. Rbrack token.Pos // position of "]"
  9. }

An SliceExpr node represents an expression followed by slice indices.

func (*SliceExpr) End

  1. func (x *SliceExpr) End() token.Pos

func (*SliceExpr) Pos

  1. func (x *SliceExpr) Pos() token.Pos

type Spec

  1. type Spec interface {
  2. Node
  3. // contains filtered or unexported methods
  4. }

The Spec type stands for any of ImportSpec, ValueSpec, and *TypeSpec.

type StarExpr

  1. type StarExpr struct {
  2. Star token.Pos // position of "*"
  3. X Expr // operand
  4. }

A StarExpr node represents an expression of the form ““ Expression.
Semantically it could be a unary “
“ expression, or a pointer type.

func (*StarExpr) End

  1. func (x *StarExpr) End() token.Pos

func (*StarExpr) Pos

  1. func (x *StarExpr) Pos() token.Pos

type Stmt

  1. type Stmt interface {
  2. Node
  3. // contains filtered or unexported methods
  4. }

All statement nodes implement the Stmt interface.

type StructType

  1. type StructType struct {
  2. Struct token.Pos // position of "struct" keyword
  3. Fields *FieldList // list of field declarations
  4. Incomplete bool // true if (source) fields are missing in the Fields list
  5. }

A StructType node represents a struct type.

func (*StructType) End

  1. func (x *StructType) End() token.Pos

func (*StructType) Pos

  1. func (x *StructType) Pos() token.Pos

type SwitchStmt

  1. type SwitchStmt struct {
  2. Switch token.Pos // position of "switch" keyword
  3. Init Stmt // initialization statement; or nil
  4. Tag Expr // tag expression; or nil
  5. Body *BlockStmt // CaseClauses only
  6. }

A SwitchStmt node represents an expression switch statement.

func (*SwitchStmt) End

  1. func (s *SwitchStmt) End() token.Pos

func (*SwitchStmt) Pos

  1. func (s *SwitchStmt) Pos() token.Pos

type TypeAssertExpr

  1. type TypeAssertExpr struct {
  2. X Expr // expression
  3. Lparen token.Pos // position of "("
  4. Type Expr // asserted type; nil means type switch X.(type)
  5. Rparen token.Pos // position of ")"
  6. }

A TypeAssertExpr node represents an expression followed by a type assertion.

func (*TypeAssertExpr) End

  1. func (x *TypeAssertExpr) End() token.Pos

func (*TypeAssertExpr) Pos

  1. func (x *TypeAssertExpr) Pos() token.Pos

type TypeSpec

  1. type TypeSpec struct {
  2. Doc *CommentGroup // associated documentation; or nil
  3. Name *Ident // type name
  4. Assign token.Pos // position of '=', if any
  5. Type Expr // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes
  6. Comment *CommentGroup // line comments; or nil
  7. }

A TypeSpec node represents a type declaration (TypeSpec production).

func (*TypeSpec) End

  1. func (s *TypeSpec) End() token.Pos

func (*TypeSpec) Pos

  1. func (s *TypeSpec) Pos() token.Pos

type TypeSwitchStmt

  1. type TypeSwitchStmt struct {
  2. Switch token.Pos // position of "switch" keyword
  3. Init Stmt // initialization statement; or nil
  4. Assign Stmt // x := y.(type) or y.(type)
  5. Body *BlockStmt // CaseClauses only
  6. }

An TypeSwitchStmt node represents a type switch statement.

func (*TypeSwitchStmt) End

  1. func (s *TypeSwitchStmt) End() token.Pos

func (*TypeSwitchStmt) Pos

  1. func (s *TypeSwitchStmt) Pos() token.Pos

type UnaryExpr

  1. type UnaryExpr struct {
  2. OpPos token.Pos // position of Op
  3. Op token.Token // operator
  4. X Expr // operand
  5. }

A UnaryExpr node represents a unary expression. Unary “*” expressions are
represented via StarExpr nodes.

func (*UnaryExpr) End

  1. func (x *UnaryExpr) End() token.Pos

func (*UnaryExpr) Pos

  1. func (x *UnaryExpr) Pos() token.Pos

type ValueSpec

  1. type ValueSpec struct {
  2. Doc *CommentGroup // associated documentation; or nil
  3. Names []*Ident // value names (len(Names) > 0)
  4. Type Expr // value type; or nil
  5. Values []Expr // initial values; or nil
  6. Comment *CommentGroup // line comments; or nil
  7. }

A ValueSpec node represents a constant or variable declaration (ConstSpec or
VarSpec production).

func (*ValueSpec) End

  1. func (s *ValueSpec) End() token.Pos

func (*ValueSpec) Pos

  1. func (s *ValueSpec) Pos() token.Pos

type Visitor

  1. type Visitor interface {
  2. Visit(node Node) (w Visitor)
  3. }

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).