-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathapi.go
255 lines (218 loc) · 6.78 KB
/
api.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
package goconst
import (
"go/ast"
"go/token"
"go/types"
"sort"
"strings"
"sync"
)
// Issue represents a finding of duplicated strings, numbers, or constants.
// Each Issue includes the position where it was found, how many times it occurs,
// the string itself, and any matching constant name.
type Issue struct {
Pos token.Position
OccurrencesCount int
Str string
MatchingConst string
DuplicateConst string
DuplicatePos token.Position
}
// Config contains all configuration options for the goconst analyzer.
type Config struct {
// IgnoreStrings is a list of regular expressions to filter strings
IgnoreStrings []string
// IgnoreTests indicates whether test files should be excluded
IgnoreTests bool
// MatchWithConstants enables matching strings with existing constants
MatchWithConstants bool
// MinStringLength is the minimum length a string must have to be reported
MinStringLength int
// MinOccurrences is the minimum number of occurrences required to report a string
MinOccurrences int
// ParseNumbers enables detection of duplicated numbers
ParseNumbers bool
// NumberMin sets the minimum value for reported number matches
NumberMin int
// NumberMax sets the maximum value for reported number matches
NumberMax int
// ExcludeTypes allows excluding specific types of contexts
ExcludeTypes map[Type]bool
// FindDuplicates enables finding constants whose values match existing constants in other packages.
FindDuplicates bool
// EvalConstExpressions enables evaluation of constant expressions like Prefix + "suffix"
EvalConstExpressions bool
}
// NewWithIgnorePatterns creates a new instance of the parser with support for multiple ignore patterns.
// This is an alternative constructor that takes a slice of ignore string patterns.
func NewWithIgnorePatterns(
path, ignore string,
ignoreStrings []string,
ignoreTests, matchConstant, numbers, findDuplicates, evalConstExpressions bool,
numberMin, numberMax, minLength, minOccurrences int,
excludeTypes map[Type]bool) *Parser {
// Join multiple patterns with OR for regex
var ignoreStringsPattern string
if len(ignoreStrings) > 0 {
if len(ignoreStrings) > 1 {
// Wrap each pattern in parentheses and join with OR
patterns := make([]string, len(ignoreStrings))
for i, pattern := range ignoreStrings {
patterns[i] = "(" + pattern + ")"
}
ignoreStringsPattern = strings.Join(patterns, "|")
} else {
// Single pattern case
ignoreStringsPattern = ignoreStrings[0]
}
}
return New(
path,
ignore,
ignoreStringsPattern,
ignoreTests,
matchConstant,
numbers,
findDuplicates,
evalConstExpressions,
numberMin,
numberMax,
minLength,
minOccurrences,
excludeTypes,
)
}
// RunWithConfig is a convenience function that runs the analysis with a Config object
// directly supporting multiple ignore patterns.
func RunWithConfig(files []*ast.File, fset *token.FileSet, typeInfo *types.Info, cfg *Config) ([]Issue, error) {
p := NewWithIgnorePatterns(
"",
"",
cfg.IgnoreStrings,
cfg.IgnoreTests,
cfg.MatchWithConstants,
cfg.ParseNumbers,
cfg.FindDuplicates,
cfg.EvalConstExpressions,
cfg.NumberMin,
cfg.NumberMax,
cfg.MinStringLength,
cfg.MinOccurrences,
cfg.ExcludeTypes,
)
// Pre-allocate slice based on estimated result size
expectedIssues := len(files) * 5 // Assuming average of 5 issues per file
if expectedIssues > 1000 {
expectedIssues = 1000 // Cap at reasonable maximum
}
// Allocate a new buffer
issueBuffer := make([]Issue, 0, expectedIssues)
// Process files concurrently
var wg sync.WaitGroup
sem := make(chan struct{}, p.maxConcurrency)
// Create a filtered files slice with capacity hint
filteredFiles := make([]*ast.File, 0, len(files))
// Filter test files first if needed
for _, f := range files {
if p.ignoreTests {
if filename := fset.Position(f.Pos()).Filename; strings.HasSuffix(filename, "_test.go") {
continue
}
}
filteredFiles = append(filteredFiles, f)
}
// Process each file in parallel
for _, f := range filteredFiles {
wg.Add(1)
sem <- struct{}{} // acquire semaphore
go func(f *ast.File) {
defer func() {
<-sem // release semaphore
wg.Done()
}()
// Use empty interned strings for package/file names
// The visitor logic will set these appropriately
emptyStr := InternString("")
ast.Walk(&treeVisitor{
fileSet: fset,
packageName: emptyStr,
p: p,
ignoreRegex: p.ignoreStringsRegex,
typeInfo: typeInfo,
}, f)
}(f)
}
wg.Wait()
p.ProcessResults()
// Process each string that passed the filters
p.stringMutex.RLock()
p.stringCountMutex.RLock()
// Create a slice to hold the string keys
stringKeys := make([]string, 0, len(p.strs))
// Create an array of strings to sort for stable output
for str := range p.strs {
if count := p.stringCount[str]; count >= p.minOccurrences {
stringKeys = append(stringKeys, str)
}
}
sort.Strings(stringKeys)
// Process strings in a predictable order for stable output
for _, str := range stringKeys {
positions := p.strs[str]
if len(positions) == 0 {
continue
}
// Use the first position as representative
fi := positions[0]
// Create issue using the counted value to avoid recounting
issue := Issue{
Pos: fi.Position,
OccurrencesCount: p.stringCount[str],
Str: str,
}
// Check for matching constants
if len(p.consts) > 0 {
p.constMutex.RLock()
if csts, ok := p.consts[str]; ok && len(csts) > 0 {
// const should be in the same package and exported
issue.MatchingConst = csts[0].Name
}
p.constMutex.RUnlock()
}
issueBuffer = append(issueBuffer, issue)
}
p.stringCountMutex.RUnlock()
p.stringMutex.RUnlock()
// process duplicate constants
p.constMutex.RLock()
// Create a new slice for const keys
stringKeys = make([]string, 0, len(p.consts))
// Create an array of strings and sort for stable output
for str := range p.consts {
if len(p.consts[str]) > 1 {
stringKeys = append(stringKeys, str)
}
}
sort.Strings(stringKeys)
// report an issue for every duplicated const
for _, str := range stringKeys {
positions := p.consts[str]
for i := 1; i < len(positions); i++ {
issueBuffer = append(issueBuffer, Issue{
Pos: positions[i].Position,
Str: str,
DuplicateConst: positions[0].Name,
DuplicatePos: positions[0].Position,
})
}
}
p.constMutex.RUnlock()
// Don't return the buffer to pool as the caller now owns it
return issueBuffer, nil
}
// Run analyzes the provided AST files for duplicated strings or numbers
// according to the provided configuration.
// It returns a slice of Issue objects containing the findings.
func Run(files []*ast.File, fset *token.FileSet, typeInfo *types.Info, cfg *Config) ([]Issue, error) {
return RunWithConfig(files, fset, typeInfo, cfg)
}