Skip to main content

lean_ctx/core/
derivation_cache.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Opt-in, content-addressed cache of pure parse derivations, shared across
3//! worktrees and data homes (GitHub #2247).
4//!
5//! An index build parses every file: BM25 chunks, the deep analysis behind the
6//! graph's import and type edges and the call graph, and the graph scan's
7//! signatures. A fresh worktree of the same repository parses almost the same
8//! files again. This store keeps those parse results by what they are a
9//! function of, so a second worktree reuses the unchanged ones and parses only
10//! its edited files.
11//!
12//! What it keeps and what it does not:
13//! - An entry is keyed by BLAKE3 over the build identity (version, commit and
14//!   the running binary), the derivation kind, its selector (language, and for
15//!   chunks the repository-relative path they name) and the exact content the
16//!   derivation read. Content that went through admission is hashed after
17//!   admission, so a policy that changes the text changes the key.
18//! - It never keeps a project index, a root, an absolute path, a retrieval
19//!   result or a permission decision. Each root reads, admits and indexes its
20//!   own files; only the pure parse of identical text is shared.
21//! - A result produced while a language is blocklisted after a parser panic is
22//!   neither stored nor served, so a regex fallback is never persisted as the
23//!   parser's output.
24//!
25//! The store is off by default. `[cache] derivations_enabled = true` or
26//! `LEAN_CTX_DERIVATION_CACHE=1` turns it on; `LEAN_CTX_DERIVATION_CACHE=0`
27//! turns it off. `derivations_dir` / `LEAN_CTX_DERIVATION_CACHE_DIR` name a
28//! directory shared by several data homes (default `<cache dir>/derivations`).
29//! The setting is read once per process: a running daemon picks up a change
30//! when it restarts.
31//!
32//! Safety: the directory must be a real directory owned by the current user
33//! and not writable by group or others, or the store stays off. It is checked
34//! when the store opens and then used by path, so a configured directory
35//! belongs under a parent only this user can write to (the default is). Entries are
36//! opened without following links and must be regular files; FIFOs, links and
37//! oversized files are refused. Writes go to a private temp file and are
38//! renamed into place. A header carries the full key and a hash of the
39//! payload; any mismatch, truncation or decode error is a miss and the entry is
40//! removed. The total size is bounded and the least recently used entries are
41//! evicted.
42
43use std::fs;
44use std::io::{Read, Write};
45use std::path::{Path, PathBuf};
46use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
47use std::sync::{Arc, Mutex};
48use std::time::{Duration, SystemTime};
49
50use serde::{Deserialize, Serialize};
51
52use crate::core::bm25_index::{ChunkKind, CodeChunk};
53use crate::core::deep_queries::{
54    CallSite, DeepAnalysis, ExtMethodDef, ImportInfo, ImportKind, TypeDef, TypeDefKind, TypeUse,
55};
56use crate::core::signatures::Signature;
57
58const MAGIC: &[u8; 8] = b"LCDERIV1";
59const HEADER_LEN: usize = 8 + 32 + 4 + 32;
60/// Largest payload stored or decoded. A file of the BM25 size cap yields far
61/// less; larger results are recomputed every time.
62pub(crate) const MAX_PAYLOAD_BYTES: usize = 8 * 1024 * 1024;
63const DEFAULT_MAX_BYTES: u64 = 512 * 1024 * 1024;
64/// Entries walked by one eviction sweep; a larger store is trimmed over sweeps.
65const SWEEP_MAX_ENTRIES: usize = 500_000;
66/// A hit refreshes the entry's mtime (its LRU age) at most this often.
67const TOUCH_AFTER: Duration = Duration::from_hours(6);
68const STALE_TMP: Duration = Duration::from_secs(3600);
69
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub(crate) enum Kind {
72    Chunks,
73    DeepAnalysis,
74    Signatures,
75}
76
77impl Kind {
78    fn tag(self) -> &'static [u8] {
79        match self {
80            Kind::Chunks => b"chunks/1",
81            Kind::DeepAnalysis => b"deep-analysis/1",
82            Kind::Signatures => b"signatures/1",
83        }
84    }
85}
86
87/// One opened, validated store directory.
88#[derive(Debug)]
89pub(crate) struct Store {
90    dir: PathBuf,
91    identity: [u8; 32],
92    max_bytes: u64,
93    written_since_sweep: AtomicU64,
94    sweeping: AtomicBool,
95    tmp_counter: AtomicU64,
96}
97
98impl Store {
99    /// Open (creating it privately if needed) the store under `root`. Returns
100    /// `None` when the directory is not a safe, same-user directory. Opening
101    /// does not sweep; the caller schedules the first [`Store::sweep`].
102    pub(crate) fn open(root: &Path, identity: [u8; 32], max_bytes: u64) -> Option<Self> {
103        let dir = root.join("v1");
104        create_private_dir(root)?;
105        create_private_dir(&dir)?;
106        Some(Self {
107            dir,
108            identity,
109            max_bytes: max_bytes.max(1024 * 1024),
110            written_since_sweep: AtomicU64::new(0),
111            sweeping: AtomicBool::new(false),
112            tmp_counter: AtomicU64::new(0),
113        })
114    }
115
116    fn key(&self, kind: Kind, selector: &str, content: &str) -> [u8; 32] {
117        let mut h = blake3::Hasher::new_derive_key("lean-ctx parse derivation cache v1");
118        h.update(&self.identity);
119        for part in [kind.tag(), selector.as_bytes(), content.as_bytes()] {
120            h.update(&(part.len() as u64).to_le_bytes());
121            h.update(part);
122        }
123        *h.finalize().as_bytes()
124    }
125
126    fn entry_path(&self, key: &[u8; 32]) -> PathBuf {
127        let hex = blake3::Hash::from(*key).to_hex();
128        self.dir.join(&hex[..2]).join(format!("{}.lcd", &hex[2..]))
129    }
130
131    fn load(&self, key: &[u8; 32]) -> Option<Vec<u8>> {
132        let path = self.entry_path(key);
133        let bytes = read_entry(&path)?;
134        if let Some(payload) = decode_entry(&bytes, key) {
135            touch(&path);
136            Some(payload.to_vec())
137        } else {
138            let _ = fs::remove_file(&path);
139            None
140        }
141    }
142
143    fn save(&self, key: &[u8; 32], payload: &[u8]) {
144        if payload.len() > MAX_PAYLOAD_BYTES {
145            return;
146        }
147        let path = self.entry_path(key);
148        let Some(shard) = path.parent() else { return };
149        if create_private_dir(shard).is_none() {
150            return;
151        }
152        let mut bytes = Vec::with_capacity(HEADER_LEN + payload.len());
153        bytes.extend_from_slice(MAGIC);
154        bytes.extend_from_slice(key);
155        bytes.extend_from_slice(&(payload.len() as u32).to_le_bytes());
156        bytes.extend_from_slice(blake3::hash(payload).as_bytes());
157        bytes.extend_from_slice(payload);
158
159        let n = self.tmp_counter.fetch_add(1, Ordering::Relaxed);
160        let tmp = shard.join(format!(".{}.{n}.tmp", std::process::id()));
161        if write_private_new(&tmp, &bytes).is_err() || fs::rename(&tmp, &path).is_err() {
162            let _ = fs::remove_file(&tmp);
163            return;
164        }
165        let written = self
166            .written_since_sweep
167            .fetch_add(bytes.len() as u64, Ordering::Relaxed)
168            + bytes.len() as u64;
169        if written >= self.max_bytes / 8 {
170            self.sweep();
171        }
172    }
173
174    /// Keep the store under its budget: remove stale temp files, then the
175    /// least recently used entries until the total is at most 80 % of it.
176    /// A sweep already running makes this a no-op that keeps the written
177    /// count, so the next save triggers a sweep again.
178    fn sweep(&self) {
179        if self.sweeping.swap(true, Ordering::AcqRel) {
180            return;
181        }
182        self.written_since_sweep.store(0, Ordering::Relaxed);
183        let now = SystemTime::now();
184        let mut entries: Vec<(SystemTime, u64, PathBuf)> = Vec::new();
185        let mut total: u64 = 0;
186        'walk: for shard in fs::read_dir(&self.dir).into_iter().flatten().flatten() {
187            let Ok(meta) = shard.metadata() else { continue };
188            if !meta.is_dir() {
189                continue;
190            }
191            for file in fs::read_dir(shard.path()).into_iter().flatten().flatten() {
192                let Ok(meta) = file.metadata() else { continue };
193                if !meta.is_file() {
194                    continue;
195                }
196                let modified = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
197                let path = file.path();
198                if path.extension().is_some_and(|e| e == "tmp") {
199                    if now.duration_since(modified).unwrap_or_default() > STALE_TMP {
200                        let _ = fs::remove_file(&path);
201                    }
202                    continue;
203                }
204                if path.extension().is_none_or(|e| e != "lcd") {
205                    continue;
206                }
207                total += meta.len();
208                entries.push((modified, meta.len(), path));
209                if entries.len() >= SWEEP_MAX_ENTRIES {
210                    break 'walk;
211                }
212            }
213        }
214        if total > self.max_bytes {
215            entries.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.2.cmp(&b.2)));
216            let target = self.max_bytes / 10 * 8;
217            for (_, len, path) in entries {
218                if total <= target {
219                    break;
220                }
221                if fs::remove_file(&path).is_ok() {
222                    total = total.saturating_sub(len);
223                }
224            }
225        }
226        self.sweeping.store(false, Ordering::Release);
227    }
228
229    /// Serve `kind` for `content` from the store, or compute it. `compute`
230    /// returns the value and whether it may be stored.
231    pub(crate) fn get_or_compute<T, S>(
232        &self,
233        kind: Kind,
234        selector: &str,
235        content: &str,
236        decode: impl FnOnce(S) -> Option<T>,
237        encode: impl FnOnce(&T) -> Option<S>,
238        compute: impl FnOnce() -> (T, bool),
239    ) -> T
240    where
241        S: Serialize + for<'de> Deserialize<'de>,
242    {
243        let key = self.key(kind, selector, content);
244        if let Some(payload) = self.load(&key) {
245            if let Some(value) = postcard::from_bytes::<S>(&payload).ok().and_then(decode) {
246                return value;
247            }
248            let _ = fs::remove_file(self.entry_path(&key));
249        }
250        let (value, storable) = compute();
251        if storable
252            && let Some(stored) = encode(&value)
253            && let Ok(payload) = postcard::to_stdvec(&stored)
254        {
255            self.save(&key, &payload);
256        }
257        value
258    }
259}
260
261fn create_private_dir(dir: &Path) -> Option<()> {
262    if fs::symlink_metadata(dir).is_err() {
263        let mut builder = fs::DirBuilder::new();
264        builder.recursive(true);
265        #[cfg(unix)]
266        {
267            use std::os::unix::fs::DirBuilderExt;
268            builder.mode(0o700);
269        }
270        builder.create(dir).ok()?;
271    }
272    let meta = fs::symlink_metadata(dir).ok()?;
273    if !meta.file_type().is_dir() {
274        return None;
275    }
276    #[cfg(unix)]
277    {
278        use std::os::unix::fs::MetadataExt;
279        // SAFETY: geteuid has no preconditions and cannot fail.
280        let euid = unsafe { libc::geteuid() };
281        if meta.uid() != euid || meta.mode() & 0o022 != 0 {
282            return None;
283        }
284    }
285    Some(())
286}
287
288fn read_entry(path: &Path) -> Option<Vec<u8>> {
289    let limit = (HEADER_LEN + MAX_PAYLOAD_BYTES) as u64;
290    let meta = fs::symlink_metadata(path).ok()?;
291    if !meta.file_type().is_file() || meta.len() > limit {
292        return None;
293    }
294    let mut options = fs::OpenOptions::new();
295    options.read(true);
296    #[cfg(unix)]
297    {
298        use std::os::unix::fs::OpenOptionsExt;
299        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
300    }
301    let file = options.open(path).ok()?;
302    let opened = file.metadata().ok()?;
303    if !opened.is_file() || opened.len() > limit {
304        return None;
305    }
306    let mut bytes = Vec::with_capacity(opened.len() as usize);
307    file.take(limit + 1).read_to_end(&mut bytes).ok()?;
308    (bytes.len() as u64 <= limit).then_some(bytes)
309}
310
311fn decode_entry<'a>(bytes: &'a [u8], key: &[u8; 32]) -> Option<&'a [u8]> {
312    if bytes.len() < HEADER_LEN || &bytes[..8] != MAGIC || &bytes[8..40] != key {
313        return None;
314    }
315    let len = u32::from_le_bytes(bytes[40..44].try_into().ok()?) as usize;
316    let payload = &bytes[HEADER_LEN..];
317    if len > MAX_PAYLOAD_BYTES || payload.len() != len {
318        return None;
319    }
320    (blake3::hash(payload).as_bytes() == &bytes[44..76]).then_some(payload)
321}
322
323fn write_private_new(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
324    let mut options = fs::OpenOptions::new();
325    options.write(true).create_new(true);
326    #[cfg(unix)]
327    {
328        use std::os::unix::fs::OpenOptionsExt;
329        options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
330    }
331    let mut file = options.open(path)?;
332    file.write_all(bytes)
333}
334
335fn touch(path: &Path) {
336    let Ok(meta) = fs::symlink_metadata(path) else {
337        return;
338    };
339    let old = meta
340        .modified()
341        .ok()
342        .and_then(|m| SystemTime::now().duration_since(m).ok())
343        .is_some_and(|age| age > TOUCH_AFTER);
344    if !old {
345        return;
346    }
347    let mut options = fs::OpenOptions::new();
348    options.write(true);
349    #[cfg(unix)]
350    {
351        use std::os::unix::fs::OpenOptionsExt;
352        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
353    }
354    if let Ok(file) = options.open(path)
355        && file.metadata().is_ok_and(|m| m.is_file())
356    {
357        let _ = file.set_modified(SystemTime::now());
358    }
359}
360
361/// The build identity: a cached derivation is only valid for the parser that
362/// produced it. The running binary's size and mtime change on every build or
363/// install, so a development build never serves another build's results.
364#[cfg_attr(test, allow(dead_code))]
365fn build_identity() -> [u8; 32] {
366    let mut h = blake3::Hasher::new_derive_key("lean-ctx parse derivation build identity v1");
367    h.update(env!("CARGO_PKG_VERSION").as_bytes());
368    h.update(b"\0");
369    h.update(option_env!("LEANCTX_BUILD_COMMIT").unwrap_or("").as_bytes());
370    h.update(b"\0");
371    h.update(option_env!("LEANCTX_BUILD_DIRTY").unwrap_or("").as_bytes());
372    h.update(&[u8::from(cfg!(feature = "tree-sitter"))]);
373    if let Ok(meta) = std::env::current_exe().and_then(fs::metadata) {
374        h.update(&meta.len().to_le_bytes());
375        let mtime = meta
376            .modified()
377            .ok()
378            .and_then(|m| m.duration_since(SystemTime::UNIX_EPOCH).ok())
379            .map_or(0, |d| d.as_nanos());
380        h.update(&mtime.to_le_bytes());
381    }
382    *h.finalize().as_bytes()
383}
384
385#[cfg_attr(test, allow(dead_code))]
386fn env_flag(name: &str) -> Option<bool> {
387    match std::env::var(name)
388        .ok()?
389        .trim()
390        .to_ascii_lowercase()
391        .as_str()
392    {
393        "1" | "true" | "yes" | "on" => Some(true),
394        "0" | "false" | "no" | "off" => Some(false),
395        _ => None,
396    }
397}
398
399#[cfg_attr(test, allow(dead_code))]
400fn open_configured() -> Option<Arc<Store>> {
401    let config = crate::core::config::Config::load().cache;
402    if !env_flag("LEAN_CTX_DERIVATION_CACHE").unwrap_or(config.derivations_enabled) {
403        return None;
404    }
405    let dir = std::env::var("LEAN_CTX_DERIVATION_CACHE_DIR")
406        .ok()
407        .filter(|d| !d.trim().is_empty())
408        .or(config.derivations_dir)
409        .map(PathBuf::from)
410        .or_else(|| {
411            crate::core::paths::cache_dir()
412                .ok()
413                .map(|d| d.join("derivations"))
414        })?;
415    let max_bytes = if config.derivations_max_bytes == 0 {
416        DEFAULT_MAX_BYTES
417    } else {
418        config.derivations_max_bytes
419    };
420    let Some(store) = Store::open(&dir, build_identity(), max_bytes) else {
421        tracing::warn!(
422            "[derivation cache: {} is not a private directory of this user — parsing without the cache]",
423            dir.display()
424        );
425        return None;
426    };
427    // The first sweep (stale temp files, a budget lowered since the last run)
428    // walks the whole store: keep it off the indexing path.
429    let store = Arc::new(store);
430    let sweeper = Arc::clone(&store);
431    let _ = std::thread::Builder::new()
432        .name("lean-ctx-derivation-sweep".into())
433        .spawn(move || sweeper.sweep());
434    Some(store)
435}
436
437#[cfg(test)]
438thread_local! {
439    static TEST_OVERRIDE: std::cell::RefCell<Option<Arc<Store>>> =
440        const { std::cell::RefCell::new(None) };
441}
442
443fn active() -> Option<Arc<Store>> {
444    #[cfg(test)]
445    {
446        TEST_OVERRIDE.with(|o| o.borrow().clone())
447    }
448    #[cfg(not(test))]
449    {
450        static STORE: std::sync::OnceLock<Option<Arc<Store>>> = std::sync::OnceLock::new();
451        STORE.get_or_init(open_configured).clone()
452    }
453}
454
455/// Run `f` with `store` as the store (tests only). The store is visible only
456/// to `f`'s thread and a private rayon pool `f` runs in, so parallel tests of
457/// other modules never read or write it.
458#[cfg(test)]
459pub(crate) fn with_store<R: Send>(store: Option<Arc<Store>>, f: impl FnOnce() -> R + Send) -> R {
460    let for_workers = store.clone();
461    let pool = rayon::ThreadPoolBuilder::new()
462        .num_threads(rayon::current_num_threads().clamp(2, 8))
463        .start_handler(move |_| {
464            TEST_OVERRIDE.with(|o| *o.borrow_mut() = for_workers.clone());
465        })
466        .build()
467        .expect("test rayon pool");
468    pool.install(|| {
469        TEST_OVERRIDE.with(|o| *o.borrow_mut() = store);
470        f()
471    })
472}
473
474// ---------------------------------------------------------------------------
475// Derivations
476// ---------------------------------------------------------------------------
477
478/// BM25 chunks of `content` at repository-relative `rel`
479/// (`bm25_index::chunking::extract_chunks`).
480pub(crate) fn chunks(rel: &str, content: &str) -> Vec<CodeChunk> {
481    let compute = || crate::core::bm25_index::extract_chunks(rel, content);
482    let Some(store) = active() else {
483        return compute();
484    };
485    store.get_or_compute(
486        Kind::Chunks,
487        rel,
488        content,
489        |stored: Vec<StoredChunk>| {
490            stored
491                .into_iter()
492                .map(|c| c.into_chunk(rel))
493                .collect::<Option<Vec<_>>>()
494        },
495        |chunks: &Vec<CodeChunk>| chunks.iter().map(StoredChunk::from_chunk).collect(),
496        || (compute(), true),
497    )
498}
499
500/// `deep_queries::analyze(content, ext)`.
501pub(crate) fn deep_analysis(content: &str, ext: &str) -> DeepAnalysis {
502    let compute = || crate::core::deep_queries::analyze(content, ext);
503    let Some(store) = active() else {
504        return compute();
505    };
506    store.get_or_compute(
507        Kind::DeepAnalysis,
508        ext,
509        content,
510        StoredAnalysis::into_analysis,
511        |a: &DeepAnalysis| Some(StoredAnalysis::from_analysis(a)),
512        || (compute(), true),
513    )
514}
515
516/// `signatures::extract_signatures(content, ext)`.
517pub(crate) fn signatures(content: &str, ext: &str) -> Vec<Signature> {
518    let blocked = crate::core::signatures::tree_sitter_language_blocked;
519    let Some(store) = active().filter(|_| !blocked(ext)) else {
520        return crate::core::signatures::extract_signatures(content, ext);
521    };
522    let mut parsed = false;
523    let (sigs, tree_sitter) = store.get_or_compute(
524        Kind::Signatures,
525        ext,
526        content,
527        StoredSignatures::into_signatures,
528        |(sigs, ts): &(Vec<Signature>, bool)| Some(StoredSignatures::from_signatures(sigs, *ts)),
529        || {
530            parsed = true;
531            let (sigs, backend) = crate::core::signatures::extract_signatures_counted(content, ext);
532            let ts = matches!(backend, crate::core::signatures::SigBackend::TreeSitter);
533            // A panic during this parse blocklists the language and returns
534            // the regex fallback: that result is not the parser's output.
535            ((sigs, ts), !blocked(ext))
536        },
537    );
538    if !parsed {
539        // A served result counts like the extraction it replaces.
540        crate::core::signatures::count_signature_backend(if tree_sitter {
541            crate::core::signatures::SigBackend::TreeSitter
542        } else {
543            crate::core::signatures::SigBackend::Regex
544        });
545    }
546    crate::core::grammar_usage::record(ext, tree_sitter);
547    sigs
548}
549
550// ---------------------------------------------------------------------------
551// Stored forms: plain data, decoded strictly; anything unknown is a miss.
552// ---------------------------------------------------------------------------
553
554#[derive(Serialize, Deserialize)]
555struct StoredChunk {
556    symbol_name: String,
557    kind: u8,
558    start_line: usize,
559    end_line: usize,
560    content: String,
561    tokens: Vec<String>,
562    token_count: usize,
563}
564
565// Kind tags. Encoding matches exhaustively, so a new upstream variant fails to
566// compile here until it has a tag; decoding an unknown tag is a miss.
567
568/// Parse-shaped chunk kinds only: external source kinds are never stored.
569fn chunk_kind_tag(kind: &ChunkKind) -> Option<u8> {
570    Some(match kind {
571        ChunkKind::Function => 0,
572        ChunkKind::Struct => 1,
573        ChunkKind::Impl => 2,
574        ChunkKind::Module => 3,
575        ChunkKind::Class => 4,
576        ChunkKind::Method => 5,
577        ChunkKind::Other => 6,
578        ChunkKind::Issue
579        | ChunkKind::PullRequest
580        | ChunkKind::WikiPage
581        | ChunkKind::DbSchema
582        | ChunkKind::ApiEndpoint
583        | ChunkKind::Ticket
584        | ChunkKind::ExternalOther => return None,
585    })
586}
587
588fn chunk_kind_from_tag(tag: u8) -> Option<ChunkKind> {
589    Some(match tag {
590        0 => ChunkKind::Function,
591        1 => ChunkKind::Struct,
592        2 => ChunkKind::Impl,
593        3 => ChunkKind::Module,
594        4 => ChunkKind::Class,
595        5 => ChunkKind::Method,
596        6 => ChunkKind::Other,
597        _ => return None,
598    })
599}
600
601fn import_kind_tag(kind: &ImportKind) -> u8 {
602    match kind {
603        ImportKind::Named => 0,
604        ImportKind::Default => 1,
605        ImportKind::Star => 2,
606        ImportKind::SideEffect => 3,
607        ImportKind::Dynamic => 4,
608        ImportKind::Reexport => 5,
609    }
610}
611
612fn import_kind_from_tag(tag: u8) -> Option<ImportKind> {
613    Some(match tag {
614        0 => ImportKind::Named,
615        1 => ImportKind::Default,
616        2 => ImportKind::Star,
617        3 => ImportKind::SideEffect,
618        4 => ImportKind::Dynamic,
619        5 => ImportKind::Reexport,
620        _ => return None,
621    })
622}
623
624fn type_kind_tag(kind: &TypeDefKind) -> u8 {
625    match kind {
626        TypeDefKind::Class => 0,
627        TypeDefKind::Interface => 1,
628        TypeDefKind::TypeAlias => 2,
629        TypeDefKind::Enum => 3,
630        TypeDefKind::Struct => 4,
631        TypeDefKind::Trait => 5,
632        TypeDefKind::Protocol => 6,
633        TypeDefKind::Record => 7,
634        TypeDefKind::Annotation => 8,
635        TypeDefKind::Union => 9,
636    }
637}
638
639fn type_kind_from_tag(tag: u8) -> Option<TypeDefKind> {
640    Some(match tag {
641        0 => TypeDefKind::Class,
642        1 => TypeDefKind::Interface,
643        2 => TypeDefKind::TypeAlias,
644        3 => TypeDefKind::Enum,
645        4 => TypeDefKind::Struct,
646        5 => TypeDefKind::Trait,
647        6 => TypeDefKind::Protocol,
648        7 => TypeDefKind::Record,
649        8 => TypeDefKind::Annotation,
650        9 => TypeDefKind::Union,
651        _ => return None,
652    })
653}
654
655impl StoredChunk {
656    /// Only parse-shaped chunks are stored: a chunk with an origin or an
657    /// external kind did not come from the parser.
658    fn from_chunk(c: &CodeChunk) -> Option<Self> {
659        if c.input_origin.is_some() {
660            return None;
661        }
662        let kind = chunk_kind_tag(&c.kind)?;
663        Some(Self {
664            symbol_name: c.symbol_name.clone(),
665            kind,
666            start_line: c.start_line,
667            end_line: c.end_line,
668            content: c.content.clone(),
669            tokens: c.tokens.clone(),
670            token_count: c.token_count,
671        })
672    }
673
674    fn into_chunk(self, rel: &str) -> Option<CodeChunk> {
675        Some(CodeChunk {
676            file_path: rel.to_string(),
677            symbol_name: self.symbol_name,
678            kind: chunk_kind_from_tag(self.kind)?,
679            start_line: self.start_line,
680            end_line: self.end_line,
681            content: self.content,
682            tokens: self.tokens,
683            token_count: self.token_count,
684            input_origin: None,
685        })
686    }
687}
688
689#[derive(Serialize, Deserialize)]
690struct StoredAnalysis {
691    imports: Vec<(String, Vec<String>, u8, usize, bool)>,
692    calls: Vec<StoredCall>,
693    types: Vec<StoredType>,
694    exports: Vec<String>,
695    type_uses: Vec<(String, usize)>,
696    ext_methods: Vec<(String, usize, usize)>,
697}
698
699#[derive(Serialize, Deserialize)]
700struct StoredCall {
701    callee: String,
702    line: usize,
703    col: usize,
704    receiver: Option<String>,
705    is_method: bool,
706    callee_pos: Option<(usize, usize)>,
707}
708
709#[derive(Serialize, Deserialize)]
710struct StoredType {
711    name: String,
712    kind: u8,
713    line: usize,
714    end_line: usize,
715    is_exported: bool,
716    generics: Vec<String>,
717    namespace: Option<String>,
718}
719
720impl StoredAnalysis {
721    fn from_analysis(a: &DeepAnalysis) -> Self {
722        Self {
723            imports: a
724                .imports
725                .iter()
726                .map(|i| {
727                    (
728                        i.source.clone(),
729                        i.names.clone(),
730                        import_kind_tag(&i.kind),
731                        i.line,
732                        i.is_type_only,
733                    )
734                })
735                .collect(),
736            calls: a
737                .calls
738                .iter()
739                .map(|c| StoredCall {
740                    callee: c.callee.clone(),
741                    line: c.line,
742                    col: c.col,
743                    receiver: c.receiver.clone(),
744                    is_method: c.is_method,
745                    callee_pos: c.callee_pos,
746                })
747                .collect(),
748            types: a
749                .types
750                .iter()
751                .map(|t| StoredType {
752                    name: t.name.clone(),
753                    kind: type_kind_tag(&t.kind),
754                    line: t.line,
755                    end_line: t.end_line,
756                    is_exported: t.is_exported,
757                    generics: t.generics.clone(),
758                    namespace: t.namespace.clone(),
759                })
760                .collect(),
761            exports: a.exports.clone(),
762            type_uses: a
763                .type_uses
764                .iter()
765                .map(|u| (u.name.clone(), u.line))
766                .collect(),
767            ext_methods: a
768                .ext_methods
769                .iter()
770                .map(|m| (m.name.clone(), m.line, m.end_line))
771                .collect(),
772        }
773    }
774
775    fn into_analysis(self) -> Option<DeepAnalysis> {
776        let imports = self
777            .imports
778            .into_iter()
779            .map(|(source, names, kind, line, is_type_only)| {
780                Some(ImportInfo {
781                    source,
782                    names,
783                    kind: import_kind_from_tag(kind)?,
784                    line,
785                    is_type_only,
786                })
787            })
788            .collect::<Option<Vec<_>>>()?;
789        let types = self
790            .types
791            .into_iter()
792            .map(|t| {
793                Some(TypeDef {
794                    name: t.name,
795                    kind: type_kind_from_tag(t.kind)?,
796                    line: t.line,
797                    end_line: t.end_line,
798                    is_exported: t.is_exported,
799                    generics: t.generics,
800                    namespace: t.namespace,
801                })
802            })
803            .collect::<Option<Vec<_>>>()?;
804        Some(DeepAnalysis {
805            imports,
806            calls: self
807                .calls
808                .into_iter()
809                .map(|c| CallSite {
810                    callee: c.callee,
811                    line: c.line,
812                    col: c.col,
813                    receiver: c.receiver,
814                    is_method: c.is_method,
815                    callee_pos: c.callee_pos,
816                })
817                .collect(),
818            types,
819            exports: self.exports,
820            type_uses: self
821                .type_uses
822                .into_iter()
823                .map(|(name, line)| TypeUse { name, line })
824                .collect(),
825            ext_methods: self
826                .ext_methods
827                .into_iter()
828                .map(|(name, line, end_line)| ExtMethodDef {
829                    name,
830                    line,
831                    end_line,
832                })
833                .collect(),
834        })
835    }
836}
837
838#[derive(Serialize, Deserialize)]
839struct StoredSignatures {
840    tree_sitter: bool,
841    sigs: Vec<StoredSignature>,
842}
843
844#[derive(Serialize, Deserialize)]
845struct StoredSignature {
846    kind: String,
847    name: String,
848    params: String,
849    return_type: String,
850    is_async: bool,
851    is_exported: bool,
852    indent: usize,
853    start_line: Option<usize>,
854    end_line: Option<usize>,
855}
856
857/// Signature kinds are `&'static str`. A decoded kind is interned once; the
858/// set is small and bounded, and a kind outside the bound is a miss.
859fn intern_kind(kind: &str) -> Option<&'static str> {
860    const MAX_KINDS: usize = 64;
861    const MAX_KIND_LEN: usize = 32;
862    static KINDS: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
863    if kind.is_empty() || kind.len() > MAX_KIND_LEN || !kind.bytes().all(|b| b.is_ascii_graphic()) {
864        return None;
865    }
866    let mut kinds = KINDS
867        .lock()
868        .unwrap_or_else(std::sync::PoisonError::into_inner);
869    if let Some(known) = kinds.iter().find(|k| **k == kind) {
870        return Some(known);
871    }
872    if kinds.len() >= MAX_KINDS {
873        return None;
874    }
875    let leaked: &'static str = Box::leak(kind.to_owned().into_boxed_str());
876    kinds.push(leaked);
877    Some(leaked)
878}
879
880impl StoredSignatures {
881    fn from_signatures(sigs: &[Signature], tree_sitter: bool) -> Self {
882        Self {
883            tree_sitter,
884            sigs: sigs
885                .iter()
886                .map(|s| StoredSignature {
887                    kind: s.kind.to_string(),
888                    name: s.name.clone(),
889                    params: s.params.clone(),
890                    return_type: s.return_type.clone(),
891                    is_async: s.is_async,
892                    is_exported: s.is_exported,
893                    indent: s.indent,
894                    start_line: s.start_line,
895                    end_line: s.end_line,
896                })
897                .collect(),
898        }
899    }
900
901    fn into_signatures(self) -> Option<(Vec<Signature>, bool)> {
902        let sigs = self
903            .sigs
904            .into_iter()
905            .map(|s| {
906                Some(Signature {
907                    kind: intern_kind(&s.kind)?,
908                    name: s.name,
909                    params: s.params,
910                    return_type: s.return_type,
911                    is_async: s.is_async,
912                    is_exported: s.is_exported,
913                    indent: s.indent,
914                    start_line: s.start_line,
915                    end_line: s.end_line,
916                })
917            })
918            .collect::<Option<Vec<_>>>()?;
919        Some((sigs, self.tree_sitter))
920    }
921}
922
923#[cfg(test)]
924#[path = "derivation_cache_tests.rs"]
925mod tests;