-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdce.go
More file actions
210 lines (189 loc) · 5.12 KB
/
dce.go
File metadata and controls
210 lines (189 loc) · 5.12 KB
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
// Package dce implements dead code elimination for generated Go source files.
// It removes top-level declarations from the runtime section that are not
// reachable from non-runtime code.
package dce
import (
"go/ast"
"go/parser"
"go/printer"
"go/token"
"strings"
)
const (
runtimeBeginMarker = "// --- oapi-runtime begin ---"
runtimeEndMarker = "// --- oapi-runtime end ---"
)
// EliminateDeadCode parses a generated Go source file, identifies runtime
// declarations (between the oapi-runtime markers), and removes any that are
// not reachable from non-runtime code.
//
// The output is re-printed via go/printer, so callers should run goimports
// afterward to normalize formatting.
func EliminateDeadCode(src string) (string, error) {
beginIdx := strings.Index(src, runtimeBeginMarker)
endIdx := strings.Index(src, runtimeEndMarker)
if beginIdx == -1 || endIdx == -1 {
return src, nil
}
// Replace markers with spaces so byte offsets are preserved for AST.
cleanSrc := strings.Replace(src, runtimeBeginMarker, strings.Repeat(" ", len(runtimeBeginMarker)), 1)
cleanSrc = strings.Replace(cleanSrc, runtimeEndMarker, strings.Repeat(" ", len(runtimeEndMarker)), 1)
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "generated.go", cleanSrc, parser.ParseComments)
if err != nil {
return "", err
}
runtimeStart := beginIdx
// Partition declarations.
var roots []ast.Decl
type candidate struct {
names []string
decl ast.Decl
}
var candidates []candidate
for _, decl := range f.Decls {
offset := fset.Position(decl.Pos()).Offset
if offset >= runtimeStart {
var names []string
switch d := decl.(type) {
case *ast.GenDecl:
names = genDeclNames(d)
case *ast.FuncDecl:
name := d.Name.Name
if d.Recv != nil && len(d.Recv.List) > 0 {
name = receiverTypeName(d.Recv.List[0].Type) + "." + name
}
names = []string{name}
}
candidates = append(candidates, candidate{names: names, decl: decl})
} else {
roots = append(roots, decl)
}
}
if len(candidates) == 0 {
return src, nil
}
// Seed reachable set from root declarations.
reachable := make(map[string]bool)
for _, d := range roots {
collectIdents(d, reachable)
}
// Transitive closure.
changed := true
for changed {
changed = false
for _, c := range candidates {
if isReachable(c.names, reachable) {
before := len(reachable)
collectIdents(c.decl, reachable)
if len(reachable) > before {
changed = true
}
}
}
}
// Keep only reachable declarations; collect positions of eliminated ones.
kept := append([]ast.Decl{}, roots...)
var eliminated []ast.Decl
for _, c := range candidates {
if isReachable(c.names, reachable) {
kept = append(kept, c.decl)
} else {
eliminated = append(eliminated, c.decl)
}
}
f.Decls = kept
// Remove comments associated with eliminated declarations so
// go/printer doesn't emit orphaned doc/inline comments.
if len(eliminated) > 0 {
// Build line ranges for eliminated declarations: from the doc
// comment (or decl start) through the last line of the decl.
removedLines := make([]lineSpan, 0, len(eliminated))
for _, d := range eliminated {
start := d.Pos()
switch dd := d.(type) {
case *ast.GenDecl:
if dd.Doc != nil {
start = dd.Doc.Pos()
}
case *ast.FuncDecl:
if dd.Doc != nil {
start = dd.Doc.Pos()
}
}
removedLines = append(removedLines, lineSpan{
startLine: fset.Position(start).Line,
endLine: fset.Position(d.End()).Line,
})
}
filtered := make([]*ast.CommentGroup, 0, len(f.Comments))
for _, cg := range f.Comments {
cgStart := fset.Position(cg.Pos()).Line
cgEnd := fset.Position(cg.End()).Line
if !linesOverlap(cgStart, cgEnd, removedLines) {
filtered = append(filtered, cg)
}
}
f.Comments = filtered
}
var buf strings.Builder
if err := printer.Fprint(&buf, fset, f); err != nil {
return "", err
}
return buf.String(), nil
}
func isReachable(names []string, reachable map[string]bool) bool {
for _, name := range names {
if reachable[name] {
return true
}
if before, _, ok := strings.Cut(name, "."); ok && reachable[before] {
return true
}
}
return false
}
func genDeclNames(d *ast.GenDecl) []string {
var names []string
for _, spec := range d.Specs {
switch s := spec.(type) {
case *ast.TypeSpec:
names = append(names, s.Name.Name)
case *ast.ValueSpec:
for _, n := range s.Names {
names = append(names, n.Name)
}
}
}
return names
}
func receiverTypeName(expr ast.Expr) string {
switch t := expr.(type) {
case *ast.StarExpr:
return receiverTypeName(t.X)
case *ast.Ident:
return t.Name
case *ast.IndexExpr:
return receiverTypeName(t.X)
case *ast.IndexListExpr:
return receiverTypeName(t.X)
}
return ""
}
type lineSpan struct{ startLine, endLine int }
func linesOverlap(cgStart, cgEnd int, spans []lineSpan) bool {
for _, s := range spans {
if cgStart >= s.startLine && cgEnd <= s.endLine {
return true
}
}
return false
}
func collectIdents(node ast.Node, idents map[string]bool) {
ast.Inspect(node, func(n ast.Node) bool {
if id, ok := n.(*ast.Ident); ok {
idents[id.Name] = true
}
return true
})
}