codegen

package module
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2021 License: MIT Imports: 4 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 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 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 build-in function `len()`

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 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) 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 *ReturnTypeDecl)

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 ...*ReturnTypeDecl) *FuncDeclaration

ReturnTypes adds return types to the function declaration

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) Name added in v0.0.7

func (p *ParamDecl) Name() string

Name gets the 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) TypeName added in v0.0.7

func (p *ParamDecl) TypeName() string

TypeName gets the type name of the parameter

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

type ReturnTypeDecl added in v0.0.5

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

func QualReturnType

func QualReturnType(alias, name string) *ReturnTypeDecl

QualReturnType creates a new return type with an alias of an imported package

func ReturnType

func ReturnType(name string) *ReturnTypeDecl

ReturnType creates a new return type for a function

func ReturnTypeError

func ReturnTypeError() *ReturnTypeDecl

ReturnTypeError create a new return type of type `error`

func (*ReturnTypeDecl) Pointer added in v0.0.5

func (r *ReturnTypeDecl) Pointer() *ReturnTypeDecl

Pointer turns the return type into a pointer value

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

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 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

Jump to

Keyboard shortcuts

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