package generator
import (
"fmt"
"os"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"unicode"
"github.com/dave/jennifer/jen"
amhelp "github.com/pancsta/asyncmachine-go/pkg/helpers"
am "github.com/pancsta/asyncmachine-go/pkg/machine"
)
type S = am .S
func WriteSchemaV3 (pkg string , schema string ) error {
if pkg == "" {
pkg = os .Getenv ("GOPACKAGE" )
}
path := strings .Split (pkg , "/" )
name := path [len (path )-1 ] + ".gen.go"
return os .WriteFile (name , []byte (schema ), 0o644 )
}
type SchemaV3 struct {
ExportName string
States am .States
Schema am .Schema
Groups any
}
func GenSchemaV3 (schemas []SchemaV3 ) string {
f := jen .NewFile ("states" )
f .HeaderComment ("Code generated by am-gen; DO NOT EDIT." )
f .HeaderComment ("//go:build tinygo" )
amPath := "github.com/pancsta/asyncmachine-go/pkg/machine"
f .ImportAlias (amPath , "am" )
f .Comment ("S is a type alias for a list of state names." )
f .Type ().Id ("S" ).Op ("=" ).Qual (amPath , "S" )
f .Line ()
suffixes := []string {}
for _ , input := range schemas {
exportName := input .ExportName
states := input .States
schema := input .Schema
groups := input .Groups
suffixStart := ToSuffix (exportName )
suffix := suffixStart
i := 2
for slices .Contains (suffixes , suffix ) {
suffix = suffixStart + strconv .Itoa (i )
i ++
}
suffixes = append (suffixes , suffix )
genStatesDef := []jen .Code {}
genGroupsDef := []jen .Code {}
genSchema := jen .Dict {}
genStatesInit := jen .Dict {}
genGroupsInit := jen .Dict {}
genStateNames := []jen .Code {}
genGroupsMap := jen .Dict {}
genGroupsNames := []jen .Code {}
for _ , name := range states .Names () {
genStateNames = append (genStateNames , jen .Lit (name ))
if name != am .StateException {
genStatesDef = append (genStatesDef , jen .Id (name ).String ())
genStatesInit [jen .Id (name )] = jen .Lit (name )
}
gen := jen .Dict {}
state := schema [name ]
if state .Auto {
gen [jen .Id ("Auto" )] = jen .Lit (true )
}
if state .Multi {
gen [jen .Id ("Multi" )] = jen .Lit (true )
}
if state .Add != nil {
genRels := []jen .Code {}
for _ , rel := range state .Add {
if slices .Contains (states .Names (), rel ) {
genRels = append (genRels , jen .Id ("ss" +suffix ).Dot (rel ))
} else {
genRels = append (genRels , jen .Lit (rel ))
}
}
gen [jen .Id ("Add" )] = jen .Id ("S" ).Values (genRels ...)
}
if state .Require != nil {
genRels := []jen .Code {}
for _ , rel := range state .Require {
if slices .Contains (states .Names (), rel ) {
genRels = append (genRels , jen .Id ("ss" +suffix ).Dot (rel ))
} else {
genRels = append (genRels , jen .Lit (rel ))
}
}
gen [jen .Id ("Require" )] = jen .Id ("S" ).Values (genRels ...)
}
if state .Remove != nil {
genRels := []jen .Code {}
for _ , rel := range state .Remove {
if slices .Contains (states .Names (), rel ) {
genRels = append (genRels , jen .Id ("ss" +suffix ).Dot (rel ))
} else {
genRels = append (genRels , jen .Lit (rel ))
}
}
gen [jen .Id ("Remove" )] = jen .Id ("S" ).Values (genRels ...)
}
if state .After != nil {
genRels := []jen .Code {}
for _ , rel := range state .After {
if slices .Contains (states .Names (), rel ) {
genRels = append (genRels , jen .Id ("ss" +suffix ).Dot (rel ))
} else {
genRels = append (genRels , jen .Lit (rel ))
}
}
gen [jen .Id ("After" )] = jen .Id ("S" ).Values (genRels ...)
}
genSchema [jen .Id ("ss" +suffix ).Dot (name )] = jen .Values (gen )
}
for _ , group := range ExtractGroupsOrdered (groups ) {
name := group .Name
gStates := group .States
genGroupsDef = append (genGroupsDef , jen .Id (name ).Id ("S" ))
genInit := []jen .Code {}
for _ , state := range gStates {
genInit = append (genInit , jen .Id ("ss" +suffix ).Dot (state ))
}
genMap := []jen .Code {}
for _ , state := range gStates {
genMap = append (genMap , jen .Lit (slices .Index (states .Names (), state )))
}
genGroupsInit [jen .Id (name )] = jen .Id ("S" ).Values (genInit ...)
genGroupsMap [jen .Lit (name )] = jen .Values (genMap ...)
genGroupsNames = append (genGroupsNames , jen .Lit (name ))
}
f .Comment ("// ///// ///// /////" )
f .Line ()
f .Comment ("// ///// " + strings .ToUpper (spaceCase (exportName )))
f .Line ()
f .Comment ("// ///// ///// /////" )
f .Line ()
f .Comment (exportName + "StatesDef contains states for " + exportName + "." )
genStatesDef = slices .Concat (
[]jen .Code {jen .Op ("*" ).Qual (amPath , "StatesBase" )}, genStatesDef )
f .Type ().Id (exportName + "StatesDef" ).Struct (genStatesDef ...)
f .Line ()
f .Comment (exportName +
"GroupsDef contains all the state groups of the " +
exportName + " state schema." )
f .Type ().Id (exportName + "GroupsDef" ).Struct (genGroupsDef ...)
f .Line ()
f .Comment (exportName +
"Schema represents all relations and properties of " +
exportName + "States." )
f .Var ().Id (exportName +"Schema" ).Op ("=" ).
Qual (amPath , "Schema" ).Values (genSchema )
f .Line ()
f .Comment ("EXPORTS AND GROUPS" )
genStatesInit [jen .Id ("StatesBase" )] = jen .Op ("&" ).Qual (amPath , "StatesBase" ).Values (jen .Dict {
jen .Id ("Exception" ): jen .Lit ("Exception" ),
})
f .Var ().Defs (
jen .Id ("ss" +suffix ).Op ("=" ).
Id (exportName +"StatesDef" ).Values (genStatesInit ),
jen .Id ("sg" +suffix ).Op ("=" ).
Id (exportName +"GroupsDef" ).Values (genGroupsInit ),
jen .Line (),
jen .Comment (exportName +"States contains all the states for the " +
exportName +" state schema." ),
jen .Id (exportName +"States" ).Op ("=" ).Id ("ss" +suffix ),
jen .Line (),
jen .Comment (exportName +"Groups contains all the state groups for the " +
exportName +" state schema." ),
jen .Id (exportName +"Groups" ).Op ("=" ).Id ("sg" +suffix ),
)
f .Line ()
f .Func ().Id ("init" ).Params ().Block (
jen .Id ("ss" +suffix ).Dot ("SetNames" ).
Call (jen .Id ("S" ).Values (genStateNames ...)),
jen .Id ("groups" ).Op (":=" ).Map (jen .String ()).
Index ().Int ().Values (genGroupsMap ),
jen .Id ("ss" +suffix ).Dot ("SetStateGroups" ).Call (
jen .Id ("groups" ),
jen .Index ().String ().Values (genGroupsNames ...),
),
)
}
return fmt .Sprintf ("%#v" , f )
}
type Group struct {
Name string
States S
}
func ExtractGroups (obj any ) map [string ]S {
result := make (map [string ]S )
extract (reflect .ValueOf (obj ), result , nil )
return result
}
func ExtractGroupsOrdered (obj any ) []Group {
result := make (map [string ]S )
order := []string {}
extract (reflect .ValueOf (obj ), result , &order )
groups := make ([]Group , 0 , len (order ))
for _ , name := range order {
groups = append (groups , Group {
Name : name ,
States : result [name ],
})
}
return groups
}
func extract(v reflect .Value , result map [string ]S , order *[]string ) {
for v .Kind () == reflect .Pointer || v .Kind () == reflect .Interface {
if v .IsNil () {
return
}
v = v .Elem ()
}
if v .Kind () != reflect .Struct {
return
}
t := v .Type ()
for i := 0 ; i < v .NumField (); i ++ {
fieldVal := v .Field (i )
fieldType := t .Field (i )
if !fieldVal .CanInterface () {
continue
}
valToInspect := fieldVal
for valToInspect .Kind () == reflect .Pointer ||
valToInspect .Kind () == reflect .Interface {
if valToInspect .IsNil () {
break
}
valToInspect = valToInspect .Elem ()
}
if !valToInspect .IsValid () {
continue
}
if valToInspect .Kind () == reflect .Struct {
extract (valToInspect , result , order )
continue
}
if slice , ok := valToInspect .Interface ().(S ); ok {
if _ , exists := result [fieldType .Name ]; !exists && order != nil {
*order = append (*order , fieldType .Name )
}
result [fieldType .Name ] = slice
}
}
}
func WriteHandlers (schema string ) error {
path := strings .Split (os .Getenv ("GOPACKAGE" ), "/" )
name := path [len (path )-1 ] + ".gen.go"
return os .WriteFile (name , []byte (schema ), 0o644 )
}
type Handlers struct {
States S
Handlers any
}
type Args struct {
}
func GenHandlers (pkg string , _ *Args , handlers ...Handlers ) string {
if pkg == "" {
pkg = os .Getenv ("GOPACKAGE" )
}
f := jen .NewFile (pkg )
f .HeaderComment ("Code generated by am-gen; DO NOT EDIT." )
f .HeaderComment ("//go:build tinygo" )
amPath := "github.com/pancsta/asyncmachine-go/pkg/machine"
f .ImportAlias (amPath , "am" )
for _ , h := range handlers {
states := h .States
v := reflect .ValueOf (h .Handlers )
if v .Kind () != reflect .Pointer || v .Elem ().Kind () != reflect .Struct {
panic ("GenHandlers expects a pointer to a struct" )
}
name := reflect .TypeOf (h .Handlers ).Elem ().Name ()
negs := jen .Dict {}
finals := jen .Dict {}
methods , err := amhelp .ListHandlers (h .Handlers , states )
if err != nil {
panic (err )
}
for _ , name := range methods {
isFinal := strings .HasSuffix (name , am .SuffixState ) ||
strings .HasSuffix (name , am .SuffixEnd )
if isFinal {
finals [jen .Lit (name )] = jen .Id ("h" ).Dot (name )
} else {
negs [jen .Lit (name )] = jen .Id ("h" ).Dot (name )
}
}
f .Func ().Id (name +"Negotiations" ).
Params (jen .Id ("h" ).Op ("*" ).Id (name )).
Map (jen .String ()).Qual (amPath , "HandlerNegotiation" ).
Block (
jen .Return (
jen .Map (jen .String ()).Qual (amPath , "HandlerNegotiation" ).Values (negs ),
),
)
f .Line ()
f .Func ().Id (name +"Finals" ).
Params (jen .Id ("h" ).Op ("*" ).Id (name )).
Map (jen .String ()).Qual (amPath , "HandlerFinal" ).
Block (
jen .Return (
jen .Map (jen .String ()).Qual (amPath , "HandlerFinal" ).Values (finals ),
),
)
}
return fmt .Sprintf ("%#v" , f )
}
func ExportedFields (obj interface {}) []string {
var fieldNames []string
t := reflect .TypeOf (obj )
if t .Kind () == reflect .Pointer {
t = t .Elem ()
}
if t .Kind () != reflect .Struct {
return fieldNames
}
for i := 0 ; i < t .NumField (); i ++ {
field := t .Field (i )
if !field .IsExported () {
continue
}
fieldNames = append (fieldNames , field .Name )
}
return fieldNames
}
func ToSuffix (s string ) string {
var builder strings .Builder
for _ , r := range s {
if unicode .IsUpper (r ) {
builder .WriteRune (r )
}
}
return builder .String ()
}
var camelCaseRe = regexp .MustCompile (`([a-z0-9])([A-Z])` )
func spaceCase(s string ) string {
spaced := camelCaseRe .ReplaceAllString (s , "$1 $2" )
return strings .ToLower (spaced )
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .