bast

package module
v0.0.0-...-76ec14b Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2024 License: MIT Imports: 17 Imported by: 1

README

BAST

Bastard AST is lightweight model of top level Go declarations constructed from go/ast and intended for simple source analysis and code genration.

Traversing go source trees can get convoluted fast so bast gives fast access to basic type info of go packages.

Status

Experimental. API is subject to change.

License

MIT.

Documentation

Overview

Package bast implements a simple intermediate object model of top level Go declarations from AST of go source files and is designed for use in text based code-generation with Go's text/template templating engine.

Bast's structure can be easily traversed from a template and provides a number of functions to help with data retrieval and other utils.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Print

func Print(w io.Writer, bast *Bast)

Print prints bas to writer w.

Types

type Bast

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

Bast holds lists of top level declarations found in a set of parsed packages.

It is a reduced model of go source which parses out only top level declarations and provides a simple model and interface for their easy retrieval, enumeration and inspection.

It is returned the by Load function.

func Load

func Load(config *Config, patterns ...string) (bast *Bast, err error)

Load loads packages specified by pattern and returns a *Bast of it or an error.

An optional config configures the underlying go build system and other details. See Config.

func (*Bast) AllConsts

func (self *Bast) AllConsts() (out []*Const)

AllConsts returns all consts in self, across all packages.

func (*Bast) AllFuncs

func (self *Bast) AllFuncs() (out []*Func)

AllFuncs returns all functions in self, across all packages.

func (*Bast) AllInterfaces

func (self *Bast) AllInterfaces() (out []*Interface)

Funcs returns all interfaces in self, across all packages.

func (*Bast) AllMethods

func (self *Bast) AllMethods() (out []*Method)

Funcs returns all methods in self, across all packages.

func (*Bast) AllPackages

func (self *Bast) AllPackages() (out []*Package)

AllPackages returns all parsed packages.

func (*Bast) AllStructs

func (self *Bast) AllStructs() (out []*Struct)

Funcs returns all structs in self, across all packages.

func (*Bast) AllTypes

func (self *Bast) AllTypes() (out []*Type)

AllTypes returns all types in self, across all packages.

func (*Bast) AllVars

func (self *Bast) AllVars() (out []*Var)

AllVars returns all variables in self, across all packages.

func (*Bast) AnyConst

func (self *Bast) AnyConst(declName string) (out *Const)

Const returns a const whose Name==declName from from any package.

func (*Bast) AnyFunc

func (self *Bast) AnyFunc(declName string) (out *Func)

Func returns a func whose Name==declName from from any package.

func (*Bast) AnyInterface

func (self *Bast) AnyInterface(declName string) (out *Interface)

Interface returns a interface whose Name==declName from from any package.

func (*Bast) AnyMethod

func (self *Bast) AnyMethod(declName string) (out *Method)

Method returns a method whose Name==declName from from any package.

func (*Bast) AnyStruct

func (self *Bast) AnyStruct(declName string) (out *Struct)

Struct returns a struct whose Name==declName from from any package.

func (*Bast) AnyType

func (self *Bast) AnyType(declName string) (out *Type)

Type returns a type whose Name==declName from from any package.

func (*Bast) AnyVar

func (self *Bast) AnyVar(declName string) (out *Var)

Var returns a variable whose Name==declName from any package.

func (*Bast) ConstsOfType

func (self *Bast) ConstsOfType(pkgPath, typeName string) (out []*Const)

ConstsOfType returns all top level constant declarations from a package named pkgPath whose type name equals typeName.

func (*Bast) FieldNames

func (self *Bast) FieldNames(pkgPath, structName string) (out []string)

FieldNames returns a slice of names of fields of a struct named by structName residing in some file in package named pkgPath.

func (*Bast) MethodSet

func (self *Bast) MethodSet(pkgPath, typeName string) (out []*Method)

MethodSet returns all methods from a package named pkgPath whose receiver type matches typeName (star prefixed or not).

func (*Bast) PackageByPath

func (self *Bast) PackageByPath(pkgPath string) (p *Package)

PackageByPath returns a package by its import path or nil if not found.

func (*Bast) PackageImportPaths

func (self *Bast) PackageImportPaths() []string

PackageImportPaths returns package paths of all loaded packages.

func (*Bast) PackageNames

func (self *Bast) PackageNames() (out []string)

PackageNames returns names of all parsed packages.

func (*Bast) Packages

func (self *Bast) Packages() []*Package

Packages returns parsed bast packages.

func (*Bast) PkgConst

func (self *Bast) PkgConst(pkgPath, declName string) (out *Const)

PkgConst returns a const whose Name==declName from a package with pkgPath.

func (*Bast) PkgConsts

func (self *Bast) PkgConsts(pkgPath string) (out []*Const)

PgkConsts returns all consts in pkgPath.

func (*Bast) PkgFunc

func (self *Bast) PkgFunc(pkgPath, declName string) (out *Func)

PkgFunc returns a func whose Name==declName from a package with pkgPath.

func (*Bast) PkgFuncs

func (self *Bast) PkgFuncs(pkgPath string) (out []*Func)

PkgFuncs returns all functions in pkgPath.

func (*Bast) PkgInterface

func (self *Bast) PkgInterface(pkgPath, declName string) (out *Interface)

PkgInterface returns an interface whose Name==declName from a package with pkgPath.

func (*Bast) PkgInterfaces

func (self *Bast) PkgInterfaces(pkgPath string) (out []*Interface)

PkgInterfaces returns all interfaces in pkgPath.

func (*Bast) PkgMethod

func (self *Bast) PkgMethod(pkgPath, declName string) (out *Method)

PkgMethod returns a method whose Name==declName from a package with pkgPath.

func (*Bast) PkgMethods

func (self *Bast) PkgMethods(pkgPath string) (out []*Method)

PkgMethods returns all methods in pkgPath.

func (*Bast) PkgStruct

func (self *Bast) PkgStruct(pkgPath, declName string) (out *Struct)

PkgStruct returns a struct whose Name==declName from a package with pkgPath.

func (*Bast) PkgStructs

func (self *Bast) PkgStructs(pkgPath string) (out []*Struct)

PkgStructs returns all structs in pkgPath.

func (*Bast) PkgType

func (self *Bast) PkgType(pkgPath, declName string) (out *Type)

PkgType returns a type whose Name==declName from a package with pkgPath.

func (*Bast) PkgTypes

func (self *Bast) PkgTypes(pkgPath string) (out []*Type)

PkgTypes returns all types in pkgPath.

func (*Bast) PkgVar

func (self *Bast) PkgVar(pkgPath, declName string) (out *Var)

PkgVar returns a variable whose Name==declName from a package with pkgPath.

func (*Bast) PkgVars

func (self *Bast) PkgVars(pkgPath string) (out []*Var)

PkgVars returns all variables in pkgPath.

func (*Bast) ResolveBasicType

func (self *Bast) ResolveBasicType(typeName string) string

ResolveBasicType returns the basic type name of a derived type typeName by searching the type hierarchy of parsed packages.

If typeName is already a name of a basic type it is returned as is. If basic type was not found resolved returns an empty string.

Requires [Config.TypeChecking].

func (*Bast) TypesOfType

func (self *Bast) TypesOfType(pkgPath, typeName string) (out []*Type)

TypesOfType returns all top level type declarations from a package named pkgPath whose type name equals typeName.

func (*Bast) VarsOfType

func (self *Bast) VarsOfType(pkgPath, typeName string) (out []*Var)

VarsOfType returns all top level variable declarations from a package named pkgPath whose type name equals typeName.

type Config

type Config struct {

	// Dir is the directory in which to run the build system's query tool
	// that provides information about the packages.
	// If Dir is empty, the tool is run in the current directory.
	//
	// Package patterns given to [ParsePackages] are relative to this directory.
	//
	// Default is "." which sets the build dir to current directory.
	Dir string `json:"dir,omitempty"`

	// BuildFlags is a list of command-line flags to be passed through to
	// the build system's query tool.
	BuildFlags []string `json:"buildFlags,omitempty"`

	// Env is the environment to use when invoking the build system's query tool.
	// If Env is nil, the current environment is used.
	// As in os/exec's Cmd, only the last value in the slice for
	// each environment key is used. To specify the setting of only
	// a few variables, append to the current environment, as in:
	//
	//	opt.Env = append(os.Environ(), "GOOS=plan9", "GOARCH=386")
	//
	Env []string `json:"env,omitempty"`

	// If Tests is set, the loader includes not just the packages
	// matching a particular pattern but also any related test packages,
	// including test-only variants of the package and the test executable.
	//
	// For example, when using the go command, loading "fmt" with Tests=true
	// returns four packages, with IDs "fmt" (the standard package),
	// "fmt [fmt.test]" (the package as compiled for the test),
	// "fmt_test" (the test functions from source files in package fmt_test),
	// and "fmt.test" (the test binary).
	//
	// In build systems with explicit names for tests,
	// setting Tests may have no effect.
	Tests bool `json:"tests,omitempty"`

	// TypeChecking enables type checking to enable few type resolution
	// related utilities like [Bast.ResolveBasicType].
	//
	// Default: true
	TypeChecking bool `json:"typeChecking,omitempty"`

	// TypeCheckingErrors if enabled will return errors during [Load] if
	// typechecking or parsed packages failed.
	//
	// Default: true
	TypeCheckingErrors bool `json:"typeCheckingErrors,omitempty"`
}

Config configures Load.

func Default

func Default() *Config

Default is an alias for DefaultConfig.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default configuration.

type Const

type Const struct {
	// Model is the declaration base.
	Model
	// Type is the const type, empty if undpecified.
	Type string
	// Value is the const value, empty if unspecified.
	Value string
}

Const contains info about a constant.

If a variable was declared with implicit type, Type will be empty.

func NewConst

func NewConst(file *File, name, typ string) *Const

NewConst returns a new *Const.

type Declaration

type Declaration interface {
	// GetFile returns the declarations parent file.
	GetFile() *File
	// GetPackage returns the declarations parent package.
	GetPackage() *Package
}

Declaration represents a top level declaration in a Go file.

type DeclarationMap

type DeclarationMap = maps.OrderedMap[string, Declaration]

DeclarationMap maps declarations by their name in parse order.

type Field

type Field struct {

	// Model is the declaration base.
	Model

	// Type is the field type.
	//
	// For [Struct] receivers, type will be the bare type name without star or
	// type parameters. If it is a pointer receiver [Field.Pointer] will be
	// true. Type parameters are ommited from the name and can be inspected in
	// parent [Struct] definition.
	Type string

	// Tag is the field raw tag string.
	Tag string

	// Unnamed is true if field is unnamed and specifies the type only.
	Unnamed bool

	// Pointer is true if this field is a pointer method receiver.
	Pointer bool
}

Field contains info about a struct field, method receiver, or method or func type params, params or results.

func NewField

func NewField(file *File, name string) *Field

NewField returns a new *Field.

type FieldMap

type FieldMap = maps.OrderedMap[string, *Field]

FieldMap maps fields by their name in parse order.

type File

type File struct {
	// Comments are the file comments, grouped by separation, including docs.
	Comments [][]string
	// Doc is the file doc comment.
	Doc []string
	// Name is the File name, a full file path.
	Name string
	// Imports is a list of file imports.
	Imports *ImportSpecMap
	// Declarations is a list of top level declarations in the file.
	Declarations *DeclarationMap
	// contains filtered or unexported fields
}

File contians info about a Go source file.

func NewFile

func NewFile(pkg *Package, name string) *File

NewFile returns a new *File.

func (*File) Const

func (self *File) Const(name string) (out *Const)

Var returns a Const declaration from File under name or nil if not found.

func (*File) Func

func (self *File) Func(name string) (out *Func)

Var returns a Func declaration from File under name or nil if not found.

func (*File) HasDecl

func (self *File) HasDecl(name string) (b bool)

HasDecl returns true if a var, const, func or method declaration with name or type, struct or interface with type name was found in this file.

func (*File) ImportSpecFromSelector

func (self *File) ImportSpecFromSelector(selectorExpr string) *ImportSpec

ImportSpecFromSelector returns an import spec from a selectorExpr. If import was not found or selectorExpr is invalid result is nil.

func (*File) Interface

func (self *File) Interface(name string) (out *Interface)

Var returns a Interface declaration from File under name or nil if not found.

func (*File) Method

func (self *File) Method(name string) (out *Method)

Var returns a Method declaration from File under name or nil if not found.

func (*File) Struct

func (self *File) Struct(name string) (out *Struct)

Var returns a Struct declaration from File under name or nil if not found.

func (*File) Type

func (self *File) Type(name string) (out *Type)

Var returns a Type declaration from File under name or nil if not found.

func (*File) Var

func (self *File) Var(name string) (out *Var)

Var returns a Var declaration from File under name or nil if not found.

type FileMap

type FileMap = maps.OrderedMap[string, *File]

FileMap maps files by their FileName in parse order.

type Func

type Func struct {
	// Model is the declaration base.
	Model
	// TypeParams are type parameters.
	TypeParams *FieldMap
	//  Params is a list of func arguments.
	Params *FieldMap
	// Results is a list of func returns.
	Results *FieldMap
}

Func contains info about a function.

func NewFunc

func NewFunc(file *File, name string) *Func

NewFunc returns a new *Func.

type ImportSpec

type ImportSpec struct {
	// Doc is the import doc comment.
	Doc []string
	// Name is the import name, possibly empty, "." or some custom name.
	Name string
	// Path is the import path.
	Path string
}

ImportSpec contains info about an Package or File import.

func NewImport

func NewImport(name, path string) *ImportSpec

NewImport returns a new *Import.

func (*ImportSpec) Base

func (self *ImportSpec) Base() string

Base returns the base name from the package path.

type ImportSpecMap

type ImportSpecMap = maps.OrderedMap[string, *ImportSpec]

ImportSpecMap maps imports by their path in parse order.

type Interface

type Interface struct {
	// Model is the declaration base.
	Model
	// Methods is a list of methods defined by the interface.
	Methods *MethodMap
	// Interface is a list of inherited interfaces.
	//
	// Map is keyed by the embeded interface type name.
	Interfaces *FieldMap
}

Interface contains info about an interface.

func NewInterface

func NewInterface(file *File, name string) *Interface

NewInterface returns a new *Interface.

type Method

type Method struct {
	// Func embeds all Func properties.
	Func
	// Receiver is the method receiver.
	//
	// Receiver is nil if this is an interface method without a receiver.
	Receiver *Field
}

Method contains info about a method.

func NewMethod

func NewMethod(file *File, name string) *Method

NewMethod returns a new *Method.

type MethodMap

type MethodMap = maps.OrderedMap[string, *Method]

MethodMap maps methods by their name in parse order.

type Model

type Model struct {

	// Doc is the declaration doc comment.
	Doc []string

	// Name is the declaration name.
	//
	// For [Struct], this will be the bare name of the struct type without type
	// parameters. Type parameters are stored separately in a [Struct]
	// definition.
	//
	// If struct field is unnamed Name will be equal to Type.
	// [Field.Unnamed] will be set to true as well.
	Name string
	// contains filtered or unexported fields
}

Model is the bast model base with fields shared by all declarations.

Model implements Declaration interface].

func (*Model) GetFile

func (self *Model) GetFile() *File

GetFile returns the declarations parent file.

func (*Model) GetPackage

func (self *Model) GetPackage() *Package

GetPackage returns the declarations parent package.

func (*Model) ImportSpecBySelectorExpr

func (self *Model) ImportSpecBySelectorExpr(selectorExpr string) *ImportSpec

ImportSpecBySelectorExpr returns an ImportSpec whose path is the path of a package from which a type qualified by selectorExpr is imported into go file being parsed. I.e.: "package.TypeName".

It returns nil if not found or selectorExpr is invalid.

func (*Model) ResolveBasicType

func (self *Model) ResolveBasicType(typeName string) string

ResolveBasicType returns the basic type name of a derived type typeName by searching the type hierarchy of parsed packages.

If typeName is already a name of a basic type it is returned as is. If basic type was not found resolved returns an empty string.

Requires [Config.TypeChecking].

type Package

type Package struct {
	// Name is the package name, without path, as it appears in source code.
	Name string
	// Path is the package import path as used by go compiler.
	Path string
	// Files maps definitions of parsed go files by their full path.
	Files *FileMap
	// contains filtered or unexported fields
}

Package contains info about a Go package.

func NewPackage

func NewPackage(name, path string, pkg *packages.Package) *Package

NewPackage returns a new *Package.

func (*Package) Const

func (self *Package) Const(name string) (out *Const)

Var returns a Const declaration from File under name or nil if not found.

func (*Package) DeclFile

func (self *Package) DeclFile(typeName string) string

DeclFile returns the full filename of a file that contains the declaration whose type equals typeName. If not found result is an empty string.

func (*Package) Func

func (self *Package) Func(name string) (out *Func)

Var returns a Func declaration from File under name or nil if not found.

func (*Package) HasDecl

func (self *Package) HasDecl(typeName string) bool

HasDecl returns true if declaration with typeName was found in this package.

func (*Package) Interface

func (self *Package) Interface(name string) (out *Interface)

Var returns a Interface declaration from File under name or nil if not found.

func (*Package) Method

func (self *Package) Method(name string) (out *Method)

Var returns a Method declaration from File under name or nil if not found.

func (*Package) Struct

func (self *Package) Struct(name string) (out *Struct)

Var returns a Struct declaration from File under name or nil if not found.

func (*Package) Type

func (self *Package) Type(name string) (out *Type)

Var returns a Type declaration from File under name or nil if not found.

func (*Package) Var

func (self *Package) Var(name string) (out *Var)

Var returns a Var declaration from File under name or nil if not found.

type PackageMap

type PackageMap = maps.OrderedMap[string, *Package]

PackageMap maps packages by their import path.

type Printer

type Printer struct {
	PrintDoc        bool
	PrintComments   bool
	PrintConsts     bool
	PrintVars       bool
	PrintTypes      bool
	PrintFuncs      bool
	PrintMethods    bool
	PrintStructs    bool
	PrintInterfaces bool
}

func DefaultPrinter

func DefaultPrinter() *Printer

DefaultPrinter returns the default print configuration.

func (*Printer) Print

func (self *Printer) Print(w io.Writer, bast *Bast)

type Struct

type Struct struct {
	// Model is the declaration base.
	Model
	// Fields is a list of struct fields.
	Fields *FieldMap
	// TypeParams are type parameters.
	TypeParams *FieldMap
}

Struct contains info about a struct.

func NewStruct

func NewStruct(file *File, name string) *Struct

NewStruct returns a new *Struct.

func (*Struct) Methods

func (self *Struct) Methods() (out []*Method)

Methods returns a slice of methods defined on this struct.

type Type

type Type struct {
	// Model is the declaration base.
	Model
	// Type is Type's underlying type.
	//
	// The name can be a selector qualifying the package it originates in.
	Type string
	// IsAlias is true if type is an alias of the type it derives from.
	IsAlias bool
	// TypeParams are type parameters.
	TypeParams *FieldMap
}

Type contains info about a type.

func NewType

func NewType(file *File, name, typ string) *Type

NewType returns a new *Type.

type Var

type Var struct {
	// Model is the declaration base.
	Model
	// Type is the const type, empty if undpecified.
	Type string
	// Value is the const value, empty if undpecified.
	Value string
}

Var contains info about a variable.

If a variable was declared with implicit type, Type will be empty. If a variable was declared without an initial value, Value will be empty.

func NewVar

func NewVar(file *File, name, typ string) *Var

NewVar returns a new *Var.

Jump to

Keyboard shortcuts

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