aster

package
v0.7.6 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2022 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Overview

Package aster can easily get the golang syntax tree and modify the code.

Copyright 2018 henrylee2cn. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const (
	AnyObjKind = ^ObjKind(0) // any object kind
	AnyTypKind = ^TypKind(0) // any type kind
)

any kinds

Variables

This section is empty.

Functions

This section is empty.

Types

type Facade added in v0.3.0

type Facade interface {

	// FileSet returns the *token.FileSet
	FileSet() *token.FileSet

	// FormatNode formats the node and returns the string.
	FormatNode(ast.Node) (string, error)

	// PackageInfo returns the package info.
	PackageInfo() *PackageInfo

	// File returns the file it is in.
	File() *File

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

	// Ident returns the indent.
	Ident() *ast.Ident

	// Object returns the types.Object.
	Object() types.Object

	// ObjKind returns what the facade represents.
	ObjKind() ObjKind

	// TypKind returns what the facade type represents.
	// NOTE: If the type is *type.Named, returns the underlying TypKind.
	TypKind() TypKind

	// Id is a wrapper for Id(obj.Pkg(), obj.Name()).
	Id() string

	// Name returns the type's name within its package for a defined type.
	// For other (non-defined) types it returns the empty string.
	Name() string

	// Doc returns lead comment.
	Doc() string

	// SetDoc sets lead comment.
	SetDoc(text string) bool

	// Exported reports whether the object is exported (starts with a capital letter).
	// It doesn't take into account whether the object is in a local (function) scope
	// or not.
	Exported() bool

	// String previews the object formated code and comment.
	String() string

	// Underlying returns the underlying type of a type.
	Underlying() types.Type

	// IsAlias reports whether obj is an alias name for a type.
	IsAlias() bool

	// NumMethods returns the number of explicit methods whose receiver is named type t.
	NumMethods() int

	// Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
	// NOTE: the result's TypKind is Signature.
	Method(i int) Facade

	// AssertableTo reports whether it can be asserted to have T's type.
	AssertableTo(T Facade) bool

	// AssignableTo reports whether it is assignable to a variable of T's type.
	AssignableTo(T Facade) bool

	// ConvertibleTo reports whether it is convertible to a value of T's type.
	ConvertibleTo(T Facade) bool

	// Implements reports whether it implements iface.
	// NOTE: Panic, if iface TypKind != Interface
	Implements(iface Facade, usePtr bool) bool

	// Elem returns the element type.
	// NOTE: Panic, if TypKind != (Array, Slice, Map, Chan and Pointer)
	Elem() types.Type

	// Key returns the key type of map.
	// NOTE: Panic, if TypKind != Map
	Key() types.Type

	// Len returns the length of array, or the number variables of tuple.
	// A negative result indicates an unknown length.
	// NOTE: Panic, if TypKind != Array and TypKind != Tuple
	Len() int64

	// ChanDir returns the direction of channel.
	// NOTE: Panic, if TypKind != Chan
	ChanDir() types.ChanDir

	// BasicInfo returns information about properties of basic type.
	// NOTE: Panic, if TypKind != Basic
	BasicInfo() types.BasicInfo

	// BasicKind returns the kind of basic type.
	// NOTE: Panic, if TypKind != Basic
	BasicKind() types.BasicKind

	// IsMethod returns whether it is a method.
	IsMethod() bool

	// Params returns the parameters of signature s, or nil.
	// NOTE: Panic, if TypKind != Signature
	Params() *types.Tuple

	// Recv returns the receiver of signature s (if a method), or nil if a
	// function. It is ignored when comparing signatures for identity.
	//
	// For an abstract method, Recv returns the enclosing interface either
	// as a *Named or an *Interface. Due to embedding, an interface may
	// contain methods whose receiver type is a different interface.
	// NOTE: Panic, if TypKind != Signature
	Recv() *types.Var

	// Results returns the results of signature s, or nil.
	// NOTE: Panic, if TypKind != Signature
	Results() *types.Tuple

	// Variadic reports whether the signature s is variadic.
	// NOTE: Panic, if TypKind != Signature
	Variadic() bool

	// Body returns function body.
	// NOTE: Panic, if TypKind != Signature
	Body() (string, error)

	// CoverBody covers function body.
	// NOTE: Panic, if TypKind != Signature
	CoverBody(body string) error

	// NumFields returns the number of fields in the struct (including blank and embedded fields).
	// NOTE: Panic, if TypKind != Struct
	NumFields() int

	// Field returns the i'th field for 0 <= i < NumFields().
	// NOTE:
	// Panic, if TypKind != Struct;
	// Panic, if i is not in the range [0, NumFields()).
	Field(i int) *StructField

	// FieldByName returns the struct field with the given name
	// and a boolean indicating if the field was found.
	// NOTE: Panic, if TypKind != Struct
	FieldByName(name string) (field *StructField, found bool)

	// EmbeddedType returns the i'th embedded type of interface fa for 0 <= i < fa.NumEmbeddeds().
	// NOTE: Panic, if TypKind != Interface
	IfaceEmbeddedType(i int) Facade

	// IfaceEmpty returns true if fa is the empty interface.
	IfaceEmpty() bool

	// IfaceExplicitMethod returns the i'th explicitly declared method of interface fa for 0 <= i < fa.NumExplicitMethods().
	// The methods are ordered by their unique Id.
	// NOTE:
	//  Panic, if TypKind != Interface;
	//  The result's TypKind is Signature.
	IfaceExplicitMethod(i int) Facade

	// IfaceNumEmbeddeds returns the number of embedded types in interface fa.
	// NOTE: Panic, if TypKind != Interface
	IfaceNumEmbeddeds() int

	// IfaceNumExplicitMethods returns the number of explicitly declared methods of interface fa.
	// NOTE: Panic, if TypKind != Interface
	IfaceNumExplicitMethods() int
	// contains filtered or unexported methods
}

An Facade describes a named language entity such as a package, constant, type, variable, function (incl. methods), or label. Facade interface implement all the objects.

NOTE:

Objects of ObjKind=Bad are not collected;

type File

type File struct {
	Filename string
	*ast.File
	*PackageInfo
	// contains filtered or unexported fields
}

File the 'ast.File' with filename and fileSet.

func (*File) AddImport added in v0.7.4

func (f *File) AddImport(importPath string, alias ...string) error

AddImport add a new import package

func (*File) CoverImport added in v0.7.4

func (f *File) CoverImport(originImportPath string, importPath string, alias ...string)

CoverImport cover originImportPath with importPath

func (*File) DelImport added in v0.7.4

func (f *File) DelImport(path string)

DelImport delete a import path

func (*File) Format

func (f *File) Format() (codes map[string]string, first error)

func (*File) FormatNode

func (f *File) FormatNode(node ast.Node) (string, error)

FormatNode formats the node and returns the string.

func (*File) Rewrite added in v0.7.4

func (f *File) Rewrite() (first error)

type ObjKind added in v0.3.0

type ObjKind uint32

ObjKind describes what an object statement represents. Extension based on ast.ObjKind: Buil and Nil

const (
	Bad ObjKind = 1 << iota // for error handling
	Pkg                     // package
	Con                     // constant
	Typ                     // type
	Var                     // variable
	Fun                     // function or method
	Lbl                     // label
	Bui                     // builtin
	Nil                     // nil
)

The list of possible object statement kinds.

func GetObjKind added in v0.3.0

func GetObjKind(obj types.Object) ObjKind

GetObjKind returns what the types.Object represents.

func (ObjKind) In added in v0.3.0

func (k ObjKind) In(set ObjKind) bool

In judges whether k is fully contained in set.

func (ObjKind) String added in v0.3.0

func (i ObjKind) String() string

type PackageInfo added in v0.3.0

type PackageInfo struct {
	Pkg *types.Package

	Errors []error // non-nil if the package had errors

	Files []*File
	// contains filtered or unexported fields
}

PackageInfo holds the ASTs and facts derived by the type-checker for a single package.

Not mutated once exposed via the API.

func (*PackageInfo) FindFacade added in v0.3.0

func (p *PackageInfo) FindFacade(typ types.Type) (fa Facade, found bool)

FindFacade finds Facade by types.Type in the package.

func (*PackageInfo) Format added in v0.3.0

func (p *PackageInfo) Format() (codes map[string]string, first error)

Format formats the package and returns the string. @codes <fileName,code>

func (*PackageInfo) FormatNode added in v0.3.0

func (p *PackageInfo) FormatNode(node ast.Node) (string, error)

FormatNode formats the node and returns the string.

func (*PackageInfo) Inspect added in v0.3.0

func (p *PackageInfo) Inspect(fn func(Facade) bool)

Inspect traverses facades in the package.

func (*PackageInfo) Lookup added in v0.3.0

func (p *PackageInfo) Lookup(objKindSet ObjKind, typKindSet TypKind, name string) (list []Facade)

Lookup lookups facades in the package.

Match any name if name=""; Match any ObjKind if objKindSet=0 or objKindSet=AnyObjKind; Match any TypKind if typKindSet=0 or typKindSet=AnyTypKind;

func (*PackageInfo) Preview added in v0.3.0

func (p *PackageInfo) Preview(ident *ast.Ident) string

Preview previews the formated code and comment.

func (*PackageInfo) Program added in v0.7.0

func (p *PackageInfo) Program() *Program

Program returns the program.

func (*PackageInfo) Rewrite added in v0.3.0

func (p *PackageInfo) Rewrite() (first error)

Rewrite formats the package codes and writes to local loaderFiles.

func (*PackageInfo) String added in v0.3.0

func (p *PackageInfo) String() string

PackageInfo returns the package path.

type Program added in v0.3.0

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

A Program is a Go program loaded from source.

func LoadDirs added in v0.4.0

func LoadDirs(dirs ...string) (*Program, error)

LoadDirs parses the source code of Go loaderFiles under the directories and loads a new program.

func LoadFile added in v0.3.0

func LoadFile(filename string, src interface{}) (*Program, error)

LoadFile parses the source code of a single Go file and loads a new program.

src specifies the parser input as a string, []byte, or io.Reader, and filename is its apparent name. If src is nil, the contents of filename are read from the file system.

func LoadPkgs added in v0.3.0

func LoadPkgs(pkgPath ...string) (*Program, error)

LoadPkgs imports packages and loads a new program.

the set of initial source packages located relative to $GOPATH.

func LoadPkgsWithTests added in v0.3.0

func LoadPkgsWithTests(pkgPath ...string) (*Program, error)

LoadPkgsWithTests imports packages and loads a new program.

the set of initial source packages located relative to $GOPATH.

The package will be augmented by any *_test.go loaderFiles in its directory that contain a "package x" (not "package x_test") declaration.

In addition, if any *_test.go loaderFiles contain a "package x_test" declaration, an additional package comprising just those loaderFiles will be added to CreatePkgs.

func NewProgram added in v0.3.0

func NewProgram() *Program

NewProgram creates a empty program.

func (*Program) AddFile added in v0.3.0

func (prog *Program) AddFile(filename string, src interface{}) (itself *Program)

AddFile parses the source code of a single Go source file.

src specifies the parser input as a string, []byte, or io.Reader, and filename is its apparent name. If src is nil, the contents of filename are read from the file system.

filename is used to rewrite to local file; if empty, rewrite to self-increasing number filename under the package name path.

func (*Program) FindFacade added in v0.3.0

func (prog *Program) FindFacade(typ types.Type) (fa Facade, found bool)

FindFacade finds Facade by types.Type in the program.

func (*Program) Format added in v0.3.0

func (prog *Program) Format() (codes map[string]string, first error)

Format formats the created and imported packages, and returns the string. @codes <fileName,code>

func (*Program) FormatNode added in v0.3.0

func (prog *Program) FormatNode(node ast.Node) (string, error)

FormatNode formats the node and returns the string.

func (*Program) Import added in v0.3.0

func (prog *Program) Import(pkgPath ...string) (itself *Program)

Import imports packages that will be imported from source, the set of initial source packages located relative to $GOPATH.

func (*Program) ImportWithTests added in v0.3.0

func (prog *Program) ImportWithTests(pkgPath ...string) (itself *Program)

ImportWithTests imports packages that will be imported from source, the set of initial source packages located relative to $GOPATH. The package will be augmented by any *_test.go loaderFiles in its directory that contain a "package x" (not "package x_test") declaration.

In addition, if any *_test.go loaderFiles contain a "package x_test" declaration, an additional package comprising just those loaderFiles will be added to CreatePkgs.

func (*Program) InitialPackages added in v0.3.0

func (prog *Program) InitialPackages() []*PackageInfo

InitialPackages returns a new slice containing the set of initial packages (created + imported) in unspecified order.

func (*Program) Inspect added in v0.3.0

func (prog *Program) Inspect(fn func(Facade) bool)

Inspect traverses created and imported packages in the program.

func (*Program) Load added in v0.3.0

func (prog *Program) Load() (itself *Program, err error)

Load loads the program's packages, and loads their dependencies packages as needed.

On failure, returns an error. It is an error if no packages were loaded.

func (*Program) Lookup added in v0.3.0

func (prog *Program) Lookup(objKindSet ObjKind, typKindSet TypKind, name string) (list []Facade)

Lookup lookups facades in the program.

Match any name if name=""; Match any ObjKind if objKindSet=0 or objKindSet=AnyObjKind; Match any TypKind if typKindSet=0 or typKindSet=AnyTypKind;

func (*Program) MustLoad added in v0.3.0

func (prog *Program) MustLoad() (itself *Program)

MustLoad is the same as Load(), but panic when error occur.

func (*Program) Package added in v0.3.0

func (prog *Program) Package(path string) *PackageInfo

Package returns the ASTs and results of type checking for the specified package. NOTE: return nil, if the package does not exist.

func (*Program) PrintResume added in v0.3.0

func (prog *Program) PrintResume()

PrintResume prints the program resume.

func (*Program) Rewrite added in v0.3.0

func (prog *Program) Rewrite() (first error)

Rewrite formats the created and imported packages codes and writes to local loaderFiles.

type StructField

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

StructField struct field object.

func (*StructField) Anonymous

func (sf *StructField) Anonymous() bool

Anonymous reports whether the variable is an embedded field. Same as Embedded; only present for backward-compatibility.

func (*StructField) Comment

func (sf *StructField) Comment() string

Comment returns line comment.

func (*StructField) Doc

func (sf *StructField) Doc() string

Doc returns lead comment.

func (*StructField) Embedded added in v0.3.0

func (sf *StructField) Embedded() bool

Embedded reports whether the variable is an embedded field.

func (*StructField) Exported added in v0.3.0

func (sf *StructField) Exported() bool

Exported reports whether the object is exported (starts with a capital letter). It doesn't take into account whether the object is in a local (function) scope or not.

func (*StructField) Name

func (sf *StructField) Name() string

Name returns the field's name.

func (*StructField) SetComment added in v0.7.4

func (sf *StructField) SetComment(text string)

SetComment sets line comment.

func (*StructField) SetDoc added in v0.7.4

func (sf *StructField) SetDoc(text string)

SetDoc sets lead comment.

func (*StructField) Tags

func (sf *StructField) Tags() *Tags

Tags returns the field's tag object.

type Tag

type Tag = structtag.Tag

Tag defines a single struct's string literal tag

type Tag struct { Key is the tag key, such as json, xml, etc.. i.e: `json:"foo,omitempty". Here key is: "json" Key string

Name is a part of the value i.e: `json:"foo,omitempty". Here name is: "foo" Name string

Options is a part of the value. It contains a slice of tag options i.e: `json:"foo,omitempty". Here options is: ["omitempty"] Options []string }

type Tags added in v0.3.0

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

A Tags is the tag string in a struct field.

By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

func (*Tags) AddOptions added in v0.3.0

func (s *Tags) AddOptions(key string, options ...string)

AddOptions adds the given option for the given key. If the option already exists it doesn't add it again. NOTE:

Automatically call the Flush method.

func (*Tags) Delete added in v0.3.0

func (s *Tags) Delete(keys ...string)

Delete deletes the tag for the given keys. NOTE:

Automatically call the Flush method.

func (*Tags) DeleteOptions added in v0.3.0

func (s *Tags) DeleteOptions(key string, options ...string)

DeleteOptions deletes the given options for the given key. NOTE:

Automatically call the Flush method.

func (*Tags) Flush added in v0.5.0

func (s *Tags) Flush()

Flush resets the tags object into the struct field.

func (*Tags) Get added in v0.3.0

func (s *Tags) Get(key string) (*Tag, error)

Get returns the tag associated with the given key. If the key is present in the tag the value (which may be empty) is returned. Otherwise the returned value will be the empty string. The ok return value reports whether the tag exists or not (which the return value is nil).

func (*Tags) Keys added in v0.3.0

func (s *Tags) Keys() []string

Keys returns a slice of tag keys. The order is the original tag order unless it was changed.

func (*Tags) Set added in v0.3.0

func (s *Tags) Set(tag *Tag) error

Set sets the given tag. If the tag key already exists it'll override it. NOTE:

Automatically call the Flush method.

func (*Tags) String added in v0.3.0

func (s *Tags) String() string

String reassembles the tags into a valid literal tag field representation

func (*Tags) Tags added in v0.3.0

func (s *Tags) Tags() []*Tag

Tags returns a slice of tags. The order is the original tag order unless it was changed.

type TypKind added in v0.3.0

type TypKind uint32

TypKind describes what an object type represents.

const (
	Invalid TypKind = 1 << iota // type is invalid
	Basic
	Array
	Slice
	Struct
	Pointer
	Tuple
	Signature // non-builtin function or method
	Interface
	Map
	Chan
)

The list of possible object type kinds.

func GetTypKind added in v0.3.0

func GetTypKind(typ types.Type) TypKind

GetTypKind returns what the types.Type represents.

func (TypKind) In added in v0.3.0

func (k TypKind) In(set TypKind) bool

In judges whether k is fully contained in set.

func (TypKind) String added in v0.3.0

func (i TypKind) String() string

Jump to

Keyboard shortcuts

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