ast

package
v0.0.0-...-48c028d Latest Latest
Warning

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

Go to latest
Published: May 29, 2018 License: MIT Imports: 27 Imported by: 14

README

AST

Ast provides the ability to distill go packages and files into individual structures that better represent their type, data and content. It provides a cleaner and more usage structures that extra as much details from the Go ast so you don't have to.

This structures then make it possible to transform existing code structures as desired, more so, ast targets annotation based types, where Go types such has interfaces, structs, function and other types can be annotated with markers using the @ prefix.

By relying on this annotation, AST then lets you provide functions to generate new code or content to be written to file has dictated by you. It is barebones but very flexible for creating custom code generation possibilities.

Annotation Code Generation

Moz provides a annotation style code generation system apart from it's code generation structures. This is provide to allow descriptive annotations to be added to giving Go structures (interface, struct, type alises) within their comments and as well as to the package.

This annotation then are passed by the moz annotation CLI tooling which can generate a series of files and packages based on the internal logic of the generator associated with that annotation to meet the needs for that type.

For example: If we wanted to be able to generate code for database CRUD activities without having to use ORMs or write such code manually, with the Moz annotation code generation ability, we can create a struct generator that can use a @mongo annotation, which generates mongo CRUD functions which expect such a type and perform the appropriate CRUD operations.

See the Example directory, which demonstrates use of annotations to code generate other parts of a project or mock up implementation detail for an interface using annotations.

AST Annotation Functions

AST provides 4 types of Annotation generators, which are function types which provide the necessary operations to be performed to create the underline series of sources to be generated for each annotation. More so, these functions all receiving a string has their first argument, which is the relative path of a directory (existing/not-existing) that whatever content to be written will be created into. This allows the functions to be aware of path changes as needed in the contents they may generate.

AST provide the following generators type functions:

StructType Code Generators

These functions types are used to provide code generation instructions for Go type declarations and are the ones who define the end result of what an annotation produces.

See Annotations for code samples of different annotation functions.

type StructAnnotationGenerator func(string, AnnotationDeclaration, StructDeclaration, PackageDeclaration, Package) ([]gen.WriteDirective, error)

This function is expected to return a slice of WriteDirective which contains file name, WriterTo object and a possible Dir relative path which the contents should be written to.

InterfaceType Code Generators

This functions are specific to provide code generation instructions for interface declarations which the given annotation is attached to.

type InterfaceAnnotationGenerator func(string,AnnotationDeclaration, InterfaceDeclaration, PackageDeclaration, Package) ([]gen.WriteDirective, error)

This function is expected to return a slice of WriteDirective which contains file name, WriterTo object and a possible Dir relative path which the contents should be written to.

PackageType Code Generators

This functions are specific to provide code generation instructions for given annotation declared on the package comment block.

type PackageAnnotationGenerator func(string, AnnotationDeclaration, PackageDeclaration, Package) ([]gen.WriteDirective, error)

This function is expected to return a slice of WriteDirective which contains file name, WriterTo object and a possible Dir relative path which the contents should be written to.

Non(Struct|Interface) Code Generators

This functions are specific to provide code generation instructions for non-struct and non-interface declarations which the given annotation is attached to.

type TypeAnnotationGenerator func(string, AnnotationDeclaration, TypeDeclaration, PackageDeclaration, Package) ([]gen.WriteDirective, error)

This function is expected to return a slice of WriteDirective which contains file name, WriterTo object and a possible Dir relative path which the contents should be written to.

Example

Generate code structures from an interface
  1. Create a file and add the following contents defining a interface we wish to create it's implementation structures by annotating with a @iface annotation.
package mock

//go:generate moz generate

import (
	"io"

	toml "github.com/BurntSushi/toml"
)

// MofInitable defines a interface for a Mof.
// @iface
type MofInitable interface {
	Ignitable
	Crunch() (cr string)
	Configuration() toml.Primitive
	Location(string) (GPSLoc, error)
	WriterTo(io.Writer) (int64, error)
	Maps(string) (map[string]GPSLoc, error)
	MapsIn(string) (map[string]*GPSLoc, error)
	MapsOut(string) (map[*GPSLoc]string, error)
	Drop() (*GPSLoc, *toml.Primitive, *[]byte, *[5]byte)
	Close() (chan struct{}, chan toml.Primitive, chan string, chan []byte, chan *[]string)
	Bob() chan chan struct{}
}


// Ignitable defines a struct which is used to ignite the package.
type Ignitable interface {
	Ignite() string
}

// GPSLoc defines a struct to hold long and lat values for a gps location.
type GPSLoc struct {
	Lat  float64
	Long float64
}

  1. Navigate to where file is stored (We assume it's in your GOPATH) and run
go generate

or

moz generate

The command above will generate all necessary files and packages ready for editing.

See Mock Example for end result.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyList defines a error returned for a empty array or slice.
	ErrEmptyList = errors.New("Slice/List is empty")

	// ErrPackageParseFailed defines a error returned when a package processing failed to work.
	ErrPackageParseFailed = errors.New("Package or Package file failed to be parsed")
)
View Source
var (
	ASTTemplatFuncs = map[string]interface{}{
		"getTag":            GetTag,
		"fieldFor":          FieldFor,
		"getFields":         GetFields,
		"fieldNameFor":      FieldNameFor,
		"mapFields":         MapOutFields,
		"mapValues":         MapOutValues,
		"fieldByName":       FieldByFieldName,
		"mapJSON":           MapOutFieldsToJSON,
		"mapRandomJSON":     MapOutFieldsWithRandomValuesToJSON,
		"mapFieldTypeJSON":  MapOutFieldsWithTypeToJSON,
		"mapTypeJSON":       MapOutTypeToJSON,
		"mapRandomTypeJSON": MapOutTypeToJSONWriterWithRandomValues,
		"stringValueFor":    ToValueString,
		"randomValue":       RandomFieldAssign,
		"defaultGoType":     DefaultGoTypeString,
		"defaultValue":      AssignDefaultValue,
		"randomFieldValue":  RandomFieldValue,
		"defaultType":       DefaultTypeValueString,
		"defaultFieldValue": DefaultFieldValue,
	}
)

Contains giving sets of variables exposing sytem GOPATH and GOPATHSRC.

Functions

func AssignDefaultValue

func AssignDefaultValue(item StructDeclaration, tag string, tagVal string, varName string) (string, error)

AssignDefaultValue will get the fieldName for a giving tag and tagVal and return a string of giving variable name with fieldName equal to default value.

func DefaultFieldValue

func DefaultFieldValue(fld FieldDeclaration) string

DefaultFieldValue returns the default value for a giving field.

func DefaultFieldValueFor

func DefaultFieldValueFor(item StructDeclaration, tag string, tagVal string) (string, string, error)

DefaultFieldValueFor defines a function to return a field default value.

func DefaultGoTypeString

func DefaultGoTypeString(typeName string) string

DefaultGoTypeString returns the default value string of a giving typeName.

func DefaultTypeValueString

func DefaultTypeValueString(typeName string) string

DefaultTypeValueString returns the default value string of a giving typeName.

func FieldNameFor

func FieldNameFor(item StructDeclaration, tag string, tagFieldName string) string

FieldNameFor defines a function to return actual name of field with the given tag name.

func GetIdentName

func GetIdentName(field *ast.Field) (*ast.Ident, error)

GetIdentName returns the first indent found within the field if it exists.

func GetStructSpec

func GetStructSpec(val interface{}) (*ast.TypeSpec, *ast.StructType, error)

GetStructSpec attempts to retrieve the TypeSpec and StructType if the value matches this.

func GetVariableNameAsExported

func GetVariableNameAsExported(item interface{}, basePkg string) (string, error)

GetVariableNameAsExported returns a variable type name as exported from the base package returning the string representation.

func GetVariableTypeName

func GetVariableTypeName(item interface{}) (string, error)

GetVariableTypeName returns a variable type name as exported from the base package returning the string representation.

func MapOutFields

func MapOutFields(item StructDeclaration, rootName, tagName, fallback string) (string, error)

MapOutFields defines a function to return a map of field name and value pair for the giving struct.

func MapOutFieldsToJSON

func MapOutFieldsToJSON(item StructDeclaration, tagName, fallback string) (string, error)

MapOutFieldsToJSON returns the giving map values containing string for the giving output.

func MapOutFieldsToJSONWriter

func MapOutFieldsToJSONWriter(item StructDeclaration, tagName, fallback string) (io.WriterTo, error)

MapOutFieldsToJSONWriter returns the giving map values containing string for the giving output.

func MapOutFieldsToJSONWriterWithRandomValues

func MapOutFieldsToJSONWriterWithRandomValues(item StructDeclaration, tagName, fallback string) (io.WriterTo, error)

MapOutFieldsToJSONWriterWithRandomValues returns the giving map values containing string for the giving output.

func MapOutFieldsToMap

func MapOutFieldsToMap(item StructDeclaration, rootName, tagName, fallback string) (map[string]io.WriterTo, error)

MapOutFieldsToMap defines a function to return a map of field name and value pair for the giving struct.

func MapOutFieldsValues

func MapOutFieldsValues(item StructDeclaration, onlyExported bool, name *gen.NameDeclr) io.WriterTo

MapOutFieldsValues defines a function to return a map of field name and associated placeholders as value.

func MapOutFieldsWithRandomValuesToJSON

func MapOutFieldsWithRandomValuesToJSON(item StructDeclaration, tagName, fallback string) (string, error)

MapOutFieldsWithRandomValuesToJSON returns the giving map values containing string for the giving output.

func MapOutFieldsWithTypeToJSON

func MapOutFieldsWithTypeToJSON(item StructDeclaration, rootName, tagName, fallback string) (string, error)

MapOutFieldsWithTypeToJSON runs MapOutFieldsWithTypeToMap and returns returned map as JSON.

func MapOutFieldsWithTypeToMap

func MapOutFieldsWithTypeToMap(item StructDeclaration, rootName, tagName, fallback string) (map[string]interface{}, error)

MapOutFieldsWithTypeToMap defines a function to return a map of field name that has it's type as value pair for the giving struct.

func MapOutTypeToJSON

func MapOutTypeToJSON(item TypeDeclaration) (io.WriterTo, error)

MapOutTypeToJSON returns the giving map values containing string for the giving output.

func MapOutTypeToJSONWriterWithRandomValues

func MapOutTypeToJSONWriterWithRandomValues(item TypeDeclaration) (io.WriterTo, error)

MapOutTypeToJSONWriterWithRandomValues returns the giving map values containing string for the giving output.

func MapOutValues

func MapOutValues(item StructDeclaration, onlyExported bool) (string, error)

MapOutValues defines a function to return a map of field name and associated placeholders as value.

func Parse

func Parse(toDir string, log metrics.Metrics, provider *AnnotationRegistry, doFileOverwrite bool, pkgDeclrs ...Package) error

Parse takes the provided packages parsing all internals declarations with the appropriate generators suited to the type and annotations. Relies on ParsePackage.

func ParsePackage

func ParsePackage(toDir string, log metrics.Metrics, provider *AnnotationRegistry, doFileOverwrite bool, pkgDeclrs Package) error

ParsePackage takes the provided package declrations parsing all internals with the appropriate generators suited to the type and annotations. Provided toDir must be a absolute path.

func RandomDataTypeValue

func RandomDataTypeValue(typeName string) string

RandomDataTypeValue returns the default value string of a giving typeName.

func RandomDataTypeValueJSON

func RandomDataTypeValueJSON(typeName string, varName string) string

RandomDataTypeValueJSON returns the default value string of a giving typeName.

func RandomDataTypeValueWithName

func RandomDataTypeValueWithName(typeName string, varName string) string

RandomDataTypeValueWithName returns the default value string of a giving typeName.

func RandomFieldAssign

func RandomFieldAssign(item StructDeclaration, varName string, tag string, exceptions ...string) (string, error)

RandomFieldAssign generates a random Field of a giving struct and returns a variable assignment declaration with the types default value.

func RandomFieldValue

func RandomFieldValue(fld FieldDeclaration) string

RandomFieldValue returns the default value for a giving field.

func RandomFieldWithExcept

func RandomFieldWithExcept(item StructDeclaration, tag string, exceptions ...string) (string, string, error)

RandomFieldWithExcept defines a function to return a random field name which is not included in the exceptions set.

func SimpleWriteDirective

func SimpleWriteDirective(toDir string, doFileOverwrite bool, item gen.WriteDirective) error

SimpleWriteDirective defines a function which houses the logic to write WriteDirective into file system.

func SimpleWriteDirectives

func SimpleWriteDirectives(toDir string, doFileOverwrite bool, wds ...gen.WriteDirective) error

SimpleWriteDirectives defines a function which houses the logic to write WriteDirective into file system.

func SimplyParse

func SimplyParse(toDir string, log metrics.Metrics, provider *AnnotationRegistry, doFileOverwrite bool, pkgDeclrs ...Package) error

SimplyParse takes the provided packages parsing all internals declarations with the appropriate generators suited to the type and annotations. Relies on SimpleParsePackage.

func SimplyParsePackage

func SimplyParsePackage(toDir string, log metrics.Metrics, provider *AnnotationRegistry, doFileOverwrite bool, pkgDeclrs Package) error

SimplyParsePackage takes the provided package declrations parsing all internals with the appropriate generators suited to the type and annotations. Provided toDir must be a absolute path.

func ToValueString

func ToValueString(val interface{}) string

ToValueString returns the string representation of a basic go core datatype.

func WhichPackage

func WhichPackage(toDir string, pkg Package) string

WhichPackage is an utility function which returns the appropriate package name to use if a toDir is provided as destination.

func WriteDirective

func WriteDirective(log metrics.Metrics, toDir string, doFileOverwrite bool, item gen.WriteDirective) error

WriteDirective defines a function which houses the logic to write WriteDirective into file system.

func WriteDirectives

func WriteDirectives(log metrics.Metrics, toDir string, doFileOverwrite bool, wds ...gen.WriteDirective) error

WriteDirectives defines a function which houses the logic to write WriteDirective into file system.

Types

type AnnotationAssociationDeclaration

type AnnotationAssociationDeclaration struct {
	Annotation string
	Action     string
	Template   string
	TypeName   string
	Record     AnnotationDeclaration
}

AnnotationAssociationDeclaration defines a type which defines an association between a giving annotation and a series of values.

type AnnotationDeclaration

type AnnotationDeclaration struct {
	Name      string                 `json:"name"`
	Template  string                 `json:"template"`
	Arguments []string               `json:"arguments"`
	Params    map[string]string      `json:"params"`
	Attrs     map[string]interface{} `json:"attrs"`
	Defer     bool                   `json:"defer"`
}

AnnotationDeclaration defines a annotation type which holds detail about a giving annotation.

func ReadAnnotationsFromCommentry

func ReadAnnotationsFromCommentry(r io.Reader) []AnnotationDeclaration

ReadAnnotationsFromCommentry returns a slice of all annotation passed from the provided list.

func (AnnotationDeclaration) Attr

func (ad AnnotationDeclaration) Attr(name string) interface{}

Attr returns the associated param value with giving key ("name").

func (AnnotationDeclaration) HasArg

func (ad AnnotationDeclaration) HasArg(name string) bool

HasArg returns true/false if the giving AnnotationDeclaration has a giving key in its Arguments.

func (AnnotationDeclaration) Param

func (ad AnnotationDeclaration) Param(name string) string

Param returns the associated param value with giving key ("name").

type AnnotationRegistry

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

AnnotationRegistry defines a structure which contains giving list of possible annotation generators for both package level and type level declaration.

func NewAnnotationRegistry

func NewAnnotationRegistry() *AnnotationRegistry

NewAnnotationRegistry returns a new instance of a AnnotationRegistry.

func NewAnnotationRegistryWith

func NewAnnotationRegistryWith(log metrics.Metrics) *AnnotationRegistry

NewAnnotationRegistryWith returns a new instance of a AnnotationRegistry.

func (*AnnotationRegistry) Clone

func (a *AnnotationRegistry) Clone() Annotations

Clone returns a type which contains all copies of the generators provided by the AnnotationRegistry.

func (*AnnotationRegistry) Copy

func (a *AnnotationRegistry) Copy(registry *AnnotationRegistry, strategy CopyStrategy)

Copy copies over all available type generators from the provided AnnotationRegistry with the CopyStrategy.

func (*AnnotationRegistry) GetFunctionType

func (a *AnnotationRegistry) GetFunctionType(annotation string) (FunctionAnnotationGenerator, error)

GetFunctionType returns the annotation generator associated with the giving annotation name.

func (*AnnotationRegistry) GetInterfaceType

func (a *AnnotationRegistry) GetInterfaceType(annotation string) (InterfaceAnnotationGenerator, error)

GetInterfaceType returns the annotation generator associated with the giving annotation name.

func (*AnnotationRegistry) GetPackage

func (a *AnnotationRegistry) GetPackage(annotation string) (PackageAnnotationGenerator, error)

GetPackage returns the annotation generator associated with the giving annotation name.

func (*AnnotationRegistry) GetStructType

func (a *AnnotationRegistry) GetStructType(annotation string) (StructAnnotationGenerator, error)

GetStructType returns the annotation generator associated with the giving annotation name.

func (*AnnotationRegistry) GetType

func (a *AnnotationRegistry) GetType(annotation string) (TypeAnnotationGenerator, error)

GetType returns the annotation generator associated with the giving annotation name.

func (*AnnotationRegistry) MustFunctionType

func (a *AnnotationRegistry) MustFunctionType(annotation string) FunctionAnnotationGenerator

MustFunctionType returns the annotation generator associated with the giving annotation name.

func (*AnnotationRegistry) MustInterfaceType

func (a *AnnotationRegistry) MustInterfaceType(annotation string) InterfaceAnnotationGenerator

MustInterfaceType returns the annotation generator associated with the giving annotation name.

func (*AnnotationRegistry) MustPackage

func (a *AnnotationRegistry) MustPackage(annotation string) PackageAnnotationGenerator

MustPackage returns the annotation generator associated with the giving annotation name.

func (*AnnotationRegistry) MustStructType

func (a *AnnotationRegistry) MustStructType(annotation string) StructAnnotationGenerator

MustStructType returns the annotation generator associated with the giving annotation name.

func (*AnnotationRegistry) MustType

func (a *AnnotationRegistry) MustType(annotation string) TypeAnnotationGenerator

MustType returns the annotation generator associated with the giving annotation name.

func (*AnnotationRegistry) ParseDeclr

func (a *AnnotationRegistry) ParseDeclr(pkg Package, declr PackageDeclaration, toDir string) ([]AnnotationWriteDirective, error)

ParseDeclr runs the generators suited for each declaration and type returning a slice of Annotationgen.WriteDirective that delivers the content to be created for each piece.

func (*AnnotationRegistry) Register

func (a *AnnotationRegistry) Register(name string, generator interface{}) error

Register which adds the generator depending on it's type into the appropriate registry. It only supports the following generators: 1. TypeAnnotationGenerator (see Package ast#TypeAnnotationGenerator) 2. StructAnnotationGenerator (see Package ast#StructAnnotationGenerator) 3. InterfaceAnnotationGenerator (see Package ast#InterfaceAnnotationGenerator) 4. PackageAnnotationGenerator (see Package ast#PackageAnnotationGenerator) Any other type will cause the return of an error.

func (*AnnotationRegistry) RegisterInterfaceType

func (a *AnnotationRegistry) RegisterInterfaceType(annotation string, generator InterfaceAnnotationGenerator)

RegisterInterfaceType adds a interface type level annotation generator into the registry.

func (*AnnotationRegistry) RegisterPackage

func (a *AnnotationRegistry) RegisterPackage(annotation string, generator PackageAnnotationGenerator)

RegisterPackage adds a package level annotation generator into the registry.

func (*AnnotationRegistry) RegisterStructType

func (a *AnnotationRegistry) RegisterStructType(annotation string, generator StructAnnotationGenerator)

RegisterStructType adds a struct type level annotation generator into the registry.

func (*AnnotationRegistry) RegisterType

func (a *AnnotationRegistry) RegisterType(annotation string, generator TypeAnnotationGenerator)

RegisterType adds a type(non-struct, non-interface) level annotation generator into the registry.

type AnnotationWriteDirective

type AnnotationWriteDirective struct {
	gen.WriteDirective
	Annotation string
}

AnnotationWriteDirective defines a type which provides a WriteDiretive and the associated name.

type Annotations

Annotations defines a struct which contains a map of all annotation code generator.

type ArgType

type ArgType struct {
	Owner           string
	Name            string
	Type            string
	ExType          string
	IsReturn        bool
	FromMethod      bool
	Package         string
	IsStruct        bool
	BaseType        bool
	Import          ImportDeclaration
	Import2         ImportDeclaration
	NameObject      *ast.Object
	TypeObject      *ast.Object
	StructObject    *ast.StructType
	Spec            *ast.TypeSpec
	InterfaceObject *ast.InterfaceType
	ImportedObject  *ast.SelectorExpr
	SelectPackage   *ast.Ident
	SelectObject    *ast.Ident
	ArrayType       *ast.ArrayType
	MapType         *ast.MapType
	ChanType        *ast.ChanType
	PointerType     *ast.StarExpr
	IdentType       *ast.Ident
	Tags            []TagDeclaration
	Pkg             *PackageDeclaration
}

ArgType defines a type to represent the information for a giving functions argument or return type declaration.

func GetArgTypeFromField

func GetArgTypeFromField(retCounter int, varPrefix string, method string, targetFile string, result *ast.Field, pkg *PackageDeclaration) (ArgType, error)

GetArgTypeFromField returns a ArgType that writes out the representation of the giving variable name or decleration ast.Field associated with the giving package. It returns an error if it does not know the type.

func (ArgType) GetStructJSON

func (a ArgType) GetStructJSON() string

type CopyStrategy

type CopyStrategy int

CopyStrategy defines a int type used to represent a copy strategy for cloning a AnnotationStrategy.

const (
	OursOverTheirs CopyStrategy = iota + 1
	TheirsOverOurs
)

Contains different copy strategy.

type FieldDeclaration

type FieldDeclaration struct {
	Exported      bool
	Embedded      bool
	IsStruct      bool
	FieldName     string
	FieldTypeName string
	Field         *ast.Field
	Type          *ast.Object
	Spec          *ast.TypeSpec
	Struct        *ast.StructType
	Tags          []TagDeclaration
	Arg           ArgType
}

FieldDeclaration defines a type to represent a giving struct fields and tags.

func FieldByFieldName

func FieldByFieldName(item StructDeclaration, fieldName string) (FieldDeclaration, error)

FieldByFieldName defines a function to return actual name of field with the given tag name.

func FieldFor

func FieldFor(item StructDeclaration, tag string, tagFieldName string) (FieldDeclaration, error)

FieldFor defines a function to return actual name of field with the given tag name.

func GetFields

GetFields returns all fields associated with the giving struct but skips ones it cant get details for.

func (FieldDeclaration) GetTag

func (f FieldDeclaration) GetTag(tagName string) (TagDeclaration, error)

GetTag returns the giving tag associated with the name if it exists.

type Fields

type Fields []FieldDeclaration

Fields defines a slice type of FieldDeclaration.

func (Fields) ByName

func (flds Fields) ByName(name string) (FieldDeclaration, bool)

ByName returns giving field with name.

func (Fields) Embedded

func (flds Fields) Embedded() Fields

Embedded defines a function that returns all appropriate Field that match the giving tagName

func (Fields) Normal

func (flds Fields) Normal() Fields

Normal defines a function that returns all fields which are non-embedded.

func (Fields) TagFor

func (flds Fields) TagFor(tagName string) []TagDeclaration

TagFor defines a function that returns all appropriate TagDeclaration that match the giving tagName

type FuncDeclaration

type FuncDeclaration struct {
	From                int
	Length              int
	Package             string
	Path                string
	FilePath            string
	Exported            bool
	File                string
	FuncName            string
	FuncNameWithPackage string
	RecieverName        string
	Source              string
	Comments            string
	Position            token.Pos
	TypeDeclr           ast.Decl
	FuncDeclr           *ast.FuncDecl
	Type                *ast.FuncType
	Reciever            *ast.Object
	RecieverIdent       *ast.Ident
	RecieverPointer     *ast.StarExpr
	FuncType            *ast.FieldList
	Returns             *ast.FieldList
	Arguments           *ast.FieldList
	Declr               *PackageDeclaration
	Annotations         []AnnotationDeclaration
	Associations        map[string]AnnotationAssociationDeclaration
}

FuncDeclaration defines a type used to annotate a giving type declaration associated with a ast for a function.

func (FuncDeclaration) AnnotationsFor

func (fun FuncDeclaration) AnnotationsFor(typeName string) []AnnotationDeclaration

AnnotationsFor returns all annotations with the giving name.

func (FuncDeclaration) Definition

Definition returns a FunctionDefinition for this function.

func (FuncDeclaration) GetAnnotation

func (fun FuncDeclaration) GetAnnotation(typeName string) (AnnotationDeclaration, bool)

GetAnnotation returns AnnotationDeclaration if giving FuncDeclaration has annotation at package level.

func (FuncDeclaration) HasAnnotation

func (fun FuncDeclaration) HasAnnotation(typeName string) bool

HasAnnotation returns true/false if giving FuncDeclaration has annotation at package level.

type FunctionAnnotationGenerator

FunctionAnnotationGenerator defines a function which generates specific code related to the giving Annotation. This allows you to generate a new source file containg source code for a giving struct type. It is responsible to fully contain all operations required to both generator any source and write such to.

type FunctionDefinition

type FunctionDefinition struct {
	Name      string
	Args      []ArgType
	Returns   []ArgType
	Func      *ast.FuncType
	Interface *ast.InterfaceType
	Struct    *ast.StructType
}

FunctionDefinition defines a type to represent the function/method declarations of an interface type.

func GetFunctionDefinitionFromDeclaration

func GetFunctionDefinitionFromDeclaration(funcObj FuncDeclaration, pkg *PackageDeclaration) (FunctionDefinition, error)

GetFunctionDefinitionFromDeclaration returns a FunctionDefinition withe the associated FuncDeclaration.

func GetFunctionDefinitionFromField

func GetFunctionDefinitionFromField(method *ast.Field, pkg *PackageDeclaration) (FunctionDefinition, error)

GetFunctionDefinitionFromField returns a FunctionDefinition representing a giving function.

func GetInterfaceFunctions

func GetInterfaceFunctions(intr *ast.InterfaceType, pkg *PackageDeclaration) []FunctionDefinition

GetInterfaceFunctions returns a slice of FunctionDefinitions retrieved from the provided interface type object.

func (FunctionDefinition) ArgTypePos

func (fd FunctionDefinition) ArgTypePos(wanted string) int

ArgTypePos returns position of giving type if part of the function's argument types else returning -1.

func (FunctionDefinition) ArgumentList

func (fd FunctionDefinition) ArgumentList(asFromOutside bool) string

ArgumentList returns a string version of the arguments of the giving function.

func (FunctionDefinition) ArgumentNamesList

func (fd FunctionDefinition) ArgumentNamesList() string

ArgumentNamesList returns the assignment names for the function arguments.

func (FunctionDefinition) CountOfArgType

func (fd FunctionDefinition) CountOfArgType(wanted string) int

CountOfArgType counts total number of giving type in the arguments lists of function.

func (FunctionDefinition) CountOfReturnType

func (fd FunctionDefinition) CountOfReturnType(wanted string) int

CountOfReturnType counts total number of giving type in the returns lists of function.

func (FunctionDefinition) ExArgumentList

func (fd FunctionDefinition) ExArgumentList(asFromOutside bool, pkgName string) string

ExArgumentList returns a string version of the arguments of the giving function, removing any type with provided package name `packageName.` as a prefix.

func (FunctionDefinition) ExReturnList

func (fd FunctionDefinition) ExReturnList(asFromOutside bool, pkgName string) string

ExReturnList returns a string version of the returns of the giving function, removing any type with provided package name `packageName.` as a prefix.

func (FunctionDefinition) GetArgsAt

func (fd FunctionDefinition) GetArgsAt(i int) ArgType

GetArgsAt gets argument ArgType at index point.

func (FunctionDefinition) GetReturnsAt

func (fd FunctionDefinition) GetReturnsAt(i int) ArgType

GetReturnsAt gets returns ArgType at index point.

func (FunctionDefinition) HasArgType

func (fd FunctionDefinition) HasArgType(wanted string) bool

HasArgType returns true/false if giving type is part of the function's arguments types.

func (FunctionDefinition) HasArgs

func (fd FunctionDefinition) HasArgs() bool

HasArgs returns true/false if giving function has aarguments.

func (FunctionDefinition) HasNoArgType

func (fd FunctionDefinition) HasNoArgType(wanted string) bool

HasNoArgType returns true/false if giving type is part of the function's arguments types.

func (FunctionDefinition) HasNoReturnType

func (fd FunctionDefinition) HasNoReturnType(wanted string) bool

HasNoReturnType returns true/false if giving type is not part of the function's return types.

func (FunctionDefinition) HasReturnType

func (fd FunctionDefinition) HasReturnType(wanted string) bool

HasReturnType returns true/false if giving type is part of the function's return types.

func (FunctionDefinition) HasReturns

func (fd FunctionDefinition) HasReturns() bool

HasReturns returns true/false if giving function has return types.

func (FunctionDefinition) ReturnList

func (fd FunctionDefinition) ReturnList(asFromOutside bool) string

ReturnList returns a string version of the return of the giving function.

func (FunctionDefinition) ReturnNamesList

func (fd FunctionDefinition) ReturnNamesList() string

ReturnNamesList returns the assignment names for the return arguments

func (FunctionDefinition) ReturnTypePos

func (fd FunctionDefinition) ReturnTypePos(wanted string) int

ReturnTypePos returns position of giving type if part of the function's return types else returning -1.

func (FunctionDefinition) TotalArgs

func (fd FunctionDefinition) TotalArgs() int

TotalArgs returns length of function arg set.

func (FunctionDefinition) TotalReturns

func (fd FunctionDefinition) TotalReturns() int

TotalReturns returns length of function return set.

type Functions

type Functions []FuncDeclaration

Functions defines a slice of FuncDeclaration.

func (Functions) Find

func (fnList Functions) Find(name string) (FuncDeclaration, error)

Find returns the giving Function of the giving name.

type ImportDeclaration

type ImportDeclaration struct {
	Name        string
	Path        string
	Source      string
	Comments    string
	InternalPkg bool
}

ImportDeclaration defines a type to contain import declaration within a package.

type InterfaceAnnotationGenerator

InterfaceAnnotationGenerator defines a function which generates specific code related to the giving Annotation. This allows you to generate a new source file containg source code for a giving interface type. It is responsible to fully contain all operations required to both generator any source and write such to appropriate files as intended, meta-data about package, and file paths are already include in the PackageDeclaration.

type InterfaceDeclaration

type InterfaceDeclaration struct {
	From            int
	Length          int
	Package         string
	Path            string
	Name            string
	NameWithPackage string
	Source          string
	Comments        string
	FilePath        string
	File            string
	Interface       *ast.InterfaceType
	Object          *ast.TypeSpec
	GenObj          *ast.GenDecl
	Position        token.Pos
	Declr           *PackageDeclaration

	Annotations  []AnnotationDeclaration
	Associations map[string]AnnotationAssociationDeclaration
	// contains filtered or unexported fields
}

InterfaceDeclaration defines a type which holds annotation data for a giving interface type declaration.

func FindInterfaceType

func FindInterfaceType(pkg PackageDeclaration, typeName string) (InterfaceDeclaration, error)

FindInterfaceType defines a function to search a package declaration Interface of a giving typeName.

func (*InterfaceDeclaration) GetImports

func (i *InterfaceDeclaration) GetImports(pkg *PackageDeclaration, internal bool) map[string]string

GetImports returns a map containing all import paths related to types used for the methods of giving interface.

func (*InterfaceDeclaration) Methods

GetMethods returns the associated methods for the giving interface.

type Package

type Package struct {
	Name         string
	Tag          string
	Path         string
	Dir          string
	FilePath     string
	Files        []string
	BuildPkg     *build.Package
	Packages     []PackageDeclaration
	TestPackages []PackageDeclaration
}

Package defines the central repository of all PackageDeclaration.

func PackageFileWithBuildCtx

func PackageFileWithBuildCtx(log metrics.Metrics, path string, ctx build.Context) (Package, error)

PackageFileWithBuildCtx parses the package from the provided file.

func PackageWithBuildCtx

func PackageWithBuildCtx(log metrics.Metrics, dir string, ctx build.Context) ([]Package, error)

PackageWithBuildCtx parses the package directory which generates a series of ast with associated annotation for processing by using the golang token parser, it uses the build.Context to collected context details for the package but does not use it has a means to select the files to process. PackageWithBuildCtx processes all files in package directory. If you want one which takes into consideration build.Context fields using FilteredPackageWithBuildCtx.

func ParseFileAnnotations

func ParseFileAnnotations(log metrics.Metrics, path string) (Package, error)

ParseFileAnnotations parses the package from the provided file.

func (Package) AnnotationFirstFor

func (pkg Package) AnnotationFirstFor(typeName string) (AnnotationDeclaration, PackageDeclaration, bool)

AnnotationFirstFor returns all annotations with the giving name.

func (Package) AnnotationsFor

func (pkg Package) AnnotationsFor(typeName string) []AnnotationDeclaration

AnnotationsFor returns all annotations with the giving name.

func (Package) DeclarationFor

func (pkg Package) DeclarationFor(targetFile string) (PackageDeclaration, bool)

DeclarationFor returns the associated declaration for the giving file path.

func (Package) FunctionFor

func (pkg Package) FunctionFor(typeName string) (FuncDeclaration, bool)

FunctionFor returns associated FuncDeclaration for importPath in file with the typeName.

func (Package) FunctionsFor

func (pkg Package) FunctionsFor(obj *ast.Object) []FuncDeclaration

FunctionsFor returns a slice of FuncDeclaration for the giving object.

func (Package) FunctionsForName

func (pkg Package) FunctionsForName(objName string) []FuncDeclaration

FunctionsForName returns a slice of FuncDeclaration for the giving name.

func (Package) HasAnnotation

func (pkg Package) HasAnnotation(name string) bool

HasAnnotation returns true/false if the giving package has any files having a giving annotation on the package level.

func (Package) HasFunctionFor

func (pkg Package) HasFunctionFor(str StructDeclaration, funcName string) bool

HasFunctionFor returns true/false if the giving Struct Declaration has the giving function name.

func (Package) ImportFor

func (pkg Package) ImportFor(imp string) (ImportDeclaration, error)

ImportFor returns the ImportDeclaration associated with the giving handle. Returns error if the import is not found.

func (Package) InterfaceFor

func (pkg Package) InterfaceFor(typeName string) (InterfaceDeclaration, bool)

InterfaceFor returns associated InterfaceDeclaration for importPath in file with the typeName.

func (Package) PackagesWithAnnotation

func (pkg Package) PackagesWithAnnotation(name string) []PackageDeclaration

PackagesWithAnnotation returns a slice of all PackageDeclaration which have the annotation at package level.

func (Package) StructFor

func (pkg Package) StructFor(typeName string) (StructDeclaration, bool)

StructFor returns associated StructDeclaration for importPath in file with the typeName.

func (Package) TypeFor

func (pkg Package) TypeFor(typeName string) (TypeDeclaration, bool)

TypeFor returns associated TypeDeclaration for importPath in file with the typeName.

type PackageAnnotationGenerator

type PackageAnnotationGenerator func(string, AnnotationDeclaration, PackageDeclaration, Package) ([]gen.WriteDirective, error)

PackageAnnotationGenerator defines a function which generates specific code related to the giving Annotation for a package. This allows you to apply and create new sources specifically because of a package wide annotation. It is responsible to fully contain all operations required to both generator any source and write such to All generators are expected to return

type PackageDeclaration

type PackageDeclaration struct {
	Package          string
	Path             string
	Dir              string
	FilePath         string
	File             string
	Source           string
	Comments         []string
	Imports          map[string]ImportDeclaration
	ImportedPackages map[string]Package
	Annotations      []AnnotationDeclaration
	Types            []TypeDeclaration
	Structs          []StructDeclaration
	Interfaces       []InterfaceDeclaration
	Functions        []FuncDeclaration
	Variables        []VariableDeclaration
	ObjectFunc       map[*ast.Object][]FuncDeclaration
	// contains filtered or unexported fields
}

PackageDeclaration defines a type which holds details relating to annotations declared on a giving package.

func (PackageDeclaration) AnnotationsFor

func (pkg PackageDeclaration) AnnotationsFor(typeName string) []AnnotationDeclaration

AnnotationsFor returns all annotations with the giving name.

func (PackageDeclaration) FunctionFor

func (pkg PackageDeclaration) FunctionFor(typeName string) (FuncDeclaration, bool)

FunctionFor returns associated FuncDeclaration with giving name.

func (PackageDeclaration) FunctionsFor

func (pkg PackageDeclaration) FunctionsFor(obj *ast.Object) []FuncDeclaration

FunctionsFor returns a slice of FuncDeclaration for the giving object.

func (PackageDeclaration) FunctionsForName

func (pkg PackageDeclaration) FunctionsForName(objName string) []FuncDeclaration

FunctionsForName returns a slice of FuncDeclaration for the giving name.

func (PackageDeclaration) GetAnnotation

func (pkg PackageDeclaration) GetAnnotation(typeName string) (AnnotationDeclaration, bool)

GetAnnotation returns the first annotation with the giving name.

func (PackageDeclaration) HasAnnotation

func (pkg PackageDeclaration) HasAnnotation(typeName string) bool

HasAnnotation returns true/false if giving PackageDeclaration has annotation at package level.

func (PackageDeclaration) HasFunctionFor

func (pkg PackageDeclaration) HasFunctionFor(str StructDeclaration, funcName string) bool

HasFunctionFor returns true/false if the giving Struct Declaration has the giving function name.

func (PackageDeclaration) ImportFor

func (pkg PackageDeclaration) ImportFor(imp string) (ImportDeclaration, error)

ImportFor returns the ImportDeclaration associated with the giving handle. Returns error if the import is not found.

func (PackageDeclaration) ImportedPackageFor

func (pkg PackageDeclaration) ImportedPackageFor(packageName string) (Package, bool)

ImportedPackageFor returns the Package for a giving imported package based on the package name or aliased used in the package for this declaration.

func (PackageDeclaration) InterfaceFor

func (pkg PackageDeclaration) InterfaceFor(intrName string) (InterfaceDeclaration, bool)

InterfaceFor returns associated InterfaceDeclaration associated with name.

func (PackageDeclaration) MethodFor

func (pkg PackageDeclaration) MethodFor(structName string) ([]FuncDeclaration, bool)

MethodFor returns associated FuncDeclaration with has struct declaration has receiver.

func (PackageDeclaration) StructFor

func (pkg PackageDeclaration) StructFor(structName string) (StructDeclaration, bool)

StructFor returns associated StructDeclaration associated with name.

func (PackageDeclaration) TypeFor

func (pkg PackageDeclaration) TypeFor(typeName string) (TypeDeclaration, bool)

TypeFor returns associated TypeDeclaration associated with name.

type Packages

type Packages []Package

Packages defines a type to represent a slice of Packages.

func FilteredPackageWithBuildCtx

func FilteredPackageWithBuildCtx(log metrics.Metrics, dir string, ctx build.Context) (Packages, error)

FilteredPackageWithBuildCtx parses the package directory which generates a series of ast with associated annotation for processing by using the golang token parser, it uses the build.Context to collected context details for the package and only processes the files found by the build context. If you need something more broad without filtering, use PackageWithBuildCtx.

func ParseAnnotations

func ParseAnnotations(log metrics.Metrics, dir string) (Packages, error)

ParseAnnotations parses the package which generates a series of ast with associated annotation for processing.

func (Packages) PackageFor

func (pkgs Packages) PackageFor(path string) (Package, bool)

PackageFor returns package associated with path.

func (Packages) PackageForFile

func (pkgs Packages) PackageForFile(path string, targetFile string) (PackageDeclaration, Package, bool)

PackageForFile returns package associated with path.

func (Packages) TestPackageFor

func (pkgs Packages) TestPackageFor(path string) (Package, bool)

TestPackageFor returns package associated with path for its tests.

func (Packages) TestPackageForFile

func (pkgs Packages) TestPackageForFile(path string, targetFile string) (PackageDeclaration, Package, bool)

TestPackageForFile returns package associated with path.

type StructAnnotationGenerator

StructAnnotationGenerator defines a function which generates specific code related to the giving Annotation. This allows you to generate a new source file containg source code for a giving struct type. It is responsible to fully contain all operations required to both generator any source and write such to.

type StructDeclaration

type StructDeclaration struct {
	From            int
	Length          int
	Package         string
	Name            string
	NameWithPackage string
	Path            string
	FilePath        string
	Source          string
	Comments        string
	File            string
	Struct          *ast.StructType
	Object          *ast.TypeSpec
	GenObj          *ast.GenDecl
	Position        token.Pos
	Declr           *PackageDeclaration
	Annotations     []AnnotationDeclaration
	Associations    map[string]AnnotationAssociationDeclaration
}

StructDeclaration defines a type which holds annotation data for a giving struct type declaration.

func FindStructType

func FindStructType(pkg PackageDeclaration, typeName string) (StructDeclaration, error)

FindStructType defines a function to search a package declaration Structs of a giving typeName.

func (StructDeclaration) AnnotationsFor

func (str StructDeclaration) AnnotationsFor(typeName string) []AnnotationDeclaration

AnnotationsFor returns all annotations with the giving name.

func (StructDeclaration) Fields

func (str StructDeclaration) Fields() ([]FieldDeclaration, error)

Fields returns a slice containing all fields of giving struct. If struct has no associated PackageDeclaration, error is returned.

type TagDeclaration

type TagDeclaration struct {
	Name  string
	Value string
	Metas []string
	Base  string
	Field FieldDeclaration
}

TagDeclaration defines a type which represents a giving tag declaration for a provided type.

func GetTag

func GetTag(f FieldDeclaration, tagName string, fallback string) (TagDeclaration, error)

GetTag returns the giving tag associated with the name if it exists.

func (TagDeclaration) Has

func (t TagDeclaration) Has(item string) bool

Has returns true/false if the tag.Metas has the given value in the list.

type TypeAnnotationGenerator

TypeAnnotationGenerator defines a function which generates specific code related to the giving Annotation for a non-struct, non-interface type declaration. This allows you to apply and create new sources specifically for a giving type(non-struct, non-interface). It is responsible to fully contain all operations required to both generator any source and write such to

type TypeDeclaration

type TypeDeclaration struct {
	From            int
	Length          int
	Package         string
	Name            string
	NameWithPackage string
	Path            string
	FilePath        string
	Source          string
	Comments        string
	File            string
	Aliased         bool
	Type            *ast.Ident
	TypeInfo        *ArgType
	AliasedType     *ast.Object
	AliasedTypeSpec *ast.TypeSpec
	Object          *ast.TypeSpec
	GenObj          *ast.GenDecl
	Position        token.Pos
	Declr           *PackageDeclaration
	Annotations     []AnnotationDeclaration
	Associations    map[string]AnnotationAssociationDeclaration
}

TypeDeclaration defines a type which holds annotation data for a giving type declaration.

func FindType

func FindType(pkg PackageDeclaration, typeName string) (TypeDeclaration, error)

FindType defines a function to search a package declaration Structs of a giving typeName.

func (TypeDeclaration) AnnotationsFor

func (ty TypeDeclaration) AnnotationsFor(typeName string) []AnnotationDeclaration

AnnotationsFor returns all annotations with the giving name.

type VariableDeclaration

type VariableDeclaration struct {
	From            int
	Length          int
	Package         string
	Path            string
	Name            string
	NameWithPackage string
	NameIdent       *ast.Ident
	FilePath        string
	Source          string
	Comments        string
	File            string
	Position        token.Pos
	Object          *ast.ValueSpec
	GenObj          *ast.GenDecl
	Declr           *PackageDeclaration
	Annotations     []AnnotationDeclaration
	Associations    map[string]AnnotationAssociationDeclaration
}

VariableDeclaration defines a type which holds annotation data for a giving variable declaration.

Jump to

Keyboard shortcuts

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