astutil

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package astutil 提供通用 Go AST 操作库,基于 dave/dst 封装。

Package astutil 提供通用 Go AST 操作库,基于 dave/dst 封装。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Field

type Field struct {
	Names []string // 参数名列表,可以为空(如匿名返回值)。
	Type  dst.Expr // 类型表达式。
}

Field 表示函数参数或返回值。

type File

type File struct {
	// contains filtered or unexported fields
}

File 表示一个可操作的 Go 源文件。

func ParseFile

func ParseFile(path string) (*File, error)

ParseFile 从文件路径解析。

func ParseSource

func ParseSource(src []byte) (*File, error)

ParseSource 从源代码解析。

func (*File) Apply

func (f *File) Apply(ops ...Op)

Apply 应用多个修改操作。

func (*File) FindDecls

func (f *File) FindDecls(declType any) []dst.Decl

FindDecls 返回所有匹配指定类型的顶层声明。 declType 应为声明类型的零值,如 *dst.GenDecl 或 *dst.FuncDecl。

func (*File) FindFunction

func (f *File) FindFunction(name string) *dst.FuncDecl

FindFunction 按名称查找函数。

func (*File) FindFunctions

func (f *File) FindFunctions() []*dst.FuncDecl

FindFunctions 返回所有函数声明。

func (*File) FindGenDecls

func (f *File) FindGenDecls(tok interface{ String() string }) []*dst.GenDecl

FindGenDecls 返回所有匹配指定 token 类型的 GenDecl。 例如传入 token.IMPORT、token.TYPE、token.CONST、token.VAR。

func (*File) FindImports

func (f *File) FindImports() []*dst.ImportSpec

FindImports 返回所有 import。

func (*File) Format

func (f *File) Format() ([]byte, error)

Format 返回格式化后的源码。

func (*File) WriteTo

func (f *File) WriteTo(path string) error

WriteTo 写入文件。

type Op

type Op func(*dst.File)

Op 表示一个 AST 修改操作。

func AddImport

func AddImport(path string) Op

AddImport 添加 import 语句(幂等,重复添加不会生效)。

func EnsureFunction

func EnsureFunction(name string, params, results []Field, body []dst.Stmt) Op

EnsureFunction 确保指定函数存在,不存在则创建。 函数存在时不做任何操作,不存在时创建新的函数声明并添加到文件末尾。

func InsertAfter

func InsertAfter(marker any, nodes ...dst.Decl) Op

InsertAfter 在指定标记后插入代码。 marker 可以是以下类型:

  • string:查找包含该字符串的注释标记(如 "//inject:here"),在该注释所在声明后插入
  • dst.Decl:在该节点后插入(通过指针比较定位)

如果找不到标记,操作不执行(no-op)。

func RemoveImport

func RemoveImport(path string) Op

RemoveImport 移除 import 语句。

func ReplaceNode

func ReplaceNode(oldNode, newNode dst.Decl) Op

ReplaceNode 替换指定的 AST 节点。 通过指针比较(oldNode == decl)在 f.Decls 中定位目标节点, 找到后用 newNode 替换。如果找不到 oldNode,不执行替换(no-op)。

Directories

Path Synopsis
Package gen 提供 jennifer 风格的流式 API,用于从零生成 Go 代码。
Package gen 提供 jennifer 风格的流式 API,用于从零生成 Go 代码。

Jump to

Keyboard shortcuts

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