Debian Codegraph @

gopls/internal/cache/parse_cache.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package cache
6
7 import (
8 "bytes"
9 "container/heap"
10 "context"
11 "fmt"
12 "go/parser"
13 "go/token"
14 "math/bits"
15 "runtime"
16 "sync"
17 "time"
18
19 "golang.org/x/sync/errgroup"
20 "golang.org/x/tools/gopls/internal/cache/parsego"
21 "golang.org/x/tools/gopls/internal/file"
22 "golang.org/x/tools/gopls/internal/protocol"
23 "golang.org/x/tools/gopls/internal/util/memoize"
24 )
25
26 // This file contains an implementation of an LRU parse cache, that offsets the
27 // base token.Pos value of each cached file so that they may be later described
28 // by a single dedicated FileSet.
29 //
30 // This is achieved by tracking a monotonic offset in the token.Pos space, that
31 // is incremented before parsing allow room for the resulting parsed file.
32
33 // reservedForParsing defines the room in the token.Pos space reserved for
34 // cached parsed files.
35 //
36 // Files parsed through the parseCache are guaranteed not to have overlapping
37 // spans: the parseCache tracks a monotonic base for newly parsed files.
38 //
39 // By offsetting the initial base of a FileSet, we can allow other operations
40 // accepting the FileSet (such as the gcimporter) to add new files using the
41 // normal FileSet APIs without overlapping with cached parsed files.
42 //
43 // Note that 1<<60 represents an exabyte of parsed data, more than any gopls
44 // process can ever parse.
45 //
46 // On 32-bit systems we don't cache parse results (see parseFiles).
47 const reservedForParsing = 1 << (bits.UintSize - 4)
48
49 // fileSetWithBase returns a new token.FileSet with Base() equal to the
50 // requested base.
51 //
52 // If base < 1, fileSetWithBase panics.
53 // (1 is the smallest permitted FileSet base).
54 func fileSetWithBase(base int) *token.FileSet {
55 fset := token.NewFileSet()
56 if base > 1 {
57 // Add a dummy file to set the base of fset. We won't ever use the
58 // resulting FileSet, so it doesn't matter how we achieve this.
59 //
60 // FileSets leave a 1-byte padding between files, so we set the base by
61 // adding a zero-length file at base-1.
62 fset.AddFile("", base-1, 0)
63 }
64 if fset.Base() != base {
65 panic("unexpected FileSet.Base")
66 }
67 return fset
68 }
69
70 const (
71 // Always keep 100 recent files, independent of their wall-clock age, to
72 // optimize the case where the user resumes editing after a delay.
73 parseCacheMinFiles = 100
74 )
75
76 // parsePadding is additional padding allocated to allow for increases in
77 // length (such as appending missing braces) caused by fixAST.
78 //
79 // This is used to mitigate a chicken and egg problem: we must know the base
80 // offset of the file we're about to parse, before we start parsing, and yet
81 // src fixups may affect the actual size of the parsed content (and therefore
82 // the offsets of subsequent files).
83 //
84 // When we encounter a file that no longer fits in its allocated space in the
85 // fileset, we have no choice but to re-parse it. Leaving a generous padding
86 // reduces the likelihood of this "slow path".
87 //
88 // This value is mutable for testing, so that we can exercise the slow path.
89 var parsePadding = 1000 // mutable for testing
90
91 // A parseCache holds recently accessed parsed Go files. After new files are
92 // stored, older files may be evicted from the cache via garbage collection.
93 //
94 // The parseCache.parseFiles method exposes a batch API for parsing (and
95 // caching) multiple files. This is necessary for type-checking, where files
96 // must be parsed in a common fileset.
97 type parseCache struct {
98 expireAfter time.Duration // interval at which to collect expired cache entries
99 done chan struct{} // closed when GC is stopped
100
101 mu sync.Mutex
102 m map[parseKey]*parseCacheEntry
103 lru queue // min-atime priority queue of *parseCacheEntry
104 clock uint64 // clock time, incremented when the cache is updated
105 nextBase int // base offset for the next parsed file
106 }
107
108 // newParseCache creates a new parse cache and starts a goroutine to garbage
109 // collect entries whose age is at least expireAfter.
110 //
111 // Callers must call parseCache.stop when the parse cache is no longer in use.
112 func newParseCache(expireAfter time.Duration) *parseCache {
113 c := &parseCache{
114 expireAfter: expireAfter,
115 m: make(map[parseKey]*parseCacheEntry),
116 done: make(chan struct{}),
117 }
118 go c.gc()
119 return c
120 }
121
122 // stop causes the GC goroutine to exit.
123 func (c *parseCache) stop() {
124 close(c.done)
125 }
126
127 // parseKey uniquely identifies a parsed Go file.
128 type parseKey struct {
129 uri protocol.DocumentURI
130 mode parser.Mode
131 purgeFuncBodies bool
132 }
133
134 type parseCacheEntry struct {
135 key parseKey
136 hash file.Hash
137 promise *memoize.Promise // memoize.Promise[*parsego.File]
138 atime uint64 // clock time of last access, for use in LRU sorting
139 walltime time.Time // actual time of last access, for use in time-based eviction; too coarse for LRU on some systems
140 lruIndex int // owned by the queue implementation
141 }
142
143 // startParse prepares a parsing pass, creating new promises in the cache for
144 // any cache misses.
145 //
146 // The resulting slice has an entry for every given file handle, though some
147 // entries may be nil if there was an error reading the file (in which case the
148 // resulting error will be non-nil).
149 func (c *parseCache) startParse(mode parser.Mode, purgeFuncBodies bool, fhs ...file.Handle) ([]*memoize.Promise, error) {
150 c.mu.Lock()
151 defer c.mu.Unlock()
152
153 // Any parsing pass increments the clock, as we'll update access times.
154 // (technically, if fhs is empty this isn't necessary, but that's a degenerate case).
155 //
156 // All entries parsed from a single call get the same access time.
157 c.clock++
158 walltime := time.Now()
159
160 // Read file data and collect cacheable files.
161 var (
162 data = make([][]byte, len(fhs)) // file content for each readable file
163 promises = make([]*memoize.Promise, len(fhs))
164 firstReadError error // first error from fh.Read, or nil
165 )
166 for i, fh := range fhs {
167 content, err := fh.Content()
168 if err != nil {
169 if firstReadError == nil {
170 firstReadError = err
171 }
172 continue
173 }
174 data[i] = content
175
176 key := parseKey{
177 uri: fh.URI(),
178 mode: mode,
179 purgeFuncBodies: purgeFuncBodies,
180 }
181
182 if e, ok := c.m[key]; ok {
183 if e.hash == fh.Identity().Hash { // cache hit
184 e.atime = c.clock
185 e.walltime = walltime
186 heap.Fix(&c.lru, e.lruIndex)
187 promises[i] = e.promise
188 continue
189 } else {
190 // A cache hit, for a different version. Delete it.
191 delete(c.m, e.key)
192 heap.Remove(&c.lru, e.lruIndex)
193 }
194 }
195
196 uri := fh.URI()
197 promise := memoize.NewPromise("parseCache.parse", func(ctx context.Context, _ any) any {
198 // Allocate 2*len(content)+parsePadding to allow for re-parsing once
199 // inside of parseGoSrc without exceeding the allocated space.
200 base, nextBase := c.allocateSpace(2*len(content) + parsePadding)
201
202 pgf, fixes1 := parsego.Parse(ctx, fileSetWithBase(base), uri, content, mode, purgeFuncBodies)
203 file := pgf.Tok
204 if file.Base()+file.Size()+1 > nextBase {
205 // The parsed file exceeds its allocated space, likely due to multiple
206 // passes of src fixing. In this case, we have no choice but to re-do
207 // the operation with the correct size.
208 //
209 // Even though the final successful parse requires only file.Size()
210 // bytes of Pos space, we need to accommodate all the missteps to get
211 // there, as parseGoSrc will repeat them.
212 actual := file.Base() + file.Size() - base // actual size consumed, after re-parsing
213 base2, nextBase2 := c.allocateSpace(actual)
214 pgf2, fixes2 := parsego.Parse(ctx, fileSetWithBase(base2), uri, content, mode, purgeFuncBodies)
215
216 // In golang/go#59097 we observed that this panic condition was hit.
217 // One bug was found and fixed, but record more information here in
218 // case there is still a bug here.
219 if end := pgf2.Tok.Base() + pgf2.Tok.Size(); end != nextBase2-1 {
220 var errBuf bytes.Buffer
221 fmt.Fprintf(&errBuf, "internal error: non-deterministic parsing result:\n")
222 fmt.Fprintf(&errBuf, "\t%q (%d-%d) does not span %d-%d\n", uri, pgf2.Tok.Base(), base2, end, nextBase2-1)
223 fmt.Fprintf(&errBuf, "\tfirst %q (%d-%d)\n", pgf.URI, pgf.Tok.Base(), pgf.Tok.Base()+pgf.Tok.Size())
224 fmt.Fprintf(&errBuf, "\tfirst space: (%d-%d), second space: (%d-%d)\n", base, nextBase, base2, nextBase2)
225 fmt.Fprintf(&errBuf, "\tfirst mode: %v, second mode: %v", pgf.Mode, pgf2.Mode)
226 fmt.Fprintf(&errBuf, "\tfirst err: %v, second err: %v", pgf.ParseErr, pgf2.ParseErr)
227 fmt.Fprintf(&errBuf, "\tfirst fixes: %v, second fixes: %v", fixes1, fixes2)
228 panic(errBuf.String())
229 }
230 pgf = pgf2
231 }
232 return pgf
233 })
234 promises[i] = promise
235
236 // add new entry; entries are gc'ed asynchronously
237 e := &parseCacheEntry{
238 key: key,
239 hash: fh.Identity().Hash,
240 promise: promise,
241 atime: c.clock,
242 walltime: walltime,
243 }
244 c.m[e.key] = e
245 heap.Push(&c.lru, e)
246 }
247
248 if len(c.m) != len(c.lru) {
249 panic("map and LRU are inconsistent")
250 }
251
252 return promises, firstReadError
253 }
254
255 func (c *parseCache) gc() {
256 const period = 10 * time.Second // gc period
257 timer := time.NewTicker(period)
258 defer timer.Stop()
259
260 for {
261 select {
262 case <-c.done:
263 return
264 case <-timer.C:
265 }
266
267 c.gcOnce()
268 }
269 }
270
271 func (c *parseCache) gcOnce() {
272 now := time.Now()
273 c.mu.Lock()
274 defer c.mu.Unlock()
275
276 for len(c.m) > parseCacheMinFiles {
277 e := heap.Pop(&c.lru).(*parseCacheEntry)
278 if now.Sub(e.walltime) >= c.expireAfter {
279 delete(c.m, e.key)
280 } else {
281 heap.Push(&c.lru, e)
282 break
283 }
284 }
285 }
286
287 // allocateSpace reserves the next n bytes of token.Pos space in the
288 // cache.
289 //
290 // It returns the resulting file base, next base, and an offset FileSet to use
291 // for parsing.
292 func (c *parseCache) allocateSpace(size int) (int, int) {
293 c.mu.Lock()
294 defer c.mu.Unlock()
295
296 if c.nextBase == 0 {
297 // FileSet base values must be at least 1.
298 c.nextBase = 1
299 }
300 base := c.nextBase
301 c.nextBase += size + 1
302 return base, c.nextBase
303 }
304
305 // parseFiles returns a parsego.File for each file handle in fhs, in the
306 // requested parse mode.
307 //
308 // For parsed files that already exists in the cache, access time will be
309 // updated. For others, parseFiles will parse and store as many results in the
310 // cache as space allows.
311 //
312 // The token.File for each resulting parsed file will be added to the provided
313 // FileSet, using the tokeninternal.AddExistingFiles API. Consequently, the
314 // given fset should only be used in other APIs if its base is >=
315 // reservedForParsing.
316 //
317 // If parseFiles returns an error, it still returns a slice,
318 // but with a nil entry for each file that could not be parsed.
319 func (c *parseCache) parseFiles(ctx context.Context, fset *token.FileSet, mode parser.Mode, purgeFuncBodies bool, fhs ...file.Handle) ([]*parsego.File, error) {
320 pgfs := make([]*parsego.File, len(fhs))
321
322 // Temporary fall-back for 32-bit systems, where reservedForParsing is too
323 // small to be viable. We don't actually support 32-bit systems, so this
324 // workaround is only for tests and can be removed when we stop running
325 // 32-bit TryBots for gopls.
326 if bits.UintSize == 32 {
327 for i, fh := range fhs {
328 var err error
329 pgfs[i], err = parseGoImpl(ctx, fset, fh, mode, purgeFuncBodies)
330 if err != nil {
331 return pgfs, err
332 }
333 }
334 return pgfs, nil
335 }
336
337 promises, firstErr := c.startParse(mode, purgeFuncBodies, fhs...)
338
339 // Await all parsing.
340 var g errgroup.Group
341 g.SetLimit(runtime.GOMAXPROCS(-1)) // parsing is CPU-bound.
342 for i, promise := range promises {
343 if promise == nil {
344 continue
345 }
346 i := i
347 promise := promise
348 g.Go(func() error {
349 result, err := promise.Get(ctx, nil)
350 if err != nil {
351 return err
352 }
353 pgfs[i] = result.(*parsego.File)
354 return nil
355 })
356 }
357
358 if err := g.Wait(); err != nil && firstErr == nil {
359 firstErr = err
360 }
361
362 // Augment the FileSet to map all parsed files.
363 var tokenFiles []*token.File
364 for _, pgf := range pgfs {
365 if pgf == nil {
366 continue
367 }
368 tokenFiles = append(tokenFiles, pgf.Tok)
369 }
370 fset.AddExistingFiles(tokenFiles...)
371
372 const debugIssue59080 = true
373 if debugIssue59080 {
374 for _, f := range tokenFiles {
375 pos := token.Pos(f.Base())
376 f2 := fset.File(pos)
377 if f2 != f {
378 panic(fmt.Sprintf("internal error: File(%d (start)) = %v, not %v", pos, f2, f))
379 }
380 pos = token.Pos(f.Base() + f.Size())
381 f2 = fset.File(pos)
382 if f2 != f {
383 panic(fmt.Sprintf("internal error: File(%d (end)) = %v, not %v", pos, f2, f))
384 }
385 }
386 }
387
388 return pgfs, firstErr
389 }
390
391 // -- priority queue boilerplate --
392
393 // queue is a min-atime priority queue of cache entries.
394 type queue []*parseCacheEntry
395
396 func (q queue) Len() int { return len(q) }
397
398 func (q queue) Less(i, j int) bool { return q[i].atime < q[j].atime }
399
400 func (q queue) Swap(i, j int) {
401 q[i], q[j] = q[j], q[i]
402 q[i].lruIndex = i
403 q[j].lruIndex = j
404 }
405
406 func (q *queue) Push(x any) {
407 e := x.(*parseCacheEntry)
408 e.lruIndex = len(*q)
409 *q = append(*q, e)
410 }
411
412 func (q *queue) Pop() any {
413 last := len(*q) - 1
414 e := (*q)[last]
415 (*q)[last] = nil // aid GC
416 *q = (*q)[:last]
417 return e
418 }