goext/bfcodegen/enum-generate.go

374 lines
9.1 KiB
Go
Raw Permalink Normal View History

2023-06-05 13:30:32 +02:00
package bfcodegen
2023-06-05 13:24:52 +02:00
import (
"bytes"
_ "embed"
"encoding/json"
2023-06-05 13:24:52 +02:00
"errors"
"fmt"
"go/format"
2023-06-07 12:36:41 +02:00
"gogs.mikescher.com/BlackForestBytes/goext"
"gogs.mikescher.com/BlackForestBytes/goext/cryptext"
2023-06-05 13:24:52 +02:00
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"gogs.mikescher.com/BlackForestBytes/goext/rext"
"io"
"os"
2023-06-07 12:39:21 +02:00
"path"
2023-06-10 00:19:17 +02:00
"path/filepath"
"reflect"
2023-06-05 13:24:52 +02:00
"regexp"
"strings"
"text/template"
2023-06-05 13:24:52 +02:00
)
type EnumDefVal struct {
VarName string
Value string
Description *string
Data *map[string]any
RawComment *string
2023-06-05 13:24:52 +02:00
}
type EnumDef struct {
File string
2023-06-10 00:19:17 +02:00
FileRelative string
2023-06-05 13:24:52 +02:00
EnumTypeName string
Type string
Values []EnumDefVal
}
type EnumGenOptions struct {
DebugOutput *bool
GoFormat *bool
}
2023-09-18 10:38:25 +02:00
var rexEnumPackage = rext.W(regexp.MustCompile(`^package\s+(?P<name>[A-Za-z0-9_]+)\s*$`))
2023-06-05 13:24:52 +02:00
2023-07-26 10:44:26 +02:00
var rexEnumDef = rext.W(regexp.MustCompile(`^\s*type\s+(?P<name>[A-Za-z0-9_]+)\s+(?P<type>[A-Za-z0-9_]+)\s*//\s*(@enum:type).*$`))
2023-06-05 13:24:52 +02:00
var rexEnumValueDef = rext.W(regexp.MustCompile(`^\s*(?P<name>[A-Za-z0-9_]+)\s+(?P<type>[A-Za-z0-9_]+)\s*=\s*(?P<value>("[A-Za-z0-9_:\s\-.]*"|[0-9]+))\s*(//(?P<comm>.*))?.*$`))
2023-06-05 13:24:52 +02:00
2023-09-18 10:38:25 +02:00
var rexEnumChecksumConst = rext.W(regexp.MustCompile(`const ChecksumEnumGenerator = "(?P<cs>[A-Za-z0-9_]*)"`))
2023-06-07 12:36:41 +02:00
//go:embed enum-generate.template
var templateEnumGenerateText string
func GenerateEnumSpecs(sourceDir string, destFile string, opt EnumGenOptions) error {
2023-06-05 13:24:52 +02:00
2023-06-07 12:36:41 +02:00
oldChecksum := "N/A"
if _, err := os.Stat(destFile); !os.IsNotExist(err) {
content, err := os.ReadFile(destFile)
if err != nil {
return err
}
2023-09-18 10:38:25 +02:00
if m, ok := rexEnumChecksumConst.MatchFirst(string(content)); ok {
2023-06-07 12:36:41 +02:00
oldChecksum = m.GroupByName("cs").Value()
}
}
gocode, _, changed, err := _generateEnumSpecs(sourceDir, destFile, oldChecksum, langext.Coalesce(opt.GoFormat, true), langext.Coalesce(opt.DebugOutput, false))
if err != nil {
return err
}
2023-12-07 19:39:31 +01:00
if !changed {
2023-12-07 19:36:21 +01:00
return nil
}
err = os.WriteFile(destFile, []byte(gocode), 0o755)
if err != nil {
return err
}
return nil
}
func _generateEnumSpecs(sourceDir string, destFile string, oldChecksum string, gofmt bool, debugOutput bool) (string, string, bool, error) {
files, err := os.ReadDir(sourceDir)
if err != nil {
2023-12-07 19:36:21 +01:00
return "", "", false, err
}
2023-06-07 12:45:48 +02:00
files = langext.ArrFilter(files, func(v os.DirEntry) bool { return v.Name() != path.Base(destFile) })
files = langext.ArrFilter(files, func(v os.DirEntry) bool { return strings.HasSuffix(v.Name(), ".go") })
files = langext.ArrFilter(files, func(v os.DirEntry) bool { return !strings.HasSuffix(v.Name(), "_gen.go") })
2023-06-07 12:36:41 +02:00
langext.SortBy(files, func(v os.DirEntry) string { return v.Name() })
2023-06-07 12:39:21 +02:00
newChecksumStr := goext.GoextVersion
2023-06-07 12:36:41 +02:00
for _, f := range files {
2023-06-07 12:45:48 +02:00
content, err := os.ReadFile(path.Join(sourceDir, f.Name()))
2023-06-07 12:36:41 +02:00
if err != nil {
2023-12-07 19:36:21 +01:00
return "", "", false, err
2023-06-07 12:36:41 +02:00
}
newChecksumStr += "\n" + f.Name() + "\t" + cryptext.BytesSha256(content)
}
newChecksum := cryptext.BytesSha256([]byte(newChecksumStr))
if newChecksum != oldChecksum {
fmt.Printf("[EnumGenerate] Checksum has changed ( %s -> %s ), will generate new file\n\n", oldChecksum, newChecksum)
} else {
fmt.Printf("[EnumGenerate] Checksum unchanged ( %s ), nothing to do\n", oldChecksum)
2023-12-07 19:36:21 +01:00
return "", oldChecksum, false, nil
2023-06-07 12:36:41 +02:00
}
2023-06-05 13:24:52 +02:00
allEnums := make([]EnumDef, 0)
pkgname := ""
for _, f := range files {
if debugOutput {
fmt.Printf("========= %s =========\n\n", f.Name())
}
fileEnums, pn, err := processEnumFile(sourceDir, path.Join(sourceDir, f.Name()), debugOutput)
2023-06-05 13:24:52 +02:00
if err != nil {
2023-12-07 19:36:21 +01:00
return "", "", false, err
2023-06-05 13:24:52 +02:00
}
if debugOutput {
fmt.Printf("\n")
}
2023-06-05 13:24:52 +02:00
allEnums = append(allEnums, fileEnums...)
if pn != "" {
pkgname = pn
}
}
if pkgname == "" {
2023-12-07 19:36:21 +01:00
return "", "", false, errors.New("no package name found in any file")
2023-06-05 13:24:52 +02:00
}
rdata := fmtEnumOutput(newChecksum, allEnums, pkgname)
if !gofmt {
2023-12-07 19:36:21 +01:00
return rdata, newChecksum, true, nil
2023-06-05 13:24:52 +02:00
}
fdata, err := format.Source([]byte(rdata))
2023-06-05 13:24:52 +02:00
if err != nil {
2023-12-07 19:36:21 +01:00
return "", "", false, err
2023-06-05 13:24:52 +02:00
}
2023-12-07 19:36:21 +01:00
return string(fdata), newChecksum, true, nil
2023-06-05 13:24:52 +02:00
}
func processEnumFile(basedir string, fn string, debugOutput bool) ([]EnumDef, string, error) {
2023-06-05 13:24:52 +02:00
file, err := os.Open(fn)
if err != nil {
return nil, "", err
}
defer func() { _ = file.Close() }()
bin, err := io.ReadAll(file)
if err != nil {
return nil, "", err
}
lines := strings.Split(string(bin), "\n")
enums := make([]EnumDef, 0)
pkgname := ""
for i, line := range lines {
if i == 0 && strings.HasPrefix(line, "// Code generated by") {
break
}
2023-09-18 10:38:25 +02:00
if match, ok := rexEnumPackage.MatchFirst(line); i == 0 && ok {
2023-06-05 13:24:52 +02:00
pkgname = match.GroupByName("name").Value()
continue
}
if match, ok := rexEnumDef.MatchFirst(line); ok {
2023-06-10 00:19:17 +02:00
rfp, err := filepath.Rel(basedir, fn)
if err != nil {
return nil, "", err
}
2023-06-05 13:24:52 +02:00
def := EnumDef{
File: fn,
2023-06-10 00:19:17 +02:00
FileRelative: rfp,
2023-06-05 13:24:52 +02:00
EnumTypeName: match.GroupByName("name").Value(),
Type: match.GroupByName("type").Value(),
Values: make([]EnumDefVal, 0),
}
enums = append(enums, def)
if debugOutput {
fmt.Printf("Found enum definition { '%s' -> '%s' }\n", def.EnumTypeName, def.Type)
}
2023-06-05 13:24:52 +02:00
}
2023-09-18 10:38:25 +02:00
if match, ok := rexEnumValueDef.MatchFirst(line); ok {
2023-06-05 13:24:52 +02:00
typename := match.GroupByName("type").Value()
comment := match.GroupByNameOrEmpty("comm").ValueOrNil()
var descr *string = nil
var data *map[string]any = nil
if comment != nil {
comment = langext.Ptr(strings.TrimSpace(*comment))
if strings.HasPrefix(*comment, "{") {
if v, ok := tryParseDataComment(*comment); ok {
data = &v
if anyDataDescr, ok := v["description"]; ok {
if dataDescr, ok := anyDataDescr.(string); ok {
descr = &dataDescr
}
}
} else {
descr = comment
}
} else {
descr = comment
}
}
2023-06-05 13:24:52 +02:00
def := EnumDefVal{
VarName: match.GroupByName("name").Value(),
Value: match.GroupByName("value").Value(),
RawComment: comment,
Description: descr,
Data: data,
2023-06-05 13:24:52 +02:00
}
found := false
for i, v := range enums {
if v.EnumTypeName == typename {
enums[i].Values = append(enums[i].Values, def)
found = true
if debugOutput {
if def.Description != nil {
fmt.Printf("Found enum value [%s] for '%s' ('%s')\n", def.Value, def.VarName, *def.Description)
} else {
fmt.Printf("Found enum value [%s] for '%s'\n", def.Value, def.VarName)
}
2023-06-05 13:24:52 +02:00
}
break
}
}
if !found {
if debugOutput {
fmt.Printf("Found non-enum value [%s] for '%s' ( looks like enum value, but no matching @enum:type )\n", def.Value, def.VarName)
}
2023-06-05 13:24:52 +02:00
}
}
}
return enums, pkgname, nil
}
func tryParseDataComment(s string) (map[string]any, bool) {
r := make(map[string]any)
err := json.Unmarshal([]byte(s), &r)
if err != nil {
return nil, false
}
for _, v := range r {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Ptr && rv.IsNil() {
continue
}
if rv.Kind() == reflect.Bool {
continue
}
if rv.Kind() == reflect.String {
continue
}
if rv.Kind() == reflect.Int64 {
continue
}
if rv.Kind() == reflect.Float64 {
continue
}
return nil, false
}
return r, true
}
2023-09-18 10:38:25 +02:00
func fmtEnumOutput(cs string, enums []EnumDef, pkgname string) string {
2023-06-05 13:24:52 +02:00
templ := template.New("enum-generate")
2023-06-05 13:24:52 +02:00
templ = templ.Funcs(template.FuncMap{
"boolToStr": func(b bool) string { return langext.Conditional(b, "true", "false") },
"deref": func(v *string) string { return *v },
"trimSpace": func(str string) string { return strings.TrimSpace(str) },
"hasStr": func(v EnumDef) bool { return v.Type == "string" },
"hasDescr": func(v EnumDef) bool {
return langext.ArrAll(v.Values, func(val EnumDefVal) bool { return val.Description != nil })
},
"hasData": func(v EnumDef) bool {
return len(v.Values) > 0 && langext.ArrAll(v.Values, func(val EnumDefVal) bool { return val.Data != nil })
},
"gostr": func(v any) string {
return fmt.Sprintf("%#+v", v)
},
"goobj": func(name string, v any) string {
return fmt.Sprintf("%#+v", v)
},
"godatakey": func(v string) string {
return strings.ToUpper(v[0:1]) + v[1:]
},
"godatavalue": func(v any) string {
return fmt.Sprintf("%#+v", v)
},
"godatatype": func(v any) string {
return fmt.Sprintf("%T", v)
},
"mapindex": func(v map[string]any, k string) any {
return v[k]
},
"generalDataKeys": func(v EnumDef) map[string]string {
r0 := make(map[string]int)
for _, eval := range v.Values {
for k := range *eval.Data {
if ctr, ok := r0[k]; ok {
r0[k] = ctr + 1
} else {
r0[k] = 1
}
}
}
r1 := langext.MapToArr(r0)
r2 := langext.ArrFilter(r1, func(p langext.MapEntry[string, int]) bool { return p.Value == len(v.Values) })
r3 := langext.ArrMap(r2, func(p langext.MapEntry[string, int]) string { return p.Key })
r4 := langext.ArrToKVMap(r3, func(p string) string { return p }, func(p string) string { return fmt.Sprintf("%T", (*v.Values[0].Data)[p]) })
return r4
},
})
2023-06-05 13:24:52 +02:00
templ = template.Must(templ.Parse(templateEnumGenerateText))
2023-06-05 13:24:52 +02:00
buffer := bytes.Buffer{}
2023-06-05 13:24:52 +02:00
err := templ.Execute(&buffer, langext.H{
"PkgName": pkgname,
"Checksum": cs,
"GoextVersion": goext.GoextVersion,
"Enums": enums,
})
if err != nil {
panic(err)
2023-06-05 13:24:52 +02:00
}
return buffer.String()
2023-06-05 13:24:52 +02:00
}