Initial commit.

This commit is contained in:
gmp
2018-08-03 15:08:30 -04:00
commit b880a5671d
6 changed files with 849 additions and 0 deletions
+150
View File
@@ -0,0 +1,150 @@
package main
import (
"log"
"go/ast"
"go/format"
"go/parser"
"go/token"
"golang.org/x/tools/go/ast/astutil"
"os"
"regexp"
)
type subspec struct {
r *regexp.Regexp
s string
}
var (
firstone bool
gfset *token.FileSet
fspec, tspec, nspec subspec
ntspecs []subspec
nodes *ast.File
)
type gvisit struct{}
func subs(dst *string, specs []subspec) {
for _,spec := range(specs) {
sub(dst,spec)
}
}
func sub(dst *string,spec subspec) {
if spec.r.MatchString(*dst) {
*dst = spec.r.ReplaceAllString(*dst,spec.s)
}
}
func (v *gvisit) Visit(node ast.Node) ast.Visitor {
switch n := node.(type) {
case *ast.Ident:
if n.Obj != nil && n.Obj.Kind == ast.Typ {
subs(&n.Name,ntspecs)
subs(&n.Obj.Name,ntspecs)
}
case *ast.TypeSwitchStmt:
for _,s := range(n.Body.List) {
cs, ok := s.(*ast.CaseClause); if !ok { continue }
for _,c := range(cs.List) {
ci, ok := c.(*ast.Ident); if !ok { continue }
subs(&ci.Name,ntspecs)
}
}
case *ast.TypeAssertExpr:
nt, ok := n.Type.(*ast.Ident); if !ok { return v }
subs(&nt.Name,ntspecs)
case *ast.Ellipsis:
nt, ok := n.Elt.(*ast.Ident); if !ok { return v }
subs(&nt.Name,ntspecs)
case *ast.Field:
nt, ok := n.Type.(*ast.Ident); if !ok { return v }
subs(&nt.Name,ntspecs)
case *ast.StarExpr:
nt, ok := n.X.(*ast.Ident); if !ok { return v }
subs(&nt.Name,ntspecs)
case *ast.TypeSpec:
//ast.Print(gfset,n)
case *ast.ValueSpec:
nt, ok := n.Type.(*ast.Ident); if !ok { return v }
subs(&nt.Name,ntspecs)
case *ast.ArrayType:
nt, ok := n.Elt.(*ast.Ident); if !ok { return v }
subs(&nt.Name,ntspecs)
case *ast.MapType:
nt, ok := n.Key.(*ast.Ident); if ok {
subs(&nt.Name,ntspecs)
}
nt, ok = n.Value.(*ast.Ident); if ok {
subs(&nt.Name,ntspecs)
}
case *ast.FuncDecl:
sub(&n.Name.Name,fspec)
//ast.Print(gfset,n)
}
return v
}
func init() {
firstone = true
err := os.Remove("pgen.go")
if err != nil && os.IsExist(err) {
log.Fatal("Removing pgen.go:",err)
}
}
func add(newName, typName, typ string) {
fspec = subspec{regexp.MustCompile("New"), newName}
nspec = subspec{regexp.MustCompile("_N"), typName}
tspec = subspec{regexp.MustCompile("_T"), typ}
ntspecs = []subspec{nspec,tspec}
gfset = token.NewFileSet()
f, err := parser.ParseFile(gfset, "", template, 0)
if err != nil {
log.Fatal("Parsing persist/template.T:",err)
}
var v = &gvisit{}
ast.Walk(v,f)
if firstone {
nodes = f
} else {
for _,decl := range(f.Decls) {
imp, ok := decl.(*ast.GenDecl); if ok {
if imp.Tok == token.IMPORT {
continue // skip imports
}
}
nodes.Decls = append(nodes.Decls,decl)
}
}
firstone = false
}
func newImportSpec(name string) *ast.ImportSpec {
path := &ast.BasicLit{ Value: name }
ret := &ast.ImportSpec{ Path: path }
return ret
}
func gen(wantImps []string) {
of, err := os.Create("pgen.go")
if err != nil {
log.Fatal("Cannot open pgen.go")
}
qexp := regexp.MustCompile(`"`)
for _,v := range wantImps {
v = qexp.ReplaceAllString(v,"")
astutil.AddImport(gfset, nodes, v)
}
err = format.Node(of,gfset,nodes)
if err != nil {
log.Fatal("Generate error:",err)
}
}
+124
View File
@@ -0,0 +1,124 @@
package main
import (
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"log"
"regexp"
"strings"
)
type visitor struct{}
func trimType(n *string) {
*n = pkgreg.ReplaceAllString(*n,"")
}
func (v *visitor) Visit(node ast.Node) ast.Visitor {
x, ok := node.(*ast.CallExpr); if !ok { return v }
id,ok := x.Fun.(*ast.Ident); if !ok { return v }
if !reg.MatchString(id.Name) { return v }
if len(x.Args) != 2 {
log.Fatal("Wrong number of arguments in persist_T call.")
}
var tp string
switch arg := x.Args[1].(type) {
case *ast.BasicLit:
tp = strings.ToLower(arg.Kind.String())
if tp == "float" {
tp = "float64"
}
case *ast.Ident:
if arg.Obj.Kind != ast.Var { return v }
inner := pkg.Scope().Innermost(arg.Pos())
_,obj := inner.LookupParent(arg.Obj.Name,arg.Pos())
tp = types.TypeString(obj.Type(),types.RelativeTo(pkg))
trimType(&tp)
for _, submatches := range impreg.FindAllStringSubmatchIndex(tp, -1) {
pkgname := impreg.ExpandString(make([]byte,0), "$1", tp, submatches)
needImps[string(pkgname)] = true
}
default:
}
name := reg.ReplaceAllString(id.Name,"$1")
ts[name] = tps{fun: id.Name, name: name, typ: tp}
return nil
}
type tps struct {
fun,name,typ string
}
var fset *token.FileSet
var pkg *types.Package
var ts map[string]tps
var reg *regexp.Regexp
var pkgreg *regexp.Regexp
var impreg *regexp.Regexp
var imps map[string]string
var needImps map[string]bool
func chkpkg(p *ast.Package) {
fs := make([]*ast.File,0)
for _,f := range p.Files {
fs = append(fs,f)
}
conf := types.Config{Error: func(error) {}, Importer: importer.Default()}
var err error
pkg, err = conf.Check("main", fset, fs, nil)
if err != nil {
log.Print("Check:",err)
}
var v = &visitor{}
for _,f := range fs {
for _,is := range f.Imports {
name := is.Path.Value
shortName := pkgreg.ReplaceAllString(name,"")
imps[shortName] = name
}
ast.Walk(v,f)
}
}
func init() {
reg = regexp.MustCompile("^persist([a-zA-Z_]+[a-zA-Z_0-9]*)")
pkgreg = regexp.MustCompile(`[a-zA-Z_]+[a-zA-Z_0-9\.]*/|"`)
impreg = regexp.MustCompile(`([a-zA-Z_]+[a-zA-Z_0-9]+)\.[a-zA-Z_]+[a-zA-Z_0-9]+`)
imps = make(map[string]string)
needImps = make(map[string]bool)
ts = make(map[string]tps)
fset = token.NewFileSet()
}
func main() {
// In naming imported identifiers, keep only the last part of the
// path to the imported package. This does not take named imports
// into account but should allow the code generator to find the
// right libary to import and generate valid code.
pkgs, err := parser.ParseDir(fset, ".", nil, 0)
if err != nil {
log.Fatal("Parse:",err)
}
for _,pkg := range pkgs {
chkpkg(pkg)
}
addImps := make([]string,0)
for k := range needImps {
addImps = append(addImps,imps[k])
}
for _,v := range ts {
add(v.fun, v.name, v.typ)
}
gen(addImps)
}
+36
View File
@@ -0,0 +1,36 @@
package main
const template string = `package main
import (
"time"
"unsafe"
"gitlab.wow.st/gmp/persist"
)
type Var_N persist.Var
func New(name string, xs ..._T) *Var_N {
var x _T
if len(xs) > 0 {
x = xs[0]
}
ptr := persist.New(name, x)
ret := (*Var_N)(unsafe.Pointer(ptr))
return ret
}
func (v *Var_N) Set(x _T) error {
ptr := (*persist.Var)(unsafe.Pointer(v))
return ptr.Set(x)
}
func (v *Var_N) Get(ts ...time.Time) _T {
ptr := (*persist.Var)(unsafe.Pointer(v))
return ptr.Get(ts...).(_T)
}
func (v *Var_N) History() ([]persist.TVar, error) {
ptr := (*persist.Var)(unsafe.Pointer(v))
return ptr.History()
}
`