ast
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package ast declares the types used to represent syntax trees for Gopackages.
Syntax trees may be constructed directly, but they are typicallyproduced from Go source code by the parser; see the ParseFilefunction in packagego/parser.
Index¶
- func FileExports(src *File) bool
- func FilterDecl(decl Decl, f Filter) bool
- func FilterFile(src *File, f Filter) bool
- func FilterPackage(pkg *Package, f Filter) booldeprecated
- func Fprint(w io.Writer, fset *token.FileSet, x any, f FieldFilter) error
- func Inspect(node Node, f func(Node) bool)
- func IsExported(name string) bool
- func IsGenerated(file *File) bool
- func NotNilFilter(_ string, v reflect.Value) bool
- func PackageExports(pkg *Package) booldeprecated
- func Preorder(root Node) iter.Seq[Node]
- func PreorderStack(root Node, stack []Node, f func(n Node, stack []Node) bool)
- func Print(fset *token.FileSet, x any) error
- func SortImports(fset *token.FileSet, f *File)
- func Walk(v Visitor, node Node)
- type ArrayType
- type AssignStmt
- type BadDecl
- type BadExpr
- type BadStmt
- type BasicLit
- type BinaryExpr
- type BlockStmt
- type BranchStmt
- type CallExpr
- type CaseClause
- type ChanDir
- type ChanType
- type CommClause
- type Comment
- type CommentGroup
- type CommentMap
- type CompositeLit
- type Decl
- type DeclStmt
- type DeferStmt
- type Ellipsis
- type EmptyStmt
- type Expr
- type ExprStmt
- type Field
- type FieldFilter
- type FieldList
- type File
- type Filter
- type ForStmt
- type FuncDecl
- type FuncLit
- type FuncType
- type GenDecl
- type GoStmt
- type Ident
- type IfStmt
- type ImportSpec
- type Importerdeprecated
- type IncDecStmt
- type IndexExpr
- type IndexListExpr
- type InterfaceType
- type KeyValueExpr
- type LabeledStmt
- type MapType
- type MergeModedeprecated
- type Node
- type ObjKind
- type Objectdeprecated
- type Packagedeprecated
- type ParenExpr
- type RangeStmt
- type ReturnStmt
- type Scopedeprecated
- type SelectStmt
- type SelectorExpr
- type SendStmt
- type SliceExpr
- type Spec
- type StarExpr
- type Stmt
- type StructType
- type SwitchStmt
- type TypeAssertExpr
- type TypeSpec
- type TypeSwitchStmt
- type UnaryExpr
- type ValueSpec
- type Visitor
Examples¶
Constants¶
This section is empty.
Variables¶
This section is empty.
Functions¶
funcFileExports¶
FileExports trims the AST for a Go source file in place such thatonly exported nodes remain: all top-level identifiers which are not exportedand their associated information (such as type, initial value, or functionbody) are removed. Non-exported fields and methods of exported types arestripped. The [File.Comments] list is not changed.
FileExports reports whether there are exported declarations.
funcFilterDecl¶
FilterDecl trims the AST for a Go declaration in place by removingall names (including struct field and interface method names, butnot from parameter lists) that don't pass through the filter f.
FilterDecl reports whether there are any declared names left afterfiltering.
funcFilterFile¶
FilterFile trims the AST for a Go file in place by removing allnames from top-level declarations (including struct field andinterface method names, but not from parameter lists) that don'tpass through the filter f. If the declaration is empty afterwards,the declaration is removed from the AST. Import declarations arealways removed. The [File.Comments] list is not changed.
FilterFile reports whether there are any top-level declarationsleft after filtering.
funcFilterPackagedeprecated
FilterPackage trims the AST for a Go package in place by removingall names from top-level declarations (including struct field andinterface method names, but not from parameter lists) that don'tpass through the filter f. If the declaration is empty afterwards,the declaration is removed from the AST. The pkg.Files list is notchanged, so that file names and top-level package comments don't getlost.
FilterPackage reports whether there are any top-level declarationsleft after filtering.
Deprecated: use the type checkergo/types instead ofPackage;seeObject. Alternatively, useFilterFile.
funcFprint¶
Fprint prints the (sub-)tree starting at AST node x to w.If fset != nil, position information is interpreted relativeto that file set. Otherwise positions are printed as integervalues (file set specific offsets).
A non-nilFieldFilter f may be provided to control the output:struct fields for which f(fieldname, fieldvalue) is true areprinted; all others are filtered from the output. Unexportedstruct fields are never printed.
funcInspect¶
Inspect traverses an AST in depth-first order: It starts by callingf(node); node must not be nil. If f returns true, Inspect invokes frecursively for each of the non-nil children of node, followed by acall of f(nil).
In many cases it may be more convenient to usePreorder, whichreturns an iterator over the sqeuence of nodes, orPreorderStack,which (likeInspect) provides control over descent into subtrees,but additionally reports the stack of enclosing nodes.
Example¶
This example demonstrates how to inspect the AST of a Go program.
package mainimport ("fmt""go/ast""go/parser""go/token")func main() {// src is the input for which we want to inspect the AST.src := `package pconst c = 1.0var X = f(3.14)*2 + c`// Create the AST by parsing src.fset := token.NewFileSet() // positions are relative to fsetf, 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 stringswitch x := n.(type) {case *ast.BasicLit:s = x.Valuecase *ast.Ident:s = x.Name}if s != "" {fmt.Printf("%s:\t%s\n", fset.Position(n.Pos()), s)}return true})}Output:src.go:2:9:psrc.go:3:7:csrc.go:3:11:1.0src.go:4:5:Xsrc.go:4:9:fsrc.go:4:11:3.14src.go:4:17:2src.go:4:21:c
funcIsExported¶
IsExported reports whether name starts with an upper-case letter.
funcIsGenerated¶added ingo1.21.0
IsGenerated reports whether the file was generated by a program,not handwritten, by detecting the special comment describedathttps://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)funcNotNilFilter¶
NotNilFilter is aFieldFilter that returns true for field valuesthat are not nil; it returns false otherwise.
funcPackageExportsdeprecated
PackageExports trims the AST for a Go package in place such thatonly exported nodes remain. The pkg.Files list is not changed, so thatfile names and top-level package comments don't get lost.
PackageExports reports whether there are exported declarations;it returns false otherwise.
Deprecated: use the type checkergo/types instead ofPackage;seeObject. Alternatively, useFileExports.
funcPreorder¶added ingo1.23.0
Preorder returns an iterator over all the nodes of the syntax treebeneath (and including) the specified root, in depth-firstpreorder.
For greater control over the traversal of each subtree, useInspect orPreorderStack.
Example¶
package mainimport ("fmt""go/ast""go/parser""go/token")func main() {src := `package pfunc 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 orderfor n := range ast.Preorder(f) {id, ok := n.(*ast.Ident)if !ok {continue}fmt.Println(id.Name)}}Output:pfxyintprintxy
funcPreorderStack¶added ingo1.25.0
PreorderStack traverses the tree rooted at root,calling f before visiting each node.
Each call to f provides the current node and traversal stack,consisting of the original value of stack appended with all nodesfrom root to n, excluding n itself. (This design allows callsto PreorderStack to be nested without double counting.)
If f returns false, the traversal skips over that subtree. UnlikeInspect, no second call to f is made after visiting node n.(In practice, the second call is nearly always used only to pop thestack, and it is surprisingly tricky to do this correctly.)
funcPrint¶
Print prints x to standard output, skipping nil fields.Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter).
Example¶
This example shows what an AST looks like when printed for debugging.
package mainimport ("go/ast""go/parser""go/token")func main() {// src is the input for which we want to print the AST.src := `package mainfunc main() {println("Hello, World!")}`// Create the AST by parsing src.fset := token.NewFileSet() // positions are relative to fsetf, err := parser.ParseFile(fset, "", src, 0)if err != nil {panic(err)}// Print the AST.ast.Print(fset, f)}Output: 0 *ast.File { 1 . Package: 2:1 2 . Name: *ast.Ident { 3 . . NamePos: 2:9 4 . . Name: "main" 5 . } 6 . Decls: []ast.Decl (len = 1) { 7 . . 0: *ast.FuncDecl { 8 . . . Name: *ast.Ident { 9 . . . . NamePos: 3:6 10 . . . . Name: "main" 11 . . . . Obj: *ast.Object { 12 . . . . . Kind: func 13 . . . . . Name: "main" 14 . . . . . Decl: *(obj @ 7) 15 . . . . } 16 . . . } 17 . . . Type: *ast.FuncType { 18 . . . . Func: 3:1 19 . . . . Params: *ast.FieldList { 20 . . . . . Opening: 3:10 21 . . . . . Closing: 3:11 22 . . . . } 23 . . . } 24 . . . Body: *ast.BlockStmt { 25 . . . . Lbrace: 3:13 26 . . . . List: []ast.Stmt (len = 1) { 27 . . . . . 0: *ast.ExprStmt { 28 . . . . . . X: *ast.CallExpr { 29 . . . . . . . Fun: *ast.Ident { 30 . . . . . . . . NamePos: 4:2 31 . . . . . . . . Name: "println" 32 . . . . . . . } 33 . . . . . . . Lparen: 4:9 34 . . . . . . . Args: []ast.Expr (len = 1) { 35 . . . . . . . . 0: *ast.BasicLit { 36 . . . . . . . . . ValuePos: 4:10 37 . . . . . . . . . Kind: STRING 38 . . . . . . . . . Value: "\"Hello, World!\"" 39 . . . . . . . . } 40 . . . . . . . } 41 . . . . . . . Ellipsis: - 42 . . . . . . . Rparen: 4:25 43 . . . . . . } 44 . . . . . } 45 . . . . } 46 . . . . Rbrace: 5:1 47 . . . } 48 . . } 49 . } 50 . FileStart: 1:1 51 . FileEnd: 5:3 52 . Scope: *ast.Scope { 53 . . Objects: map[string]*ast.Object (len = 1) { 54 . . . "main": *(obj @ 11) 55 . . } 56 . } 57 . Unresolved: []*ast.Ident (len = 1) { 58 . . 0: *(obj @ 29) 59 . } 60 . GoVersion: "" 61 }
funcSortImports¶
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.
Types¶
typeArrayType¶
type ArrayType struct {Lbracktoken.Pos// position of "["LenExpr// Ellipsis node for [...]T array types, nil for slice typesEltExpr// element type}An ArrayType node represents an array or slice type.
typeAssignStmt¶
type AssignStmt struct {Lhs []ExprTokPostoken.Pos// position of TokToktoken.Token// assignment token, DEFINERhs []Expr}An AssignStmt node represents an assignment ora short variable declaration.
func (*AssignStmt)End¶
func (s *AssignStmt) End()token.Pos
func (*AssignStmt)Pos¶
func (s *AssignStmt) Pos()token.Pos
typeBadDecl¶
A BadDecl node is a placeholder for a declaration containingsyntax errors for which a correct declaration node cannot becreated.
typeBadExpr¶
A BadExpr node is a placeholder for an expression containingsyntax errors for which a correct expression node cannot becreated.
typeBadStmt¶
A BadStmt node is a placeholder for statements containingsyntax errors for which no correct statement nodes can becreated.
typeBasicLit¶
type BasicLit struct {ValuePostoken.Pos// literal positionKindtoken.Token// token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRINGValuestring// literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o`}A BasicLit node represents a literal of basic type.
Note that for the CHAR and STRING kinds, the literal is storedwith its quotes. For example, for a double-quoted STRING, thefirst and the last rune in the Value field will be ". Thestrconv.Unquote andstrconv.UnquoteChar functions can beused to unquote STRING and CHAR values, respectively.
For raw string literals (Kind == token.STRING && Value[0] == '`'),the Value field contains the string text without carriage returns (\r) thatmay have been present in the source. Because the end position iscomputed using len(Value), the position reported byBasicLit.End does not match thetrue source end position for raw string literals containing carriage returns.
typeBinaryExpr¶
type BinaryExpr struct {XExpr// left operandOpPostoken.Pos// position of OpOptoken.Token// operatorYExpr// right operand}A BinaryExpr node represents a binary expression.
func (*BinaryExpr)End¶
func (x *BinaryExpr) End()token.Pos
func (*BinaryExpr)Pos¶
func (x *BinaryExpr) Pos()token.Pos
typeBlockStmt¶
type BlockStmt struct {Lbracetoken.Pos// position of "{"List []StmtRbracetoken.Pos// position of "}", if any (may be absent due to syntax error)}A BlockStmt node represents a braced statement list.
typeBranchStmt¶
type BranchStmt struct {TokPostoken.Pos// position of TokToktoken.Token// keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH)Label *Ident// label name; or nil}A BranchStmt node represents a break, continue, goto,or fallthrough statement.
func (*BranchStmt)End¶
func (s *BranchStmt) End()token.Pos
func (*BranchStmt)Pos¶
func (s *BranchStmt) Pos()token.Pos
typeCallExpr¶
type CallExpr struct {FunExpr// function expressionLparentoken.Pos// position of "("Args []Expr// function arguments; or nilEllipsistoken.Pos// position of "..." (token.NoPos if there is no "...")Rparentoken.Pos// position of ")"}A CallExpr node represents an expression followed by an argument list.
typeCaseClause¶
type CaseClause struct {Casetoken.Pos// position of "case" or "default" keywordList []Expr// list of expressions or types; nil means default caseColontoken.Pos// position of ":"Body []Stmt// statement list; or nil}A CaseClause represents a case of an expression or type switch statement.
func (*CaseClause)End¶
func (s *CaseClause) End()token.Pos
func (*CaseClause)Pos¶
func (s *CaseClause) Pos()token.Pos
typeChanDir¶
type ChanDirint
The direction of a channel type is indicated by a bitmask including one or both of the following constants.
typeChanType¶
type ChanType struct {Begintoken.Pos// position of "chan" keyword or "<-" (whichever comes first)Arrowtoken.Pos// position of "<-" (token.NoPos if there is no "<-")DirChanDir// channel directionValueExpr// value type}A ChanType node represents a channel type.
typeCommClause¶
type CommClause struct {Casetoken.Pos// position of "case" or "default" keywordCommStmt// send or receive statement; nil means default caseColontoken.Pos// position of ":"Body []Stmt// statement list; or nil}A CommClause node represents a case of a select statement.
func (*CommClause)End¶
func (s *CommClause) End()token.Pos
func (*CommClause)Pos¶
func (s *CommClause) Pos()token.Pos
typeComment¶
type Comment struct {Slashtoken.Pos// position of "/" starting the commentTextstring// comment text (excluding '\n' for //-style comments)}A Comment node represents a single //-style or /*-style comment.
The Text field contains the comment text without carriage returns (\r) thatmay have been present in the source. Because a comment's end position iscomputed using len(Text), the position reported byComment.End does not match thetrue source end position for comments containing carriage returns.
typeCommentGroup¶
type CommentGroup struct {List []*Comment// len(List) > 0}A CommentGroup represents a sequence of commentswith no other tokens and no empty lines between.
func (*CommentGroup)End¶
func (g *CommentGroup) End()token.Pos
func (*CommentGroup)Pos¶
func (g *CommentGroup) Pos()token.Pos
func (*CommentGroup)Text¶
func (g *CommentGroup) Text()string
Text returns the text of the comment.Comment markers (//, /*, and */), the first space of a line comment, andleading 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.
typeCommentMap¶added ingo1.1
type CommentMap map[Node][]*CommentGroup
A CommentMap maps an AST node to a list of comment groupsassociated with it. SeeNewCommentMap for a description ofthe association.
Example¶
This example illustrates how to remove a variable declarationin a Go program while maintaining correct comment associationusing an ast.CommentMap.
package mainimport ("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 fsetf, 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.Builderif err := format.Node(&buf, fset, f); err != nil {panic(err)}fmt.Printf("%s", buf.String())}Output:// This is the package comment.package main// This comment is associated with the hello constant.const hello = "Hello, World!" // line comment 1// This comment is associated with the main function.func main() {fmt.Println(hello) // line comment 3}
funcNewCommentMap¶added ingo1.1
func NewCommentMap(fset *token.FileSet, nodeNode, comments []*CommentGroup)CommentMap
NewCommentMap creates a new comment map by associating comment groupsof 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 isat least one empty line after g and before the next node
- g starts before n and is not associated to the node before nvia the previous rules
NewCommentMap tries to associate a comment group to the "largest"node possible: For instance, if the comment is a line commenttrailing an assignment, the comment is associated with the entireassignment rather than just the last operand in the assignment.
func (CommentMap)Comments¶added ingo1.1
func (cmapCommentMap) Comments() []*CommentGroup
Comments returns the list of comment groups in the comment map.The result is sorted in source order.
func (CommentMap)Filter¶added ingo1.1
func (cmapCommentMap) Filter(nodeNode)CommentMap
Filter returns a new comment map consisting of only thoseentries of cmap for which a corresponding node exists inthe AST specified by node.
func (CommentMap)String¶added ingo1.1
func (cmapCommentMap) String()string
func (CommentMap)Update¶added ingo1.1
func (cmapCommentMap) Update(old, newNode)Node
Update replaces an old node in the comment map with the new nodeand returns the new node. Comments that were associated with theold node are associated with the new node.
typeCompositeLit¶
type CompositeLit struct {TypeExpr// literal type; or nilLbracetoken.Pos// position of "{"Elts []Expr// list of composite elements; or nilRbracetoken.Pos// position of "}"Incompletebool// true if (source) expressions are missing in the Elts list}A CompositeLit node represents a composite literal.
func (*CompositeLit)End¶
func (x *CompositeLit) End()token.Pos
func (*CompositeLit)Pos¶
func (x *CompositeLit) Pos()token.Pos
typeDecl¶
type Decl interface {Node// contains filtered or unexported methods}All declaration nodes implement the Decl interface.
typeDeclStmt¶
type DeclStmt struct {DeclDecl// *GenDecl with CONST, TYPE, or VAR token}A DeclStmt node represents a declaration in a statement list.
typeEllipsis¶
type Ellipsis struct {Ellipsistoken.Pos// position of "..."EltExpr// ellipsis element type (parameter lists only); or nil}An Ellipsis node stands for the "..." type in aparameter list or the "..." length in an array type.
typeEmptyStmt¶
type EmptyStmt struct {Semicolontoken.Pos// position of following ";"Implicitbool// if set, ";" was omitted in the source}An EmptyStmt node represents an empty statement.The "position" of the empty statement is the positionof the immediately following (explicit or implicit) semicolon.
typeExpr¶
type Expr interface {Node// contains filtered or unexported methods}All expression nodes implement the Expr interface.
typeExprStmt¶
type ExprStmt struct {XExpr// expression}An ExprStmt node represents a (stand-alone) expressionin a statement list.
typeField¶
type Field struct {Doc *CommentGroup// associated documentation; or nilNames []*Ident// field/method/(type) parameter names; or nilTypeExpr// field/method/parameter type; or nilTag *BasicLit// field tag; or nilComment *CommentGroup// line comments; or nil}A Field represents a Field declaration list in a struct type,a method list in an interface type, or a parameter/result declarationin 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.
typeFieldFilter¶
A FieldFilter may be provided toFprint to control the output.
typeFieldList¶
type FieldList struct {Openingtoken.Pos// position of opening parenthesis/brace/bracket, if anyList []*Field// field list; or nilClosingtoken.Pos// position of closing parenthesis/brace/bracket, if any}A FieldList represents a list of Fields, enclosed by parentheses,curly braces, or square brackets.
typeFile¶
type File struct {Doc *CommentGroup// associated documentation; or nilPackagetoken.Pos// position of "package" keywordName *Ident// package nameDecls []Decl// top-level declarations; or nilFileStart, FileEndtoken.Pos// start and end of entire fileScope *Scope// package scope (this file only). Deprecated: see ObjectImports []*ImportSpec// imports in this fileUnresolved []*Ident// unresolved identifiers in this file. Deprecated: see ObjectComments []*CommentGroup// list of all comments in the source fileGoVersionstring// minimum Go version required by //go:build or // +build directives}A File node represents a Go source file.
The Comments list contains all comments in the source file in order ofappearance, including the comments that are pointed to from other nodesvia Doc and Comment fields.
For correct printing of source code containing comments (using packagesgo/format and go/printer), special care must be taken to update commentswhen a File's syntax tree is modified: For printing, comments are interspersedbetween tokens based on their position. If syntax tree nodes areremoved or moved, relevant comments in their vicinity must also be removed(from the [File.Comments] list) or moved accordingly (by updating theirpositions). ACommentMap may be used to facilitate some of these operations.
Whether and how a comment is associated with a node depends on theinterpretation of the syntax tree by the manipulating program: except for DocandComment comments directly associated with nodes, the remaining commentsare "free-floating" (see also issues#18593,#20744).
funcMergePackageFilesdeprecated
typeForStmt¶
type ForStmt struct {Fortoken.Pos// position of "for" keywordInitStmt// initialization statement; or nilCondExpr// condition; or nilPostStmt// post iteration statement; or nilBody *BlockStmt}A ForStmt represents a for statement.
typeFuncDecl¶
type FuncDecl struct {Doc *CommentGroup// associated documentation; or nilRecv *FieldList// receiver (methods); or nil (functions)Name *Ident// function/method nameType *FuncType// function signature: type and value parameters, results, and position of "func" keywordBody *BlockStmt// function body; or nil for external (non-Go) function}A FuncDecl node represents a function declaration.
typeFuncType¶
type FuncType struct {Functoken.Pos// position of "func" keyword (token.NoPos if there is no "func")TypeParams *FieldList// type parameters; or nilParams *FieldList// (incoming) parameters; non-nilResults *FieldList// (outgoing) results; or nil}A FuncType node represents a function type.
typeGenDecl¶
type GenDecl struct {Doc *CommentGroup// associated documentation; or nilTokPostoken.Pos// position of TokToktoken.Token// IMPORT, CONST, TYPE, or VARLparentoken.Pos// position of '(', if anySpecs []SpecRparentoken.Pos// position of ')', if any}A GenDecl node (generic declaration node) represents an import,constant, type or variable declaration. A valid Lparen position(Lparen.IsValid()) indicates a parenthesized declaration.
Relationship between Tok value and Specs element type:
token.IMPORT *ImportSpectoken.CONST *ValueSpectoken.TYPE *TypeSpectoken.VAR *ValueSpec
typeIdent¶
type Ident struct {NamePostoken.Pos// identifier positionNamestring// identifier nameObj *Object// denoted object, or nil. Deprecated: see Object.}An Ident node represents an identifier.
funcNewIdent¶
NewIdent creates a newIdent without position.Useful for ASTs generated by code other than the Go parser.
func (*Ident)IsExported¶
IsExported reports whether id starts with an upper-case letter.
typeIfStmt¶
type IfStmt struct {Iftoken.Pos// position of "if" keywordInitStmt// initialization statement; or nilCondExpr// conditionBody *BlockStmtElseStmt// else branch; or nil}An IfStmt node represents an if statement.
typeImportSpec¶
type ImportSpec struct {Doc *CommentGroup// associated documentation; or nilName *Ident// local package name (including "."); or nilPath *BasicLit// import pathComment *CommentGroup// line comments; or nilEndPostoken.Pos// end of spec (overrides Path.Pos if nonzero)}An ImportSpec node represents a single package import.
func (*ImportSpec)End¶
func (s *ImportSpec) End()token.Pos
func (*ImportSpec)Pos¶
func (s *ImportSpec) Pos()token.Pos
typeImporterdeprecated
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 andcheck the map to see if it is already present in the imports map.If so, the Importer can return the map entry. Otherwise, theImporter should load the package data for the given path intoa new *Object (pkg), record pkg in the imports map, and thenreturn pkg.
Deprecated: use the type checkergo/types instead; seeObject.
typeIncDecStmt¶
An IncDecStmt node represents an increment or decrement statement.
func (*IncDecStmt)End¶
func (s *IncDecStmt) End()token.Pos
func (*IncDecStmt)Pos¶
func (s *IncDecStmt) Pos()token.Pos
typeIndexExpr¶
type IndexExpr struct {XExpr// expressionLbracktoken.Pos// position of "["IndexExpr// index expressionRbracktoken.Pos// position of "]"}An IndexExpr node represents an expression followed by an index.
typeIndexListExpr¶added ingo1.18
type IndexListExpr struct {XExpr// expressionLbracktoken.Pos// position of "["Indices []Expr// index expressionsRbracktoken.Pos// position of "]"}An IndexListExpr node represents an expression followed by multipleindices.
func (*IndexListExpr)End¶added ingo1.18
func (x *IndexListExpr) End()token.Pos
func (*IndexListExpr)Pos¶added ingo1.18
func (x *IndexListExpr) Pos()token.Pos
typeInterfaceType¶
type InterfaceType struct {Interfacetoken.Pos// position of "interface" keywordMethods *FieldList// list of embedded interfaces, methods, or typesIncompletebool// true if (source) methods or types are missing in the Methods list}An InterfaceType node represents an interface type.
func (*InterfaceType)End¶
func (x *InterfaceType) End()token.Pos
func (*InterfaceType)Pos¶
func (x *InterfaceType) Pos()token.Pos
typeKeyValueExpr¶
A KeyValueExpr node represents (key : value) pairsin composite literals.
func (*KeyValueExpr)End¶
func (x *KeyValueExpr) End()token.Pos
func (*KeyValueExpr)Pos¶
func (x *KeyValueExpr) Pos()token.Pos
typeLabeledStmt¶
A LabeledStmt node represents a labeled statement.
func (*LabeledStmt)End¶
func (s *LabeledStmt) End()token.Pos
func (*LabeledStmt)Pos¶
func (s *LabeledStmt) Pos()token.Pos
typeMergeModedeprecated
type MergeModeuint
The MergeMode flags control the behavior ofMergePackageFiles.
Deprecated: use the type checkergo/types instead ofPackage;seeObject.
const (// If set, duplicate function declarations are excluded.FilterFuncDuplicatesMergeMode = 1 <<iota// If set, comments that are not associated with a specific// AST node (as Doc or Comment) are excluded.FilterUnassociatedComments// If set, duplicate import declarations are excluded.FilterImportDuplicates)
Deprecated: use the type checkergo/types instead ofPackage;seeObject.
typeNode¶
type Node interface {Pos()token.Pos// position of first character belonging to the nodeEnd()token.Pos// position of first character immediately after the node}All node types implement the Node interface.
typeObjKind¶
type ObjKindint
ObjKind describes what anObject represents.
typeObjectdeprecated
type Object struct {KindObjKindNamestring// declared nameDeclany// corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nilDataany// object-specific data; or nilTypeany// placeholder for type information; may be nil}An Object describes a named language entity such as a package,constant, type, variable, function (incl. methods), or label.
The Data fields contains object-specific data:
Kind Data type Data valuePkg *Scope package scopeCon int iota for the respective declaration
Deprecated: The relationship between Idents and Objects cannot becorrectly computed without type information. For example, theexpression T{K: 0} may denote a struct, map, slice, or arrayliteral, depending on the type of T. If T is a struct, then Krefers to a field of T, whereas for the other types it refers to avalue in the environment.
New programs should set the [parser.SkipObjectResolution] parserflag to disable syntactic object resolution (which also saves CPUand memory), and instead use the type checkergo/types if objectresolution is desired. See the Defs, Uses, and Implicits fields ofthe [types.Info] struct for details.
typePackagedeprecated
type Package struct {Namestring// package nameScope *Scope// package scope across all filesImports map[string]*Object// map of package id -> package objectFiles map[string]*File// Go source files by filename}A Package node represents a set of source filescollectively building a Go package.
Deprecated: use the type checkergo/types instead; seeObject.
funcNewPackagedeprecated
func NewPackage(fset *token.FileSet, files map[string]*File, importerImporter, universe *Scope) (*Package,error)
NewPackage creates a newPackage node from a set ofFile nodes. It resolvesunresolved identifiers across files and updates each file's Unresolved listaccordingly. If a non-nil importer and universe scope are provided, they areused to resolve identifiers not declared in any of the package files. Anyremaining unresolved identifiers are reported as undeclared. If the filesbelong to different packages, one package name is selected and files withdifferent package names are reported and then ignored.The result is a package node and ascanner.ErrorList if there were errors.
Deprecated: use the type checkergo/types instead; seeObject.
typeParenExpr¶
type ParenExpr struct {Lparentoken.Pos// position of "("XExpr// parenthesized expressionRparentoken.Pos// position of ")"}A ParenExpr node represents a parenthesized expression.
typeRangeStmt¶
type RangeStmt struct {Fortoken.Pos// position of "for" keywordKey, ValueExpr// Key, Value may be nilTokPostoken.Pos// position of Tok; invalid if Key == nilToktoken.Token// ILLEGAL if Key == nil, ASSIGN, DEFINERangetoken.Pos// position of "range" keywordXExpr// value to range overBody *BlockStmt}A RangeStmt represents a for statement with a range clause.
typeReturnStmt¶
type ReturnStmt struct {Returntoken.Pos// position of "return" keywordResults []Expr// result expressions; or nil}A ReturnStmt node represents a return statement.
func (*ReturnStmt)End¶
func (s *ReturnStmt) End()token.Pos
func (*ReturnStmt)Pos¶
func (s *ReturnStmt) Pos()token.Pos
typeScopedeprecated
A Scope maintains the set of named language entities declaredin the scope and a link to the immediately surrounding (outer)scope.
Deprecated: use the type checkergo/types instead; seeObject.
func (*Scope)Insert¶
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. Otherwiseit inserts obj and returns nil.
typeSelectStmt¶
type SelectStmt struct {Selecttoken.Pos// position of "select" keywordBody *BlockStmt// CommClauses only}A SelectStmt node represents a select statement.
func (*SelectStmt)End¶
func (s *SelectStmt) End()token.Pos
func (*SelectStmt)Pos¶
func (s *SelectStmt) Pos()token.Pos
typeSelectorExpr¶
A SelectorExpr node represents an expression followed by a selector.
func (*SelectorExpr)End¶
func (x *SelectorExpr) End()token.Pos
func (*SelectorExpr)Pos¶
func (x *SelectorExpr) Pos()token.Pos
typeSliceExpr¶
type SliceExpr struct {XExpr// expressionLbracktoken.Pos// position of "["LowExpr// begin of slice range; or nilHighExpr// end of slice range; or nilMaxExpr// maximum capacity of slice; or nilSlice3bool// true if 3-index slice (2 colons present)Rbracktoken.Pos// position of "]"}A SliceExpr node represents an expression followed by slice indices.
typeSpec¶
type Spec interface {Node// contains filtered or unexported methods}The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec.
typeStarExpr¶
A StarExpr node represents an expression of the form "*" Expression.Semantically it could be a unary "*" expression, or a pointer type.
typeStmt¶
type Stmt interface {Node// contains filtered or unexported methods}All statement nodes implement the Stmt interface.
typeStructType¶
type StructType struct {Structtoken.Pos// position of "struct" keywordFields *FieldList// list of field declarationsIncompletebool// true if (source) fields are missing in the Fields list}A StructType node represents a struct type.
func (*StructType)End¶
func (x *StructType) End()token.Pos
func (*StructType)Pos¶
func (x *StructType) Pos()token.Pos
typeSwitchStmt¶
type SwitchStmt struct {Switchtoken.Pos// position of "switch" keywordInitStmt// initialization statement; or nilTagExpr// tag expression; or nilBody *BlockStmt// CaseClauses only}A SwitchStmt node represents an expression switch statement.
func (*SwitchStmt)End¶
func (s *SwitchStmt) End()token.Pos
func (*SwitchStmt)Pos¶
func (s *SwitchStmt) Pos()token.Pos
typeTypeAssertExpr¶
type TypeAssertExpr struct {XExpr// expressionLparentoken.Pos// position of "("TypeExpr// asserted type; nil means type switch X.(type)Rparentoken.Pos// position of ")"}A TypeAssertExpr node represents an expression followed by atype assertion.
func (*TypeAssertExpr)End¶
func (x *TypeAssertExpr) End()token.Pos
func (*TypeAssertExpr)Pos¶
func (x *TypeAssertExpr) Pos()token.Pos
typeTypeSpec¶
type TypeSpec struct {Doc *CommentGroup// associated documentation; or nilName *Ident// type nameTypeParams *FieldList// type parameters; or nilAssigntoken.Pos// position of '=', if anyTypeExpr// *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypesComment *CommentGroup// line comments; or nil}A TypeSpec node represents a type declaration (TypeSpec production).
typeTypeSwitchStmt¶
type TypeSwitchStmt struct {Switchtoken.Pos// position of "switch" keywordInitStmt// initialization statement; or nilAssignStmt// x := y.(type) or y.(type)Body *BlockStmt// CaseClauses only}A TypeSwitchStmt node represents a type switch statement.
func (*TypeSwitchStmt)End¶
func (s *TypeSwitchStmt) End()token.Pos
func (*TypeSwitchStmt)Pos¶
func (s *TypeSwitchStmt) Pos()token.Pos
typeUnaryExpr¶
A UnaryExpr node represents a unary expression.Unary "*" expressions are represented via StarExpr nodes.
typeValueSpec¶
type ValueSpec struct {Doc *CommentGroup// associated documentation; or nilNames []*Ident// value names (len(Names) > 0)TypeExpr// value type; or nilValues []Expr// initial values; or nilComment *CommentGroup// line comments; or nil}A ValueSpec node represents a constant or variable declaration(ConstSpec or VarSpec production).