package ast

Import Path
	go/ast (on go.dev)

Dependency Relation
	imports 12 packages, and imported by 9 packages

Involved Source Files Package ast declares the types used to represent syntax trees for Go packages. commentmap.go filter.go import.go print.go resolve.go scope.go walk.go
Code Examples package main import ( "fmt" "go/ast" "go/format" "go/parser" "go/token" "strings" ) 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 strings.Builder if err := format.Node(&buf, fset, f); err != nil { panic(err) } fmt.Printf("%s", buf.String()) } 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 ( "fmt" "go/ast" "go/parser" "go/token" ) func main() { src := ` package p func f(x, y int) { print(x + y) } ` fset := token.NewFileSet() f, err := parser.ParseFile(fset, "", src, 0) if err != nil { panic(err) } // Print identifiers in order for n := range ast.Preorder(f) { id, ok := n.(*ast.Ident) if !ok { continue } fmt.Println(id.Name) } } 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 71)
/* sort 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 : Expr *ArrayType : Node
An AssignStmt node represents an assignment or a short variable declaration. Lhs []Expr Rhs []Expr // assignment token, DEFINE // position of Tok (*AssignStmt) End() token.Pos (*AssignStmt) Pos() token.Pos *AssignStmt : Node *AssignStmt : Stmt
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 *BadDecl : Decl *BadDecl : Node
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 *BadExpr : Expr *BadExpr : Node
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 *BadStmt : Node *BadStmt : Stmt
A BasicLit node represents a literal of basic type. // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o` // literal position (*BasicLit) End() token.Pos (*BasicLit) Pos() token.Pos *BasicLit : Expr *BasicLit : Node
A BinaryExpr node represents a binary expression. // operator // position of Op // left operand // right operand (*BinaryExpr) End() token.Pos (*BinaryExpr) Pos() token.Pos *BinaryExpr : Expr *BinaryExpr : Node
A BlockStmt node represents a braced statement list. // position of "{" List []Stmt // position of "}", if any (may be absent due to syntax error) (*BlockStmt) End() token.Pos (*BlockStmt) Pos() token.Pos *BlockStmt : Node *BlockStmt : Stmt
A BranchStmt node represents a break, continue, goto, or fallthrough statement. // label name; or nil // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH) // position of Tok (*BranchStmt) End() token.Pos (*BranchStmt) Pos() token.Pos *BranchStmt : Node *BranchStmt : Stmt
A CallExpr node represents an expression followed by an argument list. // function arguments; or nil // position of "..." (token.NoPos if there is no "...") // function expression // position of "(" // position of ")" (*CallExpr) End() token.Pos (*CallExpr) Pos() token.Pos *CallExpr : Expr *CallExpr : Node
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 : Node *CaseClause : Stmt
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 : Expr *ChanType : Node
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 : Node *CommClause : Stmt
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 [Comment.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
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 func CommentMap.Comments() []*CommentGroup func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap
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 : expvar.Var CommentMap : fmt.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 : Expr *CompositeLit : Node
All declaration nodes implement the Decl interface. // position of first character immediately after the node // position of first character belonging to the node *BadDecl *FuncDecl *GenDecl Decl : Node func FilterDecl(decl Decl, f Filter) 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 : Node *DeclStmt : Stmt
A DeferStmt node represents a defer statement. Call *CallExpr // position of "defer" keyword (*DeferStmt) End() token.Pos (*DeferStmt) Pos() token.Pos *DeferStmt : Node *DeferStmt : Stmt
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 : Expr *Ellipsis : Node
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 : Node *EmptyStmt : Stmt
All expression nodes implement the Expr interface. // position of first character immediately after the node // position of first character belonging to the node *ArrayType *BadExpr *BasicLit *BinaryExpr *CallExpr *ChanType *CompositeLit *Ellipsis *FuncLit *FuncType *Ident *IndexExpr *IndexListExpr *InterfaceType *KeyValueExpr *MapType *ParenExpr *SelectorExpr *SliceExpr *StarExpr *StructType *TypeAssertExpr *UnaryExpr Expr : Node func Unparen(e Expr) Expr func go/internal/typeparams.PackIndexExpr(x Expr, lbrack token.Pos, exprs []Expr, rbrack token.Pos) Expr func go/parser.ParseExpr(x string) (Expr, error) func go/parser.ParseExprFrom(fset *token.FileSet, filename string, src any, mode parser.Mode) (expr Expr, err error) func Unparen(e Expr) Expr func go/internal/typeparams.PackIndexExpr(x Expr, lbrack token.Pos, exprs []Expr, rbrack token.Pos) Expr func go/internal/typeparams.PackIndexExpr(x Expr, lbrack token.Pos, exprs []Expr, rbrack token.Pos) Expr func go/types.CheckExpr(fset *token.FileSet, pkg *types.Package, pos token.Pos, expr Expr, info *types.Info) (err error) func go/types.ExprString(x Expr) string func go/types.WriteExpr(buf *bytes.Buffer, x Expr) func go/types.(*Info).TypeOf(e Expr) types.Type
An ExprStmt node represents a (stand-alone) expression in a statement list. // expression (*ExprStmt) End() token.Pos (*ExprStmt) Pos() token.Pos *ExprStmt : Node *ExprStmt : Stmt
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
A FieldFilter may be provided to [Fprint] to control the output. func Fprint(w io.Writer, fset *token.FileSet, x any, f FieldFilter) error
A FieldList represents a list of Fields, enclosed by parentheses, curly braces, or square brackets. // position of closing parenthesis/brace/bracket, if any // field list; or nil // position of opening parenthesis/brace/bracket, if any (*FieldList) End() token.Pos NumFields returns the number of parameters or struct fields represented by a [FieldList]. (*FieldList) Pos() token.Pos *FieldList : Node
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 // start and end of entire file // start and end of entire file // minimum Go version required by //go:build or // +build directives // imports in this file // package name // position of "package" keyword // package scope (this file only). Deprecated: see Object // unresolved identifiers in this file. Deprecated: see Object End returns the end of the last declaration in the file. (Use FileEnd for the end of the entire file.) Pos returns the position of the package declaration. (Use FileStart for the start of the entire file.) *File : Node 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 FileExports(src *File) bool func FilterFile(src *File, f Filter) bool func IsGenerated(file *File) 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) (err error) func go/types.(*Config).Check(path string, fset *token.FileSet, files []*File, info *types.Info) (*types.Package, error)
func FilterDecl(decl Decl, f Filter) bool func FilterFile(src *File, f Filter) bool func FilterPackage(pkg *Package, f Filter) bool
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 : Node *ForStmt : Stmt
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 : Decl *FuncDecl : Node
A FuncLit node represents a function literal. // function body // function type (*FuncLit) End() token.Pos (*FuncLit) Pos() token.Pos *FuncLit : Expr *FuncLit : Node
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 : Expr *FuncType : Node
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 : Decl *GenDecl : Node
A GoStmt node represents a go statement. Call *CallExpr // position of "go" keyword (*GoStmt) End() token.Pos (*GoStmt) Pos() token.Pos *GoStmt : Node *GoStmt : Stmt
An Ident node represents an identifier. // identifier name // identifier position // denoted object, or nil. Deprecated: see Object. (*Ident) End() token.Pos IsExported reports whether id starts with an upper-case letter. (*Ident) Pos() token.Pos (*Ident) String() string *Ident : Expr *Ident : Node *Ident : expvar.Var *Ident : fmt.Stringer func NewIdent(name string) *Ident func go/types.(*Info).ObjectOf(id *Ident) types.Object
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 : Node *IfStmt : Stmt
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. Deprecated: use the type checker [go/types] instead; see [Object]. 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 *ImportSpec : Node *ImportSpec : Spec func go/types.(*Info).PkgNameOf(imp *ImportSpec) *types.PkgName
An IncDecStmt node represents an increment or decrement statement. // INC or DEC // position of Tok X Expr (*IncDecStmt) End() token.Pos (*IncDecStmt) Pos() token.Pos *IncDecStmt : Node *IncDecStmt : Stmt
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 : Expr *IndexExpr : Node
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 : Expr *IndexListExpr : Node
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 : Expr *InterfaceType : Node
A KeyValueExpr node represents (key : value) pairs in composite literals. // position of ":" Key Expr Value Expr (*KeyValueExpr) End() token.Pos (*KeyValueExpr) Pos() token.Pos *KeyValueExpr : Expr *KeyValueExpr : Node
A LabeledStmt node represents a labeled statement. // position of ":" Label *Ident Stmt Stmt (*LabeledStmt) End() token.Pos (*LabeledStmt) Pos() token.Pos *LabeledStmt : Node *LabeledStmt : Stmt
A MapType node represents a map type. Key Expr // position of "map" keyword Value Expr (*MapType) End() token.Pos (*MapType) Pos() token.Pos *MapType : Expr *MapType : Node
The MergeMode flags control the behavior of [MergePackageFiles]. func MergePackageFiles(pkg *Package, mode MergeMode) *File const FilterFuncDuplicates const FilterImportDuplicates const FilterUnassociatedComments
All node types implement the Node interface. // position of first character immediately after the node // position of first character belonging to the node *ArrayType *AssignStmt *BadDecl *BadExpr *BadStmt *BasicLit *BinaryExpr *BlockStmt *BranchStmt *CallExpr *CaseClause *ChanType *CommClause *Comment *CommentGroup *CompositeLit Decl (interface) *DeclStmt *DeferStmt *Ellipsis *EmptyStmt Expr (interface) *ExprStmt *Field *FieldList *File *ForStmt *FuncDecl *FuncLit *FuncType *GenDecl *GoStmt *Ident *IfStmt *ImportSpec *IncDecStmt *IndexExpr *IndexListExpr *InterfaceType *KeyValueExpr *LabeledStmt *MapType *Package *ParenExpr *RangeStmt *ReturnStmt *SelectorExpr *SelectStmt *SendStmt *SliceExpr Spec (interface) *StarExpr Stmt (interface) *StructType *SwitchStmt *TypeAssertExpr *TypeSpec *TypeSwitchStmt *UnaryExpr *ValueSpec *go/types.Scope func CommentMap.Update(old, new Node) Node func Inspect(node Node, f func(Node) bool) func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap func Preorder(root Node) iter.Seq[Node] func Walk(v Visitor, node Node) func CommentMap.Filter(node Node) CommentMap func CommentMap.Update(old, new Node) Node func Visitor.Visit(node Node) (w Visitor) func go/internal/typeparams.UnpackIndexExpr(n Node) *typeparams.IndexExpr
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 Deprecated: The relationship between Idents and Objects cannot be correctly computed without type information. For example, the expression T{K: 0} may denote a struct, map, slice, or array literal, depending on the type of T. If T is a struct, then K refers to a field of T, whereas for the other types it refers to a value in the environment. New programs should set the [parser.SkipObjectResolution] parser flag to disable syntactic object resolution (which also saves CPU and memory), and instead use the type checker [go/types] if object resolution is desired. See the Defs, Uses, and Implicits fields of the [types.Info] struct for details. // object-specific data; or nil // corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil Kind ObjKind // 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). func NewObj(kind ObjKind, name string) *Object func (*Scope).Insert(obj *Object) (alt *Object) func (*Scope).Lookup(name string) *Object func (*Scope).Insert(obj *Object) (alt *Object)
ObjKind describes what an [Object] represents. ( ObjKind) String() string ObjKind : expvar.Var ObjKind : fmt.Stringer func NewObj(kind ObjKind, name string) *Object const Bad const Con const Fun const Lbl const Pkg const Typ const Var
A Package node represents a set of source files collectively building a Go package. Deprecated: use the type checker [go/types] instead; see [Object]. // Go source files by filename // map of package id -> package object // package name // package scope across all files (*Package) End() token.Pos (*Package) Pos() token.Pos *Package : Node func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error) func go/parser.ParseDir(fset *token.FileSet, path string, filter func(fs.FileInfo) bool, mode parser.Mode) (pkgs map[string]*Package, first error) func FilterPackage(pkg *Package, f Filter) bool func MergePackageFiles(pkg *Package, mode MergeMode) *File func PackageExports(pkg *Package) bool func go/doc.New(pkg *Package, importPath string, mode doc.Mode) *doc.Package
A ParenExpr node represents a parenthesized expression. // position of "(" // position of ")" // parenthesized expression (*ParenExpr) End() token.Pos (*ParenExpr) Pos() token.Pos *ParenExpr : Expr *ParenExpr : Node
A RangeStmt represents a for statement with a range clause. Body *BlockStmt // position of "for" keyword // Key, Value may be nil // position of "range" keyword // 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 : Node *RangeStmt : Stmt
A ReturnStmt node represents a return statement. // result expressions; or nil // position of "return" keyword (*ReturnStmt) End() token.Pos (*ReturnStmt) Pos() token.Pos *ReturnStmt : Node *ReturnStmt : Stmt
A Scope maintains the set of named language entities declared in the scope and a link to the immediately surrounding (outer) scope. Deprecated: use the type checker [go/types] instead; see [Object]. Objects map[string]*Object Outer *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 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
A SelectorExpr node represents an expression followed by a selector. // field selector // expression (*SelectorExpr) End() token.Pos (*SelectorExpr) Pos() token.Pos *SelectorExpr : Expr *SelectorExpr : Node
A SelectStmt node represents a select statement. // CommClauses only // position of "select" keyword (*SelectStmt) End() token.Pos (*SelectStmt) Pos() token.Pos *SelectStmt : Node *SelectStmt : Stmt
A SendStmt node represents a send statement. // position of "<-" Chan Expr Value Expr (*SendStmt) End() token.Pos (*SendStmt) Pos() token.Pos *SendStmt : Node *SendStmt : Stmt
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 : Expr *SliceExpr : Node
The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec. // position of first character immediately after the node // position of first character belonging to the node *ImportSpec *TypeSpec *ValueSpec Spec : Node
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 : Expr *StarExpr : Node
All statement nodes implement the Stmt interface. // position of first character immediately after the node // position of first character belonging to the node *AssignStmt *BadStmt *BlockStmt *BranchStmt *CaseClause *CommClause *DeclStmt *DeferStmt *EmptyStmt *ExprStmt *ForStmt *GoStmt *IfStmt *IncDecStmt *LabeledStmt *RangeStmt *ReturnStmt *SelectStmt *SendStmt *SwitchStmt *TypeSwitchStmt Stmt : Node
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 : Expr *StructType : Node
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 : Node *SwitchStmt : Stmt
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 : Expr *TypeAssertExpr : Node
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 : Node *TypeSpec : Spec
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 : Node *TypeSwitchStmt : Stmt
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 : Expr *UnaryExpr : Node
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 : Node *ValueSpec : Spec
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) func Visitor.Visit(node Node) (w Visitor) func Walk(v Visitor, node Node)
Package-Level Functions (total 21)
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.
IsGenerated reports whether the file was generated by a program, not handwritten, by detecting the special comment described at https://go.dev/s/generatedcode. The syntax tree must have been parsed with the [parser.ParseComments] flag. Example: f, err := parser.ParseFile(fset, filename, src, parser.ParseComments|parser.PackageClauseOnly) if err != nil { ... } gen := ast.IsGenerated(f)
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. Deprecated: use the type checker [go/types] instead; see [Object].
NewScope creates a new scope nested in the outer scope.
NotNilFilter is a [FieldFilter] that 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.
Preorder returns an iterator over all the nodes of the syntax tree beneath (and including) the specified root, in depth-first preorder. For greater control over the traversal of each subtree, use [Inspect].
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.
Unparen returns the expression with any enclosing parentheses removed.
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).
Package-Level Constants (total 12)
The list of possible [Object] kinds.
The list of possible [Object] kinds.
If set, duplicate function declarations are excluded.
If set, duplicate import declarations are excluded.
If set, comments that are not associated with a specific AST node (as Doc or Comment) are excluded.
The list of possible [Object] kinds.
The list of possible [Object] kinds.
The list of possible [Object] kinds.
const RECV ChanDir = 2
const SEND ChanDir = 1
The list of possible [Object] kinds.
The list of possible [Object] kinds.