astvisit

package module
v0.0.0-...-2d1ef5b Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2023 License: MIT Imports: 21 Imported by: 4

README

go-astvisit

Typed visitor to traverse and modify Go AST without much reflection

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrPackageNotFound = errors.New("package not found")

Functions

func ExprString

func ExprString(expr ast.Expr) string

func ExprStringWithExportedNameQualifyer

func ExprStringWithExportedNameQualifyer(expr ast.Expr, qualifyer string) string

func FieldString

func FieldString(field *ast.Field) string

func FormatFileWithImports

func FormatFileWithImports(fset *token.FileSet, sourceCode []byte, importLines Imports, localImportPrefixes ...string) ([]byte, error)

FormatFileWithImports formats sourceCode and makes sure that the passed importLines are included. Imports with localImportPrefixes will be sorted into separated groups after the third party imports.

func FprintfVerbose

func FprintfVerbose(verboseOut io.Writer, format string, args ...any) error

FprintfVerbose calls fmt.Fprintf if verboseOut is not nil

func FuncTypeString

func FuncTypeString(funcType *ast.FuncType) string

func ImportNameAndPathOfImportLine

func ImportNameAndPathOfImportLine(importLine string) (importName, importPath string, err error)

ImportNameAndPathOfImportLine splits an importLine as used in an import statement into a importName and importPath part. The importName will be empty if the import is not explicitely named.

func NodeType

func NodeType(node ast.Node) string

func ParseDeclarations

func ParseDeclarations(fset *token.FileSet, sourceCode string) ([]ast.Decl, []*ast.CommentGroup, error)

ParseDeclarations either from a complete source file or from a code snippet without a package clause.

func ParsePackage

func ParsePackage(fset *token.FileSet, pkgDir string, filter func(fs.FileInfo) bool) (pkg *ast.Package, err error)

ParsePackage parses the package source in pkgDir including comments. If filter != nil, only the files with fs.FileInfo entries passing through the filter (and ending in ".go") are considered. Returns a wrapped ErrPackageNotFound error if the filtered pkgDir does not contain Go source for a package.

func ParseStatements

func ParseStatements(fset *token.FileSet, sourceCode string) ([]ast.Stmt, []*ast.CommentGroup, error)

ParseStatements a from a code snippet

func Rewrite

func Rewrite(path string, verboseOut, resultOut io.Writer, rewriteFileFunc RewriteFileFunc) error
Example
cwd, _ := os.Getwd()
cwd += string(os.PathSeparator)
// Use verboseWriter to print encountered file paths
err := Rewrite(
	"./...",
	nil, // verboseOut
	nil, // resultOut
	func(fset *token.FileSet, filePkg *ast.Package, astFile *ast.File, filePath string, verboseWriter io.Writer) ([]byte, error) {
		info, err := os.Stat(filePath)
		if err != nil {
			return nil, err
		}
		if info.IsDir() {
			return nil, errors.New("listed directory")
		}
		if filepath.Ext(filePath) != ".go" {
			return nil, errors.New("listed non .go file")
		}
		_, err = fmt.Println(strings.TrimPrefix(filePath, cwd))
		return nil, err
	})
if err != nil {
	panic(err)
}
Output:

cursor.go
errors.go
nodereplacements.go
nodetype.go
packagelocation.go
parse.go
path.go
pathitem.go
rewrite.go
tostring.go
visit.go
visitor.go
visitorimpl.go
test/dummy.go

func RewriteWithReplacements

func RewriteWithReplacements(path string, verboseOut, resultOut io.Writer, debug bool, fileReplacementsFunc FileReplacementsFunc) error

func TypeExprNameQualifyers

func TypeExprNameQualifyers(expr ast.Expr, qualifyers map[string]struct{})

TypeExprNameQualifyers sets all type name qualifyers (package names) at the massed map that are used in any ast.SelectorExpr recursively found within the passed type expression.

func Visit

func Visit(root ast.Node, pre, post Visitor) (result ast.Node)

Types

type Cursor

type Cursor interface {
	// Path returns the current path of the cursor
	Path() Path

	// Node returns the current Node.
	Node() ast.Node

	// Parent returns the parent of the current Node.
	Parent() ast.Node

	// ParentField returns the name of the parent Node field that contains the current Node.
	// If the parent is a *ast.Package and the current Node is a *ast.File, ParentField returns
	// the filename for the current Node.
	ParentField() string

	// ParentFieldIndex reports the index >= 0 of the current Node in the slice of Nodes that
	// contains it, or a value < 0 if the current Node is not part of a slice.
	// The index of the current node changes if InsertBefore is called while
	// processing the current node.
	ParentFieldIndex() int

	// Replace replaces the current Node with n.
	// The replacement node is not walked by Apply.
	Replace(n ast.Node)

	// Delete deletes the current Node from its containing slice.
	// If the current Node is not part of a slice, Delete panics.
	// As a special case, if the current node is a package file,
	// Delete removes it from the package's Files map.
	Delete()

	// InsertAfter inserts n after the current Node in its containing slice.
	// If the current Node is not part of a slice, InsertAfter panics.
	// Apply does not walk n.
	InsertAfter(n ast.Node)

	// InsertBefore inserts n before the current Node in its containing slice.
	// If the current Node is not part of a slice, InsertBefore panics.
	// Apply will not walk n.
	InsertBefore(n ast.Node)
}

type FileReplacementsFunc

type FileReplacementsFunc func(fset *token.FileSet, pkg *ast.Package, astFile *ast.File, filePath string, verboseOut io.Writer) (NodeReplacements, Imports, error)

FileReplacementsFunc is called for a source file by RewriteWithReplacements to return NodeReplacements and Imports that will be applied to the source file.

type Imports

type Imports map[string]struct{}

func (Imports) Add

func (imports Imports) Add(line string)

func (Imports) Contains

func (imports Imports) Contains(line string) bool

func (Imports) Remove

func (imports Imports) Remove(line string)

func (Imports) Sorted

func (imports Imports) Sorted() []string

type NodeRange

type NodeRange []ast.Node

func (NodeRange) End

func (r NodeRange) End() token.Pos

func (NodeRange) Pos

func (r NodeRange) Pos() token.Pos

type NodeReplacement

type NodeReplacement struct {
	Node        ast.Node
	Replacement any // nil, string, []byte, or anything accepted by format.Node
	DebugID     string
}

type NodeReplacements

type NodeReplacements []NodeReplacement

func (*NodeReplacements) Add

func (repls *NodeReplacements) Add(other NodeReplacements)

func (*NodeReplacements) AddInsertAfter

func (repls *NodeReplacements) AddInsertAfter(node ast.Node, insertion any, debugID ...string)

func (*NodeReplacements) AddRemoval

func (repls *NodeReplacements) AddRemoval(node ast.Node, debugID ...string)

func (*NodeReplacements) AddReplacement

func (repls *NodeReplacements) AddReplacement(node ast.Node, replacement any, debugID ...string)

func (NodeReplacements) Apply

func (repls NodeReplacements) Apply(fset *token.FileSet, source []byte) ([]byte, error)

func (NodeReplacements) DebugApply

func (repls NodeReplacements) DebugApply(fset *token.FileSet, source []byte) ([]byte, error)

func (NodeReplacements) Sort

func (repls NodeReplacements) Sort()

type PackageLocation

type PackageLocation struct {
	PkgName    string
	SourcePath string
	Std        bool
}

func LocatePackage

func LocatePackage(projectDir, importPath string) (*PackageLocation, error)

func LocatePackageOfImportLine

func LocatePackageOfImportLine(projectDir, importLine string) (importName string, loc *PackageLocation, err error)

func LocatePackageOfImportSpec

func LocatePackageOfImportSpec(projectDir string, importSpec *ast.ImportSpec) (importName string, loc *PackageLocation, err error)

type Path

type Path []PathItem

func (Path) Last

func (s Path) Last() PathItem

func (Path) String

func (s Path) String() string

type PathItem

type PathItem struct {
	ParentField      string
	ParentFieldIndex int

	Node ast.Node
	Type string
}

func (*PathItem) String

func (item *PathItem) String() string

type PosNode

type PosNode token.Pos

PosNode implements ast.Node by returning the same underlying token.Pos from its Pos() and End() methods. Usable as zero size replacement node to mark the position of a code insertion.

func (PosNode) End

func (p PosNode) End() token.Pos

func (PosNode) Pos

func (p PosNode) Pos() token.Pos

type RewriteFileFunc

type RewriteFileFunc func(fset *token.FileSet, pkg *ast.Package, astFile *ast.File, filePath string, verboseOut io.Writer) ([]byte, error)

RewriteFileFunc is called for a source file by Rewrite to return the rewritten source or nil if the file should not be changed.

type Visitor

type Visitor interface {
	VisitComment(*ast.Comment, Cursor) bool
	VisitCommentGroup(*ast.CommentGroup, Cursor) bool
	VisitField(*ast.Field, Cursor) bool
	VisitFieldList(*ast.FieldList, Cursor) bool
	VisitBadExpr(*ast.BadExpr, Cursor) bool
	VisitIdent(*ast.Ident, Cursor) bool
	VisitBasicLit(*ast.BasicLit, Cursor) bool
	VisitEllipsis(*ast.Ellipsis, Cursor) bool
	VisitFuncLit(*ast.FuncLit, Cursor) bool
	VisitCompositeLit(*ast.CompositeLit, Cursor) bool
	VisitParenExpr(*ast.ParenExpr, Cursor) bool
	VisitSelectorExpr(*ast.SelectorExpr, Cursor) bool
	VisitIndexExpr(*ast.IndexExpr, Cursor) bool
	VisitSliceExpr(*ast.SliceExpr, Cursor) bool
	VisitTypeAssertExpr(*ast.TypeAssertExpr, Cursor) bool
	VisitCallExpr(*ast.CallExpr, Cursor) bool
	VisitStarExpr(*ast.StarExpr, Cursor) bool
	VisitUnaryExpr(*ast.UnaryExpr, Cursor) bool
	VisitBinaryExpr(*ast.BinaryExpr, Cursor) bool
	VisitKeyValueExpr(*ast.KeyValueExpr, Cursor) bool
	VisitArrayType(*ast.ArrayType, Cursor) bool
	VisitStructType(*ast.StructType, Cursor) bool
	VisitFuncType(*ast.FuncType, Cursor) bool
	VisitInterfaceType(*ast.InterfaceType, Cursor) bool
	VisitMapType(*ast.MapType, Cursor) bool
	VisitChanType(*ast.ChanType, Cursor) bool
	VisitBadStmt(*ast.BadStmt, Cursor) bool
	VisitDeclStmt(*ast.DeclStmt, Cursor) bool
	VisitEmptyStmt(*ast.EmptyStmt, Cursor) bool
	VisitLabeledStmt(*ast.LabeledStmt, Cursor) bool
	VisitExprStmt(*ast.ExprStmt, Cursor) bool
	VisitSendStmt(*ast.SendStmt, Cursor) bool
	VisitIncDecStmt(*ast.IncDecStmt, Cursor) bool
	VisitAssignStmt(*ast.AssignStmt, Cursor) bool
	VisitGoStmt(*ast.GoStmt, Cursor) bool
	VisitDeferStmt(*ast.DeferStmt, Cursor) bool
	VisitReturnStmt(*ast.ReturnStmt, Cursor) bool
	VisitBranchStmt(*ast.BranchStmt, Cursor) bool
	VisitBlockStmt(*ast.BlockStmt, Cursor) bool
	VisitIfStmt(*ast.IfStmt, Cursor) bool
	VisitCaseClause(*ast.CaseClause, Cursor) bool
	VisitSwitchStmt(*ast.SwitchStmt, Cursor) bool
	VisitTypeSwitchStmt(*ast.TypeSwitchStmt, Cursor) bool
	VisitCommClause(*ast.CommClause, Cursor) bool
	VisitSelectStmt(*ast.SelectStmt, Cursor) bool
	VisitForStmt(*ast.ForStmt, Cursor) bool
	VisitRangeStmt(*ast.RangeStmt, Cursor) bool
	VisitImportSpec(*ast.ImportSpec, Cursor) bool
	VisitValueSpec(*ast.ValueSpec, Cursor) bool
	VisitTypeSpec(*ast.TypeSpec, Cursor) bool
	VisitBadDecl(*ast.BadDecl, Cursor) bool
	VisitGenDecl(*ast.GenDecl, Cursor) bool
	VisitFuncDecl(*ast.FuncDecl, Cursor) bool
	VisitFile(*ast.File, Cursor) bool
	VisitPackage(*ast.Package, Cursor) bool
}

type VisitorImpl

type VisitorImpl struct{}

func (VisitorImpl) VisitArrayType

func (VisitorImpl) VisitArrayType(*ast.ArrayType, Cursor) bool

func (VisitorImpl) VisitAssignStmt

func (VisitorImpl) VisitAssignStmt(*ast.AssignStmt, Cursor) bool

func (VisitorImpl) VisitBadDecl

func (VisitorImpl) VisitBadDecl(*ast.BadDecl, Cursor) bool

func (VisitorImpl) VisitBadExpr

func (VisitorImpl) VisitBadExpr(*ast.BadExpr, Cursor) bool

func (VisitorImpl) VisitBadStmt

func (VisitorImpl) VisitBadStmt(*ast.BadStmt, Cursor) bool

func (VisitorImpl) VisitBasicLit

func (VisitorImpl) VisitBasicLit(*ast.BasicLit, Cursor) bool

func (VisitorImpl) VisitBinaryExpr

func (VisitorImpl) VisitBinaryExpr(*ast.BinaryExpr, Cursor) bool

func (VisitorImpl) VisitBlockStmt

func (VisitorImpl) VisitBlockStmt(*ast.BlockStmt, Cursor) bool

func (VisitorImpl) VisitBranchStmt

func (VisitorImpl) VisitBranchStmt(*ast.BranchStmt, Cursor) bool

func (VisitorImpl) VisitCallExpr

func (VisitorImpl) VisitCallExpr(*ast.CallExpr, Cursor) bool

func (VisitorImpl) VisitCaseClause

func (VisitorImpl) VisitCaseClause(*ast.CaseClause, Cursor) bool

func (VisitorImpl) VisitChanType

func (VisitorImpl) VisitChanType(*ast.ChanType, Cursor) bool

func (VisitorImpl) VisitCommClause

func (VisitorImpl) VisitCommClause(*ast.CommClause, Cursor) bool

func (VisitorImpl) VisitComment

func (VisitorImpl) VisitComment(*ast.Comment, Cursor) bool

func (VisitorImpl) VisitCommentGroup

func (VisitorImpl) VisitCommentGroup(*ast.CommentGroup, Cursor) bool

func (VisitorImpl) VisitCompositeLit

func (VisitorImpl) VisitCompositeLit(*ast.CompositeLit, Cursor) bool

func (VisitorImpl) VisitDeclStmt

func (VisitorImpl) VisitDeclStmt(*ast.DeclStmt, Cursor) bool

func (VisitorImpl) VisitDeferStmt

func (VisitorImpl) VisitDeferStmt(*ast.DeferStmt, Cursor) bool

func (VisitorImpl) VisitEllipsis

func (VisitorImpl) VisitEllipsis(*ast.Ellipsis, Cursor) bool

func (VisitorImpl) VisitEmptyStmt

func (VisitorImpl) VisitEmptyStmt(*ast.EmptyStmt, Cursor) bool

func (VisitorImpl) VisitExprStmt

func (VisitorImpl) VisitExprStmt(*ast.ExprStmt, Cursor) bool

func (VisitorImpl) VisitField

func (VisitorImpl) VisitField(*ast.Field, Cursor) bool

func (VisitorImpl) VisitFieldList

func (VisitorImpl) VisitFieldList(*ast.FieldList, Cursor) bool

func (VisitorImpl) VisitFile

func (VisitorImpl) VisitFile(*ast.File, Cursor) bool

func (VisitorImpl) VisitForStmt

func (VisitorImpl) VisitForStmt(*ast.ForStmt, Cursor) bool

func (VisitorImpl) VisitFuncDecl

func (VisitorImpl) VisitFuncDecl(*ast.FuncDecl, Cursor) bool

func (VisitorImpl) VisitFuncLit

func (VisitorImpl) VisitFuncLit(*ast.FuncLit, Cursor) bool

func (VisitorImpl) VisitFuncType

func (VisitorImpl) VisitFuncType(*ast.FuncType, Cursor) bool

func (VisitorImpl) VisitGenDecl

func (VisitorImpl) VisitGenDecl(*ast.GenDecl, Cursor) bool

func (VisitorImpl) VisitGoStmt

func (VisitorImpl) VisitGoStmt(*ast.GoStmt, Cursor) bool

func (VisitorImpl) VisitIdent

func (VisitorImpl) VisitIdent(*ast.Ident, Cursor) bool

func (VisitorImpl) VisitIfStmt

func (VisitorImpl) VisitIfStmt(*ast.IfStmt, Cursor) bool

func (VisitorImpl) VisitImportSpec

func (VisitorImpl) VisitImportSpec(*ast.ImportSpec, Cursor) bool

func (VisitorImpl) VisitIncDecStmt

func (VisitorImpl) VisitIncDecStmt(*ast.IncDecStmt, Cursor) bool

func (VisitorImpl) VisitIndexExpr

func (VisitorImpl) VisitIndexExpr(*ast.IndexExpr, Cursor) bool

func (VisitorImpl) VisitInterfaceType

func (VisitorImpl) VisitInterfaceType(*ast.InterfaceType, Cursor) bool

func (VisitorImpl) VisitKeyValueExpr

func (VisitorImpl) VisitKeyValueExpr(*ast.KeyValueExpr, Cursor) bool

func (VisitorImpl) VisitLabeledStmt

func (VisitorImpl) VisitLabeledStmt(*ast.LabeledStmt, Cursor) bool

func (VisitorImpl) VisitMapType

func (VisitorImpl) VisitMapType(*ast.MapType, Cursor) bool

func (VisitorImpl) VisitPackage

func (VisitorImpl) VisitPackage(*ast.Package, Cursor) bool

func (VisitorImpl) VisitParenExpr

func (VisitorImpl) VisitParenExpr(*ast.ParenExpr, Cursor) bool

func (VisitorImpl) VisitRangeStmt

func (VisitorImpl) VisitRangeStmt(*ast.RangeStmt, Cursor) bool

func (VisitorImpl) VisitReturnStmt

func (VisitorImpl) VisitReturnStmt(*ast.ReturnStmt, Cursor) bool

func (VisitorImpl) VisitSelectStmt

func (VisitorImpl) VisitSelectStmt(*ast.SelectStmt, Cursor) bool

func (VisitorImpl) VisitSelectorExpr

func (VisitorImpl) VisitSelectorExpr(*ast.SelectorExpr, Cursor) bool

func (VisitorImpl) VisitSendStmt

func (VisitorImpl) VisitSendStmt(*ast.SendStmt, Cursor) bool

func (VisitorImpl) VisitSliceExpr

func (VisitorImpl) VisitSliceExpr(*ast.SliceExpr, Cursor) bool

func (VisitorImpl) VisitStarExpr

func (VisitorImpl) VisitStarExpr(*ast.StarExpr, Cursor) bool

func (VisitorImpl) VisitStructType

func (VisitorImpl) VisitStructType(*ast.StructType, Cursor) bool

func (VisitorImpl) VisitSwitchStmt

func (VisitorImpl) VisitSwitchStmt(*ast.SwitchStmt, Cursor) bool

func (VisitorImpl) VisitTypeAssertExpr

func (VisitorImpl) VisitTypeAssertExpr(*ast.TypeAssertExpr, Cursor) bool

func (VisitorImpl) VisitTypeSpec

func (VisitorImpl) VisitTypeSpec(*ast.TypeSpec, Cursor) bool

func (VisitorImpl) VisitTypeSwitchStmt

func (VisitorImpl) VisitTypeSwitchStmt(*ast.TypeSwitchStmt, Cursor) bool

func (VisitorImpl) VisitUnaryExpr

func (VisitorImpl) VisitUnaryExpr(*ast.UnaryExpr, Cursor) bool

func (VisitorImpl) VisitValueSpec

func (VisitorImpl) VisitValueSpec(*ast.ValueSpec, Cursor) bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL