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
|
// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
// +build ignore
package main
import (
"bytes"
"go/ast"
"go/format"
"go/parser"
"go/token"
"log"
"os"
"path/filepath"
"strings"
"text/template"
)
const definedTemplate = `// Code generated by "go generate gonum.org/v1/gonum/unit/constant”; DO NOT EDIT.
// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
// +build ignore
package main
import "gonum.org/v1/gonum/unit"
var definedTypes = []struct{
unit unit.Uniter
name string
}{
{{range .}} {unit: unit.{{.}}(1), name: "unit.{{.}}"{{"}"}},
{{end}}}
func definedEquivalentOf(q unit.Uniter) string {
for _, u := range definedTypes {
if unit.DimensionsMatch(q, u.unit) {
return u.name
}
}
return ""
}
`
var defined = template.Must(template.New("defined").Parse(definedTemplate))
func main() {
names, err := filepath.Glob("../*.go")
if err != nil {
log.Fatal(err)
}
var units []string
fset := token.NewFileSet()
for _, fn := range names {
if strings.Contains(fn, "_test") {
continue
}
b, err := os.ReadFile(fn)
if bytes.Contains(b, []byte("+build ignore")) {
continue
}
f, err := parser.ParseFile(fset, fn, nil, 0)
if err != nil {
log.Fatalf("failed to parse %q: %v", fn, err) // parse error
}
if f.Name.Name != "unit" {
log.Fatalf("not parsing unit package: %q", f.Name.Name)
}
for _, d := range f.Decls {
if decl, ok := d.(*ast.GenDecl); ok {
for _, s := range decl.Specs {
if ts, ok := s.(*ast.TypeSpec); ok {
if id, ok := ts.Type.(*ast.Ident); !ok || id.Name != "float64" {
continue
}
units = append(units, ts.Name.Name)
}
}
}
}
}
f, err := os.Create("defined_types.go")
if err != nil {
log.Fatal(err)
}
defer f.Close()
var buf bytes.Buffer
err = defined.Execute(&buf, units)
if err != nil {
log.Fatal(err)
}
b, err := format.Source(buf.Bytes())
if err != nil {
f.Write(buf.Bytes()) // This is here to debug bad format.
log.Fatalf("error formatting %q: %s", f.Name(), err)
}
f.Write(b)
}
|