ast

Imports

Imports #

"bytes"
"cmp"
"fmt"
"go/token"
"slices"
"strings"
"go/token"
"slices"
"cmp"
"go/token"
"slices"
"strconv"
"fmt"
"go/token"
"io"
"os"
"reflect"
"fmt"
"go/scanner"
"go/token"
"strconv"
"fmt"
"go/token"
"strings"
"fmt"
"iter"
"go/token"
"strings"

Constants & Variables

Bad const #

The list of possible [Object] kinds.

const Bad ObjKind = iota

Con const #

The list of possible [Object] kinds.

const Con

FilterFuncDuplicates const #

If set, duplicate function declarations are excluded.

const FilterFuncDuplicates MergeMode = *ast.BinaryExpr

FilterImportDuplicates const #

If set, duplicate import declarations are excluded.

const FilterImportDuplicates

FilterUnassociatedComments const #

If set, comments that are not associated with a specific AST node (as Doc or Comment) are excluded.

const FilterUnassociatedComments

Fun const #

The list of possible [Object] kinds.

const Fun

Lbl const #

The list of possible [Object] kinds.

const Lbl

Pkg const #

The list of possible [Object] kinds.

const Pkg

RECV const #

const RECV

SEND const #

const SEND ChanDir = *ast.BinaryExpr

Typ const #

The list of possible [Object] kinds.

const Typ

Var const #

The list of possible [Object] kinds.

const Var

indent var #

var indent = *ast.CallExpr

objKindStrings var #

var objKindStrings = [...]string{...}

separator var #

separator is an empty //-style comment that is interspersed between different comment groups when they are concatenated into a single group

var separator = *ast.UnaryExpr

Type Aliases

ChanDir type #

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

type ChanDir int

CommentMap type #

A CommentMap maps an AST node to a list of comment groups associated with it. See [NewCommentMap] for a description of the association.

type CommentMap map[Node][]*CommentGroup

FieldFilter type #

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

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

Filter type #

type Filter func(string) bool

Importer type #

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

type Importer func(imports map[string]*Object, path string) (pkg *Object, err error)

MergeMode type #

The MergeMode flags control the behavior of [MergePackageFiles].

type MergeMode uint

ObjKind type #

ObjKind describes what an [Object] represents.

type ObjKind int

inspector type #

type inspector func(Node) bool

nodeStack type #

A nodeStack keeps track of nested nodes. A node lower on the stack lexically contains the nodes higher on the stack.

type nodeStack []Node

Interfaces

Decl interface #

All declaration nodes implement the Decl interface.

type Decl interface {
Node
declNode()
}

Expr interface #

All expression nodes implement the Expr interface.

type Expr interface {
Node
exprNode()
}

Node interface #

All node types implement the Node interface.

type Node interface {
Pos() token.Pos
End() token.Pos
}

Spec interface #

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

type Spec interface {
Node
specNode()
}

Stmt interface #

All statement nodes implement the Stmt interface.

type Stmt interface {
Node
stmtNode()
}

Visitor interface #

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

type Visitor interface {
Visit(node Node) w Visitor
}

Structs

ArrayType struct #

An ArrayType node represents an array or slice type.

type ArrayType struct {
Lbrack token.Pos
Len Expr
Elt Expr
}

AssignStmt struct #

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

type AssignStmt struct {
Lhs []Expr
TokPos token.Pos
Tok token.Token
Rhs []Expr
}

BadDecl struct #

A BadDecl node is a placeholder for a declaration containing syntax errors for which a correct declaration node cannot be created.

type BadDecl struct {
From token.Pos
To token.Pos
}

BadExpr struct #

A BadExpr node is a placeholder for an expression containing syntax errors for which a correct expression node cannot be created.

type BadExpr struct {
From token.Pos
To token.Pos
}

BadStmt struct #

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

type BadStmt struct {
From token.Pos
To token.Pos
}

BasicLit struct #

A BasicLit node represents a literal of basic type. Note that for the CHAR and STRING kinds, the literal is stored with its quotes. For example, for a double-quoted STRING, the first and the last rune in the Value field will be ". The [strconv.Unquote] and [strconv.UnquoteChar] functions can be used 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) that may have been present in the source. Because the end position is computed using len(Value), the position reported by [BasicLit.End] does not match the true source end position for raw string literals containing carriage returns.

type BasicLit struct {
ValuePos token.Pos
Kind token.Token
Value string
}

BinaryExpr struct #

A BinaryExpr node represents a binary expression.

type BinaryExpr struct {
X Expr
OpPos token.Pos
Op token.Token
Y Expr
}

BlockStmt struct #

A BlockStmt node represents a braced statement list.

type BlockStmt struct {
Lbrace token.Pos
List []Stmt
Rbrace token.Pos
}

BranchStmt struct #

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

type BranchStmt struct {
TokPos token.Pos
Tok token.Token
Label *Ident
}

CallExpr struct #

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

type CallExpr struct {
Fun Expr
Lparen token.Pos
Args []Expr
Ellipsis token.Pos
Rparen token.Pos
}

CaseClause struct #

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

type CaseClause struct {
Case token.Pos
List []Expr
Colon token.Pos
Body []Stmt
}

ChanType struct #

A ChanType node represents a channel type.

type ChanType struct {
Begin token.Pos
Arrow token.Pos
Dir ChanDir
Value Expr
}

CommClause struct #

A CommClause node represents a case of a select statement.

type CommClause struct {
Case token.Pos
Comm Stmt
Colon token.Pos
Body []Stmt
}

Comment struct #

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.

type Comment struct {
Slash token.Pos
Text string
}

CommentGroup struct #

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

type CommentGroup struct {
List []*Comment
}

CompositeLit struct #

A CompositeLit node represents a composite literal.

type CompositeLit struct {
Type Expr
Lbrace token.Pos
Elts []Expr
Rbrace token.Pos
Incomplete bool
}

DeclStmt struct #

A DeclStmt node represents a declaration in a statement list.

type DeclStmt struct {
Decl Decl
}

DeferStmt struct #

A DeferStmt node represents a defer statement.

type DeferStmt struct {
Defer token.Pos
Call *CallExpr
}

Ellipsis struct #

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

type Ellipsis struct {
Ellipsis token.Pos
Elt Expr
}

EmptyStmt struct #

An EmptyStmt node represents an empty statement. The "position" of the empty statement is the position of the immediately following (explicit or implicit) semicolon.

type EmptyStmt struct {
Semicolon token.Pos
Implicit bool
}

ExprStmt struct #

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

type ExprStmt struct {
X Expr
}

Field struct #

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.

type Field struct {
Doc *CommentGroup
Names []*Ident
Type Expr
Tag *BasicLit
Comment *CommentGroup
}

FieldList struct #

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

type FieldList struct {
Opening token.Pos
List []*Field
Closing token.Pos
}

File struct #

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]). [#18593]: https://go.dev/issue/18593 [#20744]: https://go.dev/issue/20744

type File struct {
Doc *CommentGroup
Package token.Pos
Name *Ident
Decls []Decl
FileStart token.Pos
FileEnd token.Pos
Scope *Scope
Imports []*ImportSpec
Unresolved []*Ident
Comments []*CommentGroup
GoVersion string
}

ForStmt struct #

A ForStmt represents a for statement.

type ForStmt struct {
For token.Pos
Init Stmt
Cond Expr
Post Stmt
Body *BlockStmt
}

FuncDecl struct #

A FuncDecl node represents a function declaration.

type FuncDecl struct {
Doc *CommentGroup
Recv *FieldList
Name *Ident
Type *FuncType
Body *BlockStmt
}

FuncLit struct #

A FuncLit node represents a function literal.

type FuncLit struct {
Type *FuncType
Body *BlockStmt
}

FuncType struct #

A FuncType node represents a function type.

type FuncType struct {
Func token.Pos
TypeParams *FieldList
Params *FieldList
Results *FieldList
}

GenDecl struct #

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

type GenDecl struct {
Doc *CommentGroup
TokPos token.Pos
Tok token.Token
Lparen token.Pos
Specs []Spec
Rparen token.Pos
}

GoStmt struct #

A GoStmt node represents a go statement.

type GoStmt struct {
Go token.Pos
Call *CallExpr
}

Ident struct #

An Ident node represents an identifier.

type Ident struct {
NamePos token.Pos
Name string
Obj *Object
}

IfStmt struct #

An IfStmt node represents an if statement.

type IfStmt struct {
If token.Pos
Init Stmt
Cond Expr
Body *BlockStmt
Else Stmt
}

ImportSpec struct #

An ImportSpec node represents a single package import.

type ImportSpec struct {
Doc *CommentGroup
Name *Ident
Path *BasicLit
Comment *CommentGroup
EndPos token.Pos
}

IncDecStmt struct #

An IncDecStmt node represents an increment or decrement statement.

type IncDecStmt struct {
X Expr
TokPos token.Pos
Tok token.Token
}

IndexExpr struct #

An IndexExpr node represents an expression followed by an index.

type IndexExpr struct {
X Expr
Lbrack token.Pos
Index Expr
Rbrack token.Pos
}

IndexListExpr struct #

An IndexListExpr node represents an expression followed by multiple indices.

type IndexListExpr struct {
X Expr
Lbrack token.Pos
Indices []Expr
Rbrack token.Pos
}

InterfaceType struct #

An InterfaceType node represents an interface type.

type InterfaceType struct {
Interface token.Pos
Methods *FieldList
Incomplete bool
}

KeyValueExpr struct #

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

type KeyValueExpr struct {
Key Expr
Colon token.Pos
Value Expr
}

LabeledStmt struct #

A LabeledStmt node represents a labeled statement.

type LabeledStmt struct {
Label *Ident
Colon token.Pos
Stmt Stmt
}

MapType struct #

A MapType node represents a map type.

type MapType struct {
Map token.Pos
Key Expr
Value Expr
}

Object struct #

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.

type Object struct {
Kind ObjKind
Name string
Decl any
Data any
Type any
}

Package struct #

A Package node represents a set of source files collectively building a Go package. Deprecated: use the type checker [go/types] instead; see [Object].

type Package struct {
Name string
Scope *Scope
Imports map[string]*Object
Files map[string]*File
}

ParenExpr struct #

A ParenExpr node represents a parenthesized expression.

type ParenExpr struct {
Lparen token.Pos
X Expr
Rparen token.Pos
}

RangeStmt struct #

A RangeStmt represents a for statement with a range clause.

type RangeStmt struct {
For token.Pos
Key Expr
Value Expr
TokPos token.Pos
Tok token.Token
Range token.Pos
X Expr
Body *BlockStmt
}

ReturnStmt struct #

A ReturnStmt node represents a return statement.

type ReturnStmt struct {
Return token.Pos
Results []Expr
}

Scope struct #

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

type Scope struct {
Outer *Scope
Objects map[string]*Object
}

SelectStmt struct #

A SelectStmt node represents a select statement.

type SelectStmt struct {
Select token.Pos
Body *BlockStmt
}

SelectorExpr struct #

A SelectorExpr node represents an expression followed by a selector.

type SelectorExpr struct {
X Expr
Sel *Ident
}

SendStmt struct #

A SendStmt node represents a send statement.

type SendStmt struct {
Chan Expr
Arrow token.Pos
Value Expr
}

SliceExpr struct #

A SliceExpr node represents an expression followed by slice indices.

type SliceExpr struct {
X Expr
Lbrack token.Pos
Low Expr
High Expr
Max Expr
Slice3 bool
Rbrack token.Pos
}

StarExpr struct #

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

type StarExpr struct {
Star token.Pos
X Expr
}

StructType struct #

A StructType node represents a struct type.

type StructType struct {
Struct token.Pos
Fields *FieldList
Incomplete bool
}

SwitchStmt struct #

A SwitchStmt node represents an expression switch statement.

type SwitchStmt struct {
Switch token.Pos
Init Stmt
Tag Expr
Body *BlockStmt
}

TypeAssertExpr struct #

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

type TypeAssertExpr struct {
X Expr
Lparen token.Pos
Type Expr
Rparen token.Pos
}

TypeSpec struct #

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

type TypeSpec struct {
Doc *CommentGroup
Name *Ident
TypeParams *FieldList
Assign token.Pos
Type Expr
Comment *CommentGroup
}

TypeSwitchStmt struct #

A TypeSwitchStmt node represents a type switch statement.

type TypeSwitchStmt struct {
Switch token.Pos
Init Stmt
Assign Stmt
Body *BlockStmt
}

UnaryExpr struct #

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

type UnaryExpr struct {
OpPos token.Pos
Op token.Token
X Expr
}

ValueSpec struct #

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

type ValueSpec struct {
Doc *CommentGroup
Names []*Ident
Type Expr
Values []Expr
Comment *CommentGroup
}

cgPos struct #

type cgPos struct {
left bool
cg *CommentGroup
}

commentListReader struct #

A commentListReader helps iterating through a list of comment groups.

type commentListReader struct {
fset *token.FileSet
list []*CommentGroup
index int
comment *CommentGroup
pos token.Position
end token.Position
}

localError struct #

localError wraps locally caught errors so we can distinguish them from genuine panics which we don't want to return as errors.

type localError struct {
err error
}

pkgBuilder struct #

type pkgBuilder struct {
fset *token.FileSet
errors scanner.ErrorList
}

posSpan struct #

type posSpan struct {
Start token.Pos
End token.Pos
}

printer struct #

type printer struct {
output io.Writer
fset *token.FileSet
filter FieldFilter
ptrmap map[any]int
indent int
last byte
line int
}

Functions

Comments method #

Comments returns the list of comment groups in the comment map. The result is sorted in source order.

func (cmap CommentMap) Comments() []*CommentGroup

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

End returns the end of the last declaration in the file. It may be invalid, for example in an empty file. (Use FileEnd for the end of the entire file. It is always valid.)

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

func (x *IndexListExpr) End() token.Pos

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

End method #

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

FileExports function #

FileExports trims the AST for a Go source file in place such that only exported nodes remain: all top-level identifiers which are not exported and their associated information (such as type, initial value, or function body) are removed. Non-exported fields and methods of exported types are stripped. The [File.Comments] list is not changed. FileExports reports whether there are exported declarations.

func FileExports(src *File) bool

Filter method #

Filter returns a new comment map consisting of only those entries of cmap for which a corresponding node exists in the AST specified by node.

func (cmap CommentMap) Filter(node Node) CommentMap

FilterDecl function #

FilterDecl trims the AST for a Go declaration in place by removing all names (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f. FilterDecl reports whether there are any declared names left after filtering.

func FilterDecl(decl Decl, f Filter) bool

FilterFile function #

FilterFile trims the AST for a Go file in place by removing all names from top-level declarations (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f. If the declaration is empty afterwards, the declaration is removed from the AST. Import declarations are always removed. The [File.Comments] list is not changed. FilterFile reports whether there are any top-level declarations left after filtering.

func FilterFile(src *File, f Filter) bool

FilterPackage function #

FilterPackage trims the AST for a Go package in place by removing all names from top-level declarations (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f. If the declaration is empty afterwards, the declaration is removed from the AST. The pkg.Files list is not changed, so that file names and top-level package comments don't get lost. FilterPackage reports whether there are any top-level declarations left after filtering.

func FilterPackage(pkg *Package, f Filter) bool

Fprint function #

Fprint prints the (sub-)tree starting at AST node x to w. If fset != nil, position information is interpreted relative to that file set. Otherwise positions are printed as integer values (file set specific offsets). A non-nil [FieldFilter] f may be provided to control the output: struct fields for which f(fieldname, fieldvalue) is true are printed; all others are filtered from the output. Unexported struct fields are never printed.

func Fprint(w io.Writer, fset *token.FileSet, x any, f FieldFilter) error

Insert method #

Insert attempts to insert a named object obj into the scope s. If the scope already contains an object alt with the same name, Insert leaves the scope unchanged and returns alt. Otherwise it inserts obj and returns nil.

func (s *Scope) Insert(obj *Object) (alt *Object)

Inspect function #

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

func Inspect(node Node, f func(Node) bool)

IsExported method #

IsExported reports whether id starts with an upper-case letter.

func (id *Ident) IsExported() bool

IsExported function #

IsExported reports whether name starts with an upper-case letter.

func IsExported(name string) bool

IsGenerated function #

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)

func IsGenerated(file *File) bool

Lookup method #

Lookup returns the object with the given name if it is found in scope s, otherwise it returns nil. Outer scopes are ignored.

func (s *Scope) Lookup(name string) *Object

MergePackageFiles function #

MergePackageFiles creates a file AST by merging the ASTs of the files belonging to a package. The mode flags control merging behavior.

func MergePackageFiles(pkg *Package, mode MergeMode) *File

NewCommentMap function #

NewCommentMap creates a new comment map by associating comment groups of the comments list with the nodes of the AST specified by node. A comment group g is associated with a node n if: - g starts on the same line as n ends - g starts on the line immediately following n, and there is at least one empty line after g and before the next node - g starts before n and is not associated to the node before n via the previous rules NewCommentMap tries to associate a comment group to the "largest" node possible: For instance, if the comment is a line comment trailing an assignment, the comment is associated with the entire assignment rather than just the last operand in the assignment.

func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap

NewIdent function #

NewIdent creates a new [Ident] without position. Useful for ASTs generated by code other than the Go parser.

func NewIdent(name string) *Ident

NewObj function #

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

func NewObj(kind ObjKind, name string) *Object

NewPackage function #

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

func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error)

NewScope function #

NewScope creates a new scope nested in the outer scope.

func NewScope(outer *Scope) *Scope

NotNilFilter function #

NotNilFilter is a [FieldFilter] that returns true for field values that are not nil; it returns false otherwise.

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

NumFields method #

NumFields returns the number of parameters or struct fields represented by a [FieldList].

func (f *FieldList) NumFields() int

PackageExports function #

PackageExports trims the AST for a Go package in place such that only exported nodes remain. The pkg.Files list is not changed, so that file names and top-level package comments don't get lost. PackageExports reports whether there are exported declarations; it returns false otherwise.

func PackageExports(pkg *Package) bool

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

func (x *IndexListExpr) Pos() token.Pos

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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 (obj *Object) Pos() token.Pos

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

Pos returns the position of the package declaration. It may be invalid, for example in an empty file. (Use FileStart for the start of the entire file. It is always valid.)

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Pos method #

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

Preorder function #

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

func Preorder(root Node) *ast.IndexExpr

Print function #

Print prints x to standard output, skipping nil fields. Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter).

func Print(fset *token.FileSet, x any) error

SortImports function #

SortImports sorts runs of consecutive import lines in import blocks in f. It also removes duplicate imports when it is possible to do so without data loss.

func SortImports(fset *token.FileSet, f *File)

String method #

func (cmap CommentMap) String() string

String method #

func (id *Ident) String() string

String method #

Debugging support

func (s *Scope) String() string

String method #

func (kind ObjKind) String() string

Text method #

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.

func (g *CommentGroup) Text() string

Unparen function #

Unparen returns the expression with any enclosing parentheses removed.

func Unparen(e Expr) Expr

Update method #

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.

func (cmap CommentMap) Update(old Node, new Node) Node

Visit method #

func (f inspector) Visit(node Node) Visitor

Walk function #

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

func Walk(v Visitor, node Node)

Write method #

func (p *printer) Write(data []byte) (n int, err error)

addComment method #

func (cmap CommentMap) addComment(n Node, c *CommentGroup)

collapse function #

collapse indicates whether prev may be removed, leaving only next.

func collapse(prev Spec, next Spec) bool

declNode method #

declNode() ensures that only declaration nodes can be assigned to a Decl.

func (*BadDecl) declNode()

declNode method #

func (*GenDecl) declNode()

declNode method #

func (*FuncDecl) declNode()

declare method #

func (p *pkgBuilder) declare(scope *Scope, altScope *Scope, obj *Object)

eol method #

func (r *commentListReader) eol() bool

error method #

func (p *pkgBuilder) error(pos token.Pos, msg string)

errorf method #

func (p *pkgBuilder) errorf(pos token.Pos, format string, args ...any)

exportFilter function #

exportFilter is a special filter function to extract exported nodes.

func exportFilter(name string) bool

exprNode method #

func (*Ident) exprNode()

exprNode method #

func (*StarExpr) exprNode()

exprNode method #

func (*SelectorExpr) exprNode()

exprNode method #

func (*ParenExpr) exprNode()

exprNode method #

func (*CompositeLit) exprNode()

exprNode method #

func (*FuncLit) exprNode()

exprNode method #

func (*BasicLit) exprNode()

exprNode method #

func (*Ellipsis) exprNode()

exprNode method #

func (*IndexListExpr) exprNode()

exprNode method #

exprNode() ensures that only expression/type nodes can be assigned to an Expr.

func (*BadExpr) exprNode()

exprNode method #

func (*CallExpr) exprNode()

exprNode method #

func (*SliceExpr) exprNode()

exprNode method #

func (*TypeAssertExpr) exprNode()

exprNode method #

func (*IndexExpr) exprNode()

exprNode method #

func (*UnaryExpr) exprNode()

exprNode method #

func (*BinaryExpr) exprNode()

exprNode method #

func (*KeyValueExpr) exprNode()

exprNode method #

func (*ArrayType) exprNode()

exprNode method #

func (*ChanType) exprNode()

exprNode method #

func (*MapType) exprNode()

exprNode method #

func (*InterfaceType) exprNode()

exprNode method #

func (*StructType) exprNode()

exprNode method #

func (*FuncType) exprNode()

fieldName function #

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.

func fieldName(x Expr) *Ident

filterCompositeLit function #

func filterCompositeLit(lit *CompositeLit, filter Filter, export bool)

filterDecl function #

func filterDecl(decl Decl, f Filter, export bool) bool

filterExprList function #

func filterExprList(list []Expr, filter Filter, export bool) []Expr

filterFieldList function #

func filterFieldList(fields *FieldList, filter Filter, export bool) (removedFields bool)

filterFile function #

func filterFile(src *File, f Filter, export bool) bool

filterIdentList function #

func filterIdentList(list []*Ident, f Filter) []*Ident

filterPackage function #

func filterPackage(pkg *Package, f Filter, export bool) bool

filterParamList function #

func filterParamList(fields *FieldList, filter Filter, export bool) bool

filterSpec function #

func filterSpec(spec Spec, f Filter, export bool) bool

filterSpecList function #

func filterSpecList(list []Spec, f Filter, export bool) []Spec

filterType function #

func filterType(typ Expr, f Filter, export bool) bool

fprint function #

func fprint(w io.Writer, fset *token.FileSet, x any, f FieldFilter) (err error)

generator function #

func generator(file *File) (string, bool)

importComment function #

func importComment(s Spec) string

importName function #

func importName(s Spec) string

importPath function #

func importPath(s Spec) string

isDirective function #

isDirective reports whether c is a comment directive. This code is also in go/printer.

func isDirective(c string) bool

isWhitespace function #

func isWhitespace(ch byte) bool

lineAt function #

func lineAt(fset *token.FileSet, pos token.Pos) int

nameOf function #

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.

func nameOf(f *FuncDecl) string

next method #

func (r *commentListReader) next()

nodeList function #

nodeList returns the list of nodes of the AST n in source order.

func nodeList(n Node) []Node

pop method #

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.

func (s *nodeStack) pop(pos token.Pos) (top Node)

print method #

func (p *printer) print(x reflect.Value)

printf method #

printf is a convenience wrapper that takes care of print errors.

func (p *printer) printf(format string, args ...any)

push method #

push pops all nodes that appear lexically before n and then pushes n on the stack.

func (s *nodeStack) push(n Node)

resolve function #

func resolve(scope *Scope, ident *Ident) bool

sortComments function #

sortComments sorts the list of comment groups in source order.

func sortComments(list []*CommentGroup)

sortSpecs function #

func sortSpecs(fset *token.FileSet, f *File, specs []Spec) []Spec

specNode method #

specNode() ensures that only spec nodes can be assigned to a Spec.

func (*ImportSpec) specNode()

specNode method #

func (*TypeSpec) specNode()

specNode method #

func (*ValueSpec) specNode()

stmtNode method #

func (*AssignStmt) stmtNode()

stmtNode method #

func (*ReturnStmt) stmtNode()

stmtNode method #

func (*ForStmt) stmtNode()

stmtNode method #

func (*SelectStmt) stmtNode()

stmtNode method #

func (*CommClause) stmtNode()

stmtNode method #

func (*TypeSwitchStmt) stmtNode()

stmtNode method #

func (*SwitchStmt) stmtNode()

stmtNode method #

func (*CaseClause) stmtNode()

stmtNode method #

func (*IfStmt) stmtNode()

stmtNode method #

func (*BlockStmt) stmtNode()

stmtNode method #

func (*BranchStmt) stmtNode()

stmtNode method #

func (*RangeStmt) stmtNode()

stmtNode method #

stmtNode() ensures that only statement nodes can be assigned to a Stmt.

func (*BadStmt) stmtNode()

stmtNode method #

func (*DeferStmt) stmtNode()

stmtNode method #

func (*GoStmt) stmtNode()

stmtNode method #

func (*IncDecStmt) stmtNode()

stmtNode method #

func (*DeclStmt) stmtNode()

stmtNode method #

func (*SendStmt) stmtNode()

stmtNode method #

func (*EmptyStmt) stmtNode()

stmtNode method #

func (*ExprStmt) stmtNode()

stmtNode method #

func (*LabeledStmt) stmtNode()

stripTrailingWhitespace function #

func stripTrailingWhitespace(s string) string

summary function #

func summary(list []*CommentGroup) string

walkList function #

func walkList(v Visitor, list []N)

Generated with Arrow