-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
218 lines (191 loc) · 4.58 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Constrainer is a tool to generate acces methods from virtual tables types definitions.
// This reduces toil in what is mostly a routine work.
//
// The code follows the semantics of the `vtab` mini-language, and makes sure that:
//
// - required fields have an access method with the right type
// - filtered fields have an access method with two forms (T, bool)
// - non-filtered fields do not have an access method
package main
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/format"
"go/token"
"go/types"
"log"
"os"
"reflect"
"strings"
"text/template"
"golang.org/x/tools/go/packages"
)
var tpl = template.Must(template.New("").Parse(`
func (r {{.VTable}}) Get{{.Field}}(cs sqlite.Constraints) (v {{.RType}}, {{if not .Required}}ok bool{{end}}) {
match := 0
for _, c := range cs {
if c.Column == "{{.Column}}" {
if c.Operation == sqlite.ConstraintEQ {
{{- if .Accessor}}
v = c.{{.Accessor}}()
{{- else}}
v = c.Value.({{.RType}})
{{- end}}
match++
} else {
panic("Value getter with non-constrained values")
}
}
}
{{if .Required}}
if match != 1 {
panic("field should have been filtered")
}
return v
{{- else -}}
if match == 0 {
return v, false
}
if match == 1 {
return v, true
}
panic("more than one match")
{{- end -}}
}
`))
type accessor struct {
VTable string
Field string
Column string
RType string
Accessor string
Required bool
}
func main() {
flag.Parse()
typename := flag.Arg(0)
pkg, err := packages.Load(&packages.Config{
Fset: token.NewFileSet(),
Mode: packages.NeedName | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedSyntax,
Tests: false,
}, ".")
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
fmt.Fprint(&buf, "// Code generated by the constrainer; DO NOT EDIT.\n//go:build linux\n\n")
imports := map[string]struct{}{
"github.com/TroutSoftware/sqlite": {},
}
var gens []accessor
var loc token.Position
for _, pkg := range pkg {
for _, f := range pkg.Syntax {
ast.Inspect(f, func(n ast.Node) bool {
ts, ok := n.(*ast.TypeSpec)
if !ok {
return true
}
stdef, ok := pkg.TypesInfo.Defs[ts.Name].Type().Underlying().(*types.Struct)
if !ok {
return true
}
if ts.Name.Name != typename {
return true
}
loc = pkg.Fset.Position(n.Pos())
fmt.Fprintf(&buf, "package %s\n", pkg.Name)
for i := 0; i < stdef.NumFields(); i++ {
tags := strings.Split(reflect.StructTag(stdef.Tag(i)).Get("vtab"), ",")
acc := accessor{
VTable: ts.Name.Name,
Field: stdef.Field(i).Name(),
Column: tags[0],
}
include := false
for _, v := range tags[1:] {
if v == "required" {
acc.Required = true
include = true
}
if v == "filtered" || v == "hidden" {
include = true
}
}
if !include {
continue
}
qname := types.TypeString(stdef.Field(i).Type(), rel(pkg.Types))
if pkgname(stdef.Field(i).Type()) != pkg.PkgPath {
imports[pkgname(stdef.Field(i).Type())] = struct{}{}
}
acc.RType = qname
switch qname {
default:
case "bool":
acc.Accessor = "ValueBool"
case "[]byte":
acc.Accessor = "ValueBytes"
case "string":
acc.Accessor = "ValueString"
case "int":
acc.Accessor = "ValueInt"
}
gens = append(gens, acc)
}
return true
})
}
}
if len(gens) == 0 {
fmt.Fprintf(os.Stderr, "<warning>: no fields are `required`, `filtered` or `hidden` in type %s (in %s). No accessors will be generated.\n", typename, loc)
return
}
fmt.Fprint(&buf, "import (\n")
for i := range imports {
if i == "" {
continue
}
fmt.Fprintf(&buf, "%q\n", i)
}
fmt.Fprint(&buf, ")\n")
for _, g := range gens {
if err := tpl.Execute(&buf, g); err != nil {
log.Fatal(err)
}
}
out, err := format.Source(buf.Bytes())
if err != nil {
log.Fatalf("invalid code generated: %s\n\n%s", err, buf.Bytes())
}
if err := os.WriteFile(strings.ToLower(typename)+"_access.go", out, 0644); err != nil {
log.Fatal("cannot write generated file", err)
}
}
func rel(pkg *types.Package) types.Qualifier {
if pkg == nil {
return nil
}
return func(other *types.Package) string {
if pkg == other {
return "" // same package; unqualified
}
return other.Name()
}
}
func pkgname(t types.Type) string {
switch t := t.(type) {
case *types.Pointer:
return pkgname(t.Elem())
case *types.Named:
return t.Obj().Pkg().Path()
case *types.Basic:
return ""
case *types.Slice:
return pkgname(t.Elem())
default:
panic("not implemented" + t.String())
}
}