codegen

package module
v0.0.27 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2021 License: MIT Imports: 5 Imported by: 3

README

Basic sample

This is a code generator for Go.

package main

import (
	gen "github.com/MyNihongo/codegen"
	"fmt"
)

func main() {
	f := gen.NewFile("cool", "my-generator").Imports(
		gen.Import("fmt"),
		gen.ImportAlias("strings", "str"),
	)

	f.Func("main").Block(
		gen.Declare("val").Values(gen.QualFuncCall("str", "Title").Args(gen.String("hello, 世界!"))),
		gen.QualFuncCall("fmt", "Println").Args(gen.Identifier("val")),
	)

	if err := f.Save(`path to the file.go`); err != nil {
		fmt.Println(err)
	}
}

This code will produce the following output

// Code generated by my-generator. DO NOT EDIT.
package cool

import (
	"fmt"
	str "strings"
)

func main() {
	val := str.Title("hello, 世界!")
	fmt.Println(val)
}

Motivation

I have used Jennifer for code generation (don't get me wrong, the library is awesome 🚀), but I thought that its API is a bit too low-level.

With this library I aim to provide high-level functions with will resemble the actual Go code and will not require to write low-level statements.

  • gofmt is used for formatting
  • auto-generation comment is added automatically

Documentation

Identifiers
gen.Identifier("a")
// a

gen.Identifier("a").Pointer()
// *a

gen.Identifier("a").Address()
// &(a)
Useful identifier methods
gen.Identifier("a").Equals(gen.Identifier("b"))
// a == b

gen.Identifier("a").NotEquals(gen.Identifier("b"))
// a != b

gen.Err().IsNotNil()
// err != nil

gen.Err().IsNil()
// err == nil

gen.String("my string").IsNotEmpty()
// len("my string") != 0
Declare / assign variables
gen.Declare("val").Values(gen.String("my string"))
// val := "my string"

gen.Assign("val").Values(gen.String("my string"))
// val = "my string"

gen.Declare("val", "err").Values(FuncCall("myFunc").Args(Identifier("a")))
// val, err := myFunc(a)

gen.Assign("val", "err").Values(FuncCall("myFunc").Args(Identifier("a")))
// val, err = myFunc(a)

gen.DeclareVars(
	gen.Var("val", "string"),
	gen.QualVar("sb", "strings", "Builder"),
)
// var val string
// var sb strings.Builder

gen.Identifier("myVar").Assign(gen.Identifier("val"))
// myVar = val
Initialise structs
gen.InitStruct("myStruct").Props(
	gen.PropValue("prop", gen.String("string value")),
)
// myStruct{prop:"string value"}

gen.InitStruct("myStruct").Props(
	gen.PropValue("prop", gen.FuncCall("myFunc")),
).Address()
// &myStruct{prop:myFunc()}
Call functions
gen.FuncCall("myFunc")
// myFunc()

gen.FuncCall("myFunc").Args(
	gen.Identifier("a"),
	gen.FuncCall("anotherFunc"),
)
// myFunc(a, anotherFunc())

gen.QualFuncCall("fmt", "Println").Args(
	gen.String("string value")
)
// fmt.Println("string value")
Call go functions
gen.Len(Identifier("str"))
// len(str)
Defer functions
gen.Defer(gen.FuncCall("myFunc"))
// defer myFunc()

gen.Defer(gen.Identifier("a").Call("MyFunc"))
// defer a.MyFunc()

gen.Defer(gen.Lambda().Block(
	gen.Identifier("a").Call("MyFunc"),
).Call())
// defer func () {
//	a.MyFunc()
// }()
}
Access fields, call methods
gen.Identifier("a").
	Field("field").
	Call("myFunc").Args(String("str")).
	Field("field2")
// a.field.myFunc("str").field2

gen.FuncCall("myFunc").
	Call("anotherFunc").Args(Identifier("a")).
	Field("field")
// myFunc().anotherFunc(a).field
Pointers
gen.Identifier("a").Pointer().
	Field("field")
// (*a).field

gen.FuncCall("myFunc").Pointer().
	Field("field")
// (*myFunc()).field
Functions and methods

For methods the first argument is formatted according to Go conventions (first letter of the type in lowercase)

f := gen.NewFile("cool", "my-generator")
f.Func("myFunc")
// func myFunc() {}

f.Func("myFunc").
	Params(
		gen.Param("val", "string"),
		gen.QualParam("sb", "strings", "Builder").Pointer(),
	)
// func myFunc(val string, sb *strings.Builder) {
// }

f.Func("myFunc").ReturnTypes(
		gen.ReturnType("myType").Pointer(),
		gen.ReturnTypeError(),
	).Block(
		gen.Return(gen.Identifier("a"), gen.Nil()),
	)
// func myFunc() (*myType, error) {
//	return a, nil
// }

f.Func("myFunc").Block(
	gen.Return(),
)
// func myFunc() {
//	return
// }

Function API is available for methods as well

f := gen.NewFile("cool", "my-generator")
f.Method(
	gen.This("MyTypeName"),
	"coolMethod",
).ReturnTypes(
	gen.ReturnType("string"),
).Block(
	gen.Return(gen.Identifier("m").Field("field")),
)
// func (m MyTypeName) coolMethod() string {
//	return m.field
// }
If statements

If, else-if and else statements can be chained

gen.If(
	gen.Identifier("val").IsNotNil(),
).Block(
	gen.Return(Identifier("val")),
).Else(
	gen.Return(Nil()),
)
// if val != nil{
//	return val
// } else {
//	return nil
// }

gen.IfDecl(
	gen.Declare("val", "err").Values(gen.QualFuncCall("strconv", "Atoi").Args(gen.QualFuncCall("os", "Getenv").Args(gen.String("ENV_VAR")))),
	gen.Err().IsNil(),
).Block(
	gen.Identifier("config").Field("myVar").Assign(gen.Identifier("val")),
)
// if val, err := strconv.Atoi(os.Getenv("ENV_VAR")); err == nil {
//	config.myVar = val
// }
Structs and interfaces
f := gen.NewFile("cool", "my-generator")
f.Struct("myStruct").Props(
	gen.Property("name", "int").Pointer(),
)
// type myStruct struct {
//	name *int
// }

f.Interface("myInterface").Funcs(
	gen.FuncDecl("myFunc").Params(gen.Param("param", "int")).ReturnTypes(gen.ReturnType("string"))
)
// type myInterface interface {
//	myFunc(param int) string
// }

f.Type("myType", "int64")
// type myType int64

Utility methods

Generate a getter
f := gen.NewFile("cool", "my-generator").
f.GenerateGetter(gen.This("TypeName").Pointer(), "myField", gen.ReturnType("int"))
// func (t *TypeName) MyField() int {
//	return t.myField
// }

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Append added in v0.0.19

func Append(sliceValue Value, elementValues ...Value) *goFuncValue

Append creates a new function call of the built-in function `append`

func Assign added in v0.0.7

func Assign(vars ...string) *declarationValues

Assign creates a new assignment statement without variable values (will not compile). In order to assign values call `Values()`

func Declare

func Declare(vars ...string) *declarationValues

Declare creates a new declaration statement without variable values (will not compile). In order to assign values call `Values()`

func Err

func Err() *identifierValue

Err creates a new identifier named `err`

func For added in v0.0.19

func For(decl *declarationStmt, check Value, postStatement Stmt) *forBlock

For creates a new for-loop block

func FuncCall

func FuncCall(name string) *funcCallValue

FuncCall creates a new function call

func Identifier

func Identifier(name string) *identifierValue

Identifier creates a new identifier (variable, value, etc.)

func If

func If(val Value) *ifStmt

Creates a new if statement

func IfDecl added in v0.0.5

func IfDecl(declare *declarationStmt, val Value) *ifStmt

Creates a new if statement with variable declaration

func Import

func Import(path string) *importLine

Import creates a new import statemet without an alias

func ImportAlias

func ImportAlias(path, alias string) *importLine

ImportAlias creates a new import statement with an alias

func InitStruct added in v0.0.6

func InitStruct(structName string) *structValue

InitStruct creates a new struct initialisation

func Int

func Int(intVal int) *identifierValue

Int creates a new integer (int32) value identifier

func Lambda added in v0.0.10

func Lambda() *lambdaValue

Lambda creates a new lambda function value

func Len

func Len(val Value) *goFuncValue

Len creates a new function call of the Go built-in function `len()`

func MakeMap added in v0.0.24

func MakeMap(mapType *MapTypeDecl) *goFuncValue

MakeMap creates a new function call of the Go built-in function `make()` for an empty map

func MakeMapWithCount added in v0.0.24

func MakeMapWithCount(mapType *MapTypeDecl, count int) *goFuncValue

MakeMapWithCount creates a new function call of the Go built-in function `make()` for a map with count

func MakeSlice added in v0.0.24

func MakeSlice(sliceType *TypeDecl) *goFuncValue

MakeSlice creates a new function call of the Go built-in function `make()` for an empty slice

func MakeSliceWithCount added in v0.0.24

func MakeSliceWithCount(sliceType *TypeDecl, count int) *goFuncValue

MakeSliceWithCount creates a new function call of the Go built-in function `make()` for a slice with count

func New added in v0.0.14

func New(identifier string) *newValue

New creates a new pointer initialisation value

func Nil

func Nil() *identifierValue

Nil creates a new identifier named `nil`

func QualFuncCall

func QualFuncCall(alias, name string) *funcCallValue

QualFuncCall creates a new function call with a package alias

func QualIdentifier

func QualIdentifier(alias, name string) *identifierValue

Identifier creates a new identifier with a package alias (variable, value, etc.)

func QualNew added in v0.0.14

func QualNew(alias, identifier string) *newValue

QualNew creates a new pointer initialisation value with an alias

func QualThis

func QualThis(alias, typeName string) *thisDecl

QualThis creates a new this-parameter for a method with a package alias

func String

func String(strValue string) *identifierValue

String creates a new stiring value identifier

func This

func This(typeName string) *thisDecl

This creates a new method this-parameter for a

Types

type Block added in v0.0.3

type Block interface {
	// contains filtered or unexported methods
}

type File

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

func NewFile

func NewFile(packageName, generatorName string) *File

NewFile adds a package name and a comment that the file is auto-generated

func (*File) AddImport added in v0.0.13

func (f *File) AddImport(path string)

AddImport adds a new import statement to the import block

func (*File) AddImportAlias added in v0.0.13

func (f *File) AddImportAlias(path, alias string)

AddImportAlias adds a new import statement with its package alias to the import block

func (*File) CommentF

func (f *File) CommentF(format string, args ...interface{}) *File

CommentF creates a new comment statement according to a format

func (*File) DeclareVars added in v0.0.9

func (f *File) DeclareVars(vars ...*VarValue) Block

DeclareVars creates a new variable declaration block

func (*File) Func

func (f *File) Func(name string) *funcBlock

Func creates a new function code block

func (*File) GenerateGetter

func (f *File) GenerateGetter(this *thisDecl, fieldName string, returnType *TypeDecl)

GenerateGetter creates a public getter method according to the field

func (*File) GoString added in v0.0.2

func (f *File) GoString() string

func (*File) Imports

func (f *File) Imports(imports ...*importLine) *importsBlock

Imports creates a new imports block

func (*File) Interface added in v0.0.8

func (f *File) Interface(interfaceName string) *interfaceBlock

Interface creates a new interface declaration block

func (*File) Method

func (f *File) Method(this *thisDecl, name string) *methodBlock

Method creates a new method block

func (*File) QualType added in v0.0.8

func (f *File) QualType(typeName, alias, baseType string) *typeBlock

Type creates a new type block with a package alias

func (*File) Save

func (f *File) Save(filePath string) error

Save creates a new file for the generated code

func (*File) Struct added in v0.0.8

func (f *File) Struct(structName string) *structBlock

Struct creates a new struct block

func (*File) Type added in v0.0.8

func (f *File) Type(typeName, baseType string) *typeBlock

Type creates a new type block

type FuncDeclaration added in v0.0.8

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

func FuncDecl added in v0.0.8

func FuncDecl(funcName string) *FuncDeclaration

FuncDecl creates a new function declaration

func (*FuncDeclaration) Params added in v0.0.8

func (f *FuncDeclaration) Params(params ...*ParamDecl) *FuncDeclaration

Params adds parameters to the function declaration

func (*FuncDeclaration) ReturnTypes added in v0.0.8

func (f *FuncDeclaration) ReturnTypes(returnTypes ...*TypeDecl) *FuncDeclaration

ReturnTypes adds return types to the function declaration

type MapTypeDecl added in v0.0.24

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

func MapType added in v0.0.24

func MapType(keyType *TypeDecl, valueType *TypeDecl) *MapTypeDecl

func (*MapTypeDecl) String added in v0.0.24

func (m *MapTypeDecl) String() string

type ParamDecl added in v0.0.7

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

func Param

func Param(name, typeName string) *ParamDecl

Param creates a new function parameter

func QualParam

func QualParam(name, alias, typeName string) *ParamDecl

QualParam creates a new function parameter with a package alias

func (*ParamDecl) Array added in v0.0.26

func (p *ParamDecl) Array() *ParamDecl

Array sets the parameter to an array type

func (*ParamDecl) GetFullType added in v0.0.16

func (p *ParamDecl) GetFullType() string

GetFullType gets the full string representation of the type

func (*ParamDecl) GetIsArray added in v0.0.26

func (p *ParamDecl) GetIsArray() bool

GetIsArray gets a flag whether or not the parameter is an array or not

func (*ParamDecl) GetIsPointer added in v0.0.17

func (p *ParamDecl) GetIsPointer() bool

GetIsPointer gets a flag whether or not the parameter type is a pointer

func (*ParamDecl) GetName added in v0.0.16

func (p *ParamDecl) GetName() string

GetName gets the name of the parameter

func (*ParamDecl) GetTypeAlias added in v0.0.16

func (p *ParamDecl) GetTypeAlias() string

GetTypeAlias return an alias of the type package (if any) from there the type is imported

func (*ParamDecl) GetTypeName added in v0.0.16

func (p *ParamDecl) GetTypeName() string

GetTypeName gets the type name of the parameter

func (*ParamDecl) Pointer added in v0.0.7

func (p *ParamDecl) Pointer() *ParamDecl

Pointer turns the parameter into a pointer type

func (*ParamDecl) SetIsArray added in v0.0.26

func (p *ParamDecl) SetIsArray(isArray bool) *ParamDecl

SetIsArray sets whether or not the parameter is an array

func (*ParamDecl) SetIsPointer added in v0.0.13

func (p *ParamDecl) SetIsPointer(isPointer bool) *ParamDecl

SetIsPointer sets whether or not the parameter is a pointer

type PropertyDecl added in v0.0.8

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

func EmbeddedProperty added in v0.0.9

func EmbeddedProperty(typeName string) *PropertyDecl

EmbeddedProp crates a new embedded property

func Property added in v0.0.8

func Property(propertyName, typeName string) *PropertyDecl

Property creates a new property declaration

func QualEmbeddedProperty added in v0.0.9

func QualEmbeddedProperty(alias, typeName string) *PropertyDecl

QualEmbeddedProperty creates a new embedded property with a package alias

func QualProperty added in v0.0.8

func QualProperty(propertyName, alias, typeName string) *PropertyDecl

QualProperty creates a new property declaration with a package alias

func (*PropertyDecl) Pointer added in v0.0.8

func (p *PropertyDecl) Pointer() *PropertyDecl

Pointer turns the property into a pointer type

func (*PropertyDecl) SetIsPointer added in v0.0.13

func (p *PropertyDecl) SetIsPointer(isPointer bool) *PropertyDecl

SetIsPointer sets whether or not a property is a pointer

type Stmt added in v0.0.3

type Stmt interface {
	// contains filtered or unexported methods
}

func DeclareVars added in v0.0.5

func DeclareVars(vars ...*VarValue) Stmt

DeclareVars creates a new variable declaration statement

func Defer added in v0.0.10

func Defer(call caller) Stmt

Defer creates a new defer statement

func Return

func Return(values ...Value) Stmt

Return creates a new return statement

func Stmts added in v0.0.27

func Stmts(stmts []Stmt) Stmt

Stmts combines multiple statements into a single one

type StructPropertyValue added in v0.0.6

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

func PropValue added in v0.0.6

func PropValue(propertyName string, propertyValue Value) *StructPropertyValue

PropValue creates a new property with its value

type TypeDecl added in v0.0.19

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

func QualType added in v0.0.19

func QualType(alias, name string) *TypeDecl

QualType creates a new type with an alias of an imported package

func ReturnTypeError

func ReturnTypeError() *TypeDecl

ReturnTypeError create a new type of type `error`

func Type added in v0.0.19

func Type(name string) *TypeDecl

Type creates a new type for a function

func (*TypeDecl) Array added in v0.0.19

func (t *TypeDecl) Array() *TypeDecl

Array converts the type to the array type

func (*TypeDecl) GetIsPointer added in v0.0.19

func (t *TypeDecl) GetIsPointer() bool

GetIsPointer gets a flag whether or not the type is a pointer

func (*TypeDecl) GetTypeAlias added in v0.0.19

func (t *TypeDecl) GetTypeAlias() string

GetTypeAlias gets a type alias (if any) of the return declaration

func (*TypeDecl) GetTypeName added in v0.0.19

func (t *TypeDecl) GetTypeName() string

GetTypeName gets a type name of the return declaration

func (*TypeDecl) Pointer added in v0.0.19

func (t *TypeDecl) Pointer() *TypeDecl

Pointer turns the type into a pointer value

func (*TypeDecl) SetIsArray added in v0.0.20

func (t *TypeDecl) SetIsArray(isArray bool) *TypeDecl

SetIsArray sets whether or not the type is an array

func (*TypeDecl) SetIsPointer added in v0.0.19

func (t *TypeDecl) SetIsPointer(isPointer bool) *TypeDecl

SetIsPointer sets whether or not the type is a pointer

type Value added in v0.0.3

type Value interface {
	// contains filtered or unexported methods
}

type VarValue added in v0.0.5

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

func QualVar added in v0.0.5

func QualVar(varName, typeAlias, typeName string) *VarValue

QualVar creates a new variable with a type name and its alias

func Var added in v0.0.5

func Var(varName, typeName string) *VarValue

Var creates a new variable with a type name

func (*VarValue) Pointer added in v0.0.5

func (v *VarValue) Pointer() *VarValue

Pointer turns the variable type into a pointer

func (*VarValue) SetIsPointer added in v0.0.13

func (v *VarValue) SetIsPointer(isPointer bool) *VarValue

SetIsPointer sets whether or not a variable is a pointer

Jump to

Keyboard shortcuts

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