Movatterモバイル変換


[0]ホーム

URL:


ast

packagestandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:12Imported by:39,682

Details

Repository

cs.opensource.google/go/go

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

funcFileExports

func FileExports(src *File)bool

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

func FilterDecl(declDecl, fFilter)bool

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

func FilterFile(src *File, fFilter)bool

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

func FilterPackage(pkg *Package, fFilter)bool

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

func Fprint(wio.Writer, fset *token.FileSet, xany, fFieldFilter)error

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

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

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

func IsExported(namestring)bool

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

funcIsGeneratedadded ingo1.21.0

func IsGenerated(file *File)bool

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

func NotNilFilter(_string, vreflect.Value)bool

NotNilFilter is aFieldFilter that returns true for field valuesthat are not nil; it returns false otherwise.

funcPackageExportsdeprecated

func PackageExports(pkg *Package)bool

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.

funcPreorderadded ingo1.23.0

func Preorder(rootNode)iter.Seq[Node]

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

funcPreorderStackadded ingo1.25.0

func PreorderStack(rootNode, stack []Node, f func(nNode, stack []Node)bool)

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

func Print(fset *token.FileSet, xany)error

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

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

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

funcWalk

func Walk(vVisitor, nodeNode)

Walk traverses an AST in depth-first order: It starts by callingv.Visit(node); node must not be nil. If the visitor w returned byv.Visit(node) is not nil, Walk is invoked recursively with visitorw for each of the non-nil children of node, followed by a call ofw.Visit(nil).

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.

func (*ArrayType)End

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

func (*ArrayType)Pos

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

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

type BadDecl struct {From, Totoken.Pos// position range of bad declaration}

A BadDecl node is a placeholder for a declaration containingsyntax errors for which a correct declaration node cannot becreated.

func (*BadDecl)End

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

func (*BadDecl)Pos

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

typeBadExpr

type BadExpr struct {From, Totoken.Pos// position range of bad expression}

A BadExpr node is a placeholder for an expression containingsyntax errors for which a correct expression node cannot becreated.

func (*BadExpr)End

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

func (*BadExpr)Pos

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

typeBadStmt

type BadStmt struct {From, Totoken.Pos// position range of bad statement}

A BadStmt node is a placeholder for statements containingsyntax errors for which no correct statement nodes can becreated.

func (*BadStmt)End

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

func (*BadStmt)Pos

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

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.

func (*BasicLit)End

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

func (*BasicLit)Pos

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

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.

func (*BlockStmt)End

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

func (*BlockStmt)Pos

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

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.

func (*CallExpr)End

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

func (*CallExpr)Pos

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

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.

const (SENDChanDir = 1 <<iotaRECV)

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.

func (*ChanType)End

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

func (*ChanType)Pos

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

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.

func (*Comment)End

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

func (*Comment)Pos

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

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.

typeCommentMapadded 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}

funcNewCommentMapadded 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)Commentsadded 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)Filteradded 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)Stringadded ingo1.1

func (cmapCommentMap) String()string

func (CommentMap)Updateadded 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.

func (*DeclStmt)End

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

func (*DeclStmt)Pos

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

typeDeferStmt

type DeferStmt struct {Defertoken.Pos// position of "defer" keywordCall  *CallExpr}

A DeferStmt node represents a defer statement.

func (*DeferStmt)End

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

func (*DeferStmt)Pos

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

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.

func (*Ellipsis)End

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

func (*Ellipsis)Pos

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

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.

func (*EmptyStmt)End

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

func (*EmptyStmt)Pos

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

typeExpr

type Expr interface {Node// contains filtered or unexported methods}

All expression nodes implement the Expr interface.

funcUnparenadded ingo1.22.0

func Unparen(eExpr)Expr

Unparen returns the expression with any enclosing parentheses removed.

typeExprStmt

type ExprStmt struct {XExpr// expression}

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

func (*ExprStmt)End

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

func (*ExprStmt)Pos

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

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.

func (*Field)End

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

func (*Field)Pos

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

typeFieldFilter

type FieldFilter func(namestring, valuereflect.Value)bool

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.

func (*FieldList)End

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

func (*FieldList)NumFields

func (f *FieldList) NumFields()int

NumFields returns the number of parameters or struct fields represented by aFieldList.

func (*FieldList)Pos

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

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

func MergePackageFiles(pkg *Package, modeMergeMode) *File

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

Deprecated: this function is poorly specified and has unfixablebugs; alsoPackage is deprecated.

func (*File)End

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

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 (*File)Pos

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

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

typeFilter

type Filter func(string)bool

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.

func (*ForStmt)End

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

func (*ForStmt)Pos

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

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.

func (*FuncDecl)End

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

func (*FuncDecl)Pos

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

typeFuncLit

type FuncLit struct {Type *FuncType// function typeBody *BlockStmt// function body}

A FuncLit node represents a function literal.

func (*FuncLit)End

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

func (*FuncLit)Pos

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

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.

func (*FuncType)End

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

func (*FuncType)Pos

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

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

func (*GenDecl)End

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

func (*GenDecl)Pos

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

typeGoStmt

type GoStmt struct {Gotoken.Pos// position of "go" keywordCall *CallExpr}

A GoStmt node represents a go statement.

func (*GoStmt)End

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

func (*GoStmt)Pos

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

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

func NewIdent(namestring) *Ident

NewIdent creates a newIdent without position.Useful for ASTs generated by code other than the Go parser.

func (*Ident)End

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

func (*Ident)IsExported

func (id *Ident) IsExported()bool

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

func (*Ident)Pos

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

func (*Ident)String

func (id *Ident) String()string

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.

func (*IfStmt)End

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

func (*IfStmt)Pos

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

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

type Importer func(imports map[string]*Object, pathstring) (pkg *Object, errerror)

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

type IncDecStmt struct {XExprTokPostoken.Pos// position of TokToktoken.Token// INC or DEC}

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.

func (*IndexExpr)End

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

func (*IndexExpr)Pos

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

typeIndexListExpradded 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)Endadded ingo1.18

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

func (*IndexListExpr)Posadded 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

type KeyValueExpr struct {KeyExprColontoken.Pos// position of ":"ValueExpr}

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

type LabeledStmt struct {Label *IdentColontoken.Pos// position of ":"StmtStmt}

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

typeMapType

type MapType struct {Maptoken.Pos// position of "map" keywordKeyExprValueExpr}

A MapType node represents a map type.

func (*MapType)End

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

func (*MapType)Pos

func (x *MapType) 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.

const (BadObjKind =iota// for error handlingPkg// packageCon// constantTyp// typeVar// variableFun// function or methodLbl// label)

The list of possibleObject kinds.

func (ObjKind)String

func (kindObjKind) String()string

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.

funcNewObj

func NewObj(kindObjKind, namestring) *Object

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

func (*Object)Pos

func (obj *Object) Pos()token.Pos

Pos computes the source position of the declaration of an object name.The result may be an invalid position if it cannot be computed(obj.Decl may be nil or not correct).

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.

func (*Package)End

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

func (*Package)Pos

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

typeParenExpr

type ParenExpr struct {Lparentoken.Pos// position of "("XExpr// parenthesized expressionRparentoken.Pos// position of ")"}

A ParenExpr node represents a parenthesized expression.

func (*ParenExpr)End

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

func (*ParenExpr)Pos

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

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.

func (*RangeStmt)End

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

func (*RangeStmt)Pos

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

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

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

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.

funcNewScope

func NewScope(outer *Scope) *Scope

NewScope creates a new scope nested in the outer scope.

func (*Scope)Insert

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

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

func (*Scope)Lookup

func (s *Scope) Lookup(namestring) *Object

Lookup returns the object with the given name if it isfound in scope s, otherwise it returns nil. Outer scopesare ignored.

func (*Scope)String

func (s *Scope) String()string

Debugging support

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

type SelectorExpr struct {XExpr// expressionSel *Ident// field selector}

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

typeSendStmt

type SendStmt struct {ChanExprArrowtoken.Pos// position of "<-"ValueExpr}

A SendStmt node represents a send statement.

func (*SendStmt)End

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

func (*SendStmt)Pos

func (s *SendStmt) 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.

func (*SliceExpr)End

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

func (*SliceExpr)Pos

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

typeSpec

type Spec interface {Node// contains filtered or unexported methods}

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

typeStarExpr

type StarExpr struct {Startoken.Pos// position of "*"XExpr// operand}

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

func (*StarExpr)End

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

func (*StarExpr)Pos

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

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

func (*TypeSpec)End

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

func (*TypeSpec)Pos

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

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

type UnaryExpr struct {OpPostoken.Pos// position of OpOptoken.Token// operatorXExpr// operand}

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

func (*UnaryExpr)End

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

func (*UnaryExpr)Pos

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

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

func (*ValueSpec)End

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

func (*ValueSpec)Pos

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

typeVisitor

type Visitor interface {Visit(nodeNode) (wVisitor)}

A Visitor's Visit method is invoked for each node encountered byWalk.If the result visitor w is not nil,Walk visits each of the childrenof node with the visitor w, followed by a call of w.Visit(nil).

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp