goext/bfcodegen/enum-generate.go

337 lines
9.8 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 (
"errors"
"fmt"
2023-06-07 12:36:41 +02:00
"gogs.mikescher.com/BlackForestBytes/goext"
2023-06-05 13:24:52 +02:00
"gogs.mikescher.com/BlackForestBytes/goext/cmdext"
2023-06-07 12:36:41 +02:00
"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"
2023-06-05 13:24:52 +02:00
"regexp"
"strings"
"time"
)
type EnumDefVal struct {
VarName string
Value string
Description *string
}
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
}
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
2023-09-18 10:38:25 +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_:]+"|[0-9]+))\s*(//(?P<descr>.*))?.*$`))
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
2023-06-05 13:24:52 +02:00
func GenerateEnumSpecs(sourceDir string, destFile string) error {
files, err := os.ReadDir(sourceDir)
if err != nil {
return err
}
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()
}
}
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 {
return err
}
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)
return nil
}
2023-06-05 13:24:52 +02:00
allEnums := make([]EnumDef, 0)
pkgname := ""
for _, f := range files {
fmt.Printf("========= %s =========\n\n", f.Name())
2023-09-18 10:38:25 +02:00
fileEnums, pn, err := processEnumFile(sourceDir, path.Join(sourceDir, f.Name()))
2023-06-05 13:24:52 +02:00
if err != nil {
return err
}
fmt.Printf("\n")
allEnums = append(allEnums, fileEnums...)
if pn != "" {
pkgname = pn
}
}
if pkgname == "" {
return errors.New("no package name found in any file")
}
2023-09-18 10:38:25 +02:00
err = os.WriteFile(destFile, []byte(fmtEnumOutput(newChecksum, allEnums, pkgname)), 0o755)
2023-06-05 13:24:52 +02:00
if err != nil {
return err
}
res, err := cmdext.RunCommand("go", []string{"fmt", destFile}, langext.Ptr(2*time.Second))
if err != nil {
return err
}
if res.CommandTimedOut {
fmt.Println(res.StdCombined)
return errors.New("go fmt timed out")
}
if res.ExitCode != 0 {
fmt.Println(res.StdCombined)
return errors.New("go fmt did not succeed")
}
return nil
}
2023-09-18 10:38:25 +02:00
func processEnumFile(basedir string, fn string) ([]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)
fmt.Printf("Found enum definition { '%s' -> '%s' }\n", def.EnumTypeName, def.Type)
}
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()
def := EnumDefVal{
VarName: match.GroupByName("name").Value(),
Value: match.GroupByName("value").Value(),
Description: match.GroupByNameOrEmpty("descr").ValueOrNil(),
}
found := false
for i, v := range enums {
if v.EnumTypeName == typename {
enums[i].Values = append(enums[i].Values, def)
found = true
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)
}
break
}
}
if !found {
fmt.Printf("Found non-enum value [%s] for '%s' ( looks like enum value, but no matching @enum:type )\n", def.Value, def.VarName)
}
}
}
return enums, pkgname, nil
}
2023-09-18 10:38:25 +02:00
func fmtEnumOutput(cs string, enums []EnumDef, pkgname string) string {
2023-06-07 12:36:41 +02:00
str := "// Code generated by enum-generate.go DO NOT EDIT.\n"
2023-06-05 13:24:52 +02:00
str += "\n"
str += "package " + pkgname + "\n"
str += "\n"
str += "import \"gogs.mikescher.com/BlackForestBytes/goext/langext\"" + "\n"
2023-08-09 14:40:16 +02:00
str += "import \"gogs.mikescher.com/BlackForestBytes/goext/enums\"" + "\n"
2023-06-05 13:24:52 +02:00
str += "\n"
2023-09-18 10:38:25 +02:00
str += "const ChecksumEnumGenerator = \"" + cs + "\" // GoExtVersion: " + goext.GoextVersion + "\n"
2023-06-05 13:24:52 +02:00
str += "\n"
for _, enumdef := range enums {
hasDescr := langext.ArrAll(enumdef.Values, func(val EnumDefVal) bool { return val.Description != nil })
hasStr := enumdef.Type == "string"
str += "// ================================ " + enumdef.EnumTypeName + " ================================" + "\n"
str += "//" + "\n"
2023-06-10 00:19:17 +02:00
str += "// File: " + enumdef.FileRelative + "\n"
2023-06-05 13:24:52 +02:00
str += "// StringEnum: " + langext.Conditional(hasStr, "true", "false") + "\n"
str += "// DescrEnum: " + langext.Conditional(hasDescr, "true", "false") + "\n"
str += "//" + "\n"
str += "" + "\n"
str += "var __" + enumdef.EnumTypeName + "Values = []" + enumdef.EnumTypeName + "{" + "\n"
for _, v := range enumdef.Values {
str += " " + v.VarName + "," + "\n"
}
str += "}" + "\n"
str += "" + "\n"
if hasDescr {
str += "var __" + enumdef.EnumTypeName + "Descriptions = map[" + enumdef.EnumTypeName + "]string{" + "\n"
for _, v := range enumdef.Values {
str += " " + v.VarName + ": \"" + strings.TrimSpace(*v.Description) + "\"," + "\n"
}
str += "}" + "\n"
str += "" + "\n"
}
str += "var __" + enumdef.EnumTypeName + "Varnames = map[" + enumdef.EnumTypeName + "]string{" + "\n"
for _, v := range enumdef.Values {
str += " " + v.VarName + ": \"" + v.VarName + "\"," + "\n"
}
str += "}" + "\n"
str += "" + "\n"
str += "func (e " + enumdef.EnumTypeName + ") Valid() bool {" + "\n"
str += " return langext.InArray(e, __" + enumdef.EnumTypeName + "Values)" + "\n"
str += "}" + "\n"
str += "" + "\n"
str += "func (e " + enumdef.EnumTypeName + ") Values() []" + enumdef.EnumTypeName + " {" + "\n"
str += " return __" + enumdef.EnumTypeName + "Values" + "\n"
str += "}" + "\n"
str += "" + "\n"
str += "func (e " + enumdef.EnumTypeName + ") ValuesAny() []any {" + "\n"
str += " return langext.ArrCastToAny(__" + enumdef.EnumTypeName + "Values)" + "\n"
str += "}" + "\n"
str += "" + "\n"
2023-08-09 14:40:16 +02:00
str += "func (e " + enumdef.EnumTypeName + ") ValuesMeta() []enums.EnumMetaValue {" + "\n"
2023-07-19 19:34:39 +02:00
str += " return " + enumdef.EnumTypeName + "ValuesMeta()"
2023-06-05 13:24:52 +02:00
str += "}" + "\n"
str += "" + "\n"
if hasStr {
str += "func (e " + enumdef.EnumTypeName + ") String() string {" + "\n"
str += " return string(e)" + "\n"
str += "}" + "\n"
str += "" + "\n"
}
if hasDescr {
str += "func (e " + enumdef.EnumTypeName + ") Description() string {" + "\n"
str += " if d, ok := __" + enumdef.EnumTypeName + "Descriptions[e]; ok {" + "\n"
str += " return d" + "\n"
str += " }" + "\n"
str += " return \"\"" + "\n"
str += "}" + "\n"
str += "" + "\n"
}
str += "func (e " + enumdef.EnumTypeName + ") VarName() string {" + "\n"
str += " if d, ok := __" + enumdef.EnumTypeName + "Varnames[e]; ok {" + "\n"
str += " return d" + "\n"
str += " }" + "\n"
str += " return \"\"" + "\n"
str += "}" + "\n"
str += "" + "\n"
2023-08-09 14:40:16 +02:00
str += "func (e " + enumdef.EnumTypeName + ") Meta() enums.EnumMetaValue {" + "\n"
2023-07-19 19:34:39 +02:00
if hasDescr {
2023-08-09 14:40:16 +02:00
str += " return enums.EnumMetaValue{VarName: e.VarName(), Value: e, Description: langext.Ptr(e.Description())}"
2023-07-19 19:34:39 +02:00
} else {
2023-08-09 14:40:16 +02:00
str += " return enums.EnumMetaValue{VarName: e.VarName(), Value: e, Description: nil}"
2023-07-19 19:34:39 +02:00
}
str += "}" + "\n"
str += "" + "\n"
2023-06-05 13:24:52 +02:00
str += "func Parse" + enumdef.EnumTypeName + "(vv string) (" + enumdef.EnumTypeName + ", bool) {" + "\n"
str += " for _, ev := range __" + enumdef.EnumTypeName + "Values {" + "\n"
str += " if string(ev) == vv {" + "\n"
str += " return ev, true" + "\n"
str += " }" + "\n"
str += " }" + "\n"
str += " return \"\", false" + "\n"
str += "}" + "\n"
str += "" + "\n"
str += "func " + enumdef.EnumTypeName + "Values() []" + enumdef.EnumTypeName + " {" + "\n"
str += " return __" + enumdef.EnumTypeName + "Values" + "\n"
str += "}" + "\n"
str += "" + "\n"
2023-08-09 14:40:16 +02:00
str += "func " + enumdef.EnumTypeName + "ValuesMeta() []enums.EnumMetaValue {" + "\n"
str += " return []enums.EnumMetaValue{" + "\n"
2023-06-05 13:24:52 +02:00
for _, v := range enumdef.Values {
2023-07-19 19:34:39 +02:00
str += " " + v.VarName + ".Meta(),\n"
2023-06-05 13:24:52 +02:00
}
str += " }" + "\n"
str += "}" + "\n"
str += "" + "\n"
}
return str
}