asthlp

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2023 License: GPL-3.0 Imports: 6 Imported by: 4

README

go-ast

GO abstract syntax tree constructors helpers.

Documentation

Index

Constants

View Source
const (
	Assignment  assignToken = iota + 1 // =
	Incremental                        // +=
	Decremental                        // -=
	Definition                         // :=
)

Variables

View Source
var (
	// NewFn is a construction of the `new` function
	NewFn = makeFunc(ast.NewIdent("new"), 1, true)
	// MakeFn is a construction of the `make` function
	MakeFn = makeFunc(ast.NewIdent("make"), 1, true)
	// LengthFn is a construction of the `len` function
	LengthFn = makeFunc(ast.NewIdent("len"), 1, false)
	// CapFn is a construction of the `cap` function
	CapFn = makeFunc(ast.NewIdent("cap"), 1, false)
	// AppendFn is a construction of the `append` function
	AppendFn = makeFunc(ast.NewIdent("append"), 1, true)

	// StrconvItoaFn is a construction of the `strconv.Itoa` function
	StrconvItoaFn = makeFunc(SimpleSelector("strconv", "Itoa"), 1, false)
	// StrconvAtoiFn is a construction of the `strconv.Atoi` function
	StrconvAtoiFn = makeFunc(SimpleSelector("strconv", "Atoi"), 1, false)
	// StrconvParseIntFn is a construction of the `strconv.ParseInt` function
	StrconvParseIntFn = makeFunc(SimpleSelector("strconv", "ParseInt"), 3, false)
	// StrconvParseUintFn is a construction of the `strconv.ParseUint` function
	StrconvParseUintFn = makeFunc(SimpleSelector("strconv", "ParseUint"), 3, false)
	// StrconvParseFloatFn is a construction of the `strconv.ParseFloat` function
	StrconvParseFloatFn = makeFunc(SimpleSelector("strconv", "ParseFloat"), 2, false)
	// StrconvParseBoolFn is a construction of the `strconv.ParseBool` function
	StrconvParseBoolFn = makeFunc(SimpleSelector("strconv", "ParseBool"), 1, false)

	// StrconvFormatIntFn is a construction of the `strconv.FormatInt` function
	StrconvFormatIntFn = makeFunc(SimpleSelector("strconv", "FormatInt"), 2, false)
	// StrconvFormatFloatFn is a construction of the `strconv.FormatFloat` function
	StrconvFormatFloatFn = makeFunc(SimpleSelector("strconv", "FormatFloat"), 4, false)
	// StrconvFormatBoolFn is a construction of the `strconv.FormatBool` function
	StrconvFormatBoolFn = makeFunc(SimpleSelector("strconv", "FormatBool"), 1, false)

	// StringsEqualFoldFn is a construction of the `strings.EqualFold` function
	StringsEqualFoldFn = makeFunc(SimpleSelector("strings", "EqualFold"), 2, false)
	// StringsToLowerFn is a construction of the `strings.ToLower` function
	StringsToLowerFn = makeFunc(SimpleSelector("strings", "ToLower"), 1, false)
	// StringsJoinFn is a construction of the `strings.Join` function
	StringsJoinFn = makeFunc(SimpleSelector("strings", "Join"), 2, false)

	// BytesEqualFoldFn is a construction of the `bytes.EqualFold` function
	BytesEqualFoldFn = makeFunc(SimpleSelector("bytes", "EqualFold"), 2, false)
	// BytesEqualFn is a construction of the `bytes.EqualFold` function
	BytesEqualFn = makeFunc(SimpleSelector("bytes", "Equal"), 2, false)
	// BytesNewBufferFn is a construction of the `bytes.NewBuffer` function
	BytesNewBufferFn = makeFunc(SimpleSelector("bytes", "NewBuffer"), 1, false)

	// FmtSprintfFn is a construction of the `fmt.Sprintf` function
	FmtSprintfFn = makeFunc(SimpleSelector("fmt", "Sprintf"), 1, true)
	// FmtFscanfFn is a construction of the `fmt.Fscanf` function
	FmtFscanfFn = makeFunc(SimpleSelector("fmt", "Fscanf"), 1, true)
	// FmtErrorfFn is a construction of the `fmt.Errorf` function
	FmtErrorfFn = makeFunc(SimpleSelector("fmt", "Errorf"), 1, true)

	// JsonUnmarshal is a construction of the `json.Unmarshall` function
	JsonUnmarshal = makeFunc(SimpleSelector("json", "Unmarshal"), 2, false)
	// JsonMarshal is a construction of the `json.Marshall` function
	JsonMarshal = makeFunc(SimpleSelector("json", "Marshal"), 1, false)
	// JsonNewEncoder is a construction of the `json.NewEncoder` function
	JsonNewEncoder = makeFunc(SimpleSelector("json", "NewEncoder"), 1, false)
	// JsonNewDecoder is a construction of the `json.NewDecoder` function
	JsonNewDecoder = makeFunc(SimpleSelector("json", "NewDecoder"), 1, false)

	// TimeNowFn is a construction of the `time.Now` function
	TimeNowFn = makeFunc(SimpleSelector("time", "Now"), 0, false)

	// DbQueryFn is a construction of the `db.Query` function
	DbQueryFn = makeFunc(SimpleSelector("db", "Query"), 1, true)
	// RowsNextFn is a construction of the `rows.Next` function
	RowsNextFn = makeFunc(SimpleSelector("rows", "Next"), 0, false)
	// RowsErrFn is a construction of the `rows.Err` function
	RowsErrFn = makeFunc(SimpleSelector("rows", "Err"), 0, false)
	// RowsScanFn is a construction of the `rows.Scan` function
	RowsScanFn = makeFunc(SimpleSelector("rows", "Scan"), 1, true)

	// BytesToIntFn represents utils.BytesToInt function
	BytesToIntFn = makeFunc(SimpleSelector("utils", "BytesToInt"), 1, false)
	// BytesToUintFn represents utils.BytesToUint function
	BytesToUintFn = makeFunc(SimpleSelector("utils", "BytesToUint"), 1, false)
	// BytesToInt64Fn represents utils.BytesToInt64 function
	BytesToInt64Fn = makeFunc(SimpleSelector("utils", "BytesToInt64"), 1, false)
	// BytesToUint64Fn represents utils.BytesToUint64 function
	BytesToUint64Fn = makeFunc(SimpleSelector("utils", "BytesToUint64"), 1, false)
	// BytesToFloat64Fn represents utils.BytesToFloat64 function
	BytesToFloat64Fn = makeFunc(SimpleSelector("utils", "BytesToFloat64"), 1, false)
)
View Source
var (
	// False equals false
	False = BoolConstant(false).Expr()
	// True equals true
	True = BoolConstant(true).Expr()

	// Zero equals 0 constant
	Zero = IntegerConstant(0).Expr()
	// EmptyString equals ""
	EmptyString = StringConstant("").Expr()
	// Blank equals _ ident
	Blank = ast.NewIdent("_")
	// Nil equals nil ident
	Nil = ast.NewIdent("nil")
	// EmptyInterface equals empty interface
	EmptyInterface = &ast.InterfaceType{
		Methods: &ast.FieldList{
			Opening: 1,
			List:    nil,
			Closing: 1,
		},
	}

	// UInt represents the data type uint
	UInt = ast.NewIdent("uint")
	// UInt8 represents the data type uint8
	UInt8 = ast.NewIdent("uint8")
	// UInt16 represents the data type uint16
	UInt16 = ast.NewIdent("uint16")
	// UInt32 represents the data type uint32
	UInt32 = ast.NewIdent("uint32")
	// UInt64 represents the data type uint64
	UInt64 = ast.NewIdent("uint64")

	// Int represents the data type int
	Int = ast.NewIdent("int")
	// Int8 represents the data type int8
	Int8 = ast.NewIdent("int8")
	// Int16 represents the data type int16
	Int16 = ast.NewIdent("int16")
	// Int32 represents the data type int32
	Int32 = ast.NewIdent("int32")
	// Int64 represents the data type int64
	Int64 = ast.NewIdent("int64")

	// Float32 represents the data type float32
	Float32 = ast.NewIdent("float32")
	// Float64 represents the data type float64
	Float64 = ast.NewIdent("float64")

	// Bool represents the data type bool
	Bool = ast.NewIdent("bool")

	// String represents the data type string
	String = ast.NewIdent("string")

	// Byte represents the data type byte
	Byte = ast.NewIdent("byte")

	// Rune represents the data type rune
	Rune = ast.NewIdent("rune")

	// UUID represents the `uuid.UUID` data type
	UUID = SimpleSelector("uuid", "UUID")

	// ContextType represents the `context.Context` interface
	ContextType = SimpleSelector("context", "Context")

	// TimeTime represents the `time.Time` struct
	TimeTime = SimpleSelector("time", "Time")

	// ErrorType represents the `error` interface
	ErrorType = ast.NewIdent("error")
)

Functions

func Add

func Add(exps ...ast.Expr) ast.Expr

Add represents an addition operation

<expr1> + <expr2> + <expr3>

func And

func And(left ast.Expr, expr ...ast.Expr) ast.Expr

And represents `&&` in comparison operation

<expr> && <expr> && <expr>

func ArrayType

func ArrayType(expr ast.Expr, l ...ast.Expr) ast.Expr

ArrayType represents array expression, use `l` attribute if you want to specify array length, else omit

[<l>]<expr>

func Assign

func Assign(varNames VarNames, tok assignToken, rhs ...ast.Expr) ast.Stmt

Assign creates ast.AssignStmt which assigns a variable with a value

func Binary

func Binary(left, right ast.Expr, tok token.Token) ast.Expr

Binary represents binary expression. Use token.* constants as `tok` attribute

<left> <tok> <right> e.g. left == right

func Block

func Block(statements ...ast.Stmt) *ast.BlockStmt

Block represents block of statement

{
   ... // statements
}

nil values will be excluded from List

func Break added in v0.0.2

func Break() ast.Stmt

func Call

func Call(fn CallFunctionDescriber, args ...ast.Expr) *ast.CallExpr

Call represents a function call expression

func CallEllipsis

func CallEllipsis(fn CallFunctionDescriber, args ...ast.Expr) *ast.CallExpr

CallEllipsis represents a function call expression with ellipsis after the last argument

func CallStmt

func CallStmt(x *ast.CallExpr) ast.Stmt

func ClearEmptyExpressions

func ClearEmptyExpressions(first ast.Expr, next ...ast.Expr) []ast.Expr

ClearEmptyExpressions returns an []ast.Expr, any nil values will be excluded from this array

func CommentGroup

func CommentGroup(comments ...string) *ast.CommentGroup

CommentGroup wraps the lines in the ast.CommentGroup structure. Returns nil if arguments is omitted or empty

func CommentGroupIf

func CommentGroupIf(comments ...*string) *ast.CommentGroup

CommentGroupIf wraps the lines in the ast.CommentGroup structure if there is

func CommentGroupWithTag

func CommentGroupWithTag(tag string, comments ...string) *ast.CommentGroup

CommentGroupWithTag wraps the lines in the ast.CommentGroup structure. Returns nil if arguments is omitted or empty. Appends the contents of the tag attribute as the last line without spaces between the slashes and its contents.

func CommentStmt

func CommentStmt(comment string) ast.Stmt

func Continue added in v0.0.2

func Continue() ast.Stmt

func Decrement

func Decrement(expr ast.Expr) ast.Stmt

func DeferCall

func DeferCall(fn CallFunctionDescriber, args ...ast.Expr) ast.Stmt

DeferCall represents a deferred function call statement

func EmptyStmt

func EmptyStmt() ast.Stmt

func Equal

func Equal(left, right ast.Expr) ast.Expr

Equal represents comparison operation

<left> == <right>

func ExpressionTypeAssert

func ExpressionTypeAssert(expr, t ast.Expr) ast.Expr

ExpressionTypeAssert represents expression type assertion

<expr>.(<t>) e.g. varName.(string)

func ExpressionTypeConvert

func ExpressionTypeConvert(expr ast.Expr, t ast.Expr) ast.Expr

ExpressionTypeConvert represents the expression type conversion expression

<t>(<expr>) e.g. string(varName)

func Fallthrough added in v0.0.2

func Fallthrough() ast.Stmt

func Field

func Field(name string, tag *ast.BasicLit, fieldType ast.Expr, docAndComments ...string) *ast.Field

Field creates ast.Field. Parameter docAndComments contains the first line as Docstring, all other lines turn into CommentGroup

func FieldList

func FieldList(fields ...*ast.Field) *ast.FieldList

FieldList creates ast.FieldList, any nil values will be excluded from list

func Great

func Great(left, right ast.Expr) ast.Expr

Great represents comparison operation

<left> > <right>

func If

func If(condition ast.Expr, body ...ast.Stmt) ast.Stmt

If represents `if` statement

if <condition> { <body> }

nil values will be excluded from Body.List

func IfElse

func IfElse(condition ast.Expr, body *ast.BlockStmt, alternative *ast.BlockStmt) ast.Stmt

IfElse represents `if` statement

if <condition> { <body> } else { <alternative> }

nil values will be excluded from Body.List

func IfInit

func IfInit(initiation ast.Stmt, condition ast.Expr, body ...ast.Stmt) ast.Stmt

IfInit represents `if` statement with initialization

if <init>; <condition> { <body> }

nil values will be excluded from Body.List

func IfInitElse

func IfInitElse(initiation ast.Stmt, condition ast.Expr, body *ast.BlockStmt, alternative *ast.BlockStmt) ast.Stmt

IfInitElse represents `if` statement with initialization and with else block

if <init>; <condition> { <body> } else { <alternative> }

nil values will be excluded from Body.List

func IfKeyVal

func IfKeyVal(key string, value ast.Expr) ast.Expr

IfKeyVal returns ast.KeyValueExpr or nil if the `value` attribute is nil. useful with E helper

func Import

func Import(imports map[string]string) ast.Decl

Import represents import declaration with token.IMPORT

func Increment

func Increment(expr ast.Expr) ast.Stmt

func Index

func Index(x ast.Expr, index Expression) ast.Expr

Index creates the array element picker expression

someArr[1]

func IsNil

func IsNil(expr ast.Expr) ast.Expr

IsNil represents nil-comparison operation

<expr> == nil

func KeyValueExpr

func KeyValueExpr(key string, val ast.Expr) *ast.KeyValueExpr

KeyValueExpr creates ast.KeyValueExpr with given key and value

func MakeCallReturnIfError

func MakeCallReturnIfError(varName ast.Expr, callExpr *ast.CallExpr) ast.Stmt

MakeCallReturnIfError creates a function call statement with error checking branch contained `return err`

if <varName>, err = callExpr(); err != nil {
    return err
}

varName can be omitted

func MakeCallWithErrChecking

func MakeCallWithErrChecking(varName string, callExpr *ast.CallExpr, body ...ast.Stmt) ast.Stmt

MakeCallWithErrChecking creates a function call statement with error checking branch

if <varName>, err = callExpr(); err != nil {
    <body>
}

varName can be omitted

func MakeLenGreatThanZero

func MakeLenGreatThanZero(arrayName string) ast.Expr

MakeLenGreatThanZero makes len() > 0 expression

len(<arrayName>) > 0

func MakeSwitch added in v0.0.2

func MakeSwitch(init ast.Stmt, tag ast.Expr, cases ...SwitchCase) ast.Stmt

func MakeTagsForField

func MakeTagsForField(tags map[string][]string) *ast.BasicLit

MakeTagsForField with tags like map[tag]values, string `tag1:"values1" tag2:"values2"` is created

func MakeTypeSwitch

func MakeTypeSwitch(assign ast.Stmt, cases ...SwitchCase) ast.Stmt

func MapType

func MapType(key, expr ast.Expr) ast.Expr

MapType represents map expression

map[<T>]<expr>

func NewIdent

func NewIdent(name string) *ast.Ident

NewIdent creates new ast.Ident

func Not

func Not(expr ast.Expr) ast.Expr

Not represents inversion

!<expr>

func NotEqual

func NotEqual(left, right ast.Expr) ast.Expr

NotEqual represents comparison operation

<left> != <right>

func NotNil

func NotNil(expr ast.Expr) ast.Expr

NotNil represents non-nil-comparison operation

<expr> != nil

func Or

func Or(left ast.Expr, expr ...ast.Expr) ast.Expr

Or represents `||` in comparison operation

<expr> || <expr> || <expr>

func ParenExpr added in v0.0.2

func ParenExpr(x ast.Expr) ast.Expr

func Range

func Range(define bool, key, value string, x ast.Expr, body ...ast.Stmt) ast.Stmt

Range represents `for` statement with range expression

for <key>, <value> := range <x> { <body> }

":=" replaced by "=" if define is FALSE

func Ref

func Ref(expr ast.Expr) ast.Expr

Ref represents reference

&<expr>

func Return

func Return(results ...ast.Expr) *ast.ReturnStmt

Return represents return statement

return a, b, c, ...

nil values will be excluded

func ReturnEmpty

func ReturnEmpty() ast.Stmt

ReturnEmpty represents empty return statement

return

func Selector

func Selector(x ast.Expr, object string) ast.Expr

Selector represents a dot notation expression like "pack.object" <x>.<object>

func SimpleSelector

func SimpleSelector(pack, object string) ast.Expr

SimpleSelector represents a dot notation expression like "pack.object" from string arguments

func Slice

func Slice(varName string, lo, hi Expression) ast.Expr

func SliceExpr added in v0.0.2

func SliceExpr(x ast.Expr, lo, hi Expression) ast.Expr

func Star

func Star(expr ast.Expr) ast.Expr

Star represents star expression

*<expr>

func StructType

func StructType(fields ...*ast.Field) *ast.StructType

StructType creates ast.StructType with Type field

func Sub

func Sub(exps ...ast.Expr) ast.Expr

Sub represents a subtraction operation

<expr1> - <expr2> - <expr3>

func TypeSpec

func TypeSpec(name string, varType ast.Expr, comment ...string) *ast.TypeSpec

TypeSpec creates ast.TypeSpec with Type field

func Unary

func Unary(expr ast.Expr, tok token.Token) ast.Expr

Unary represents unary expression

<tok><expr> e.g. !expr

you can use this constant as `tok` attribute:

token.ADD     // +
token.SUB     // -
token.MUL     // *
token.QUO     // /
token.REM     // %
token.AND     // &
token.OR      // |
token.XOR     // ^
token.SHL     // <<
token.SHR     // >>
token.AND_NOT // &^

func Var

func Var(spec ...ast.Spec) ast.Stmt

Var creates ast.DeclStmt with VAR token, nil values will be excluded from List. Use VariableType to fill it in.

func VariableType

func VariableType(name string, varType ast.Expr, vals ...Expression) *ast.ValueSpec

VariableType creates ast.ValueSpec with Type field

func VariableTypeAssert

func VariableTypeAssert(varName string, t ast.Expr) ast.Expr

VariableTypeAssert represents variable type assertion expression

<varName>.(<t>) e.g. varName.(string)

func VariableTypeConvert

func VariableTypeConvert(varName string, t ast.Expr) ast.Expr

VariableTypeConvert represents variable type conversion expression

<t>(<varName>) e.g. string(varName)

func VariableValue

func VariableValue(name string, vals ...Expression) *ast.ValueSpec

VariableValue creates ast.ValueSpec with Values field

Types

type BoolConstant

type BoolConstant bool

func (BoolConstant) Expr

func (b BoolConstant) Expr() ast.Expr

type CallFunctionDescriber

type CallFunctionDescriber struct {
	FunctionName ast.Expr
	// MinimumNumberOfArguments limits the number of arguments, unless indicated that it can expand
	MinimumNumberOfArguments int
	// ExtensibleNumberOfArguments shows that the number of arguments can be increased (notation ...)
	ExtensibleNumberOfArguments bool
}

CallFunctionDescriber describes a function so that we can do minimal checks

func InlineFunc

func InlineFunc(f ast.Expr) CallFunctionDescriber

type Expression

type Expression interface {
	Expr() ast.Expr
}

func FreeExpression

func FreeExpression(e ast.Expr) Expression

FreeExpression creates Expression from ast.Expr

type FloatConstant

type FloatConstant float64 // float constant e.g. 123.45

func (FloatConstant) Expr

func (c FloatConstant) Expr() ast.Expr

Expr creates ast.BasicLit with token.FLOAT

type FuncDecl

type FuncDecl interface {
	Comments(...string) FuncDecl
	Receiver(*ast.Field) FuncDecl
	Params(...*ast.Field) FuncDecl
	Results(...*ast.Field) FuncDecl
	AppendStmt(...ast.Stmt) FuncDecl
	Decl() ast.Decl
	Lit() ast.Expr
}

func DeclareFunction

func DeclareFunction(name *ast.Ident) FuncDecl

type IntegerConstant

type IntegerConstant int64 // integer constant e.g. 123

func (IntegerConstant) Expr

func (c IntegerConstant) Expr() ast.Expr

Expr creates ast.BasicLit with token.INT

type InterfaceMethodFiller added in v0.0.4

type InterfaceMethodFiller interface {
	Inherits(name string, tag *ast.BasicLit, docAndComments ...string)
	Method(decl MethodDecl, tag *ast.BasicLit, docAndComments ...string)
	TypeSpec() *ast.TypeSpec
}

func InterfaceTypeFiller added in v0.0.4

func InterfaceTypeFiller(name string, comment ...string) InterfaceMethodFiller

type MethodDecl added in v0.0.4

type MethodDecl interface {
	Params(...*ast.Field) MethodDecl
	Results(...*ast.Field) MethodDecl
	Type() ast.Expr
	Name() *ast.Ident
}

func DeclareMethod added in v0.0.4

func DeclareMethod(name *ast.Ident) MethodDecl

type RuneConstant

type RuneConstant rune // rune constant e.g. 'r'

func (RuneConstant) Expr

func (c RuneConstant) Expr() ast.Expr

Expr creates ast.BasicLit with token.STRING

type SliceByteLiteral

type SliceByteLiteral []byte // []byte{'f', 'i', 'l', 't', 'e', 'r'}

func (SliceByteLiteral) Expr

func (s SliceByteLiteral) Expr() ast.Expr

type SliceStringLiteral added in v0.0.4

type SliceStringLiteral []string // []string{"abc", "def"}

func (SliceStringLiteral) Expr added in v0.0.4

func (s SliceStringLiteral) Expr() ast.Expr

type StringConstant

type StringConstant string // string constant e.g. "abc"

func (StringConstant) Expr

func (c StringConstant) Expr() ast.Expr

Expr creates ast.BasicLit with token.STRING

type StructFieldFiller

type StructFieldFiller interface {
	Field(name string, tag *ast.BasicLit, fieldType ast.Expr, docAndComments ...string)
	TypeSpec() *ast.TypeSpec
}

func StructTypeFiller

func StructTypeFiller(name string, comment ...string) StructFieldFiller

type StructFiller

type StructFiller interface {
	Expression
	FillKeyValue(key string, value ast.Expr) StructFiller
}

func StructLiteral

func StructLiteral(name ast.Expr) StructFiller

type SwitchCase

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

func MakeSwitchCase

func MakeSwitchCase(clause ...ast.Expr) SwitchCase

func (SwitchCase) Body

func (c SwitchCase) Body(statements ...ast.Stmt) SwitchCase

type UnsignedConstant

type UnsignedConstant uint64 // unsigned integer constant e.g. 123

func (UnsignedConstant) Expr

func (c UnsignedConstant) Expr() ast.Expr

Expr creates ast.BasicLit with token.INT

type VarDecl

type VarDecl interface {
	Comments(comments ...string) VarDecl
	AppendSpec(spec ...ast.Spec) VarDecl
	Decl() ast.Decl
	Stmt() ast.Stmt
}

func DeclareVariable

func DeclareVariable() VarDecl

type VarNames

type VarNames []ast.Expr

VarNames represents a list of variable names

func MakeVarNames

func MakeVarNames(vars ...string) VarNames

MakeVarNames creates VarNames inline

type VariableName

type VariableName string // any variable name

func (VariableName) Expr

func (c VariableName) Expr() ast.Expr

Expr creates ast.Ident with variable name

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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