Code Examples
package main
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
)
func main() {
// 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.
for i, decl := range f.Decls {
if gen, ok := decl.(*ast.GenDecl); ok && gen.Tok == token.VAR {
copy(f.Decls[i:], f.Decls[i+1:])
f.Decls = f.Decls[:len(f.Decls)-1]
break
}
}
// 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())
}
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func main() {
// 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
})
}
package main
import (
"go/ast"
"go/parser"
"go/token"
)
func main() {
// 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)
}
Package-Level Type Names (total 81, in which 71 are exported)
/* sort exporteds by: | */
An ArrayType node represents an array or slice type.
// element type
// position of "["
// Ellipsis node for [...]T array types, nil for slice types
(*ArrayType) End() token.Pos(*ArrayType) Pos() token.Pos(*ArrayType) exprNode()
*ArrayType : Expr
*ArrayType : Node
*ArrayType : go/types.positioner
An AssignStmt node represents an assignment or
a short variable declaration.
Lhs[]ExprRhs[]Expr
// assignment token, DEFINE
// position of Tok
(*AssignStmt) End() token.Pos(*AssignStmt) Pos() token.Pos(*AssignStmt) stmtNode()
*AssignStmt : Node
*AssignStmt : Stmt
*AssignStmt : go/types.positioner
A BadDecl node is a placeholder for a declaration containing
syntax errors for which a correct declaration node cannot be
created.
// position range of bad expression
// position range of bad expression
(*BadDecl) End() token.Pos(*BadDecl) Pos() token.Pos
declNode() ensures that only declaration nodes can be
assigned to a Decl.
*BadDecl : Decl
*BadDecl : Node
*BadDecl : go/types.positioner
A BadExpr node is a placeholder for an expression containing
syntax errors for which a correct expression node cannot be
created.
// position range of bad expression
// position range of bad expression
(*BadExpr) End() token.Pos(*BadExpr) Pos() token.Pos
exprNode() ensures that only expression/type nodes can be
assigned to an Expr.
*BadExpr : Expr
*BadExpr : Node
*BadExpr : go/types.positioner
A BadStmt node is a placeholder for statements containing
syntax errors for which no correct statement nodes can be
created.
// position range of bad expression
// position range of bad expression
(*BadStmt) End() token.Pos(*BadStmt) Pos() token.Pos
stmtNode() ensures that only statement nodes can be
assigned to a Stmt.
*BadStmt : Node
*BadStmt : Stmt
*BadStmt : go/types.positioner
A CaseClause represents a case of an expression or type switch statement.
// statement list; or nil
// position of "case" or "default" keyword
// position of ":"
// list of expressions or types; nil means default case
(*CaseClause) End() token.Pos(*CaseClause) Pos() token.Pos(*CaseClause) stmtNode()
*CaseClause : Node
*CaseClause : Stmt
*CaseClause : go/types.positioner
The direction of a channel type is indicated by a bit
mask including one or both of the following constants.
const RECV
const SEND
A ChanType node represents a channel type.
// position of "<-" (token.NoPos if there is no "<-")
// position of "chan" keyword or "<-" (whichever comes first)
// channel direction
// value type
(*ChanType) End() token.Pos(*ChanType) Pos() token.Pos(*ChanType) exprNode()
*ChanType : Expr
*ChanType : Node
*ChanType : go/types.positioner
A CommClause node represents a case of a select statement.
// statement list; or nil
// position of "case" or "default" keyword
// position of ":"
// send or receive statement; nil means default case
(*CommClause) End() token.Pos(*CommClause) Pos() token.Pos(*CommClause) stmtNode()
*CommClause : Node
*CommClause : Stmt
*CommClause : go/types.positioner
A Comment node represents a single //-style or /*-style comment.
The Text field contains the comment text without carriage returns (\r) that
may have been present in the source. Because a comment's end position is
computed using len(Text), the position reported by End() does not match the
true source end position for comments containing carriage returns.
// position of "/" starting the comment
// comment text (excluding '\n' for //-style comments)
(*Comment) End() token.Pos(*Comment) Pos() token.Pos
*Comment : Node
*Comment : go/types.positioner
var separator *Comment
A CommentGroup represents a sequence of comments
with no other tokens and no empty lines between.
// len(List) > 0
(*CommentGroup) End() token.Pos(*CommentGroup) Pos() token.Pos
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.
Comment directives like "//line" and "//go:noinline" are also removed.
Multiple empty lines are reduced to one, and trailing space on lines is trimmed.
Unless the result is empty, it is newline-terminated.
*CommentGroup : Node
*CommentGroup : go/types.positioner
func CommentMap.Comments() []*CommentGroup
func go/doc.lastComment(b *BlockStmt, c []*CommentGroup) (i int, last *CommentGroup)
func go/doc.stripOutputComment(body *BlockStmt, comments []*CommentGroup) (*BlockStmt, []*CommentGroup)
func go/printer.getDoc(n Node) *CommentGroup
func go/printer.getLastComment(n Node) *CommentGroup
func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap
func sortComments(list []*CommentGroup)
func summary(list []*CommentGroup) string
func CommentMap.addComment(n Node, c *CommentGroup)
func go/build.(*Context).saveCgo(filename string, di *build.Package, cg *CommentGroup) error
func go/doc.exampleOutput(b *BlockStmt, comments []*CommentGroup) (output string, unordered, ok bool)
func go/doc.lastComment(b *BlockStmt, c []*CommentGroup) (i int, last *CommentGroup)
func go/doc.stripOutputComment(body *BlockStmt, comments []*CommentGroup) (*BlockStmt, []*CommentGroup)
A CommentMap maps an AST node to a list of comment groups
associated with it. See NewCommentMap for a description of
the association.
Comments returns the list of comment groups in the comment map.
The result is sorted in source order.
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.
( CommentMap) String() string
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.
( CommentMap) addComment(n Node, c *CommentGroup)
CommentMap : expvar.Var
CommentMap : fmt.Stringer
CommentMap : context.stringer
CommentMap : github.com/aws/smithy-go/middleware.stringer
CommentMap : runtime.stringer
func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap
func CommentMap.Filter(node Node) CommentMap
A CompositeLit node represents a composite literal.
// list of composite elements; or nil
// true if (source) expressions are missing in the Elts list
// position of "{"
// position of "}"
// literal type; or nil
(*CompositeLit) End() token.Pos(*CompositeLit) Pos() token.Pos(*CompositeLit) exprNode()
*CompositeLit : Expr
*CompositeLit : Node
*CompositeLit : go/types.positioner
func filterCompositeLit(lit *CompositeLit, filter Filter, export bool)
func go/doc.filterCompositeLit(lit *CompositeLit, filter doc.Filter, export bool)
A DeclStmt node represents a declaration in a statement list.
// *GenDecl with CONST, TYPE, or VAR token
(*DeclStmt) End() token.Pos(*DeclStmt) Pos() token.Pos(*DeclStmt) stmtNode()
*DeclStmt : Node
*DeclStmt : Stmt
*DeclStmt : go/types.positioner
A DeferStmt node represents a defer statement.
Call*CallExpr
// position of "defer" keyword
(*DeferStmt) End() token.Pos(*DeferStmt) Pos() token.Pos(*DeferStmt) stmtNode()
*DeferStmt : Node
*DeferStmt : Stmt
*DeferStmt : go/types.positioner
func gotest.tools/v3/internal/source.collectDefers(node Node) []*DeferStmt
An Ellipsis node stands for the "..." type in a
parameter list or the "..." length in an array type.
// position of "..."
// ellipsis element type (parameter lists only); or nil
(*Ellipsis) End() token.Pos(*Ellipsis) Pos() token.Pos(*Ellipsis) exprNode()
*Ellipsis : Expr
*Ellipsis : Node
*Ellipsis : go/types.positioner
An EmptyStmt node represents an empty statement.
The "position" of the empty statement is the position
of the immediately following (explicit or implicit) semicolon.
// if set, ";" was omitted in the source
// position of following ";"
(*EmptyStmt) End() token.Pos(*EmptyStmt) Pos() token.Pos(*EmptyStmt) stmtNode()
*EmptyStmt : Node
*EmptyStmt : Stmt
*EmptyStmt : go/types.positioner
An ExprStmt node represents a (stand-alone) expression
in a statement list.
// expression
(*ExprStmt) End() token.Pos(*ExprStmt) Pos() token.Pos(*ExprStmt) stmtNode()
*ExprStmt : Node
*ExprStmt : Stmt
*ExprStmt : go/types.positioner
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.
Field.Names is nil for unnamed parameters (parameter lists which only contain types)
and embedded struct fields. In the latter case, the field name is the type name.
// line comments; or nil
// associated documentation; or nil
// field/method/(type) parameter names; or nil
// field tag; or nil
// field/method/parameter type; or nil
(*Field) End() token.Pos(*Field) Pos() token.Pos
*Field : Node
*Field : go/types.positioner
func go/doc.fields(typ Expr) (list []*Field, isStruct bool)
func go/types.writeFieldList(buf *bytes.Buffer, list []*Field, sep string, iface bool)
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).
// list of all comments in the source file
// top-level declarations; or nil
// associated documentation; or nil
// imports in this file
// package name
// position of "package" keyword
// package scope (this file only)
// unresolved identifiers in this file
(*File) End() token.Pos(*File) Pos() token.Pos
*File : Node
*File : go/types.positioner
func MergePackageFiles(pkg *Package, mode MergeMode) *File
func go/parser.ParseFile(fset *token.FileSet, filename string, src any, mode parser.Mode) (f *File, err error)
func go/doc.playExample(file *File, f *FuncDecl) *File
func go/doc.playExampleFile(file *File) *File
func go/format.parse(fset *token.FileSet, filename string, src []byte, fragmentOk bool) (file *File, sourceAdj func(src []byte, indent int) []byte, indentAdj int, err error)
func FileExports(src *File) bool
func FilterFile(src *File, f Filter) bool
func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error)
func SortImports(fset *token.FileSet, f *File)
func go/doc.Examples(testFiles ...*File) []*doc.Example
func go/doc.NewFromFiles(fset *token.FileSet, files []*File, importPath string, opts ...any) (*doc.Package, error)
func go/types.(*Checker).Files(files []*File) error
func go/types.(*Config).Check(path string, fset *token.FileSet, files []*File, info *types.Info) (*types.Package, error)
func gotest.tools/v3/internal/source.UpdateVariable(filename string, fileset *token.FileSet, astFile *File, ident *Ident, value string) error
func filterFile(src *File, f Filter, export bool) bool
func sortSpecs(fset *token.FileSet, f *File, specs []Spec) []Spec
func go/doc.playExample(file *File, f *FuncDecl) *File
func go/doc.playExampleFile(file *File) *File
func go/format.format(fset *token.FileSet, file *File, sourceAdj func(src []byte, indent int) []byte, indentAdj int, src []byte, cfg printer.Config) ([]byte, error)
func go/format.hasUnsortedImports(file *File) bool
func go/parser.resolveFile(file *File, handle *token.File, declErr func(token.Pos, string))
func go/types.(*Checker).checkFiles(files []*File) (err error)
func go/types.(*Checker).initFiles(files []*File)
A ForStmt represents a for statement.
Body*BlockStmt
// condition; or nil
// position of "for" keyword
// initialization statement; or nil
// post iteration statement; or nil
(*ForStmt) End() token.Pos(*ForStmt) Pos() token.Pos(*ForStmt) stmtNode()
*ForStmt : Node
*ForStmt : Stmt
*ForStmt : go/types.positioner
A FuncDecl node represents a function declaration.
// function body; or nil for external (non-Go) function
// associated documentation; or nil
// function/method name
// receiver (methods); or nil (functions)
// function signature: type and value parameters, results, and position of "func" keyword
(*FuncDecl) End() token.Pos(*FuncDecl) Pos() token.Pos(*FuncDecl) declNode()
*FuncDecl : Decl
*FuncDecl : Node
*FuncDecl : go/types.positioner
func nameOf(f *FuncDecl) string
func go/doc.playExample(file *File, f *FuncDecl) *File
A FuncLit node represents a function literal.
// function body
// function type
(*FuncLit) End() token.Pos(*FuncLit) Pos() token.Pos(*FuncLit) exprNode()
*FuncLit : Expr
*FuncLit : Node
*FuncLit : go/types.positioner
A FuncType node represents a function type.
// position of "func" keyword (token.NoPos if there is no "func")
// (incoming) parameters; non-nil
// (outgoing) results; or nil
// type parameters; or nil
(*FuncType) End() token.Pos(*FuncType) Pos() token.Pos(*FuncType) exprNode()
*FuncType : Expr
*FuncType : Node
*FuncType : go/types.positioner
func golang.org/x/tools/internal/typeparams.ForFuncType(n *FuncType) *FieldList
func go/types.writeSigExpr(buf *bytes.Buffer, sig *FuncType)
func go/types.(*Checker).funcType(sig *types.Signature, recvPar *FieldList, ftyp *FuncType)
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
// associated documentation; or nil
// position of '(', if any
// position of ')', if any
Specs[]Spec
// IMPORT, CONST, TYPE, or VAR
// position of Tok
(*GenDecl) End() token.Pos(*GenDecl) Pos() token.Pos(*GenDecl) declNode()
*GenDecl : Decl
*GenDecl : Node
*GenDecl : go/types.positioner
func go/doc.matchDecl(d *GenDecl, f doc.Filter) bool
func go/doc.sortingName(d *GenDecl) string
An IfStmt node represents an if statement.
Body*BlockStmt
// condition
// else branch; or nil
// position of "if" keyword
// initialization statement; or nil
(*IfStmt) End() token.Pos(*IfStmt) Pos() token.Pos(*IfStmt) stmtNode()
*IfStmt : Node
*IfStmt : Stmt
*IfStmt : go/types.positioner
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.
func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error)
An ImportSpec node represents a single package import.
// line comments; or nil
// associated documentation; or nil
// end of spec (overrides Path.Pos if nonzero)
// local package name (including "."); or nil
// import path
(*ImportSpec) End() token.Pos(*ImportSpec) Pos() token.Pos
specNode() ensures that only spec nodes can be
assigned to a Spec.
*ImportSpec : Node
*ImportSpec : Spec
*ImportSpec : go/types.positioner
An IncDecStmt node represents an increment or decrement statement.
// INC or DEC
// position of Tok
XExpr(*IncDecStmt) End() token.Pos(*IncDecStmt) Pos() token.Pos(*IncDecStmt) stmtNode()
*IncDecStmt : Node
*IncDecStmt : Stmt
*IncDecStmt : go/types.positioner
An IndexExpr node represents an expression followed by an index.
// index expression
// position of "["
// position of "]"
// expression
(*IndexExpr) End() token.Pos(*IndexExpr) Pos() token.Pos(*IndexExpr) exprNode()
*IndexExpr : Expr
*IndexExpr : Node
*IndexExpr : go/types.positioner
An IndexListExpr node represents an expression followed by multiple
indices.
// index expressions
// position of "["
// position of "]"
// expression
(*IndexListExpr) End() token.Pos(*IndexListExpr) Pos() token.Pos(*IndexListExpr) exprNode()
*IndexListExpr : Expr
*IndexListExpr : Node
*IndexListExpr : go/types.positioner
An InterfaceType node represents an interface type.
// true if (source) methods or types are missing in the Methods list
// position of "interface" keyword
// list of embedded interfaces, methods, or types
(*InterfaceType) End() token.Pos(*InterfaceType) Pos() token.Pos(*InterfaceType) exprNode()
*InterfaceType : Expr
*InterfaceType : Node
*InterfaceType : go/types.positioner
func go/doc.removeAnonymousField(name string, ityp *InterfaceType)
func go/types.(*Checker).interfaceType(ityp *types.Interface, iface *InterfaceType, def *types.Named)
A KeyValueExpr node represents (key : value) pairs
in composite literals.
// position of ":"
KeyExprValueExpr(*KeyValueExpr) End() token.Pos(*KeyValueExpr) Pos() token.Pos(*KeyValueExpr) exprNode()
*KeyValueExpr : Expr
*KeyValueExpr : Node
*KeyValueExpr : go/types.positioner
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
// object-specific data; or nil
// corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil
KindObjKind
// declared name
// placeholder for type information; may be nil
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).
*Object : go/types.positioner
func NewObj(kind ObjKind, name string) *Object
func (*Scope).Insert(obj *Object) (alt *Object)
func (*Scope).Lookup(name string) *Object
func go/doc.simpleImporter(imports map[string]*Object, path string) (*Object, error)
func (*Scope).Insert(obj *Object) (alt *Object)
func go/doc.simpleImporter(imports map[string]*Object, path string) (*Object, error)
var go/parser.unresolved *Object
A ParenExpr node represents a parenthesized expression.
// position of "("
// position of ")"
// parenthesized expression
(*ParenExpr) End() token.Pos(*ParenExpr) Pos() token.Pos(*ParenExpr) exprNode()
*ParenExpr : Expr
*ParenExpr : Node
*ParenExpr : go/types.positioner
A RangeStmt represents a for statement with a range clause.
Body*BlockStmt
// position of "for" keyword
// Key, Value may be nil
// ILLEGAL if Key == nil, ASSIGN, DEFINE
// position of Tok; invalid if Key == nil
// Key, Value may be nil
// value to range over
(*RangeStmt) End() token.Pos(*RangeStmt) Pos() token.Pos(*RangeStmt) stmtNode()
*RangeStmt : Node
*RangeStmt : Stmt
*RangeStmt : go/types.positioner
A ReturnStmt node represents a return statement.
// result expressions; or nil
// position of "return" keyword
(*ReturnStmt) End() token.Pos(*ReturnStmt) Pos() token.Pos(*ReturnStmt) stmtNode()
*ReturnStmt : Node
*ReturnStmt : Stmt
*ReturnStmt : go/types.positioner
A Scope maintains the set of named language entities declared
in the scope and a link to the immediately surrounding (outer)
scope.
Objectsmap[string]*ObjectOuter*Scope
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.
Lookup returns the object with the given name if it is
found in scope s, otherwise it returns nil. Outer scopes
are ignored.
Debugging support
*Scope : expvar.Var
*Scope : fmt.Stringer
*Scope : context.stringer
*Scope : github.com/aws/smithy-go/middleware.stringer
*Scope : runtime.stringer
func NewScope(outer *Scope) *Scope
func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error)
func NewScope(outer *Scope) *Scope
func resolve(scope *Scope, ident *Ident) bool
A SliceExpr node represents an expression followed by slice indices.
// end of slice range; or nil
// position of "["
// begin of slice range; or nil
// maximum capacity of slice; or nil
// position of "]"
// true if 3-index slice (2 colons present)
// expression
(*SliceExpr) End() token.Pos(*SliceExpr) Pos() token.Pos(*SliceExpr) exprNode()
*SliceExpr : Expr
*SliceExpr : Node
*SliceExpr : go/types.positioner
func go/types.(*Checker).sliceExpr(x *types.operand, e *SliceExpr)
A StarExpr node represents an expression of the form "*" Expression.
Semantically it could be a unary "*" expression, or a pointer type.
// position of "*"
// operand
(*StarExpr) End() token.Pos(*StarExpr) Pos() token.Pos(*StarExpr) exprNode()
*StarExpr : Expr
*StarExpr : Node
*StarExpr : go/types.positioner
A StructType node represents a struct type.
// list of field declarations
// true if (source) fields are missing in the Fields list
// position of "struct" keyword
(*StructType) End() token.Pos(*StructType) Pos() token.Pos(*StructType) exprNode()
*StructType : Expr
*StructType : Node
*StructType : go/types.positioner
func go/types.(*Checker).structType(styp *types.Struct, e *StructType)
A SwitchStmt node represents an expression switch statement.
// CaseClauses only
// initialization statement; or nil
// position of "switch" keyword
// tag expression; or nil
(*SwitchStmt) End() token.Pos(*SwitchStmt) Pos() token.Pos(*SwitchStmt) stmtNode()
*SwitchStmt : Node
*SwitchStmt : Stmt
*SwitchStmt : go/types.positioner
A TypeAssertExpr node represents an expression followed by a
type assertion.
// position of "("
// position of ")"
// asserted type; nil means type switch X.(type)
// expression
(*TypeAssertExpr) End() token.Pos(*TypeAssertExpr) Pos() token.Pos(*TypeAssertExpr) exprNode()
*TypeAssertExpr : Expr
*TypeAssertExpr : Node
*TypeAssertExpr : go/types.positioner
A TypeSpec node represents a type declaration (TypeSpec production).
// position of '=', if any
// line comments; or nil
// associated documentation; or nil
// type name
// *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes
// type parameters; or nil
(*TypeSpec) End() token.Pos(*TypeSpec) Pos() token.Pos(*TypeSpec) specNode()
*TypeSpec : Node
*TypeSpec : Spec
*TypeSpec : go/types.positioner
func golang.org/x/tools/internal/typeparams.ForTypeSpec(n *TypeSpec) *FieldList
func go/types.(*Checker).typeDecl(obj *types.TypeName, tdecl *TypeSpec, def *types.Named)
A TypeSwitchStmt node represents a type switch statement.
// x := y.(type) or y.(type)
// CaseClauses only
// initialization statement; or nil
// position of "switch" keyword
(*TypeSwitchStmt) End() token.Pos(*TypeSwitchStmt) Pos() token.Pos(*TypeSwitchStmt) stmtNode()
*TypeSwitchStmt : Node
*TypeSwitchStmt : Stmt
*TypeSwitchStmt : go/types.positioner
A UnaryExpr node represents a unary expression.
Unary "*" expressions are represented via StarExpr nodes.
// operator
// position of Op
// operand
(*UnaryExpr) End() token.Pos(*UnaryExpr) Pos() token.Pos(*UnaryExpr) exprNode()
*UnaryExpr : Expr
*UnaryExpr : Node
*UnaryExpr : go/types.positioner
func go/types.(*Checker).unary(x *types.operand, e *UnaryExpr)
A ValueSpec node represents a constant or variable declaration
(ConstSpec or VarSpec production).
// line comments; or nil
// associated documentation; or nil
// value names (len(Names) > 0)
// value type; or nil
// initial values; or nil
(*ValueSpec) End() token.Pos(*ValueSpec) Pos() token.Pos(*ValueSpec) specNode()
*ValueSpec : Node
*ValueSpec : Spec
*ValueSpec : go/types.positioner
func go/types.(*Checker).arityMatch(s, init *ValueSpec)
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).
( Visitor) Visit(node Node) (w Visitor)inspector
*go/parser.resolver
*gotest.tools/v3/internal/source.callExprVisitor
func Visitor.Visit(node Node) (w Visitor)
func Walk(v Visitor, node Node)
func walkDeclList(v Visitor, list []Decl)
func walkExprList(v Visitor, list []Expr)
func walkIdentList(v Visitor, list []*Ident)
func walkStmtList(v Visitor, list []Stmt)
cg*CommentGroup
// true if comment is to the left of the spec, false otherwise.
A commentListReader helps iterating through a list of comment groups.
// comment group at current index
// source interval of comment group at current index
fset*token.FileSetindexintlist[]*CommentGroup
// source interval of comment group at current index
(*commentListReader) eol() bool(*commentListReader) next()
localError wraps locally caught errors so we can distinguish
them from genuine panics which we don't want to return as errors.
errerror
A nodeStack keeps track of nested nodes.
A node lower on the stack lexically contains the nodes higher on the stack.
pop pops all nodes that appear lexically before pos
(i.e., whose lexical extent has ended before or at pos).
It returns the last node popped.
push pops all nodes that appear lexically before n
and then pushes n on the stack.
Package-Level Functions (total 50, in which 18 are exported)
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.
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.
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.
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.
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.
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).
IsExported reports whether name starts with an upper-case letter.
MergePackageFiles creates a file AST by merging the ASTs of the
files belonging to a package. The mode flags control merging behavior.
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.
NewIdent creates a new Ident without position.
Useful for ASTs generated by code other than the Go parser.
NewObj creates a new object of a given kind and name.
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.
NewScope creates a new scope nested in the outer scope.
NotNilFilter returns true for field values that are not nil;
it returns false otherwise.
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.
Print prints x to standard output, skipping nil fields.
Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter).
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.
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).
collapse indicates whether prev may be removed, leaving only next.
exportFilter is a special filter function to extract exported nodes.
fieldName assumes that x is the type of an anonymous field and
returns the corresponding field name. If x is not an acceptable
anonymous field, the result is nil.
nameOf returns the function (foo) or method name (foo.bar) for
the given function declaration. If the AST is incorrect for the
receiver, it assumes a function instead.
nodeList returns the list of nodes of the AST n in source order.