1use 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;
60pub(crate) const MAX_PAYLOAD_BYTES: usize = 8 * 1024 * 1024;
63const DEFAULT_MAX_BYTES: u64 = 512 * 1024 * 1024;
64const SWEEP_MAX_ENTRIES: usize = 500_000;
66const 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#[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 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 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 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 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#[cfg_attr(test, allow(dead_code))]
367fn build_identity() -> [u8; 32] {
368 let build = crate::core::integrity::build();
369 let mut h = blake3::Hasher::new_derive_key("lean-ctx parse derivation build identity v1");
370 h.update(env!("CARGO_PKG_VERSION").as_bytes());
371 h.update(b"\0");
372 h.update(build.commit.as_bytes());
373 h.update(b"\0");
374 h.update(if build.dirty { b"1" } else { b"0" });
375 h.update(&[u8::from(cfg!(feature = "tree-sitter"))]);
376 if let Ok(meta) = std::env::current_exe().and_then(fs::metadata) {
377 h.update(&meta.len().to_le_bytes());
378 let mtime = meta
379 .modified()
380 .ok()
381 .and_then(|m| m.duration_since(SystemTime::UNIX_EPOCH).ok())
382 .map_or(0, |d| d.as_nanos());
383 h.update(&mtime.to_le_bytes());
384 }
385 *h.finalize().as_bytes()
386}
387
388#[cfg_attr(test, allow(dead_code))]
389fn env_flag(name: &str) -> Option<bool> {
390 match std::env::var(name)
391 .ok()?
392 .trim()
393 .to_ascii_lowercase()
394 .as_str()
395 {
396 "1" | "true" | "yes" | "on" => Some(true),
397 "0" | "false" | "no" | "off" => Some(false),
398 _ => None,
399 }
400}
401
402#[cfg_attr(test, allow(dead_code))]
403fn open_configured() -> Option<Arc<Store>> {
404 let config = crate::core::config::Config::load().cache;
405 if !env_flag("LEAN_CTX_DERIVATION_CACHE").unwrap_or(config.derivations_enabled) {
406 return None;
407 }
408 let dir = std::env::var("LEAN_CTX_DERIVATION_CACHE_DIR")
409 .ok()
410 .filter(|d| !d.trim().is_empty())
411 .or(config.derivations_dir)
412 .map(PathBuf::from)
413 .or_else(|| {
414 crate::core::paths::cache_dir()
415 .ok()
416 .map(|d| d.join("derivations"))
417 })?;
418 let max_bytes = if config.derivations_max_bytes == 0 {
419 DEFAULT_MAX_BYTES
420 } else {
421 config.derivations_max_bytes
422 };
423 let Some(store) = Store::open(&dir, build_identity(), max_bytes) else {
424 tracing::warn!(
425 "[derivation cache: {} is not a private directory of this user — parsing without the cache]",
426 dir.display()
427 );
428 return None;
429 };
430 let store = Arc::new(store);
433 let sweeper = Arc::clone(&store);
434 let _ = std::thread::Builder::new()
435 .name("lean-ctx-derivation-sweep".into())
436 .spawn(move || sweeper.sweep());
437 Some(store)
438}
439
440#[cfg(test)]
441thread_local! {
442 static TEST_OVERRIDE: std::cell::RefCell<Option<Arc<Store>>> =
443 const { std::cell::RefCell::new(None) };
444}
445
446fn active() -> Option<Arc<Store>> {
447 #[cfg(test)]
448 {
449 TEST_OVERRIDE.with(|o| o.borrow().clone())
450 }
451 #[cfg(not(test))]
452 {
453 static STORE: std::sync::OnceLock<Option<Arc<Store>>> = std::sync::OnceLock::new();
454 STORE.get_or_init(open_configured).clone()
455 }
456}
457
458#[cfg(test)]
462pub(crate) fn with_store<R: Send>(store: Option<Arc<Store>>, f: impl FnOnce() -> R + Send) -> R {
463 let for_workers = store.clone();
464 let pool = rayon::ThreadPoolBuilder::new()
465 .num_threads(rayon::current_num_threads().clamp(2, 8))
466 .start_handler(move |_| {
467 TEST_OVERRIDE.with(|o| *o.borrow_mut() = for_workers.clone());
468 })
469 .build()
470 .expect("test rayon pool");
471 pool.install(|| {
472 TEST_OVERRIDE.with(|o| *o.borrow_mut() = store);
473 f()
474 })
475}
476
477pub(crate) fn chunks(rel: &str, content: &str) -> Vec<CodeChunk> {
484 let compute = || crate::core::bm25_index::extract_chunks(rel, content);
485 let Some(store) = active() else {
486 return compute();
487 };
488 store.get_or_compute(
489 Kind::Chunks,
490 rel,
491 content,
492 |stored: Vec<StoredChunk>| {
493 stored
494 .into_iter()
495 .map(|c| c.into_chunk(rel))
496 .collect::<Option<Vec<_>>>()
497 },
498 |chunks: &Vec<CodeChunk>| chunks.iter().map(StoredChunk::from_chunk).collect(),
499 || (compute(), true),
500 )
501}
502
503pub(crate) fn deep_analysis(content: &str, ext: &str) -> DeepAnalysis {
505 let compute = || crate::core::deep_queries::analyze(content, ext);
506 let Some(store) = active() else {
507 return compute();
508 };
509 store.get_or_compute(
510 Kind::DeepAnalysis,
511 ext,
512 content,
513 StoredAnalysis::into_analysis,
514 |a: &DeepAnalysis| Some(StoredAnalysis::from_analysis(a)),
515 || (compute(), true),
516 )
517}
518
519pub(crate) fn signatures(content: &str, ext: &str) -> Vec<Signature> {
521 let blocked = crate::core::signatures::tree_sitter_language_blocked;
522 let Some(store) = active().filter(|_| !blocked(ext)) else {
523 return crate::core::signatures::extract_signatures(content, ext);
524 };
525 let mut parsed = false;
526 let (sigs, tree_sitter) = store.get_or_compute(
527 Kind::Signatures,
528 ext,
529 content,
530 StoredSignatures::into_signatures,
531 |(sigs, ts): &(Vec<Signature>, bool)| Some(StoredSignatures::from_signatures(sigs, *ts)),
532 || {
533 parsed = true;
534 let (sigs, backend) = crate::core::signatures::extract_signatures_counted(content, ext);
535 let ts = matches!(backend, crate::core::signatures::SigBackend::TreeSitter);
536 ((sigs, ts), !blocked(ext))
539 },
540 );
541 if !parsed {
542 crate::core::signatures::count_signature_backend(if tree_sitter {
544 crate::core::signatures::SigBackend::TreeSitter
545 } else {
546 crate::core::signatures::SigBackend::Regex
547 });
548 }
549 crate::core::grammar_usage::record(ext, tree_sitter);
550 sigs
551}
552
553#[derive(Serialize, Deserialize)]
558struct StoredChunk {
559 symbol_name: String,
560 kind: u8,
561 start_line: usize,
562 end_line: usize,
563 content: String,
564 tokens: Vec<String>,
565 token_count: usize,
566}
567
568fn chunk_kind_tag(kind: &ChunkKind) -> Option<u8> {
573 Some(match kind {
574 ChunkKind::Function => 0,
575 ChunkKind::Struct => 1,
576 ChunkKind::Impl => 2,
577 ChunkKind::Module => 3,
578 ChunkKind::Class => 4,
579 ChunkKind::Method => 5,
580 ChunkKind::Other => 6,
581 ChunkKind::Issue
582 | ChunkKind::PullRequest
583 | ChunkKind::WikiPage
584 | ChunkKind::DbSchema
585 | ChunkKind::ApiEndpoint
586 | ChunkKind::Ticket
587 | ChunkKind::ExternalOther => return None,
588 })
589}
590
591fn chunk_kind_from_tag(tag: u8) -> Option<ChunkKind> {
592 Some(match tag {
593 0 => ChunkKind::Function,
594 1 => ChunkKind::Struct,
595 2 => ChunkKind::Impl,
596 3 => ChunkKind::Module,
597 4 => ChunkKind::Class,
598 5 => ChunkKind::Method,
599 6 => ChunkKind::Other,
600 _ => return None,
601 })
602}
603
604fn import_kind_tag(kind: &ImportKind) -> u8 {
605 match kind {
606 ImportKind::Named => 0,
607 ImportKind::Default => 1,
608 ImportKind::Star => 2,
609 ImportKind::SideEffect => 3,
610 ImportKind::Dynamic => 4,
611 ImportKind::Reexport => 5,
612 }
613}
614
615fn import_kind_from_tag(tag: u8) -> Option<ImportKind> {
616 Some(match tag {
617 0 => ImportKind::Named,
618 1 => ImportKind::Default,
619 2 => ImportKind::Star,
620 3 => ImportKind::SideEffect,
621 4 => ImportKind::Dynamic,
622 5 => ImportKind::Reexport,
623 _ => return None,
624 })
625}
626
627fn type_kind_tag(kind: &TypeDefKind) -> u8 {
628 match kind {
629 TypeDefKind::Class => 0,
630 TypeDefKind::Interface => 1,
631 TypeDefKind::TypeAlias => 2,
632 TypeDefKind::Enum => 3,
633 TypeDefKind::Struct => 4,
634 TypeDefKind::Trait => 5,
635 TypeDefKind::Protocol => 6,
636 TypeDefKind::Record => 7,
637 TypeDefKind::Annotation => 8,
638 TypeDefKind::Union => 9,
639 }
640}
641
642fn type_kind_from_tag(tag: u8) -> Option<TypeDefKind> {
643 Some(match tag {
644 0 => TypeDefKind::Class,
645 1 => TypeDefKind::Interface,
646 2 => TypeDefKind::TypeAlias,
647 3 => TypeDefKind::Enum,
648 4 => TypeDefKind::Struct,
649 5 => TypeDefKind::Trait,
650 6 => TypeDefKind::Protocol,
651 7 => TypeDefKind::Record,
652 8 => TypeDefKind::Annotation,
653 9 => TypeDefKind::Union,
654 _ => return None,
655 })
656}
657
658impl StoredChunk {
659 fn from_chunk(c: &CodeChunk) -> Option<Self> {
662 if c.input_origin.is_some() {
663 return None;
664 }
665 let kind = chunk_kind_tag(&c.kind)?;
666 Some(Self {
667 symbol_name: c.symbol_name.clone(),
668 kind,
669 start_line: c.start_line,
670 end_line: c.end_line,
671 content: c.content.clone(),
672 tokens: c.tokens.clone(),
673 token_count: c.token_count,
674 })
675 }
676
677 fn into_chunk(self, rel: &str) -> Option<CodeChunk> {
678 Some(CodeChunk {
679 file_path: rel.to_string(),
680 symbol_name: self.symbol_name,
681 kind: chunk_kind_from_tag(self.kind)?,
682 start_line: self.start_line,
683 end_line: self.end_line,
684 content: self.content,
685 tokens: self.tokens,
686 token_count: self.token_count,
687 input_origin: None,
688 })
689 }
690}
691
692#[derive(Serialize, Deserialize)]
693struct StoredAnalysis {
694 imports: Vec<(String, Vec<String>, u8, usize, bool)>,
695 calls: Vec<StoredCall>,
696 types: Vec<StoredType>,
697 exports: Vec<String>,
698 type_uses: Vec<(String, usize)>,
699 ext_methods: Vec<(String, usize, usize)>,
700}
701
702#[derive(Serialize, Deserialize)]
703struct StoredCall {
704 callee: String,
705 line: usize,
706 col: usize,
707 receiver: Option<String>,
708 is_method: bool,
709 callee_pos: Option<(usize, usize)>,
710}
711
712#[derive(Serialize, Deserialize)]
713struct StoredType {
714 name: String,
715 kind: u8,
716 line: usize,
717 end_line: usize,
718 is_exported: bool,
719 generics: Vec<String>,
720 namespace: Option<String>,
721}
722
723impl StoredAnalysis {
724 fn from_analysis(a: &DeepAnalysis) -> Self {
725 Self {
726 imports: a
727 .imports
728 .iter()
729 .map(|i| {
730 (
731 i.source.clone(),
732 i.names.clone(),
733 import_kind_tag(&i.kind),
734 i.line,
735 i.is_type_only,
736 )
737 })
738 .collect(),
739 calls: a
740 .calls
741 .iter()
742 .map(|c| StoredCall {
743 callee: c.callee.clone(),
744 line: c.line,
745 col: c.col,
746 receiver: c.receiver.clone(),
747 is_method: c.is_method,
748 callee_pos: c.callee_pos,
749 })
750 .collect(),
751 types: a
752 .types
753 .iter()
754 .map(|t| StoredType {
755 name: t.name.clone(),
756 kind: type_kind_tag(&t.kind),
757 line: t.line,
758 end_line: t.end_line,
759 is_exported: t.is_exported,
760 generics: t.generics.clone(),
761 namespace: t.namespace.clone(),
762 })
763 .collect(),
764 exports: a.exports.clone(),
765 type_uses: a
766 .type_uses
767 .iter()
768 .map(|u| (u.name.clone(), u.line))
769 .collect(),
770 ext_methods: a
771 .ext_methods
772 .iter()
773 .map(|m| (m.name.clone(), m.line, m.end_line))
774 .collect(),
775 }
776 }
777
778 fn into_analysis(self) -> Option<DeepAnalysis> {
779 let imports = self
780 .imports
781 .into_iter()
782 .map(|(source, names, kind, line, is_type_only)| {
783 Some(ImportInfo {
784 source,
785 names,
786 kind: import_kind_from_tag(kind)?,
787 line,
788 is_type_only,
789 })
790 })
791 .collect::<Option<Vec<_>>>()?;
792 let types = self
793 .types
794 .into_iter()
795 .map(|t| {
796 Some(TypeDef {
797 name: t.name,
798 kind: type_kind_from_tag(t.kind)?,
799 line: t.line,
800 end_line: t.end_line,
801 is_exported: t.is_exported,
802 generics: t.generics,
803 namespace: t.namespace,
804 })
805 })
806 .collect::<Option<Vec<_>>>()?;
807 Some(DeepAnalysis {
808 imports,
809 calls: self
810 .calls
811 .into_iter()
812 .map(|c| CallSite {
813 callee: c.callee,
814 line: c.line,
815 col: c.col,
816 receiver: c.receiver,
817 is_method: c.is_method,
818 callee_pos: c.callee_pos,
819 })
820 .collect(),
821 types,
822 exports: self.exports,
823 type_uses: self
824 .type_uses
825 .into_iter()
826 .map(|(name, line)| TypeUse { name, line })
827 .collect(),
828 ext_methods: self
829 .ext_methods
830 .into_iter()
831 .map(|(name, line, end_line)| ExtMethodDef {
832 name,
833 line,
834 end_line,
835 })
836 .collect(),
837 })
838 }
839}
840
841#[derive(Serialize, Deserialize)]
842struct StoredSignatures {
843 tree_sitter: bool,
844 sigs: Vec<StoredSignature>,
845}
846
847#[derive(Serialize, Deserialize)]
848struct StoredSignature {
849 kind: String,
850 name: String,
851 params: String,
852 return_type: String,
853 is_async: bool,
854 is_exported: bool,
855 indent: usize,
856 start_line: Option<usize>,
857 end_line: Option<usize>,
858}
859
860fn intern_kind(kind: &str) -> Option<&'static str> {
863 const MAX_KINDS: usize = 64;
864 const MAX_KIND_LEN: usize = 32;
865 static KINDS: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
866 if kind.is_empty() || kind.len() > MAX_KIND_LEN || !kind.bytes().all(|b| b.is_ascii_graphic()) {
867 return None;
868 }
869 let mut kinds = KINDS
870 .lock()
871 .unwrap_or_else(std::sync::PoisonError::into_inner);
872 if let Some(known) = kinds.iter().find(|k| **k == kind) {
873 return Some(known);
874 }
875 if kinds.len() >= MAX_KINDS {
876 return None;
877 }
878 let leaked: &'static str = Box::leak(kind.to_owned().into_boxed_str());
879 kinds.push(leaked);
880 Some(leaked)
881}
882
883impl StoredSignatures {
884 fn from_signatures(sigs: &[Signature], tree_sitter: bool) -> Self {
885 Self {
886 tree_sitter,
887 sigs: sigs
888 .iter()
889 .map(|s| StoredSignature {
890 kind: s.kind.to_string(),
891 name: s.name.clone(),
892 params: s.params.clone(),
893 return_type: s.return_type.clone(),
894 is_async: s.is_async,
895 is_exported: s.is_exported,
896 indent: s.indent,
897 start_line: s.start_line,
898 end_line: s.end_line,
899 })
900 .collect(),
901 }
902 }
903
904 fn into_signatures(self) -> Option<(Vec<Signature>, bool)> {
905 let sigs = self
906 .sigs
907 .into_iter()
908 .map(|s| {
909 Some(Signature {
910 kind: intern_kind(&s.kind)?,
911 name: s.name,
912 params: s.params,
913 return_type: s.return_type,
914 is_async: s.is_async,
915 is_exported: s.is_exported,
916 indent: s.indent,
917 start_line: s.start_line,
918 end_line: s.end_line,
919 })
920 })
921 .collect::<Option<Vec<_>>>()?;
922 Some((sigs, self.tree_sitter))
923 }
924}
925
926#[cfg(test)]
927#[path = "derivation_cache_tests.rs"]
928mod tests;