genbase

package module
v1.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: 13 Imported by: 12

README

genbase

genbase is a base library for code generator library construction.

Go ♥ code generation.

Description

genbase likes typewriter.

What is different between typewriter? genbase do code parsing and return wrapped ast only.

code generator must design structure for the output.

see jwg source code.

Documentation

Overview

genbase is a base library for code generator library construction.

Do you want to check usage in real world? see https://github.com/favclip/jwg , https://github.com/favclip/qbg , https://github.com/favclip/smg .

Example
package main

import (
	"fmt"

	"github.com/favclip/genbase"
)

func main() {
	p := &genbase.Parser{SkipSemanticsCheck: false}
	packageInfo, err := p.ParseStringSource("main.go", `
	package sample

	// Sample is sample!
	// +sample
	type Sample struct {
	  A string
	  B, C string
	}
	`)
	if err != nil {
		panic(err)
	}

	g := genbase.NewGenerator(packageInfo)
	g.AddImport("strings", "sg")
	g.AddImport(`"fmt"`, "")
	g.PrintHeader("sample", &[]string{})

	typeInfos := packageInfo.CollectTaggedTypeInfos("+sample")
	for _, typeInfo := range typeInfos {
		g.Printf("func (obj *%s) String() string {\n", typeInfo.Name())
		st, err := typeInfo.StructType()
		if err != nil {
			panic(err)
		}

		g.Printf("var ss []string\n")

		for _, fieldInfo := range st.FieldInfos() {
			for _, fieldName := range fieldInfo.Names {
				g.Printf("ss = append(ss, fmt.Sprintf(\"%s:%s\"))\n", fieldName.Name, "%v")
			}
		}

		g.Printf("return sg.Join(ss, \",\")\n")
		g.Printf("}\n")
	}

	generatedCode, err := g.Format()
	if err != nil {
		panic(err)
	}

	fmt.Println(string(generatedCode))
}
Output:

// Code generated by sample ; DO NOT EDIT

package sample

import (
	"fmt"
	sg "strings"
)

func (obj *Sample) String() string {
	var ss []string
	ss = append(ss, fmt.Sprintf("A:%v"))
	ss = append(ss, fmt.Sprintf("B:%v"))
	ss = append(ss, fmt.Sprintf("C:%v"))
	return sg.Join(ss, ",")
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotStructType shows argument is not ast.StructType.
	ErrNotStructType = errors.New("type is not ast.StructType")
)

Functions

func ExprToBaseTypeName

func ExprToBaseTypeName(expr ast.Expr) (string, error)

ExprToBaseTypeName convert ast.Expr to type name without "*" and "[]".

func ExprToTypeName

func ExprToTypeName(expr ast.Expr) (string, error)

ExprToTypeName convert ast.Expr to type name.

func GetKeys

func GetKeys(tag string) []string

GetKeys extracts tag value. likes reflect.StructTag.Get(string)

func IsReferenceToOtherPackage

func IsReferenceToOtherPackage(expr ast.Expr) (bool, string)

IsReferenceToOtherPackage returns expr contains reference to other packages. this function used with Generator#AddImport method.

Types

type FieldInfo

type FieldInfo ast.Field

FieldInfo is ast.Field synonym.

func (*FieldInfo) IsArray

func (f *FieldInfo) IsArray() bool

IsArray returns true if FieldInfo is array, otherwise returns false.

func (*FieldInfo) IsArrayPtr

func (f *FieldInfo) IsArrayPtr() bool

IsArrayPtr returns true if FieldInfo is pointer of array, otherwise returns false.

func (*FieldInfo) IsBool

func (f *FieldInfo) IsBool() bool

IsBool returns true if FieldInfo is bool, otherwise returns false.

func (*FieldInfo) IsFloat32

func (f *FieldInfo) IsFloat32() bool

IsFloat32 returns true if FieldInfo is float32, otherwise returns false.

func (*FieldInfo) IsFloat64

func (f *FieldInfo) IsFloat64() bool

IsFloat64 returns true if FieldInfo is float64, otherwise returns false.

func (*FieldInfo) IsInt

func (f *FieldInfo) IsInt() bool

IsInt returns true if FieldInfo is int, otherwise returns false.

func (*FieldInfo) IsInt64

func (f *FieldInfo) IsInt64() bool

IsInt64 returns true if FieldInfo is int64, otherwise returns false.

func (*FieldInfo) IsNumber

func (f *FieldInfo) IsNumber() bool

IsNumber returns true if FieldInfo is int or int64 or float32 or float64, otherwise returns false.

func (*FieldInfo) IsPtr

func (f *FieldInfo) IsPtr() bool

IsPtr returns true if FieldInfo is pointer, otherwise returns false.

func (*FieldInfo) IsPtrArray

func (f *FieldInfo) IsPtrArray() bool

IsPtrArray returns true if FieldInfo is pointer array, otherwise returns false.

func (*FieldInfo) IsPtrArrayPtr

func (f *FieldInfo) IsPtrArrayPtr() bool

IsPtrArrayPtr returns true if FieldInfo is pointer of pointer array, otherwise returns false.

func (*FieldInfo) IsString

func (f *FieldInfo) IsString() bool

IsString returns true if FieldInfo is string, otherwise returns false.

func (*FieldInfo) IsTime

func (f *FieldInfo) IsTime() bool

IsTime returns true if FieldInfo is time.Time, otherwise returns false.

func (*FieldInfo) TypeName

func (f *FieldInfo) TypeName() string

TypeName returns type name of field.

type FieldInfos

type FieldInfos []*FieldInfo

FieldInfos is []*FieldInfo synonym.

type FileInfo

type FileInfo ast.File

FileInfo is ast.File synonym.

func (*FileInfo) AstFile

func (file *FileInfo) AstFile() *ast.File

AstFile returns *ast.File.

func (*FileInfo) FindImportSpecByIdent

func (file *FileInfo) FindImportSpecByIdent(packageIdent string) *ast.ImportSpec

FindImportSpecByIdent finds *ast.ImportSpec by package ident.

type FileInfos

type FileInfos []*FileInfo

FileInfos is []*FileInfo synonym.

func (FileInfos) AstFiles

func (files FileInfos) AstFiles() []*ast.File

AstFiles returns []*ast.File.

type Generator

type Generator struct {
	Package *PackageInfo

	Buf             bytes.Buffer // Accumulated output.
	RequiredImports []*Import
}

Generator is the hub of genbase.

func NewGenerator

func NewGenerator(pkg *PackageInfo) *Generator

NewGenerator is create new Generator.

func (*Generator) AddImport

func (g *Generator) AddImport(path string, ident string)

AddImport is add package to generated code.

func (*Generator) Format

func (g *Generator) Format() ([]byte, error)

Format is apply gofmt to generated code.

func (*Generator) PrintHeader

func (g *Generator) PrintHeader(cmdName string, args *[]string)

PrintHeader is print header of generated code to buffer.

func (*Generator) Printf

func (g *Generator) Printf(format string, args ...interface{})

Printf is writing code for buffer for generated code.

type Import

type Import struct {
	Ident string // e.g. "gb"
	Path  string // e.g. "github.com/favclip/genbase"
}

Import is import statement information for generated code.

type PackageInfo

type PackageInfo struct {
	Dir   string
	Files FileInfos
	Types *types.Package
}

PackageInfo is specified package informations.

func (*PackageInfo) CollectTaggedTypeInfos

func (pkg *PackageInfo) CollectTaggedTypeInfos(tag string) TypeInfos

CollectTaggedTypeInfos collects tagged TypeInfos.

func (*PackageInfo) CollectTypeInfos

func (pkg *PackageInfo) CollectTypeInfos(typeNames []string) TypeInfos

CollectTypeInfos collects specified TypeInfos.

func (*PackageInfo) Name

func (pkg *PackageInfo) Name() string

Name returns package name.

func (*PackageInfo) TypeInfos

func (pkg *PackageInfo) TypeInfos() TypeInfos

TypeInfos is gathering TypeInfos, it included in package.

type Parser

type Parser struct {
	SkipSemanticsCheck bool
}

Parser is center of parsing strategy.

func (*Parser) ParsePackageDir

func (p *Parser) ParsePackageDir(directory string) (*PackageInfo, error)

ParsePackageDir parses specified directory.

func (*Parser) ParsePackageFiles

func (p *Parser) ParsePackageFiles(fileNames []string) (*PackageInfo, error)

ParsePackageFiles parses specified files.

func (*Parser) ParseStringSource

func (p *Parser) ParseStringSource(fileName string, code string) (*PackageInfo, error)

type StructTypeInfo

type StructTypeInfo ast.StructType

StructTypeInfo is ast.StructType synonym.

func (*StructTypeInfo) AstStructType

func (st *StructTypeInfo) AstStructType() *ast.StructType

AstStructType returns *ast.StructType.

func (*StructTypeInfo) FieldInfos

func (st *StructTypeInfo) FieldInfos() FieldInfos

FieldInfos returns FieldInfos of struct.

type TypeInfo

type TypeInfo struct {
	FileInfo         *FileInfo
	GenDecl          *ast.GenDecl
	TypeSpec         *ast.TypeSpec
	AnnotatedComment *ast.Comment
}

TypeInfo is type information gathering. try http://goast.yuroyoro.net/ with http://play.golang.org/p/ruqMMsbDaw

func (*TypeInfo) Doc

func (t *TypeInfo) Doc() *ast.CommentGroup

Doc returns *ast.CommentGroup of TypeInfo.

func (*TypeInfo) Name

func (t *TypeInfo) Name() string

Name return type name.

func (*TypeInfo) StructType

func (t *TypeInfo) StructType() (*StructTypeInfo, error)

StructType returns *StructTypeInfo.

type TypeInfos

type TypeInfos []*TypeInfo

TypeInfos is []*TypeInfo synonym.

Directories

Path Synopsis
misc

Jump to

Keyboard shortcuts

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