-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalls.go
More file actions
319 lines (276 loc) · 8.46 KB
/
Copy pathcalls.go
File metadata and controls
319 lines (276 loc) · 8.46 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
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
package repomap
import (
"context"
"encoding/json"
"fmt"
"io"
"os/exec"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/dotcommander/repomap/internal/lsp"
"golang.org/x/sync/errgroup"
)
// Location is a source position returned by a refs query.
type Location struct {
File string `json:"file"`
Line int `json:"line"`
Column int `json:"column"`
}
// CallsConfig controls --calls mode behaviour.
type CallsConfig struct {
// Threshold: only expand symbols in files with ImportedBy >= Threshold.
Threshold int
// Limit: max callers shown per symbol.
Limit int
// IncludeTests: when false, filter out callers whose file path contains _test.go.
IncludeTests bool
}
// RefsQuerier abstracts the refs backend so tests can inject a fake and callers
// can choose between in-process gopls and exec-based lspq.
type RefsQuerier interface {
Refs(ctx context.Context, file string, line int, symbol string) ([]Location, error)
}
// ---------------------------------------------------------------------------
// In-process querier (gopls via internal/lsp) — default for --calls
// ---------------------------------------------------------------------------
// inProcessQuerier wraps lsp.Querier to implement RefsQuerier.
type inProcessQuerier struct {
q *lsp.Querier
}
// NewInProcessQuerier returns a RefsQuerier that uses an already-running LSP
// Manager. The caller owns the Manager lifecycle (Shutdown).
func NewInProcessQuerier(mgr *lsp.Manager) RefsQuerier {
return &inProcessQuerier{q: lsp.NewQuerier(mgr)}
}
func (p *inProcessQuerier) Refs(ctx context.Context, file string, line int, symbol string) ([]Location, error) {
locs, err := p.q.Refs(ctx, file, line, symbol)
if err != nil {
return nil, err
}
out := make([]Location, len(locs))
for i, l := range locs {
out[i] = Location{File: l.File, Line: l.Line, Column: l.Column}
}
return out, nil
}
// ---------------------------------------------------------------------------
// exec-based querier (lspq binary) — kept as --calls-use-binary fallback
// ---------------------------------------------------------------------------
// lspqQuerier shells out to the lspq binary.
type lspqQuerier struct{}
// lspqRefsOutput matches the JSON shape returned by `lspq --json refs`.
type lspqRefsOutput struct {
References []Location `json:"references"`
}
const lspqMaxBytes = 1 << 20 // 1 MB cap per invocation
func (lspqQuerier) Refs(ctx context.Context, file string, line int, symbol string) ([]Location, error) {
cmd := exec.CommandContext(ctx, "lspq", "--json", "refs", file, fmt.Sprintf("%d", line), symbol)
pr, pw := io.Pipe()
cmd.Stdout = pw
if err := cmd.Start(); err != nil {
_ = pw.Close()
return nil, fmt.Errorf("lspq start: %w", err)
}
// Read up to lspqMaxBytes in a goroutine, then wait for the command.
dataCh := make(chan []byte, 1)
errCh := make(chan error, 1)
go func() {
data, err := io.ReadAll(io.LimitReader(pr, lspqMaxBytes))
_ = pr.Close()
if err != nil {
errCh <- err
return
}
dataCh <- data
}()
waitErr := cmd.Wait()
_ = pw.Close()
var data []byte
select {
case data = <-dataCh:
case err := <-errCh:
return nil, fmt.Errorf("lspq read: %w", err)
}
if waitErr != nil {
return nil, fmt.Errorf("lspq: %w", waitErr)
}
var out lspqRefsOutput
if err := json.Unmarshal(data, &out); err != nil {
return nil, fmt.Errorf("lspq parse: %w", err)
}
return out.References, nil
}
// ---------------------------------------------------------------------------
// SymbolCallers and ExpandCallers
// ---------------------------------------------------------------------------
// SymbolCallers maps "file:symbol" -> caller locations.
type SymbolCallers map[string][]Location
// callsKey builds the lookup key for a file+symbol pair.
func callsKey(file, symbol string) string {
return file + "\x00" + symbol
}
// CallsStats holds counters from a call-expansion run.
type CallsStats struct {
OK int
Timeout int
Error int
}
// SelectSemanticCallers applies the existing --calls threshold, test, and
// limit policy to callers produced by the canonical semantic analysis.
func SelectSemanticCallers(all SymbolCallers, ranked []RankedFile, cfg CallsConfig) SymbolCallers {
out := make(SymbolCallers)
for _, file := range ranked {
if file.ImportedBy < cfg.Threshold {
continue
}
for _, symbol := range file.Symbols {
if !symbol.Exported {
continue
}
locations := all.CallersForSymbol(file.Path, symbol)
filtered := make([]Location, 0, len(locations))
for _, location := range locations {
if !cfg.IncludeTests && strings.Contains(location.File, "_test.go") {
continue
}
filtered = append(filtered, location)
if cfg.Limit > 0 && len(filtered) == cfg.Limit {
break
}
}
if len(filtered) > 0 {
out[semanticCallsKey(file.Path, symbol.Receiver, symbol.Name)] = filtered
}
}
}
return out
}
// ExpandCallers queries a RefsQuerier for each exported symbol in files that
// meet the threshold, returning a SymbolCallers map and run statistics.
//
// progress is called with (done, total) as each symbol completes; pass nil to disable.
func ExpandCallers(
ctx context.Context,
root string,
ranked []RankedFile,
cfg CallsConfig,
q RefsQuerier,
progress func(done, total int),
) (SymbolCallers, CallsStats) {
type task struct {
file string // absolute path
relFile string // relative path (for key)
line int
symbol string
}
// Collect tasks: exported symbols in files meeting the threshold.
var tasks []task
for _, rf := range ranked {
if rf.ImportedBy < cfg.Threshold {
continue
}
absFile := root + "/" + rf.Path
for _, sym := range rf.Symbols {
if !sym.Exported || sym.Line == 0 {
continue
}
tasks = append(tasks, task{
file: absFile,
relFile: rf.Path,
line: sym.Line,
symbol: sym.Name,
})
}
}
total := len(tasks)
result := make(SymbolCallers, total)
var mu sync.Mutex // protect result map
var stats CallsStats
var okAtomic, timeoutAtomic, errAtomic atomic.Int64
var doneAtomic atomic.Int64
g, gctx := errgroup.WithContext(ctx)
g.SetLimit(runtime.NumCPU())
for _, t := range tasks {
g.Go(func() error {
callCtx, cancel := context.WithTimeout(gctx, 5*time.Second)
defer cancel()
locs, err := q.Refs(callCtx, t.file, t.line, t.symbol)
done := int(doneAtomic.Add(1))
if progress != nil {
progress(done, total)
}
if err != nil {
if callCtx.Err() != nil {
timeoutAtomic.Add(1)
} else {
errAtomic.Add(1)
}
return nil // don't fail the whole run
}
okAtomic.Add(1)
// Filter based on config.
filtered := filterLocations(locs, cfg, t.file, t.line)
if len(filtered) > cfg.Limit {
filtered = filtered[:cfg.Limit]
}
if len(filtered) > 0 {
key := callsKey(t.relFile, t.symbol)
mu.Lock()
result[key] = filtered
mu.Unlock()
}
return nil
})
}
_ = g.Wait()
stats.OK = int(okAtomic.Load())
stats.Timeout = int(timeoutAtomic.Load())
stats.Error = int(errAtomic.Load())
return result, stats
}
// filterLocations removes the definition site itself and optionally test files.
func filterLocations(locs []Location, cfg CallsConfig, defFile string, defLine int) []Location {
filtered := make([]Location, 0, len(locs))
for _, loc := range locs {
// Skip the definition itself.
if loc.Line == defLine && isSameFile(loc.File, defFile) {
continue
}
// Skip test files unless requested.
if !cfg.IncludeTests && strings.Contains(loc.File, "_test.go") {
continue
}
filtered = append(filtered, loc)
}
return filtered
}
// isSameFile does a simple suffix comparison — refs may return relative or
// absolute paths; we just check whether one is a suffix of the other.
func isSameFile(a, b string) bool {
if a == b {
return true
}
return strings.HasSuffix(a, b) || strings.HasSuffix(b, a)
}
// CheckLspq verifies that the lspq binary is on PATH, returning a descriptive
// error if it is not. Used only when --calls-use-binary is set.
func CheckLspq() error {
if _, err := exec.LookPath("lspq"); err != nil {
return fmt.Errorf("lspq not found on PATH: install it to use --calls-use-binary")
}
return nil
}
// CheckGopls verifies that gopls is on PATH.
func CheckGopls() error {
if _, err := exec.LookPath("gopls"); err != nil {
return fmt.Errorf("gopls not found on PATH: install it to use --calls (go install golang.org/x/tools/gopls@latest)")
}
return nil
}
// DefaultQuerier returns the lspq exec-based querier (legacy fallback).
func DefaultQuerier() RefsQuerier {
return lspqQuerier{}
}