-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorator.go
333 lines (292 loc) · 8.56 KB
/
decorator.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
package decorator
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"os"
"strings"
"github.com/dave/dst"
"github.com/dave/dst/decorator/resolver"
"github.com/dave/dst/decorator/resolver/gotypes"
"golang.org/x/tools/go/packages"
)
// New returns a new package decorator
func New(fset *token.FileSet) *Decorator {
return &Decorator{
Map: newMap(),
Filenames: map[*dst.File]string{},
Fset: fset,
}
}
// NewWithImports returns a new package decorator with import management attributes set.
func NewWithImports(pkg *packages.Package) *Decorator {
return &Decorator{
Map: newMap(),
Filenames: map[*dst.File]string{},
Fset: pkg.Fset,
Path: pkg.PkgPath,
Resolver: &gotypes.IdentResolver{
Info: pkg.TypesInfo,
},
}
}
type Decorator struct {
Map
Filenames map[*dst.File]string // Source file names
Fset *token.FileSet
Path string // local package path, used to ensure the local path is not set in idents
canonical string // local package path, de-vendored, set in DecorateNode
// If a Resolver is provided, it is used to resolve Ident nodes. During decoration, remote
// identifiers (e.g. usually part of a qualified identifier SelectorExpr, but sometimes on
// their own for dot-imported packages) are updated with the path of the package they are
// imported from.
Resolver resolver.IdentResolver
}
// Parse uses parser.ParseFile to parse and decorate a Go source file. The src parameter should
// be string, []byte, or io.Reader.
func (d *Decorator) Parse(src interface{}) (*dst.File, error) {
return d.ParseFile("", src, parser.ParseComments)
}
// ParseFile uses parser.ParseFile to parse and decorate a Go source file. The ParseComments flag is
// added to mode if it doesn't exist.
func (d *Decorator) ParseFile(filename string, src interface{}, mode parser.Mode) (*dst.File, error) {
// If ParseFile returns an error and also a non-nil file, the errors were just parse errors so
// we should continue decorating the file and return the error.
f, err := parser.ParseFile(d.Fset, filename, src, mode|parser.ParseComments)
if err != nil && f == nil {
return nil, err
}
return d.DecorateFile(f), err
}
// ParseDir uses parser.ParseDir to parse and decorate a directory containing Go source. The
// ParseComments flag is added to mode if it doesn't exist.
func (d *Decorator) ParseDir(dir string, filter func(os.FileInfo) bool, mode parser.Mode) (map[string]*dst.Package, error) {
pkgs, err := parser.ParseDir(d.Fset, dir, filter, mode|parser.ParseComments)
if err != nil {
return nil, err
}
out := map[string]*dst.Package{}
for k, v := range pkgs {
out[k] = d.DecorateNode(v).(*dst.Package)
}
return out, nil
}
func (d *Decorator) DecorateFile(f *ast.File) *dst.File {
return d.DecorateNode(f).(*dst.File)
}
// Decorate decorates an ast.Node and returns a dst.Node
func (d *Decorator) DecorateNode(n ast.Node) dst.Node {
d.canonical = stripVendor(d.Path)
fd := d.newFileDecorator()
if f, ok := n.(*ast.File); ok {
fd.file = f
}
fd.fragment(n)
fd.link()
out := fd.decorateNode(nil, "", n)
//fmt.Println("\nFragments:")
//fd.debug(os.Stdout)
//fmt.Println("\nDecorator:")
//debug(os.Stdout, out)
// Populate Info with filenames if we're decorating a File or Package.
switch n := n.(type) {
case *ast.Package:
for k, v := range n.Files {
d.Filenames[d.Dst.Nodes[v].(*dst.File)] = k
}
case *ast.File:
d.Filenames[out.(*dst.File)] = d.Fset.File(n.Pos()).Name()
}
return out
}
func (pd *Decorator) newFileDecorator() *fileDecorator {
return &fileDecorator{
Decorator: pd,
startIndents: map[ast.Node]int{},
endIndents: map[ast.Node]int{},
before: map[ast.Node]dst.SpaceType{},
after: map[ast.Node]dst.SpaceType{},
decorations: map[ast.Node]map[string][]string{},
}
}
type fileDecorator struct {
*Decorator
file *ast.File // file we're decorating in for import name resolution - can be nil if we're just decorating an isolated node
cursor int
fragments []fragment
startIndents map[ast.Node]int
endIndents map[ast.Node]int
before, after map[ast.Node]dst.SpaceType
decorations map[ast.Node]map[string][]string
}
type decorationInfo struct {
name string
decs []string
}
func (f *fileDecorator) resolvePath(parent ast.Node, typ string, id *ast.Ident) string {
if f.Resolver == nil {
return ""
}
// The parent field type (typ) for all idents is either "Ident" or "Expr".
//
// If the parent field type is Ident, there is no possibility of this field holding a
// SelectorExpr, so this ident cannot possibly be a qualified identifier. We avoid resolving
// the Path for these idents.
//
// Inside SelectorExpr is a special case where the logic is reversed. We avoid setting Path for
// X (Expr) but set it for Sel (Ident).
if _, sel := parent.(*ast.SelectorExpr); (typ == "Ident" && !sel) || (typ == "Expr" && sel) {
return ""
}
path, err := f.Resolver.ResolveIdent(f.file, parent, id)
if err != nil {
panic(err)
}
if path == f.canonical {
return ""
}
return path
}
func stripVendor(path string) string {
findVendor := func(path string) (index int, ok bool) {
// Two cases, depending on internal at start of string or not.
// The order matters: we must return the index of the final element,
// because the final one is where the effective import path starts.
switch {
case strings.Contains(path, "/vendor/"):
return strings.LastIndex(path, "/vendor/") + 1, true
case strings.HasPrefix(path, "vendor/"):
return 0, true
}
return 0, false
}
i, ok := findVendor(path)
if !ok {
return path
}
return path[i+len("vendor/"):]
}
func (f *fileDecorator) decorateObject(o *ast.Object) *dst.Object {
if o == nil {
return nil
}
if do, ok := f.Dst.Objects[o]; ok {
return do
}
/*
// An Object describes a named language entity such as a package,
// constant, type, variable, function (incl. methods), or label.
//
// The Data fields contains object-specific data:
//
// Kind Data type Data value
// Pkg *Scope package scope
// Con int iota for the respective declaration
//
type Object struct {
Kind ObjKind
Name string // declared name
Decl interface{} // corresponding Field, XxxSpec, FuncDecl, LabeledStmt, AssignStmt, Scope; or nil
Data interface{} // object-specific data; or nil
Type interface{} // placeholder for type information; may be nil
}
*/
out := &dst.Object{}
f.Dst.Objects[o] = out
f.Ast.Objects[out] = o
out.Kind = dst.ObjKind(o.Kind)
out.Name = o.Name
switch decl := o.Decl.(type) {
case *ast.Scope:
out.Decl = f.decorateScope(decl)
case ast.Node:
out.Decl = f.decorateNode(nil, "", decl)
case nil:
default:
panic(fmt.Sprintf("o.Decl is %T", o.Decl))
}
// TODO: I believe Data is either a *Scope or an int. We will support both and panic if something else if found.
switch data := o.Data.(type) {
case int:
out.Data = data
case *ast.Scope:
out.Data = f.decorateScope(data)
case ast.Node:
out.Data = f.decorateNode(nil, "", data)
case nil:
default:
panic(fmt.Sprintf("o.Data is %T", o.Data))
}
return out
}
func (f *fileDecorator) decorateScope(s *ast.Scope) *dst.Scope {
if s == nil {
return nil
}
if ds, ok := f.Dst.Scopes[s]; ok {
return ds
}
/*
// A Scope maintains the set of named language entities declared
// in the scope and a link to the immediately surrounding (outer)
// scope.
//
type Scope struct {
Outer *Scope
Objects map[string]*Object
}
*/
out := &dst.Scope{}
f.Dst.Scopes[s] = out
f.Ast.Scopes[out] = s
out.Outer = f.decorateScope(s.Outer)
out.Objects = map[string]*dst.Object{}
for k, v := range s.Objects {
out.Objects[k] = f.decorateObject(v)
}
return out
}
func debug(w io.Writer, file dst.Node) {
var result string
nodeType := func(n dst.Node) string {
return strings.Replace(fmt.Sprintf("%T", n), "*dst.", "", -1)
}
dst.Inspect(file, func(n dst.Node) bool {
if n == nil {
return false
}
var out string
before, after, infos := getDecorationInfo(n)
switch before {
case dst.NewLine:
out += " [New line before]"
case dst.EmptyLine:
out += " [Empty line before]"
}
for _, info := range infos {
if len(info.decs) > 0 {
var values string
for i, dec := range info.decs {
if i > 0 {
values += " "
}
values += fmt.Sprintf("%q", dec)
}
out += fmt.Sprintf(" [%s %s]", info.name, values)
}
}
switch after {
case dst.NewLine:
out += " [New line after]"
case dst.EmptyLine:
out += " [Empty line after]"
}
if out != "" {
result += nodeType(n) + out + "\n"
}
return true
})
fmt.Fprint(w, result)
}