-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpkg.go
94 lines (76 loc) · 1.7 KB
/
pkg.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
package memlayout
import (
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"go/types"
"path/filepath"
"golang.org/x/tools/go/loader"
)
// StructsFromFile returns the structs in the file with the given content.
func StructsFromFile(filename string, content []byte) ([]Struct, error) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filename, content, 0)
if err != nil {
return nil, fmt.Errorf("unable to parse file %s: %s", filename, err)
}
files, err := filepath.Glob(filepath.Join(filepath.Dir(filename), "*.go"))
if err != nil {
return nil, err
}
conf := loader.Config{
Build: &build.Default,
}
if _, err = conf.FromArgs(files, true); err != nil {
return nil, err
}
lprog, err := conf.Load()
if err != nil {
return nil, err
}
scope := lprog.InitialPackages()[0].Pkg.Scope()
var result []Struct
for _, name := range scope.Names() {
obj := scope.Lookup(name)
s, ok := structFromObject(obj)
if !ok {
continue
}
result = append(result, Struct{
Name: obj.Name(),
Pos: posOf(fset, f, obj.Name()),
Fields: Fields(s),
})
}
return result, nil
}
func structFromObject(obj types.Object) (*types.Struct, bool) {
named, ok := obj.Type().(*types.Named)
if !ok {
return nil, false
}
s, ok := named.Underlying().(*types.Struct)
return s, ok
}
func posOf(fset *token.FileSet, f *ast.File, name string) Pos {
for _, d := range f.Decls {
gd, ok := d.(*ast.GenDecl)
if !ok {
continue
}
for _, spec := range gd.Specs {
ts, ok := spec.(*ast.TypeSpec)
if !ok || ts.Name.Name != name {
continue
}
fi := fset.File(ts.Pos())
return Pos{
Start: fi.Line(ts.Pos()),
End: fi.Line(ts.End()),
}
}
}
return Pos{}
}