builders

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2020 License: MIT Imports: 5 Imported by: 4

README

astbuilders

Go Documentation codecov license

Go AST utility package

Install

go get github.com/tdakkota/astbuilders

Examples

Creating a function
package main

import (
	"go/printer"
	"go/token"
	"os"

	"github.com/tdakkota/astbuilders"
)

func main() {
	node := builders.NewFunctionBuilder("main").
		Body(func(s builders.StatementBuilder) builders.StatementBuilder {
			return s.Expr(builders.CallPackage("fmt", "Println", builders.StringLit("Hello, world!")))
		}).
		CompleteAsDecl()

	printer.Fprint(os.Stdout, token.NewFileSet(), node)
}

prints

func main() {
    fmt.Println("Hello, world!")
}
if err != nil
package main

import (
	"go/ast"
	"go/printer"
	"go/token"
	"os"
	
	"github.com/tdakkota/astbuilders"
)

func main() {
	errIdent := ast.NewIdent("err")
	nilIdent := ast.NewIdent("nil")
	cond := builders.NotEq(errIdent, nilIdent)

	s := builders.NewStatementBuilder()
	s = s.If(nil, cond, func(body builders.StatementBuilder) builders.StatementBuilder {
		return body.Return(errIdent)
	})

	stmts := s.Complete()
	node := stmts[0]
	printer.Fprint(os.Stdout, token.NewFileSet(), node)
}

prints

if err != nil {
	return err
}
Reverse from SliceTricks
package main

import (
	"go/ast"
	"go/printer"
	"go/token"
	"os"
	
	"github.com/tdakkota/astbuilders"
)

func main() {
	s := builders.NewStatementBuilder()

	a := ast.NewIdent("a")
	left, right := ast.NewIdent("left"), ast.NewIdent("right")
	one := builders.IntegerLit(1)

	// left, right := 0, len(a)-1
	init := builders.Define(left, right)(builders.IntegerLit(0), builders.Sub(builders.Len(a), one))
	// left < right
	cond := builders.Less(left, right)
	// left, right = left+1, right-1
	post := builders.Assign(left, right)(token.ASSIGN)(builders.Add(left, one), builders.Sub(right, one))

	// a[left]
	indexLeft := builders.Index(a, left)
	// a[right]
	indexRight := builders.Index(a, right)

	// for $init; $cond; $post {
	// for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
	s = s.For(init, cond, post, func(loop builders.StatementBuilder) builders.StatementBuilder {
		// a[left], a[right] = a[right], a[left]
		loop = loop.AddStmts(builders.Swap(indexLeft, indexRight))
		return loop
	})

	stmts := s.Complete()
	node := stmts[0]
	printer.Fprint(os.Stdout, token.NewFileSet(), node)
}

prints

for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
    a[left], a[right] = a[right], a[left]
}

Documentation

Overview

Example (IfElseIf)
package main

import (
	"go/ast"
	"go/printer"
	"go/token"
	"os"

	"github.com/tdakkota/astbuilders"
)

func returnString(lit string) builders.BodyFunc {
	return func(body builders.StatementBuilder) builders.StatementBuilder {
		return body.Return(builders.StringLit(lit))
	}
}

func main() {
	a := ast.NewIdent("a")
	b := ast.NewIdent("b")

	s := builders.NewStatementBuilder()
	lessCase := builders.IfElseStmt(nil, builders.Less(a, b), returnString("less"), nil)
	greaterCase := builders.IfElseStmt(nil, builders.Greater(a, b), returnString("greater"), lessCase)
	s = s.IfElseStmt(nil, builders.Eq(a, b), returnString("equal"), greaterCase)

	stmts := s.Complete()
	node := stmts[0]
	printer.Fprint(os.Stdout, token.NewFileSet(), node)
}
Output:

if a == b {
	return "equal"
} else if a > b {
	return "greater"
} else if a < b {
	return "less"
}
Example (IfErrNotNil)
// err != nil
cond := builders.NotEq(builders.Err(), builders.Nil())

s := builders.NewStatementBuilder()
s = s.If(nil, cond, func(body builders.StatementBuilder) builders.StatementBuilder {
	return body.Return(builders.Err())
})

stmts := s.Complete()
node := stmts[0]
printer.Fprint(os.Stdout, token.NewFileSet(), node)
Output:

if err != nil {
	return err
}
Example (Main)
node := builders.NewFunctionBuilder("main").
	Body(func(s builders.StatementBuilder) builders.StatementBuilder {
		return s.Expr(builders.CallPackage("fmt", "Println", builders.StringLit("Hello, world!")))
	}).
	CompleteAsDecl()

printer.Fprint(os.Stdout, token.NewFileSet(), node)
Output:

func main() {
	fmt.Println("Hello, world!")
}
Example (Reverse)
s := builders.NewStatementBuilder()

a := ast.NewIdent("a")
left, right := ast.NewIdent("left"), ast.NewIdent("right")
one := builders.IntegerLit(1)

// left, right := 0, len(a)-1
init := builders.Define(left, right)(builders.IntegerLit(0), builders.Sub(builders.Len(a), one))
// left < right
cond := builders.Less(left, right)
// left, right = left+1, right-1
post := builders.Assign(left, right)(token.ASSIGN)(builders.Add(left, one), builders.Sub(right, one))

// a[left]
indexLeft := builders.Index(a, left)
// a[right]
indexRight := builders.Index(a, right)

// for $init; $cond; $post {
// for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
s = s.For(init, cond, post, func(loop builders.StatementBuilder) builders.StatementBuilder {
	// a[left], a[right] = a[right], a[left]
	loop = loop.AddStmts(builders.Swap(indexLeft, indexRight))
	return loop
})

stmts := s.Complete()
node := stmts[0]
printer.Fprint(os.Stdout, token.NewFileSet(), node)
Output:

for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
	a[left], a[right] = a[right], a[left]
}
Example (Rewrite)
package main

import (
	"go/ast"
	"go/parser"
	"go/printer"
	"go/token"
	"os"

	"github.com/tdakkota/astbuilders"
)

const code = `
package main

import "fmt"

func main() {
	fmt.Print("Hello, ")
}
`

func main() {
	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, "", code, parser.ParseComments)
	if err != nil {
		panic(err)
	}

	for _, decl := range file.Decls {
		if v, ok := decl.(*ast.FuncDecl); ok && v.Name.Name == "main" {
			s := builders.NewStatementBuilder()
			s = s.AddStmts(v.Body.List...)
			s = s.Expr(builders.CallPackage("fmt", "Println", builders.StringLit("world!")))
			v.Body = s.CompleteAsBlock()
		}
	}

	printer.Fprint(os.Stdout, fset, file)
}
Output:

package main

import "fmt"

func main()	{ fmt.Print("Hello, "); fmt.Println("world!") }

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Add

func Add(x, y ast.Expr) *ast.BinaryExpr

Add returns x + y expression.

func AddNot

func AddNot(x, y ast.Expr) *ast.BinaryExpr

AddNot returns x &^ y expression.

func And

func And(x, y ast.Expr) *ast.BinaryExpr

And returns x && y expression.

func Append

func Append(slice ast.Expr, elem ...ast.Expr) *ast.CallExpr

Append returns append(slice, elem1, elem2, ..., elemN).

func ArrayOf

func ArrayOf(elem, size ast.Expr) *ast.ArrayType

ArrayOf returns [size]elem declaration.

func ArrayOfSize

func ArrayOfSize(e ast.Expr, size int) *ast.ArrayType

ArrayOfSize returns [size]elem declaration.

Example
integer := IdentOfKind(types.Int)
array := ArrayOfSize(integer, 2)
printer.Fprint(os.Stdout, token.NewFileSet(), array) // print ast.Node
Output:

[2]int

func BAnd

func BAnd(x, y ast.Expr) *ast.BinaryExpr

BAnd returns x & y expression.

func BNot

func BNot(e ast.Expr) *ast.UnaryExpr

BNot returns ^e expression.

func BOr

func BOr(x, y ast.Expr) *ast.BinaryExpr

BOr returns x | y expression.

func BinaryOp

func BinaryOp(x ast.Expr, tok token.Token, y ast.Expr) *ast.BinaryExpr

BinaryOp returns binary expression with given token.

func Call

func Call(f ast.Expr, args ...ast.Expr) *ast.CallExpr

Call returns f(args).

Example
call := Call(ast.NewIdent("f"), IntegerLit(0))
printer.Fprint(os.Stdout, token.NewFileSet(), call) // print ast.Node
Output:

f(0)

func CallName

func CallName(name string, args ...ast.Expr) *ast.CallExpr

CallName returns name(args). Fast path for Call.

func CallPackage

func CallPackage(pkg, name string, args ...ast.Expr) *ast.CallExpr

CallPackage returns pkg.name(args). Fast path for Call.

Example
call := CallPackage("fmt", "Println", StringLit("Hello, World!"))
printer.Fprint(os.Stdout, token.NewFileSet(), call) // print ast.Node
Output:

fmt.Println("Hello, World!")

func Cap

func Cap(x ast.Expr) *ast.CallExpr

Cap returns cap(x).

func Cast

func Cast(to, what ast.Expr) *ast.CallExpr

Cast returns to(what).

func CastPackage

func CastPackage(pkg, name string, what ast.Expr) *ast.CallExpr

CastPackage returns pkg.name(what). Fast path for Cast.

func ChanOf

func ChanOf(elem ast.Expr) *ast.ChanType

ChanOf returns chan elem declaration.

Example
str := EmptyStruct()
slice := ChanOf(str)
printer.Fprint(os.Stdout, token.NewFileSet(), slice) // print ast.Node
Output:

chan struct {
}

func CharLit

func CharLit(value rune) *ast.BasicLit

CharLit creates rune/character literal.

func Close

func Close(ch ast.Expr) *ast.CallExpr

Close returns close(ch).

func Copy

func Copy(dst, src ast.Expr) *ast.CallExpr

Copy returns copy(dst, src).

func DeRef

func DeRef(e ast.Expr) *ast.StarExpr

DeRef returns *e expression.

func Dec

func Dec(e ast.Expr) *ast.UnaryExpr

Dec returns e-- expression.

func DecStmt

func DecStmt(x ast.Expr) *ast.IncDecStmt

DecStmt returns decrement statement.

func Div

func Div(x, y ast.Expr) *ast.BinaryExpr

Div returns x / y expression.

func EmptyInterface

func EmptyInterface() *ast.InterfaceType

EmptyInterface creates new empty interface{} declaration.

func EmptyStruct

func EmptyStruct() *ast.StructType

EmptyStruct creates new empty struct{} declaration.

func Eq

func Eq(x, y ast.Expr) *ast.BinaryExpr

Eq returns x == y expression.

func Err

func Err() *ast.Ident

Err return err identifier.

func Error

func Error() *ast.Ident

Error return error identifier.

func Field

func Field(names ...*ast.Ident) func(typ ast.Expr, tag *ast.BasicLit) *ast.Field

Field builds struct field.

func FieldName

func FieldName(f *ast.Field) (r *ast.Ident, ok bool)

FieldName gets one name of field.

func FieldNames

func FieldNames(f *ast.Field) (r []*ast.Ident, ok bool)

FieldName gets all names of field.

func FloatLit

func FloatLit(value float64) *ast.BasicLit

FloatLit creates floating point literal.

func FuncType

func FuncType(params ...*ast.Field) func(results ...*ast.Field) *ast.FuncType

FuncType creates new function type using given params and results.

func GenericChanOf

func GenericChanOf(dir ast.ChanDir, elem ast.Expr) *ast.ChanType

GenericChanOf returns chan elem declaration using given direction. Dir is the direction of a channel type is indicated by a bit mask. Dir must be ast.SEND, ast.RECV, or ast.SEND | ast.RECV.

func Greater

func Greater(x, y ast.Expr) *ast.BinaryExpr

Greater returns x > y expression.

func GreaterOrEq

func GreaterOrEq(x, y ast.Expr) *ast.BinaryExpr

GreaterOrEq returns x >= y expression.

func HashSetOf

func HashSetOf(k ast.Expr) *ast.MapType

HashSetOf returns map[k]struct{} declaration.

Example
str := IdentOfKind(types.String)
slice := HashSetOf(str)
printer.Fprint(os.Stdout, token.NewFileSet(), slice) // print ast.Node
Output:

map[string]struct {
}

func IdentOfKind

func IdentOfKind(kind types.BasicKind) *ast.Ident

func Idents

func Idents(names ...string) []*ast.Ident

Idents creates array for identifiers.

func If

func If(init ast.Stmt, cond ast.Expr, ifBody BodyFunc) *ast.IfStmt

If creates if statement.

func IfElse

func IfElse(init ast.Stmt, cond ast.Expr, ifBody, elseBody BodyFunc) *ast.IfStmt

IfElse creates if-else statement.

func IfElseStmt

func IfElseStmt(init ast.Stmt, cond ast.Expr, ifBody BodyFunc, elseStmt ast.Stmt) *ast.IfStmt

IfElseStmt creates if-else statement. elseStmt should be block or if statement.

func Import

func Import(path string) *ast.ImportSpec

Import create unnamed import spec using path.

func ImportSpec

func ImportSpec(name *ast.Ident, path *ast.BasicLit) *ast.ImportSpec

ImportSpec creates *ast.ImportSpec.

func Imports

func Imports(imports ...*ast.ImportSpec) *ast.GenDecl

Imports creates import declaration from imports specs.

Example
package main

import (
	"go/printer"
	"go/token"
	"os"

	builders "github.com/tdakkota/astbuilders"
)

func main() {
	imports := builders.Imports(
		builders.Import("fmt"),
		builders.NamedImport("builders", "github.com/tdakkota/astbuilders"),
	)

	printer.Fprint(os.Stdout, token.NewFileSet(), imports)
}
Output:

import (
	"fmt"
	builders "github.com/tdakkota/astbuilders"
)

func Inc

func Inc(e ast.Expr) *ast.UnaryExpr

Inc returns e++ expression.

func IncDecStmt

func IncDecStmt(x ast.Expr, tok token.Token) *ast.IncDecStmt

IncDecStmt returns increment/decrement statement.

func IncStmt

func IncStmt(x ast.Expr) *ast.IncDecStmt

IncStmt returns increment statement.

func Index

func Index(a, index ast.Expr) *ast.IndexExpr
Example
call := Index(ast.NewIdent("arr"), IntegerLit(0))
printer.Fprint(os.Stdout, token.NewFileSet(), call) // print ast.Node
Output:

arr[0]

func IntegerLit

func IntegerLit(value int) *ast.BasicLit

IntegerLit creates integer literal.

func Len

func Len(x ast.Expr) *ast.CallExpr

Len returns len(x).

func Less

func Less(x, y ast.Expr) *ast.BinaryExpr

Less returns x < y expression.

func LessOrEq

func LessOrEq(x, y ast.Expr) *ast.BinaryExpr

LessOrEq returns x <= y expression.

func Make

func Make(typ ast.Expr, length, capacity int) *ast.CallExpr

Make returns make(typ, length) if capacity is less or equal to 0. Otherwise, returns make(typ, length, capacity)

Example
str := IdentOfKind(types.String)
slice := SliceOf(str)
makeCall := Make(slice, 10, 0)

printer.Fprint(os.Stdout, token.NewFileSet(), makeCall) // print ast.Node
Output:

make([]string, 10)
Example (Capacity)
str := IdentOfKind(types.String)
slice := SliceOf(str)
makeCall := Make(slice, 10, 20)

printer.Fprint(os.Stdout, token.NewFileSet(), makeCall) // print ast.Node
Output:

make([]string, 10, 20)

func MakeExpr

func MakeExpr(typ, length, capacity ast.Expr) *ast.CallExpr

MakeExpr returns make(typ, length) if capacity is nil Otherwise, returns make(typ, length, capacity)

func MapOf

func MapOf(k, v ast.Expr) *ast.MapType

MapOf returns map[k]v declaration.

Example
key := IdentOfKind(types.String)
value := EmptyInterface()
slice := MapOf(key, value)
printer.Fprint(os.Stdout, token.NewFileSet(), slice) // print ast.Node
Output:

map[string]interface {
}

func Mul

func Mul(x, y ast.Expr) *ast.BinaryExpr

Mul returns x * y expression.

func NamedImport

func NamedImport(name, path string) *ast.ImportSpec

Import create unnamed import spec using path.

func New

func New(x ast.Expr) *ast.CallExpr

New returns new(x).

func Nil

func Nil() *ast.Ident

Nil return nil identifier.

func Not

func Not(e ast.Expr) *ast.UnaryExpr

Not returns !e expression.

func NotEq

func NotEq(x, y ast.Expr) *ast.BinaryExpr

NotEq returns x != y expression.

func Or

func Or(x, y ast.Expr) *ast.BinaryExpr

And returns x || y expression.

func Param

func Param(names ...*ast.Ident) func(typ ast.Expr) *ast.Field

Param builds function parameter.

func Paren

func Paren(e ast.Expr) *ast.ParenExpr

Paren returns parenthesised expression.

Example
par := Paren(ast.NewIdent("parenthesized"))

printer.Fprint(os.Stdout, token.NewFileSet(), par) // print ast.Node
Output:

(parenthesized)

func Receiver

func Receiver(name *ast.Ident) func(typ ast.Expr) *ast.Field

Receiver builds function receiver.

func Recv

func Recv(e ast.Expr) *ast.UnaryExpr

Recv returns <-e expression.

func RecvChanOf

func RecvChanOf(elem ast.Expr) *ast.ChanType

RecvChanOf returns <-chan elem declaration.

Example
str := EmptyStruct()
slice := RecvChanOf(str)
printer.Fprint(os.Stdout, token.NewFileSet(), slice) // print ast.Node
Output:

<-chan struct {
}

func Ref

func Ref(e ast.Expr) *ast.UnaryExpr

Ref returns &e expression.

func RefFor

func RefFor(ident ast.Expr) *ast.StarExpr

RefFor returns *ident expression.

func Rem

func Rem(x, y ast.Expr) *ast.BinaryExpr

Rem returns x % y expression.

func Selector

func Selector(a ast.Expr, b *ast.Ident, expr ...*ast.Ident) *ast.SelectorExpr

Selector creates selector path from given identifiers.

func SelectorName

func SelectorName(a, b string, expr ...string) *ast.SelectorExpr

SelectorName creates selector path from given identifiers.

Example
abcd := SelectorName("a", "b", "c", "d")

printer.Fprint(os.Stdout, token.NewFileSet(), abcd) // print ast.Node
Output:

a.b.c.d

func Send

func Send(x, y ast.Expr) *ast.BinaryExpr

Send returns x <- y expression.

func SendChanOf

func SendChanOf(elem ast.Expr) *ast.ChanType

SendChanOf returns chan<- elem declaration.

Example
str := EmptyStruct()
slice := SendChanOf(str)
printer.Fprint(os.Stdout, token.NewFileSet(), slice) // print ast.Node
Output:

chan<- struct {
}

func ShiftLeft

func ShiftLeft(x, y ast.Expr) *ast.BinaryExpr

ShiftLeft returns x << y expression.

func ShiftRight

func ShiftRight(x, y ast.Expr) *ast.BinaryExpr

ShiftRight returns x >> y expression.

func SliceOf

func SliceOf(elem ast.Expr) *ast.ArrayType

SliceOf returns []elem declaration.

Example
str := IdentOfKind(types.String)
slice := SliceOf(str)
printer.Fprint(os.Stdout, token.NewFileSet(), slice) // print ast.Node
Output:

[]string

func StringLit

func StringLit(value string) *ast.BasicLit

StringLit creates string literal.

func Sub

func Sub(x, y ast.Expr) *ast.BinaryExpr

Sub returns x - y expression.

func Swap

func Swap(a, b ast.Expr) *ast.AssignStmt

Swap returns a, b = b, a statement.

Example
x, y := ast.NewIdent("x"), ast.NewIdent("y")
swap := Swap(x, y)

printer.Fprint(os.Stdout, token.NewFileSet(), swap) // print ast.Node
Output:

x, y = y, x

func TypeAssert

func TypeAssert(what, to ast.Expr) *ast.TypeAssertExpr

TypeAssert returns what.(to) expression.

func TypeSpec

func TypeSpec(name *ast.Ident, typ ast.Expr) *ast.TypeSpec

TypeSpec creates *ast.TypeSpec.

func UnaryOp

func UnaryOp(e ast.Expr, tok token.Token) *ast.UnaryExpr

BinaryOp returns unary expression with given token.

func ValueSpec

func ValueSpec(name *ast.Ident, names ...*ast.Ident) func(typ ast.Expr) func(...ast.Expr) *ast.ValueSpec

ValueSpec returns curried function to create *ast.ValueSpec.

func Xor

func Xor(x, y ast.Expr) *ast.BinaryExpr

BOr returns x ^ y expression.

Types

type AssignFunc

type AssignFunc = func(tok token.Token) func(ast.Expr, ...ast.Expr) *ast.AssignStmt

AssignFunc represents curried function which creates a assigment statement.

func Assign

func Assign(lhs1 ast.Expr, lhs ...ast.Expr) AssignFunc

Assign returns AssignFunc to build a assigment statement.

type BodyFunc

type BodyFunc func(s StatementBuilder) StatementBuilder

type DefineFunc

type DefineFunc = func(ast.Expr, ...ast.Expr) *ast.AssignStmt

DefineFunc represents curried function which creates a define statement.

func Define

func Define(lhs1 ast.Expr, lhs ...ast.Expr) DefineFunc

Define returns DefineFunc to build a define statement.

Example
x := ast.NewIdent("x")
swap := Define(x)(IntegerLit(0))

printer.Fprint(os.Stdout, token.NewFileSet(), swap) // print ast.Node
Output:

x := 0

type FileBuilder

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

func NewFileBuilder

func NewFileBuilder(pkg string) FileBuilder

func (FileBuilder) AddDecls

func (f FileBuilder) AddDecls(decls ...ast.Decl) FileBuilder

AddDecls adds declarations to the file.

func (FileBuilder) AddImportPaths

func (f FileBuilder) AddImportPaths(paths ...string) FileBuilder

AddImportPaths adds imports to the file.

func (FileBuilder) AddImports

func (f FileBuilder) AddImports(specs ...*ast.ImportSpec) FileBuilder

AddImports adds imports to the file.

func (FileBuilder) Complete

func (f FileBuilder) Complete() *ast.File

Complete returns built file.

func (FileBuilder) DeclareFunction

func (f FileBuilder) DeclareFunction(name string, cb func(FunctionBuilder) FunctionBuilder) FileBuilder

DeclareFunction creates and adds new function declaration to file.

func (FileBuilder) DeclareInterface

func (f FileBuilder) DeclareInterface(name string, cb func(InterfaceBuilder) InterfaceBuilder) FileBuilder

DeclareInterface creates and adds new type interface declaration to file.

func (FileBuilder) DeclareNewType

func (f FileBuilder) DeclareNewType(name string, typeExpr ast.Expr) FileBuilder

DeclareNewType creates and adds new newtype declaration to file.

func (FileBuilder) DeclarePlainStruct

func (f FileBuilder) DeclarePlainStruct(name string, fields func(StructBuilder) StructBuilder) FileBuilder

DeclareStruct creates and adds new type struct declaration to file. Same as DeclareStruct(name, fields, nil).

func (FileBuilder) DeclareStruct

func (f FileBuilder) DeclareStruct(
	name string,
	fields func(StructBuilder) StructBuilder,
	methods func(TypeBuilder) TypeBuilder,
) FileBuilder

DeclareStruct creates and adds new type struct declaration to file. If methods parameter is not nil, it is called to add methods.

func (FileBuilder) DeclareType

func (f FileBuilder) DeclareType(name string, typeExpr ast.Expr, methods func(TypeBuilder) TypeBuilder) FileBuilder

DeclareType creates and adds new type declaration to file. If methods parameter is not nil, it is called to add methods.

type FunctionBuilder

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

FunctionBuilder is function definition builder.

func NewFunctionBuilder

func NewFunctionBuilder(name string) FunctionBuilder

NewFunctionBuilder creates new FunctionBuilder.

func (FunctionBuilder) AddParameters

func (builder FunctionBuilder) AddParameters(params ...*ast.Field) FunctionBuilder

AddParameters adds elements to function parameters.

func (FunctionBuilder) AddResults

func (builder FunctionBuilder) AddResults(results ...*ast.Field) FunctionBuilder

AddParameters adds elements to result tuple.

func (FunctionBuilder) AddStmts

func (builder FunctionBuilder) AddStmts(stmts ...ast.Stmt) FunctionBuilder

AddStmts adds statements to function body.

func (FunctionBuilder) Body

func (builder FunctionBuilder) Body(f BodyFunc) FunctionBuilder

Body adds statements returned from BodyFunc to function body.

func (FunctionBuilder) CompleteAsCall

func (builder FunctionBuilder) CompleteAsCall(args ...ast.Expr) *ast.CallExpr

CompleteAsCall returns built function as function literal call.

func (FunctionBuilder) CompleteAsDecl

func (builder FunctionBuilder) CompleteAsDecl() *ast.FuncDecl

CompleteAsDecl returns built function as function declaration.

func (FunctionBuilder) CompleteAsLiteral

func (builder FunctionBuilder) CompleteAsLiteral() *ast.FuncLit

CompleteAsLiteral returns built function as function literal.

func (FunctionBuilder) CompleteAsType

func (builder FunctionBuilder) CompleteAsType() *ast.FuncType

CompleteAsType returns built function as function type.

func (FunctionBuilder) Recv

func (builder FunctionBuilder) Recv(recv *ast.Field) FunctionBuilder

Recv sets receiver of function.

func (FunctionBuilder) SetType

func (builder FunctionBuilder) SetType(typ *ast.FuncType) FunctionBuilder

SetType sets function type.

type InterfaceBuilder

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

func NewInterfaceBuilder

func NewInterfaceBuilder() InterfaceBuilder

NewInterfaceBuilder creates new InterfaceBuilder.

func (InterfaceBuilder) AddMethod

func (s InterfaceBuilder) AddMethod(name string, typ *ast.FuncType) InterfaceBuilder

AddMethod adds method to interface's method list.

func (InterfaceBuilder) BuildMethod

BuildMethod builds function type using callback and adds method to interface's method list.

Example
package main

import (
	"go/ast"
	"go/printer"
	"go/token"
	"go/types"
	"os"

	builders "github.com/tdakkota/astbuilders"
)

func main() {
	i := builders.NewInterfaceBuilder()
	integer := builders.IdentOfKind(types.Int)
	byteType := builders.IdentOfKind(types.Byte)

	i = i.BuildMethod("Write", func(builder builders.FunctionBuilder) builders.FunctionBuilder {
		return builder.
			AddParameters(
				builders.Param(ast.NewIdent("p"))(builders.SliceOf(byteType)),
			).
			AddResults(
				builders.Param(ast.NewIdent("n"))(integer),
				builders.Param(builders.Err())(builders.Error()),
			)
	})

	printer.Fprint(os.Stdout, token.NewFileSet(), i.Complete()) // print ast.Node
}
Output:

interface {
	Write(p []uint8) (n int, err error)
}

func (InterfaceBuilder) Complete

func (s InterfaceBuilder) Complete() *ast.InterfaceType

Complete returns interface definition. i.e interface{/* methods */}.

type StatementBuilder

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

StatementBuilder is block statement builder.

func NewStatementBuilder

func NewStatementBuilder() StatementBuilder

NewStatementBuilder creates new StatementBuilder.

func (StatementBuilder) Add

Add adds statements from another statement builder.

func (StatementBuilder) AddStmts

func (builder StatementBuilder) AddStmts(stmts ...ast.Stmt) StatementBuilder

AddStmts adds statements to block.

func (StatementBuilder) Assign

func (builder StatementBuilder) Assign(lhs1 ast.Expr, lhs ...ast.Expr) func(tok token.Token) func(ast.Expr, ...ast.Expr) StatementBuilder

Assign adds assign statement.

func (StatementBuilder) Block

func (builder StatementBuilder) Block(loopBody BodyFunc) StatementBuilder

Block adds block statement.

func (StatementBuilder) Branch

func (builder StatementBuilder) Branch(tok token.Token) StatementBuilder

Branch adds branch statement. token should be token.BREAK, token.CONTINUE, token.GOTO or token.FALLTHROUGH

func (StatementBuilder) BranchLabel

func (builder StatementBuilder) BranchLabel(tok token.Token, label *ast.Ident) StatementBuilder

BranchLabel adds labeled branch statement.

func (StatementBuilder) Case

func (builder StatementBuilder) Case(list []ast.Expr, caseBody BodyFunc) StatementBuilder

Case adds case statement.

func (StatementBuilder) CaseExpr

func (builder StatementBuilder) CaseExpr(expr ast.Expr, caseBody BodyFunc) StatementBuilder

CaseExpr adds case statement.

func (StatementBuilder) Complete

func (builder StatementBuilder) Complete() []ast.Stmt

Complete returns all added statements.

func (StatementBuilder) CompleteAsBlock

func (builder StatementBuilder) CompleteAsBlock() *ast.BlockStmt

Complete returns all added statements as block statement.

func (StatementBuilder) Const

func (builder StatementBuilder) Const(specs ...ast.Spec) StatementBuilder

Const adds constant declarations to block.

func (StatementBuilder) Decl

func (builder StatementBuilder) Decl(decl ast.Decl) StatementBuilder

Decl adds declaration to block.

func (StatementBuilder) Defer

func (builder StatementBuilder) Defer(call *ast.CallExpr) StatementBuilder

Defer adds defer statement.

func (StatementBuilder) Define

func (builder StatementBuilder) Define(lhs1 ast.Expr, lhs ...ast.Expr) func(ast.Expr, ...ast.Expr) StatementBuilder

Define adds define statement.

func (StatementBuilder) Expr

func (builder StatementBuilder) Expr(expr ast.Expr) StatementBuilder

Expr adds expression to block.

func (StatementBuilder) For

func (builder StatementBuilder) For(init ast.Stmt, cond ast.Expr, post ast.Stmt, loopBody BodyFunc) StatementBuilder

For adds for statement.

func (StatementBuilder) GenDecl

func (builder StatementBuilder) GenDecl(tok token.Token, specs ...ast.Spec) StatementBuilder

GenDecl adds declarations to block. tok should be token.VAR, token.CONST, token.TYPE. Also token.IMPORT can be used outside function blocks.

func (StatementBuilder) Go

func (builder StatementBuilder) Go(call *ast.CallExpr) StatementBuilder

Go adds go statement.

func (StatementBuilder) If

func (builder StatementBuilder) If(init ast.Stmt, cond ast.Expr, ifBody BodyFunc) StatementBuilder

If adds if statement.

func (StatementBuilder) IfElse

func (builder StatementBuilder) IfElse(init ast.Stmt, cond ast.Expr, ifBody, elseBody BodyFunc) StatementBuilder

IfElse adds if-else statement.

func (StatementBuilder) IfElseStmt

func (builder StatementBuilder) IfElseStmt(init ast.Stmt, cond ast.Expr, ifBody BodyFunc, elseStmt ast.Stmt) StatementBuilder

IfElseStmt adds if-else statement. elseStmt should be block or if statement.

func (StatementBuilder) Range

func (builder StatementBuilder) Range(key, value, iter ast.Expr, loopBody BodyFunc) StatementBuilder

Range adds range statement.

func (StatementBuilder) Return

func (builder StatementBuilder) Return(results ...ast.Expr) StatementBuilder

Return adds return statement.

func (StatementBuilder) Select

func (builder StatementBuilder) Select(selectBody BodyFunc) StatementBuilder

Select adds select statement.

func (StatementBuilder) SelectCase

func (builder StatementBuilder) SelectCase(comm ast.Stmt, caseBody BodyFunc) StatementBuilder

SelectCase adds case of select statement.

func (StatementBuilder) Switch

func (builder StatementBuilder) Switch(init ast.Stmt, tag ast.Expr, switchBody BodyFunc) StatementBuilder

Switch adds switch statement.

func (StatementBuilder) TypeSwitch

func (builder StatementBuilder) TypeSwitch(init, assign ast.Stmt, switchBody BodyFunc) StatementBuilder

TypeSwitch adds type-switch statement.

func (StatementBuilder) Var

func (builder StatementBuilder) Var(specs ...ast.Spec) StatementBuilder

Var adds variable declarations to block.

type StructBuilder

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

func NewStructBuilder

func NewStructBuilder() StructBuilder

NewStructBuilder creates new StructBuilder.

func (StructBuilder) AddFields

func (s StructBuilder) AddFields(fields ...*ast.Field) StructBuilder

AddFields adds fields to struct definition.

func (StructBuilder) Complete

func (s StructBuilder) Complete() *ast.StructType

Complete returns struct definition. i.e struct{/* fields */}.

func (StructBuilder) CompleteAsLit

func (s StructBuilder) CompleteAsLit(elements ...ast.Expr) *ast.CompositeLit

CompleteAsLit returns a composite literal with built struct. i.e. struct{/* fields */}{/* elements */}

type TypeBuilder

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

TypeBuilder is type declaration builder.

func NewTypeBuilder

func NewTypeBuilder(name string, typeExpr ast.Expr) TypeBuilder

NewTypeBuilder creates TypeBuilder.

func (TypeBuilder) AddMethod

func (s TypeBuilder) AddMethod(
	methodName string,
	receiver *ast.Ident,
	f func(FunctionBuilder) FunctionBuilder,
) TypeBuilder

AddMethod creates and adds an associated method.

func (TypeBuilder) AddMethodDecls

func (s TypeBuilder) AddMethodDecls(decls ...*ast.FuncDecl) TypeBuilder

AddMethodDecls adds associated methods.

func (TypeBuilder) CompleteAll

func (s TypeBuilder) CompleteAll() []ast.Decl

CompleteAll returns type declaration and all associated methods.

func (TypeBuilder) CompleteAsDecl

func (s TypeBuilder) CompleteAsDecl(tok token.Token) *ast.GenDecl

CompleteAsDecl returns a type declaration with built struct e.g type name struct{} if tok = token.TYPE. Parameter tok should be token.TYPE or token.VAR.

func (TypeBuilder) CompleteAsSpec

func (s TypeBuilder) CompleteAsSpec() *ast.TypeSpec

CompleteAsSpec returns a type declaration with built struct. i.e. name struct{/* fields */}

func (TypeBuilder) CompleteMethods

func (s TypeBuilder) CompleteMethods() []*ast.FuncDecl

CompleteMethods returns associated methods.

func (TypeBuilder) Ident

func (s TypeBuilder) Ident() *ast.Ident

Ident returns identifier of building type.

Jump to

Keyboard shortcuts

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