codegen

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 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.Declare("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)
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
// }

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

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 Declare

func Declare(vars ...string) *declarationValues

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

func Err

func Err() *identifierValue

Err creates a new identifier named `err`

func FuncCall

func FuncCall(name string) *qualNameFuncValue

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

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

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

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

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

Func creates a new function code block

func (*File) GenerateGetter

func (f *File) GenerateGetter(this *thisValue, 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) *File

Imports creates a new imports block

func (*File) Method

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

Method creates a new method block

func (*File) Save

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

Save creates a new file for the generated code

type ParamValue added in v0.0.4

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

func Param

func Param(name, typeName string) *ParamValue

Param creates a new function parameter

func QualParam

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

QualParam creates a new function parameter with a package alias

func (*ParamValue) Pointer added in v0.0.4

func (p *ParamValue) Pointer() *ParamValue

Pointer turns the parameter 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 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