/
main.go
336 lines (299 loc) · 7.86 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright ©2017 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command root-gen-datareader generates a Go struct to easily read the
// event data type stored inside a Tree.
//
// Example:
//
// $> root-gen-datareader -t tree testdata/small-flat-tree.root
// // automatically generated by root-gen-datareader.
// // DO NOT EDIT.
//
// package event
//
// type Data struct {
// ROOT_Int32 int32 `groot:"Int32"`
// ROOT_Int64 int64 `groot:"Int64"`
// ROOT_UInt32 int32 `groot:"UInt32"`
// ROOT_UInt64 int64 `groot:"UInt64"`
// ROOT_Float32 float32 `groot:"Float32"`
// ROOT_Float64 float64 `groot:"Float64"`
// ROOT_ArrayInt32 [10]int32 `groot:"ArrayInt32[10]"`
// ROOT_ArrayInt64 [10]int64 `groot:"ArrayInt64[10]"`
// ROOT_ArrayInt32 [10]int32 `groot:"ArrayInt32[10]"`
// ROOT_ArrayInt64 [10]int64 `groot:"ArrayInt64[10]"`
// ROOT_ArrayFloat32 [10]float32 `groot:"ArrayFloat32[10]"`
// ROOT_ArrayFloat64 [10]float64 `groot:"ArrayFloat64[10]"`
// ROOT_N int32 `groot:"N"`
// ROOT_SliceInt32 []int32 `groot:"SliceInt32[N]"`
// ROOT_SliceInt64 []int64 `groot:"SliceInt64[N]"`
// ROOT_SliceInt32 []int32 `groot:"SliceInt32[N]"`
// ROOT_SliceInt64 []int64 `groot:"SliceInt64[N]"`
// ROOT_SliceFloat32 []float32 `groot:"SliceFloat32[N]"`
// ROOT_SliceFloat64 []float64 `groot:"SliceFloat64[N]"`
// }
package main // import "go-hep.org/x/hep/groot/cmd/root-gen-datareader"
import (
"bytes"
"flag"
"fmt"
"go/format"
"io"
"log"
"os"
"reflect"
"strings"
"text/template"
"go-hep.org/x/hep/groot"
"go-hep.org/x/hep/groot/riofs"
"go-hep.org/x/hep/groot/rtree"
)
func main() {
log.SetPrefix("root-gen-datareader: ")
log.SetFlags(0)
var (
treeName = flag.String("t", "tree", "name of the tree to inspect")
pkgName = flag.String("p", "event", "name of the package where to generate the data model")
outName = flag.String("o", "", "name of the file where to store the generated data model (STDOUT)")
dataReader = flag.Bool("reader", false, "generate data reader code")
verbose = flag.Bool("v", false, "enable verbose mode")
)
flag.Parse()
if flag.NArg() <= 0 {
log.Printf("missing input file name")
flag.Usage()
flag.PrintDefaults()
os.Exit(1)
}
ctx := newContext(*pkgName, flag.Arg(0), *treeName, *dataReader, *verbose)
var o io.Writer = os.Stdout
if *outName != "" {
f, err := os.Create(*outName)
if err != nil {
log.Fatalf("could not create output file: %+v", err)
}
defer f.Close()
o = f
}
err := process(o, ctx)
if err != nil {
log.Fatalf("could not generate data-reader: %+v", err)
}
}
func process(w io.Writer, ctx *Context) error {
f, err := groot.Open(ctx.File)
if err != nil {
log.Fatal(err)
}
defer f.Close()
obj, err := riofs.Dir(f).Get(ctx.Tree)
if err != nil {
return fmt.Errorf("could not retrieve tree %q: %w", ctx.Tree, err)
}
var (
tree = obj.(rtree.Tree)
rvars = rtree.NewReadVars(tree)
)
ctx.printf("entries: %v\n", tree.Entries())
for i, rvar := range rvars {
ctx.printf("rvar[%03d]: %q (%v)", i, rvar.Name, reflect.Indirect(reflect.ValueOf(rvar.Value)).Kind())
rv := reflect.Indirect(reflect.ValueOf(rvar.Value))
switch rv.Kind() {
case reflect.Struct:
def := structDefFrom(ctx, rvar.Name, reflect.Indirect(reflect.ValueOf(rvar.Value)).Type())
ctx.Defs[rvar.Name] = def
ctx.DataReader.Fields = append(
ctx.DataReader.Fields,
FieldDef{
Name: goName(rvar.Name),
Tag: rvar.Name,
VarName: rvar.Name,
Type: def.Name,
},
)
case reflect.Array:
ctx.DataReader.Fields = append(
ctx.DataReader.Fields,
FieldDef{
Name: goName(rvar.Name),
Tag: fmt.Sprintf("%s[%d]", rvar.Name, rv.Type().Len()),
VarName: rvar.Name,
Type: fmt.Sprintf("%T", rv.Interface()),
},
)
ctx.checkType(rv.Type().Elem())
case reflect.Slice:
ctx.DataReader.Fields = append(
ctx.DataReader.Fields,
FieldDef{
Name: goName(rvar.Name),
Tag: rvar.Name,
VarName: rvar.Name,
Type: fmt.Sprintf("%T", rv.Interface()),
},
)
ctx.checkType(rv.Type().Elem())
default:
ctx.DataReader.Fields = append(
ctx.DataReader.Fields,
FieldDef{
Name: goName(rvar.Name),
Tag: rvar.Name,
VarName: rvar.Name,
Type: fmt.Sprintf("%T", rv.Interface()),
},
)
ctx.checkType(rv.Type())
}
}
delete(ctx.Defs, "DataReader")
err = ctx.genCode(w)
if err != nil {
return fmt.Errorf("could not generate reader code: %w", err)
}
return nil
}
func goName(s string) string {
return "ROOT_" + s
}
// StructDef models a TTree content as a Go struct, where each TBranch
// of the tree is translated as a field of the struct.
type StructDef struct {
Name string
Fields []FieldDef
}
// FieldDef describes a Go struct field, corresponding to a TTree's branch.
type FieldDef struct {
Name string
Type string
VarName string
Tag string
}
// Context holds together various informations about the TTree being processed.
type Context struct {
Package string
Imports map[string]int
DataReader *StructDef
Defs map[string]*StructDef
GenDataReader bool
File string
Tree string
Verbose bool
}
func newContext(pkg, file, tree string, dataReader, verbose bool) *Context {
ctx := &Context{
Package: pkg,
Imports: make(map[string]int),
Defs: map[string]*StructDef{
"DataReader": {
Name: "DataReader",
Fields: nil,
},
},
GenDataReader: dataReader,
File: file,
Tree: tree,
Verbose: verbose,
}
ctx.DataReader = ctx.Defs["DataReader"]
if dataReader {
ctx.Imports["go-hep.org/x/hep/groot/rtree"]++
}
return ctx
}
func (ctx *Context) printf(format string, args ...interface{}) {
if ctx.Verbose {
log.Printf(format, args...)
}
}
func (ctx *Context) genCode(w io.Writer) error {
t := template.New("top")
template.Must(t.Parse(codeTmpl))
buf := new(bytes.Buffer)
err := t.Execute(buf, ctx)
if err != nil {
return err
}
src, err := format.Source(buf.Bytes())
if err != nil {
log.Printf("source:\n%s\n", buf.Bytes())
log.Printf("error: %+v", err)
return err
}
_, err = w.Write(src)
return err
}
const codeTmpl = `// automatically generated by root-gen-datareader.
// DO NOT EDIT.
package {{.Package}}
{{$length := len .Imports}}{{if gt $length 0}}
import (
{{range $key, $value := .Imports}}
"{{$key}}"
{{- end}}
)
{{- end}}
{{range .Defs}}
type {{.Name}} struct {
{{range .Fields}} {{.Name}} {{.Type}} ` + "`groot:\"{{.Tag}}\"`" + `
{{end}}}
{{end}}
{{with .DataReader}}
// Data is the data contained in a rtree.Tree.
type Data struct {
{{ range .Fields}} {{.Name}} {{.Type}} ` + "`groot:\"{{.Tag}}\"`" + `
{{ end}}}
{{end}}
{{if .GenDataReader}}
{{with .DataReader}}
type DataReader struct {
Data Data
Tree rtree.Tree
Reader *rtree.Reader
}
{{end}}
{{end}}
`
func structDefFrom(ctx *Context, name string, rt reflect.Type) *StructDef {
def := StructDef{
Name: name,
Fields: make([]FieldDef, rt.NumField()),
}
for i := range def.Fields {
ft := rt.Field(i)
def.Fields[i] = fieldDefFrom(ctx, ft)
}
return &def
}
func fieldDefFrom(ctx *Context, typ reflect.StructField) FieldDef {
tag := typ.Tag.Get("groot")
ctx.checkType(typ.Type)
switch typ.Type.Kind() {
case reflect.Struct:
branch := tag
if i := strings.Index(branch, "["); i > 0 {
branch = branch[:i]
}
ctx.Defs[branch] = structDefFrom(ctx, branch, typ.Type)
return FieldDef{
Name: typ.Name,
Type: branch,
VarName: tag,
Tag: tag,
}
default:
return FieldDef{
Name: typ.Name,
Type: typ.Type.String(),
VarName: tag,
Tag: tag,
}
}
}
func (ctx *Context) checkType(typ reflect.Type) {
pkg := typ.PkgPath()
if pkg != "" {
ctx.Imports[pkg]++
}
}