1use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex};
6use std::time::Instant;
7
8use fallow_config::{DuplicatesConfig, ResolvedConfig, WorkspaceInfo};
9use fallow_types::cache_rejection::CacheRejection;
10use fallow_types::discover::DiscoveredFile;
11use fallow_types::extract::{ModuleInfo, SourceParseDegradation, SourceReadFailure};
12#[cfg(test)]
13use fallow_types::results::AnalysisResults;
14use fallow_types::source_fingerprint::{SourceFingerprint, now_ns};
15use fallow_types::workspace::{WorkspaceDiagnostic, merge_workspace_diagnostics};
16use rustc_hash::{FxHashMap, FxHashSet};
17
18pub use crate::session_reuse::SessionParseCounts;
19use crate::session_reuse::{
20 MAX_INCREMENTAL_REPARSE_FILES, ParseCountCells, changed_file_indices, merge_reparsed_modules,
21};
22use crate::{
23 EngineResult, core_backend, duplicates,
24 project_analysis::{
25 ProjectAnalysisArtifactOptions, ProjectAnalysisArtifacts, ProjectAnalysisOutput,
26 },
27 project_config::{ProjectConfig, config_for_project, default_project_config},
28 results::{
29 DeadCodeAnalysis, DeadCodeAnalysisArtifacts, DeadCodeAnalysisOutput, DuplicationAnalysis,
30 SharedDeadCodeAnalysisArtifacts,
31 },
32 warm_parse::{WarmParse, WarmParseKey, WarmParseStore},
33};
34
35#[derive(Debug)]
41pub struct AnalysisSession {
42 config: ResolvedConfig,
43 config_path: Option<PathBuf>,
44 config_inputs: fallow_config::ConfigInputs,
45 config_inputs_before_resolve: fallow_config::ConfigInputsSnapshot,
46 discovery: crate::discover::AnalysisDiscovery,
47 workspaces: Vec<WorkspaceInfo>,
48 workspace_diagnostics: Vec<WorkspaceDiagnostic>,
49 parsed_cache: Mutex<Option<ParsedModuleCache>>,
50 styling_cache: Mutex<Option<Arc<crate::health::StylingAnalysisArtifacts>>>,
51 cancellation: Option<Arc<AtomicBool>>,
52 warm_parse: Option<Arc<WarmParseStore>>,
53 preloaded_workspaces: bool,
56 parse_counts: ParseCountCells,
57 disk_cache_stale: AtomicBool,
60}
61
62#[derive(Debug)]
63struct ParsedModuleCache {
64 need_complexity: bool,
65 fingerprints: Vec<SourceFingerprint>,
66 read_started_ns: u64,
71 modules: Arc<[ModuleInfo]>,
72 read_failures: Vec<SourceReadFailure>,
75 parse_degradations: Vec<SourceParseDegradation>,
77}
78
79#[derive(Debug)]
81pub struct AnalysisSessionParts {
82 pub config: ResolvedConfig,
84 pub config_path: Option<PathBuf>,
86 pub files: Vec<DiscoveredFile>,
88 pub workspaces: Vec<WorkspaceInfo>,
90 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
92}
93
94#[derive(Debug)]
96pub struct ParsedAnalysisSessionParts {
97 pub config: ResolvedConfig,
99 pub config_path: Option<PathBuf>,
101 pub files: Vec<DiscoveredFile>,
103 pub modules: Vec<ModuleInfo>,
105 pub workspaces: Vec<WorkspaceInfo>,
107 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
109 pub parse_ms: f64,
111 pub cache_update_ms: f64,
113 pub cache_hits: usize,
115 pub cache_misses: usize,
117 pub parse_cpu_ms: f64,
119}
120
121#[derive(Debug)]
122pub(crate) struct SharedParsedAnalysisSessionParts {
123 pub(crate) config: ResolvedConfig,
124 pub(crate) files: Vec<DiscoveredFile>,
125 pub(crate) modules: Arc<[ModuleInfo]>,
126 pub workspaces: Vec<WorkspaceInfo>,
127 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
128 pub parse_ms: f64,
129 pub parse_cpu_ms: f64,
130}
131
132#[derive(Debug)]
134pub struct AnalysisSessionArtifacts {
135 pub analysis: DeadCodeAnalysisArtifacts,
137 pub changed_files: Option<FxHashSet<PathBuf>>,
139 pub source_fingerprints: FxHashMap<PathBuf, SourceFingerprint>,
141}
142
143impl AnalysisSession {
144 pub fn load(root: &Path, config_path: Option<&Path>) -> EngineResult<Self> {
150 let project_config = config_for_project(root, config_path)?;
151 Ok(Self::from_config(project_config))
152 }
153
154 pub fn load_with_config(
161 root: &Path,
162 config_path: Option<&Path>,
163 configure: impl FnOnce(&mut ResolvedConfig),
164 ) -> EngineResult<Self> {
165 Self::load_with_config_options(
166 root,
167 config_path,
168 fallow_config::ConfigLoadOptions::default(),
169 configure,
170 )
171 }
172
173 pub fn load_with_config_options(
180 root: &Path,
181 config_path: Option<&Path>,
182 load_options: fallow_config::ConfigLoadOptions,
183 configure: impl FnOnce(&mut ResolvedConfig),
184 ) -> EngineResult<Self> {
185 let mut project_config = crate::project_config::config_for_project_with_load_options(
186 root,
187 config_path,
188 load_options,
189 )?;
190 configure(&mut project_config.config);
191 Ok(Self::from_config(
192 project_config.without_workspace_metadata(),
193 ))
194 }
195
196 #[must_use]
201 pub fn load_default(root: &Path) -> Self {
202 Self::load_default_with_config(root, |_| {})
203 }
204
205 #[must_use]
208 pub fn load_default_with_config(
209 root: &Path,
210 configure: impl FnOnce(&mut ResolvedConfig),
211 ) -> Self {
212 let mut project_config = default_project_config(root);
213 configure(&mut project_config.config);
214 Self::from_config(project_config)
215 }
216
217 #[must_use]
219 pub fn from_config(project_config: ProjectConfig) -> Self {
220 let uses_preloaded_workspaces = project_config.workspace_discovery_ms.is_some();
221 let discovery = if let Some(workspace_discovery_ms) = project_config.workspace_discovery_ms
222 {
223 crate::discover::prepare_analysis_discovery_with_workspaces(
224 &project_config.config,
225 &project_config.workspaces,
226 workspace_discovery_ms,
227 )
228 } else {
229 crate::discover::prepare_analysis_discovery(&project_config.config)
230 };
231 let workspaces = if uses_preloaded_workspaces {
232 project_config.workspaces
233 } else {
234 discovery.workspaces().to_vec()
235 };
236 let workspace_diagnostics = merge_workspace_diagnostics(
248 merge_workspace_diagnostics(
249 project_config.workspace_diagnostics,
250 fallow_config::workspace_diagnostics_for(&project_config.config.root)
251 .into_iter()
252 .filter(|diagnostic| {
253 !diagnostic.kind.is_analysis_stage()
254 && !diagnostic.kind.is_source_discovery()
255 })
256 .collect(),
257 ),
258 discovery.source_diagnostics().to_vec(),
259 );
260 Self {
261 config: project_config.config,
262 config_path: project_config.path,
263 config_inputs: project_config.inputs,
264 config_inputs_before_resolve: project_config.inputs_before_resolve,
265 discovery,
266 workspaces,
267 workspace_diagnostics,
268 parsed_cache: Mutex::new(None),
269 styling_cache: Mutex::new(None),
270 cancellation: None,
271 warm_parse: crate::warm_parse::installed(),
272 preloaded_workspaces: uses_preloaded_workspaces,
273 parse_counts: ParseCountCells::default(),
274 disk_cache_stale: AtomicBool::new(false),
275 }
276 }
277
278 #[must_use]
293 pub fn with_cancellation(mut self, cancellation: Arc<AtomicBool>) -> Self {
294 self.cancellation = Some(cancellation);
295 self
296 }
297
298 #[cfg(all(test, unix))]
302 fn with_warm_parse(mut self, store: Option<Arc<WarmParseStore>>) -> Self {
303 self.warm_parse = store;
304 self
305 }
306
307 pub fn set_cancellation(&mut self, cancellation: Arc<AtomicBool>) {
312 self.cancellation = Some(cancellation);
313 }
314
315 #[must_use]
317 pub fn parse_counts(&self) -> SessionParseCounts {
318 self.parse_counts.snapshot()
319 }
320
321 pub fn refresh_discovery(&mut self) -> bool {
336 let discovery = if self.preloaded_workspaces {
337 crate::discover::prepare_analysis_discovery_with_workspaces(
338 &self.config,
339 &self.workspaces,
340 0.0,
341 )
342 } else {
343 crate::discover::prepare_analysis_discovery(&self.config)
344 };
345 let same_files = discovery.files().len() == self.files().len()
346 && discovery
347 .files()
348 .iter()
349 .zip(self.files())
350 .all(|(fresh, known)| fresh.path == known.path);
351 if !same_files || !self.cached_fingerprints_are_trustworthy() {
352 self.flush_parse_cache();
353 *self
354 .parsed_cache
355 .get_mut()
356 .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
357 self.clear_styling_cache();
358 }
359 if !self.preloaded_workspaces {
360 self.workspaces = discovery.workspaces().to_vec();
361 }
362 self.discovery = discovery;
363 !same_files
364 }
365
366 fn cached_fingerprints_are_trustworthy(&mut self) -> bool {
369 self.parsed_cache
370 .get_mut()
371 .unwrap_or_else(std::sync::PoisonError::into_inner)
372 .as_ref()
373 .is_none_or(|cache| {
374 cache
375 .fingerprints
376 .iter()
377 .all(|fingerprint| fingerprint.is_trustworthy_without_content())
378 })
379 }
380
381 pub fn flush_parse_cache(&self) {
395 if self.config.no_cache || !self.disk_cache_stale.swap(false, Ordering::SeqCst) {
396 return;
397 }
398 let Ok(cache) = self.parsed_cache.lock() else {
399 return;
400 };
401 let Some(cache) = cache.as_ref() else {
402 return;
403 };
404 let cache_max_size_bytes =
405 crate::project_config::resolve_cache_max_size_bytes(&self.config);
406 let mut store = fallow_extract::cache::CacheStore::load(
407 &self.config.cache_dir,
408 &self.config.root,
409 self.config.cache_config_hash,
410 cache_max_size_bytes,
411 )
412 .ok();
413 let files = self.files();
414 write_parse_cache(
415 &self.config,
416 &mut store,
417 &ParseCacheWrite {
418 modules: &cache.modules,
419 files,
420 need_complexity: cache.need_complexity,
421 fingerprint_of: &|file: &DiscoveredFile| {
422 cache.fingerprints.get(file.id.0 as usize).map_or_else(
423 || SourceFingerprint::new(0, 0),
424 |fingerprint| fingerprint.for_content_read_at(cache.read_started_ns),
425 )
426 },
427 },
428 );
429 }
430
431 pub fn prewarm_parsed_modules(&self, need_complexity: bool) -> EngineResult<()> {
440 self.shared_parsed_modules_cancellable(need_complexity, "prewarm")
441 .map(drop)
442 }
443
444 fn clear_styling_cache(&self) {
445 if let Ok(mut cache) = self.styling_cache.lock() {
446 *cache = None;
447 }
448 }
449
450 #[must_use]
452 pub fn is_cancelled(&self) -> bool {
453 self.cancellation
454 .as_ref()
455 .is_some_and(|cancelled| cancelled.load(Ordering::SeqCst))
456 }
457
458 fn ensure_not_cancelled(&self, stage: &str) -> EngineResult<()> {
459 if self.is_cancelled() {
460 return Err(crate::EngineError::cancelled(stage));
461 }
462 Ok(())
463 }
464
465 pub fn from_resolved_config(config: ResolvedConfig) -> EngineResult<Self> {
473 let (workspaces, workspace_diagnostics, workspace_discovery_ms) =
474 crate::project_config::collect_workspace_metadata(&config)?;
475 Ok(Self::from_config(ProjectConfig {
476 inputs: fallow_config::ConfigInputs::default(),
477 inputs_before_resolve: fallow_config::ConfigInputsSnapshot::default(),
478 config,
479 path: None,
480 workspaces,
481 workspace_diagnostics,
482 workspace_discovery_ms: Some(workspace_discovery_ms),
483 }))
484 }
485
486 #[must_use]
488 pub fn root(&self) -> &Path {
489 &self.config.root
490 }
491
492 #[must_use]
494 pub fn config(&self) -> &ResolvedConfig {
495 &self.config
496 }
497
498 #[must_use]
500 pub fn config_path(&self) -> Option<&Path> {
501 self.config_path.as_deref()
502 }
503
504 #[must_use]
508 pub const fn config_inputs(&self) -> &fallow_config::ConfigInputs {
509 &self.config_inputs
510 }
511
512 #[must_use]
516 pub const fn config_inputs_before_resolve(&self) -> &fallow_config::ConfigInputsSnapshot {
517 &self.config_inputs_before_resolve
518 }
519
520 #[must_use]
525 pub fn retained_bytes_estimate(&self) -> u64 {
526 self.parsed_cache
527 .lock()
528 .ok()
529 .and_then(|cache| {
530 cache
531 .as_ref()
532 .map(|cache| crate::warm_parse::estimated_retained_bytes(&cache.fingerprints))
533 })
534 .unwrap_or(0)
535 }
536
537 #[must_use]
539 pub fn files(&self) -> &[DiscoveredFile] {
540 self.discovery.files()
541 }
542
543 #[must_use]
545 pub fn workspaces(&self) -> &[WorkspaceInfo] {
546 &self.workspaces
547 }
548
549 #[must_use]
551 fn source_fingerprints(&self) -> FxHashMap<PathBuf, SourceFingerprint> {
552 self.discovery
553 .files()
554 .iter()
555 .map(|file| {
556 let fingerprint = std::fs::metadata(&file.path).map_or_else(
557 |_| SourceFingerprint::new(0, file.size_bytes),
558 |metadata| SourceFingerprint::from_metadata(&metadata),
559 );
560 (file.path.clone(), fingerprint)
561 })
562 .collect()
563 }
564
565 pub(crate) fn changed_files_since(
572 &self,
573 git_ref: &str,
574 ) -> Result<FxHashSet<PathBuf>, crate::changed_files::ChangedFilesError> {
575 crate::changed_files::changed_files(&self.config.root, git_ref)
576 }
577
578 pub(crate) const fn discovery(&self) -> &crate::discover::AnalysisDiscovery {
580 &self.discovery
581 }
582
583 #[must_use]
585 pub fn workspace_diagnostics(&self) -> &[WorkspaceDiagnostic] {
586 &self.workspace_diagnostics
587 }
588
589 #[must_use]
602 pub fn current_workspace_diagnostics(&self) -> Vec<WorkspaceDiagnostic> {
603 merge_workspace_diagnostics(
604 self.workspace_diagnostics.clone(),
605 fallow_config::registry_diagnostics_to_fold(&self.config.root),
606 )
607 }
608
609 pub(crate) fn styling_analysis_artifacts(
610 &self,
611 ) -> Arc<crate::health::StylingAnalysisArtifacts> {
612 if let Ok(cache) = self.styling_cache.lock()
613 && let Some(artifacts) = cache.as_ref()
614 {
615 return Arc::clone(artifacts);
616 }
617
618 let modules = self.shared_parsed_modules(false);
619 let artifacts = Arc::new(crate::health::build_styling_analysis_artifacts(
620 self.files(),
621 &modules,
622 self.config(),
623 ));
624 if let Ok(mut cache) = self.styling_cache.lock() {
625 *cache = Some(Arc::clone(&artifacts));
626 }
627 artifacts
628 }
629
630 #[must_use]
632 pub fn into_parts(self) -> AnalysisSessionParts {
633 let workspace_diagnostics = self.current_workspace_diagnostics();
634 AnalysisSessionParts {
635 config: self.config,
636 config_path: self.config_path,
637 files: self.discovery.into_files(),
638 workspaces: self.workspaces,
639 workspace_diagnostics,
640 }
641 }
642
643 #[must_use]
645 pub fn parsed_parts(&self, need_complexity: bool) -> ParsedAnalysisSessionParts {
646 let SharedParsedModules { modules, metrics } = self.parse_modules(need_complexity, None);
647 self.parsed_parts_from_modules(modules.to_vec(), metrics)
648 }
649
650 #[must_use]
652 pub(crate) fn shared_parsed_parts(
653 &self,
654 need_complexity: bool,
655 ) -> SharedParsedAnalysisSessionParts {
656 let SharedParsedModules { modules, metrics } = self.parse_modules(need_complexity, None);
657 SharedParsedAnalysisSessionParts {
658 config: self.config.clone(),
659 files: self.discovery.files().to_vec(),
660 modules,
661 workspaces: self.workspaces.clone(),
662 workspace_diagnostics: self.current_workspace_diagnostics(),
663 parse_ms: metrics.parse_ms,
664 parse_cpu_ms: metrics.parse_cpu_ms,
665 }
666 }
667
668 #[doc(hidden)]
674 #[must_use]
675 pub(crate) fn shared_parsed_modules(&self, need_complexity: bool) -> Arc<[ModuleInfo]> {
676 self.parse_modules(need_complexity, None).modules
677 }
678
679 pub(crate) fn shared_parsed_modules_cancellable(
690 &self,
691 need_complexity: bool,
692 stage: &str,
693 ) -> EngineResult<Arc<[ModuleInfo]>> {
694 self.ensure_not_cancelled("parsing")?;
695 let modules = self
696 .parse_modules(need_complexity, self.cancellation.as_deref())
697 .modules;
698 self.ensure_not_cancelled(stage)?;
699 Ok(modules)
700 }
701
702 #[must_use]
705 pub fn parsed_parts_uncached(&self, need_complexity: bool) -> ParsedAnalysisSessionParts {
706 let read_started_ns = now_ns();
707 let fingerprints = self
708 .warm_parse
709 .as_ref()
710 .and_then(|_| source_fingerprints_for_files(self.files()));
711 if let Some(warm) = self.warm_parse(
712 need_complexity,
713 fingerprints.as_deref(),
714 read_started_ns,
715 None,
716 ) {
717 return self.parsed_parts_from_modules(warm.modules.to_vec(), warm.metrics);
718 }
719 let ParsedModules {
720 modules, metrics, ..
721 } = parse_files_with_config(&self.config, self.files(), need_complexity, None);
722 self.parsed_parts_from_modules(modules, metrics)
723 }
724
725 fn parsed_parts_from_modules(
726 &self,
727 modules: Vec<ModuleInfo>,
728 metrics: core_backend::ParseMetrics,
729 ) -> ParsedAnalysisSessionParts {
730 ParsedAnalysisSessionParts {
731 config: self.config.clone(),
732 config_path: self.config_path.clone(),
733 files: self.discovery.files().to_vec(),
734 modules,
735 workspaces: self.workspaces.clone(),
736 workspace_diagnostics: self.current_workspace_diagnostics(),
737 parse_ms: metrics.parse_ms,
738 cache_update_ms: metrics.cache_ms,
739 cache_hits: metrics.cache_hits,
740 cache_misses: metrics.cache_misses,
741 parse_cpu_ms: metrics.parse_cpu_ms,
742 }
743 }
744
745 pub fn analyze_dead_code(&self) -> EngineResult<DeadCodeAnalysis> {
751 self.analyze_dead_code_with_artifacts(false, false)
752 .map(|output| DeadCodeAnalysis {
753 results: output.results,
754 })
755 }
756
757 pub fn analyze_dead_code_with_complexity(&self) -> EngineResult<DeadCodeAnalysisOutput> {
763 self.analyze_dead_code_with_artifacts(true, false)
764 .map(|output| DeadCodeAnalysisOutput {
765 results: output.results,
766 modules: output.modules,
767 files: output.files,
768 })
769 }
770
771 pub fn analyze_dead_code_with_artifacts(
777 &self,
778 need_complexity: bool,
779 retain_graph: bool,
780 ) -> EngineResult<DeadCodeAnalysisArtifacts> {
781 self.analyze_dead_code_with_shared_artifacts(need_complexity, retain_graph)
782 .map(SharedDeadCodeAnalysisArtifacts::into_owned)
783 }
784
785 #[doc(hidden)]
795 pub fn analyze_dead_code_with_shared_artifacts(
796 &self,
797 need_complexity: bool,
798 retain_graph: bool,
799 ) -> EngineResult<SharedDeadCodeAnalysisArtifacts> {
800 self.analyze_dead_code_with_reuse_artifacts(need_complexity, retain_graph, need_complexity)
801 }
802
803 pub fn analyze_dead_code_retaining_files(
810 &self,
811 need_complexity: bool,
812 retain_graph: bool,
813 ) -> EngineResult<DeadCodeAnalysisArtifacts> {
814 self.analyze_dead_code_with_reuse_artifacts(need_complexity, retain_graph, true)
815 .map(SharedDeadCodeAnalysisArtifacts::into_owned)
816 }
817
818 pub fn analyze_dead_code_with_parsed_modules(
827 &self,
828 modules: &[ModuleInfo],
829 ) -> EngineResult<DeadCodeAnalysisArtifacts> {
830 self.analyze_dead_code_with_shared_modules(Arc::from(modules))
831 }
832
833 #[doc(hidden)]
839 pub(crate) fn analyze_dead_code_with_shared_modules(
840 &self,
841 modules: Arc<[ModuleInfo]>,
842 ) -> EngineResult<DeadCodeAnalysisArtifacts> {
843 run_engine_owned_dead_code_pipeline(EngineDeadCodePipelineInput {
844 config: &self.config,
845 discovery: &self.discovery,
846 modules,
847 metrics: reused_parse_metrics(),
848 collect_usages: true,
849 graph: crate::session_graph::GraphChoice::WithTrace,
850 retain_modules: false,
851 retain_files: false,
852 cancellation: self.cancellation.as_deref(),
853 })
854 .map(SharedDeadCodeAnalysisArtifacts::into_owned)
855 }
856
857 pub(crate) fn analyze_dead_code_with_reuse_artifacts(
858 &self,
859 need_complexity: bool,
860 graph: impl Into<crate::session_graph::GraphChoice>,
861 retain_files: bool,
862 ) -> EngineResult<SharedDeadCodeAnalysisArtifacts> {
863 self.ensure_not_cancelled("parsing")?;
864 let SharedParsedModules { modules, metrics } =
865 self.parse_modules(need_complexity, self.cancellation.as_deref());
866 self.ensure_not_cancelled("the dead-code pipeline")?;
870 run_engine_owned_dead_code_pipeline(EngineDeadCodePipelineInput {
871 config: &self.config,
872 discovery: &self.discovery,
873 modules,
874 metrics,
875 collect_usages: true,
876 graph: graph.into(),
877 retain_modules: need_complexity,
878 retain_files,
879 cancellation: self.cancellation.as_deref(),
880 })
881 }
882
883 pub fn analyze_dead_code_with_session_artifacts(
894 &self,
895 need_complexity: bool,
896 retain_graph: bool,
897 changed_files: Option<FxHashSet<PathBuf>>,
898 ) -> EngineResult<AnalysisSessionArtifacts> {
899 Ok(AnalysisSessionArtifacts {
900 analysis: self.analyze_dead_code_with_artifacts(need_complexity, retain_graph)?,
901 changed_files,
902 source_fingerprints: self.source_fingerprints(),
903 })
904 }
905
906 pub fn analyze_project_with(
915 &self,
916 duplicates_config: &DuplicatesConfig,
917 retain_complexity_artifacts: bool,
918 ) -> EngineResult<ProjectAnalysisOutput> {
919 self.analyze_project_with_artifacts(
920 duplicates_config,
921 ProjectAnalysisArtifactOptions {
922 retain_complexity_artifacts,
923 ..ProjectAnalysisArtifactOptions::default()
924 },
925 )
926 .map(ProjectAnalysisArtifacts::into_output)
927 }
928
929 pub fn analyze_project_with_artifacts(
939 &self,
940 duplicates_config: &DuplicatesConfig,
941 options: ProjectAnalysisArtifactOptions,
942 ) -> EngineResult<ProjectAnalysisArtifacts> {
943 self.ensure_not_cancelled("duplication detection")?;
944 let cache_dir = (!self.config.no_cache).then_some(self.config.cache_dir.as_path());
945 let duplication = if let Some(changed_files) = options.changed_files.as_ref() {
946 let changed_files = changed_files.iter().cloned().collect::<Vec<_>>();
947 self.find_duplicates_touching_files_with_defaults(
948 duplicates_config,
949 &changed_files,
950 cache_dir,
951 )
952 .report
953 } else {
954 self.find_duplicates_with_defaults(duplicates_config, cache_dir)
955 .report
956 };
957 self.ensure_not_cancelled("the dead-code half of project analysis")?;
961 let source_fingerprints = options
962 .collect_source_fingerprints
963 .then(|| self.source_fingerprints());
964 Ok(ProjectAnalysisArtifacts {
965 dead_code: self.analyze_dead_code_with_artifacts(
966 options.retain_complexity_artifacts,
967 options.retain_graph,
968 )?,
969 duplication,
970 changed_files: options.changed_files,
971 source_fingerprints,
972 })
973 }
974
975 #[must_use]
977 pub fn find_duplicates_with_defaults(
978 &self,
979 config: &DuplicatesConfig,
980 cache_dir: Option<&Path>,
981 ) -> DuplicationAnalysis {
982 duplicates::find_duplicates_with_defaults(
983 &self.config.root,
984 self.files(),
985 config,
986 cache_dir,
987 )
988 }
989
990 #[must_use]
992 pub fn find_duplicates_touching_files_with_defaults(
993 &self,
994 config: &DuplicatesConfig,
995 changed_files: &[PathBuf],
996 cache_dir: Option<&Path>,
997 ) -> DuplicationAnalysis {
998 duplicates::find_duplicates_touching_files_with_defaults(
999 &self.config.root,
1000 self.files(),
1001 config,
1002 changed_files,
1003 cache_dir,
1004 )
1005 }
1006
1007 fn parse_modules(
1013 &self,
1014 need_complexity: bool,
1015 cancellation: Option<&AtomicBool>,
1016 ) -> SharedParsedModules {
1017 let read_started_ns = now_ns();
1018 let fingerprints = source_fingerprints_for_files(self.files());
1019 if let Some(fingerprints) = fingerprints.as_ref()
1020 && let Some(parsed) = self.reparse_changed_modules(
1021 need_complexity,
1022 fingerprints,
1023 read_started_ns,
1024 cancellation,
1025 )
1026 {
1027 return parsed;
1028 }
1029
1030 let (modules, metrics, has_complexity, modules_reused, problems) = if let Some(warm) = self
1031 .warm_parse(
1032 need_complexity,
1033 fingerprints.as_deref(),
1034 read_started_ns,
1035 cancellation,
1036 ) {
1037 let reused = if warm.reused { warm.modules.len() } else { 0 };
1038 (warm.modules, warm.metrics, true, reused, warm.problems)
1039 } else {
1040 let ParsedModules {
1041 modules,
1042 metrics,
1043 read_failures,
1044 parse_degradations,
1045 } = parse_files_with_config(&self.config, self.files(), need_complexity, cancellation);
1046 let problems = SourceProblems {
1047 read_failures,
1048 parse_degradations,
1049 };
1050 (modules.into(), metrics, need_complexity, 0, problems)
1051 };
1052 self.parse_counts.record(SessionParseCounts {
1053 modules_parsed: metrics.cache_misses,
1054 disk_cache_hits: metrics.cache_hits,
1055 modules_reused,
1056 });
1057 if !token_is_set(cancellation)
1061 && let Some(fingerprints) = fingerprints
1062 && let Ok(mut cache) = self.parsed_cache.lock()
1063 {
1064 *cache = Some(ParsedModuleCache {
1065 need_complexity: has_complexity,
1066 fingerprints,
1067 read_started_ns,
1068 modules: Arc::clone(&modules),
1069 read_failures: problems.read_failures,
1070 parse_degradations: problems.parse_degradations,
1071 });
1072 self.disk_cache_stale.store(false, Ordering::SeqCst);
1074 self.clear_styling_cache();
1075 }
1076 SharedParsedModules { modules, metrics }
1077 }
1078
1079 fn warm_parse(
1092 &self,
1093 need_complexity: bool,
1094 fingerprints: Option<&[SourceFingerprint]>,
1095 read_started_ns: u64,
1096 cancellation: Option<&AtomicBool>,
1097 ) -> Option<WarmParsedModules> {
1098 let store = self.warm_parse.as_deref()?;
1099 if self.config.no_cache {
1100 return None;
1101 }
1102 let key = WarmParseKey {
1103 root: &self.config.root,
1104 cache_config_hash: self.config.cache_config_hash,
1105 files: self.files(),
1106 fingerprints: fingerprints?,
1107 read_started_ns,
1108 };
1109 if !key.is_reusable() {
1110 return None;
1111 }
1112 let need_call_facts = self.config.reads_call_facts();
1113 if let Some(parse) = store.get(&key, need_complexity, need_call_facts) {
1114 record_source_diagnostics(
1119 &self.config,
1120 &parse.read_failures,
1121 &parse.parse_degradations,
1122 );
1123 return Some(WarmParsedModules {
1124 modules: parse.modules,
1125 metrics: reused_parse_metrics(),
1126 reused: true,
1127 problems: SourceProblems {
1128 read_failures: parse.read_failures.to_vec(),
1129 parse_degradations: parse.parse_degradations.to_vec(),
1130 },
1131 });
1132 }
1133
1134 let parsed = parse_files_with_config(&self.config, self.files(), true, cancellation);
1135 store.record_parse(parsed.metrics.cache_misses, parsed.metrics.cache_hits);
1136 let modules: Arc<[ModuleInfo]> = parsed.modules.into();
1137 if !token_is_set(cancellation) {
1138 store.put(
1139 &key,
1140 true,
1141 need_call_facts,
1142 WarmParse {
1143 modules: Arc::clone(&modules),
1144 read_failures: parsed.read_failures.clone().into(),
1145 parse_degradations: parsed.parse_degradations.clone().into(),
1146 },
1147 );
1148 }
1149 Some(WarmParsedModules {
1150 modules,
1151 metrics: parsed.metrics,
1152 reused: false,
1153 problems: SourceProblems {
1154 read_failures: parsed.read_failures,
1155 parse_degradations: parsed.parse_degradations,
1156 },
1157 })
1158 }
1159
1160 fn changed_since_kept_parse(
1168 &self,
1169 need_complexity: bool,
1170 fingerprints: &[SourceFingerprint],
1171 ) -> Option<(Vec<usize>, u64, Arc<[ModuleInfo]>)> {
1172 let unsettled = std::cell::RefCell::new(Vec::new());
1173 let guard = self.parsed_cache.lock().ok()?;
1174 let cache = guard.as_ref()?;
1175 if need_complexity && !cache.need_complexity {
1176 return None;
1177 }
1178 let mut changed = changed_file_indices(
1179 &cache.fingerprints,
1180 cache.read_started_ns,
1181 fingerprints,
1182 &|index| {
1183 unsettled.borrow_mut().push(index);
1184 true
1185 },
1186 )?;
1187 let kept_read_started_ns = cache.read_started_ns;
1188 let kept_modules = Arc::clone(&cache.modules);
1189 drop(guard);
1190 changed.extend(unsettled.into_inner().into_iter().filter(|&index| {
1191 !self.files().get(index).is_some_and(|file| {
1192 crate::session_reuse::module_matches_source(&kept_modules, file.id, &file.path)
1193 })
1194 }));
1195 changed.sort_unstable();
1196 Some((changed, kept_read_started_ns, kept_modules))
1197 }
1198
1199 fn reparse_changed_modules(
1208 &self,
1209 need_complexity: bool,
1210 fingerprints: &[SourceFingerprint],
1211 read_started_ns: u64,
1212 cancellation: Option<&AtomicBool>,
1213 ) -> Option<SharedParsedModules> {
1214 let (changed, kept_read_started_ns, kept_modules) =
1215 self.changed_since_kept_parse(need_complexity, fingerprints)?;
1216 let mut guard = self.parsed_cache.lock().ok()?;
1217 let cache = guard.as_mut()?;
1218 if !Arc::ptr_eq(&cache.modules, &kept_modules)
1221 || cache.read_started_ns != kept_read_started_ns
1222 {
1223 return None;
1224 }
1225 drop(kept_modules);
1228 if changed.is_empty() {
1229 cache.read_started_ns = read_started_ns;
1233 let modules = Arc::clone(&cache.modules);
1234 drop(guard);
1235 self.parse_counts.record(SessionParseCounts {
1236 modules_reused: modules.len(),
1237 ..SessionParseCounts::default()
1238 });
1239 return Some(SharedParsedModules {
1240 modules,
1241 metrics: reused_parse_metrics(),
1242 });
1243 }
1244 if changed.len() > MAX_INCREMENTAL_REPARSE_FILES {
1245 return None;
1246 }
1247 let files: Vec<DiscoveredFile> = changed
1248 .iter()
1249 .filter_map(|&index| self.files().get(index).cloned())
1250 .collect();
1251 let parse_start = Instant::now();
1252 let parsed = crate::source::parse_all_files(
1253 &files,
1254 None,
1255 fallow_extract::ParseNeeds {
1256 complexity: cache.need_complexity,
1257 call_facts: self.config.reads_call_facts(),
1258 },
1259 cancellation,
1260 &self.config.flags.patterns(),
1261 self.config.extraction_mode,
1262 );
1263 if token_is_set(cancellation) {
1266 return Some(SharedParsedModules {
1267 modules: Arc::clone(&cache.modules),
1268 metrics: reused_parse_metrics(),
1269 });
1270 }
1271 let mut fresh = parsed.modules;
1272 for module in &mut fresh {
1273 module.prepare_analysis_facts();
1274 }
1275 let fresh_count = fresh.len();
1276 let reparsed: Vec<_> = files.iter().map(|file| file.id).collect();
1277 merge_reparsed_modules(&mut cache.modules, &reparsed, fresh);
1278 cache.fingerprints = fingerprints.to_vec();
1279 cache.read_started_ns = read_started_ns;
1280 cache
1281 .read_failures
1282 .retain(|failure| !reparsed.contains(&failure.file_id));
1283 cache.read_failures.extend(parsed.read_failures);
1284 cache
1285 .parse_degradations
1286 .retain(|degradation| !reparsed.contains(°radation.file_id));
1287 cache.parse_degradations.extend(parsed.parse_degradations);
1288 record_source_diagnostics(
1289 &self.config,
1290 &cache.read_failures,
1291 &cache.parse_degradations,
1292 );
1293 self.parse_counts.record(SessionParseCounts {
1294 modules_parsed: parsed.cache_misses,
1295 disk_cache_hits: 0,
1296 modules_reused: cache.modules.len().saturating_sub(fresh_count),
1297 });
1298 let modules = Arc::clone(&cache.modules);
1299 drop(guard);
1300 self.disk_cache_stale.store(true, Ordering::SeqCst);
1301 self.clear_styling_cache();
1302 Some(SharedParsedModules {
1303 modules,
1304 metrics: core_backend::ParseMetrics {
1305 parse_ms: parse_start.elapsed().as_secs_f64() * 1000.0,
1306 cache_ms: 0.0,
1307 cache_hits: 0,
1308 cache_misses: parsed.cache_misses,
1309 parse_cpu_ms: parsed.parse_cpu_ms,
1310 cache_rejection: None,
1311 files_read: parsed.files_read,
1312 source_bytes_read: parsed.source_bytes_read,
1313 parse_cache_bytes_read: 0,
1314 css_masked_bytes: parsed.css_masked_bytes,
1315 parse_cache_load_ms: 0.0,
1316 },
1317 })
1318 }
1319}
1320
1321struct ParsedModules {
1322 modules: Vec<ModuleInfo>,
1323 metrics: core_backend::ParseMetrics,
1324 read_failures: Vec<SourceReadFailure>,
1325 parse_degradations: Vec<SourceParseDegradation>,
1326}
1327
1328struct SharedParsedModules {
1329 modules: Arc<[ModuleInfo]>,
1330 metrics: core_backend::ParseMetrics,
1331}
1332
1333struct WarmParsedModules {
1335 modules: Arc<[ModuleInfo]>,
1336 metrics: core_backend::ParseMetrics,
1337 reused: bool,
1339 problems: SourceProblems,
1340}
1341
1342struct SourceProblems {
1344 read_failures: Vec<SourceReadFailure>,
1345 parse_degradations: Vec<SourceParseDegradation>,
1346}
1347
1348#[path = "session_parse.rs"]
1349mod parsing;
1350use parsing::parse_files_with_config;
1351fn token_is_set(cancellation: Option<&AtomicBool>) -> bool {
1352 cancellation.is_some_and(|cancelled| cancelled.load(Ordering::SeqCst))
1353}
1354
1355fn record_source_diagnostics(
1358 config: &ResolvedConfig,
1359 read_failures: &[SourceReadFailure],
1360 parse_degradations: &[SourceParseDegradation],
1361) -> Vec<WorkspaceDiagnostic> {
1362 let mut diagnostics = fallow_config::record_source_read_failures(&config.root, read_failures);
1363 diagnostics.extend(fallow_config::record_source_parse_degradations(
1364 config,
1365 parse_degradations,
1366 ));
1367 diagnostics
1368}
1369
1370fn reused_parse_metrics() -> core_backend::ParseMetrics {
1371 core_backend::ParseMetrics {
1372 parse_ms: 0.0,
1373 cache_ms: 0.0,
1374 cache_hits: 0,
1375 cache_misses: 0,
1376 parse_cpu_ms: 0.0,
1377 cache_rejection: None,
1378 files_read: 0,
1379 source_bytes_read: 0,
1380 parse_cache_bytes_read: 0,
1381 css_masked_bytes: 0,
1382 parse_cache_load_ms: 0.0,
1383 }
1384}
1385
1386fn source_fingerprints_for_files(files: &[DiscoveredFile]) -> Option<Vec<SourceFingerprint>> {
1387 files
1388 .iter()
1389 .map(|file| {
1390 std::fs::metadata(&file.path)
1391 .ok()
1392 .map(|metadata| SourceFingerprint::from_metadata(&metadata))
1393 .filter(|fingerprint| fingerprint.has_known_mtime())
1394 })
1395 .collect()
1396}
1397
1398fn update_parse_cache_if_enabled(
1399 config: &ResolvedConfig,
1400 cache: &mut Option<fallow_extract::cache::CacheStore>,
1401 write: &ParseCacheWrite<'_>,
1402) -> f64 {
1403 let start = Instant::now();
1404 write_parse_cache(config, cache, write);
1405 start.elapsed().as_secs_f64() * 1000.0
1406}
1407
1408struct ParseCacheWrite<'a> {
1411 modules: &'a [ModuleInfo],
1412 files: &'a [DiscoveredFile],
1413 need_complexity: bool,
1414 fingerprint_of: &'a dyn Fn(&DiscoveredFile) -> SourceFingerprint,
1415}
1416
1417fn write_parse_cache(
1418 config: &ResolvedConfig,
1419 cache: &mut Option<fallow_extract::cache::CacheStore>,
1420 write: &ParseCacheWrite<'_>,
1421) {
1422 if config.no_cache {
1423 return;
1424 }
1425
1426 let cache_max_size_bytes = crate::project_config::resolve_cache_max_size_bytes(config);
1427 let store = cache.get_or_insert_with(|| fallow_extract::cache::CacheStore::new(&config.root));
1428 if update_parse_cache(store, write, config.reads_call_facts())
1429 && let Err(error) = store.save(
1430 config.cache_target(),
1431 config.cache_config_hash,
1432 cache_max_size_bytes,
1433 )
1434 {
1435 tracing::warn!("Failed to save cache: {error}");
1436 }
1437}
1438
1439fn update_parse_cache(
1443 store: &mut fallow_extract::cache::CacheStore,
1444 write: &ParseCacheWrite<'_>,
1445 need_call_facts: bool,
1446) -> bool {
1447 let ParseCacheWrite {
1448 modules,
1449 files,
1450 need_complexity,
1451 fingerprint_of,
1452 } = *write;
1453 let mut dirty = false;
1454 for module in modules {
1455 if let Some(file) = files.get(module.file_id.0 as usize) {
1456 dirty |= store.record_module(
1457 &file.path,
1458 module,
1459 fingerprint_of(file),
1460 need_complexity,
1461 need_call_facts,
1462 );
1463 }
1464 }
1465 store.retain_paths(files) || dirty
1466}
1467
1468fn source_fingerprint(path: &Path) -> SourceFingerprint {
1469 std::fs::metadata(path).map_or_else(
1470 |_| SourceFingerprint::new(0, 0),
1471 |metadata| SourceFingerprint::from_metadata(&metadata),
1472 )
1473}
1474
1475struct EngineDeadCodePipelineInput<'a> {
1476 config: &'a ResolvedConfig,
1477 discovery: &'a crate::discover::AnalysisDiscovery,
1478 modules: Arc<[ModuleInfo]>,
1479 metrics: core_backend::ParseMetrics,
1480 collect_usages: bool,
1481 graph: crate::session_graph::GraphChoice,
1482 retain_modules: bool,
1483 retain_files: bool,
1484 cancellation: Option<&'a AtomicBool>,
1485}
1486
1487fn run_engine_owned_dead_code_pipeline(
1488 input: EngineDeadCodePipelineInput<'_>,
1489) -> EngineResult<SharedDeadCodeAnalysisArtifacts> {
1490 let EngineDeadCodePipelineInput {
1491 config,
1492 discovery,
1493 modules,
1494 metrics,
1495 collect_usages,
1496 graph: retention,
1497 retain_modules,
1498 retain_files,
1499 cancellation,
1500 } = input;
1501 let stopped = |stage: &str| -> EngineResult<()> {
1502 if token_is_set(cancellation) {
1503 return Err(crate::EngineError::cancelled(stage));
1504 }
1505 Ok(())
1506 };
1507 stopped("the dead-code prelude")?;
1508 let prelude = core_backend::prepare_dead_code_backend_prelude(config, discovery)?;
1509 let prelude_timings = prelude.timings();
1510 stopped("dead-code entry-point discovery")?;
1511 let entry_points = core_backend::discover_dead_code_entry_points(&prelude);
1512 stopped("import resolution and graph construction")?;
1513 let (resolved, graph, graph_cache_rejection) =
1514 resolve_or_build_dead_code_graph(&prelude, &entry_points, &modules);
1515 stopped("the dead-code detectors")?;
1516
1517 let mut detector = core_backend::run_dead_code_detectors(
1518 &prelude,
1519 &graph.graph,
1520 &resolved.project.modules,
1521 &modules,
1522 collect_usages,
1523 &entry_points,
1524 );
1525 detector.results.shared_state = crate::shared_state::inventory(
1526 config,
1527 &modules,
1528 &resolved.project.modules,
1529 graph.graph.as_graph(),
1530 );
1531 if let Some(inventory) = &mut detector.results.shared_state {
1532 inventory.complete &= modules.len() == discovery.files().len()
1533 && crate::shared_state::sources_complete(config, discovery);
1534 }
1535 crate::dead_code::stamp_finding_ids(&mut detector.results, &config.root);
1538 crate::security::stamp_security_finding_ids(&mut detector.results, &config.root);
1540 crate::dead_code::filter_configured_ignored_findings(&mut detector.results, config);
1541 stopped("assembling the dead-code report")?;
1546 let profile =
1547 core_backend::dead_code_pipeline_profile(core_backend::DeadCodePipelineProfileInput {
1548 retain_timings: retention.traces(),
1549 prelude: &prelude,
1550 prelude_timings,
1551 parse_metrics: metrics,
1552 module_count: modules.len(),
1553 entry_points: &entry_points,
1554 resolved: &resolved,
1555 graph: &graph,
1556 detector: &detector,
1557 file_count: discovery.files().len(),
1558 workspace_count: discovery.workspaces().len(),
1559 graph_cache_rejection,
1560 });
1561 let script_used_packages = prelude.script_used_packages();
1562 let trace_provenance = prelude.trace_provenance(&modules, retention.traces(), &entry_points);
1563 prelude.finish();
1564 let file_hashes = collect_file_hashes(&modules, discovery.files());
1565
1566 Ok(SharedDeadCodeAnalysisArtifacts {
1567 results: detector.results,
1568 timings: profile.timings,
1569 graph: retention.keeps_graph().then_some(graph.graph),
1570 modules: retain_modules.then_some(modules),
1571 files: retain_files.then(|| discovery.files().to_vec()),
1572 script_used_packages,
1573 trace_provenance,
1574 file_hashes,
1575 })
1576}
1577
1578fn resolve_or_build_dead_code_graph(
1586 prelude: &core_backend::DeadCodeBackendPrelude,
1587 entry_points: &core_backend::DeadCodeEntryPoints,
1588 modules: &[ModuleInfo],
1589) -> (
1590 core_backend::DeadCodeResolvedModules,
1591 core_backend::DeadCodeGraphRun,
1592 Option<CacheRejection>,
1593) {
1594 let rejection =
1595 match core_backend::try_load_dead_code_graph_cache(prelude, entry_points, modules) {
1596 Ok((resolved, graph)) => return (resolved, graph, None),
1597 Err(rejection) => rejection,
1598 };
1599
1600 let mut resolved = core_backend::resolve_dead_code_imports(prelude, modules);
1601 let graph =
1602 core_backend::build_dead_code_graph(prelude, &mut resolved.project, entry_points, modules);
1603 (resolved, graph, rejection)
1604}
1605
1606fn collect_file_hashes(
1607 modules: &[ModuleInfo],
1608 files: &[DiscoveredFile],
1609) -> FxHashMap<PathBuf, u64> {
1610 modules
1611 .iter()
1612 .filter_map(|module| {
1613 files
1614 .get(module.file_id.0 as usize)
1615 .map(|file| (file.path.clone(), module.content_hash))
1616 })
1617 .collect()
1618}
1619
1620pub(crate) fn analyze_dead_code_with_parse_result_from_config(
1621 config: &ResolvedConfig,
1622 modules: &[ModuleInfo],
1623) -> EngineResult<DeadCodeAnalysisArtifacts> {
1624 let (workspaces, _diagnostics, workspaces_ms) =
1625 crate::project_config::collect_workspace_metadata(config)?;
1626 let discovery = crate::discover::prepare_analysis_discovery_with_workspaces(
1627 config,
1628 &workspaces,
1629 workspaces_ms,
1630 );
1631 run_engine_owned_dead_code_pipeline(EngineDeadCodePipelineInput {
1632 config,
1633 discovery: &discovery,
1634 modules: Arc::from(modules),
1635 metrics: reused_parse_metrics(),
1636 collect_usages: true,
1637 graph: crate::session_graph::GraphChoice::WithTrace,
1638 retain_modules: false,
1639 retain_files: false,
1640 cancellation: None,
1641 })
1642 .map(SharedDeadCodeAnalysisArtifacts::into_owned)
1643}
1644
1645#[cfg(test)]
1646mod tests {
1647 use std::fmt::Write as _;
1648 use std::time::Duration;
1649
1650 use super::*;
1651
1652 fn session_with_source(source: &str) -> (tempfile::TempDir, AnalysisSession) {
1653 let project = tempfile::tempdir().expect("project");
1654 let root = project.path();
1655 std::fs::create_dir(root.join("src")).expect("create source directory");
1656 std::fs::write(root.join("src/index.ts"), source).expect("write source");
1657 let session = AnalysisSession::load_default(root);
1658 (project, session)
1659 }
1660
1661 fn class_projection_session(root: &Path) -> AnalysisSession {
1662 AnalysisSession::load_default_with_config(root, |config| {
1663 config.rules.unused_class_members = fallow_config::Severity::Error;
1664 })
1665 }
1666
1667 fn session_class_projection(session: &AnalysisSession) -> Vec<String> {
1668 let analysis = session.analyze_dead_code().expect("class member analysis");
1669 assert!(analysis.results.unresolved_imports.is_empty());
1670 let mut members: Vec<_> = analysis
1671 .results
1672 .unused_class_members
1673 .iter()
1674 .filter(|finding| finding.member.parent_name == "C")
1675 .map(|finding| finding.member.member_name.clone())
1676 .collect();
1677 members.sort();
1678 members
1679 }
1680
1681 #[test]
1682 fn factory_property_proof_refresh_matches_fresh_sessions() {
1683 for (present, absent) in [
1684 (
1685 "import { C } from './classes'; const make = (): C => new C(); export const createUi = () => ({ page: make() });",
1686 "export const createUi = () => ({ page: { used() {} } });",
1687 ),
1688 (
1689 "import { Owner } from './owner'; export const createUi = () => { const owner = new Owner(); return { page: owner.widget }; };",
1690 "export const createUi = () => ({ page: { used() {} } });",
1691 ),
1692 ] {
1693 let project = tempfile::tempdir().expect("session fixture");
1694 let root = project.path();
1695 std::fs::write(
1696 root.join("package.json"),
1697 r#"{"name":"producer-refresh","type":"module","main":"index.ts"}"#,
1698 )
1699 .expect("package");
1700 std::fs::write(
1701 root.join("classes.ts"),
1702 "export class C { control() {} used() {} dead() {} }",
1703 )
1704 .expect("class");
1705 std::fs::write(
1706 root.join("owner.ts"),
1707 "import { C } from './classes'; export class Owner { widget: C = new C(); }",
1708 )
1709 .expect("owner");
1710 std::fs::write(root.join("index.ts"), "import { createUi } from './factory'; const ui = createUi(); ui.page.used(); import { C } from './classes'; new C().control();").expect("consumer");
1711 let path = root.join("factory.ts");
1712 std::fs::write(&path, present).expect("initial producer");
1713 let mut session = class_projection_session(root);
1714 assert_eq!(session_class_projection(&session), ["dead"]);
1715 for (source, expected) in [(absent, vec!["dead", "used"]), (present, vec!["dead"])] {
1716 std::fs::write(&path, source).expect("producer update");
1717 session.refresh_discovery();
1718 assert_eq!(session_class_projection(&session), expected);
1719 assert_eq!(
1720 session_class_projection(&session),
1721 session_class_projection(&class_projection_session(root))
1722 );
1723 }
1724 }
1725 }
1726
1727 #[test]
1728 fn callback_property_proof_refresh_matches_fresh_sessions() {
1729 for (present, absent) in [
1730 (
1731 "export function wrap<T>(callback: () => T) { return { value: callback() }; }",
1732 "export function wrap<T>(callback: () => T) { return { value: { used() {} } }; }",
1733 ),
1734 (
1735 "export { computed as wrap } from 'vue';",
1736 "export { computed as wrap } from 'foreign';",
1737 ),
1738 ] {
1739 let project = tempfile::tempdir().expect("callback session fixture");
1740 let root = project.path();
1741 std::fs::write(
1742 root.join("package.json"),
1743 r#"{"name":"callback-refresh","type":"module","main":"index.ts","dependencies":{"vue":"*","foreign":"*"}}"#,
1744 )
1745 .expect("package");
1746 std::fs::write(
1747 root.join("classes.ts"),
1748 "export class C { control() {} used() {} dead() {} }",
1749 )
1750 .expect("class");
1751 std::fs::write(root.join("index.ts"), "import { wrap } from './factory'; import { C } from './classes'; new C().control(); wrap(() => new C()).value.used();").expect("consumer");
1752 let path = root.join("factory.ts");
1753 std::fs::write(&path, present).expect("initial producer");
1754 let mut session = class_projection_session(root);
1755 assert_eq!(session_class_projection(&session), ["dead"]);
1756 for (source, expected) in [(absent, vec!["dead", "used"]), (present, vec!["dead"])] {
1757 std::fs::write(&path, source).expect("producer update");
1758 session.refresh_discovery();
1759 assert_eq!(session_class_projection(&session), expected);
1760 assert_eq!(
1761 session_class_projection(&session),
1762 session_class_projection(&class_projection_session(root))
1763 );
1764 }
1765 }
1766 }
1767
1768 #[test]
1769 fn callback_review_proof_refresh_matches_fresh_sessions() {
1770 for (present, absent) in [
1771 (
1772 "let current = new C(); wrap((ignored = 0) => current).value.used();",
1773 "let current = new C(); wrap((ignored = (current = { used() {} })) => current).value.used();",
1774 ),
1775 (
1776 "import { computed } from 'vue'; const getter = () => new C(); const alias = getter; const options = { get: alias, set: value => {} }; computed(options).value.used();",
1777 "import { computed } from 'vue'; const getter = () => new C(); const alias = getter; const options = { get: alias, set: value => {} }; options.get = () => ({ used() {} }); computed(options).value.used();",
1778 ),
1779 (
1780 "let current = new C(); wrap(() => current).value.used();",
1781 "let current = new C(); wrap(() => { current = { used() {} }; return current; }).value.used();",
1782 ),
1783 (
1784 "import { computed } from 'vue'; const options = { get: () => new C(), set: value => {} }; const alias = options; computed(alias).value.used();",
1785 "import { computed } from 'vue'; const options = { get: () => new C(), set: value => {} }; const alias = options; alias.get = () => ({ used() {} }); computed(options).value.used();",
1786 ),
1787 ] {
1788 let project = tempfile::tempdir().expect("callback review session fixture");
1789 let root = project.path();
1790 std::fs::write(root.join("package.json"), r#"{"name":"callback-review-refresh","type":"module","main":"index.ts","dependencies":{"vue":"*"}}"#).expect("package");
1791 std::fs::write(
1792 root.join("classes.ts"),
1793 "export class C { control() {} used() {} dead() {} }",
1794 )
1795 .expect("class");
1796 std::fs::write(
1797 root.join("helper.ts"),
1798 "export function wrap(fn) { return { value: fn() }; }",
1799 )
1800 .expect("helper");
1801 let path = root.join("index.ts");
1802 let source = |body: &str| {
1803 format!(
1804 "import {{ C }} from './classes'; import {{ wrap }} from './helper'; new C().control(); {body}"
1805 )
1806 };
1807 std::fs::write(&path, source(present)).expect("initial source");
1808 let mut session = class_projection_session(root);
1809 assert_eq!(session_class_projection(&session), ["dead"]);
1810 for (body, expected) in [(absent, vec!["dead", "used"]), (present, vec!["dead"])] {
1811 std::fs::write(&path, source(body)).expect("source update");
1812 session.refresh_discovery();
1813 assert_eq!(session_class_projection(&session), expected);
1814 assert_eq!(
1815 session_class_projection(&session),
1816 session_class_projection(&class_projection_session(root))
1817 );
1818 }
1819 }
1820 }
1821
1822 #[test]
1823 fn indexed_source_proof_removal_and_restoration_matches_fresh_sessions() {
1824 for (label, present, absent, access) in [
1825 (
1826 "literal",
1827 "const items = [new C()];",
1828 "const items = [new Other()];",
1829 "items[0].used();",
1830 ),
1831 (
1832 "vue",
1833 "import { computed } from 'vue';const items = computed(() => [new C()]);",
1834 "import { computed } from 'foreign';const items = computed(() => [new C()]);",
1835 "items.value[0].used();",
1836 ),
1837 ] {
1838 let project = tempfile::tempdir().expect("session fixture");
1839 let root = project.path();
1840 std::fs::create_dir(root.join("src")).expect("source directory");
1841 std::fs::write(root.join("package.json"),
1842 r#"{"name":"session-array-proof","type":"module","main":"src/index.ts","dependencies":{"vue":"*","foreign":"*"}}"#)
1843 .expect("package manifest");
1844 std::fs::write(root.join("src/classes.ts"),
1845 "export class C { control() {} used() {} dead() {} } export class Other { used() {} }")
1846 .expect("classes");
1847 for provider in ["vue", "foreign"] {
1848 let directory = root.join("node_modules").join(provider);
1849 std::fs::create_dir_all(&directory).expect("provider directory");
1850 std::fs::write(
1851 directory.join("package.json"),
1852 format!(r#"{{"name":"{provider}","type":"module","main":"index.js"}}"#),
1853 )
1854 .expect("provider package");
1855 std::fs::write(
1856 directory.join("index.js"),
1857 "export const computed = getter => ({ get value() { return getter(); } });",
1858 )
1859 .expect("provider source");
1860 }
1861 let source = |producer: &str| {
1862 format!(
1863 "import {{ C, Other }} from './classes';new C().control();\n{producer}\n{access}\n"
1864 )
1865 };
1866 let original = source(present);
1867 let path = root.join("src/index.ts");
1868 std::fs::write(&path, &original).expect("initial source");
1869 let mut retained = class_projection_session(root);
1870 for (phase, content, expected) in [
1871 ("initial", original.as_str(), vec!["dead"]),
1872 ("removed", source(absent).as_str(), vec!["dead", "used"]),
1873 ("restored", original.as_str(), vec!["dead"]),
1874 ] {
1875 std::fs::write(&path, content).expect("update proof source");
1876 retained.refresh_discovery();
1877 let actual = session_class_projection(&retained);
1878 assert_eq!(actual, expected, "{label}: {phase}");
1879 assert_eq!(
1880 actual,
1881 session_class_projection(&class_projection_session(root)),
1882 "{label}: retained and fresh differ after {phase}"
1883 );
1884 }
1885 }
1886 }
1887
1888 #[test]
1891 fn a_cancelled_session_returns_a_cancellation_error_not_an_empty_result() {
1892 let project = tempfile::tempdir().expect("project");
1893 let root = project.path();
1894 std::fs::create_dir(root.join("src")).expect("create source directory");
1895 std::fs::write(root.join("src/index.ts"), "export const entry = 1;\n").expect("entry");
1896 std::fs::write(root.join("src/orphan.ts"), "export const orphan = 1;\n").expect("orphan");
1897
1898 let baseline = AnalysisSession::load_default(root)
1899 .analyze_dead_code()
1900 .expect("an uncancelled session analyzes");
1901 assert!(
1902 !baseline.results.unused_files.is_empty(),
1903 "the fixture must have findings, so an empty result would be a plausible wrong answer"
1904 );
1905
1906 let error = AnalysisSession::load_default(root)
1907 .with_cancellation(Arc::new(AtomicBool::new(true)))
1908 .analyze_dead_code()
1909 .expect_err("a cancelled session must not return results");
1910 assert!(error.is_cancelled(), "unexpected error: {error}");
1911 assert!(error.message().contains("cancelled"));
1912 }
1913
1914 #[test]
1920 fn a_refused_graph_cache_names_its_reason_in_the_engine_timings() {
1921 let project = tempfile::tempdir().expect("project");
1922 let root = project.path();
1923 std::fs::create_dir(root.join("src")).expect("create source directory");
1924 std::fs::write(root.join("src/index.ts"), "export const entry = 1;\n").expect("entry");
1925
1926 let cold = AnalysisSession::load_default(root)
1927 .analyze_dead_code_with_artifacts(false, true)
1928 .expect("cold run analyzes");
1929 assert_eq!(
1930 cold.timings
1931 .expect("cold timings retained")
1932 .graph_cache_rejection,
1933 Some(CacheRejection::Absent),
1934 "a first run has no persisted graph to refuse"
1935 );
1936
1937 std::fs::write(
1938 root.join("src/index.ts"),
1939 "export const entry = 1;\nexport const added = 2;\n",
1940 )
1941 .expect("edit the entry");
1942
1943 let warm = AnalysisSession::load_default(root)
1944 .analyze_dead_code_with_artifacts(false, true)
1945 .expect("warm run analyzes");
1946 assert_eq!(
1947 warm.timings
1948 .expect("warm timings retained")
1949 .graph_cache_rejection,
1950 Some(CacheRejection::FingerprintChanged),
1951 "the decoded graph was refused because a file changed, and the run must say so"
1952 );
1953 }
1954
1955 #[test]
1958 fn a_session_without_a_token_is_never_cancelled() {
1959 let (_project, session) = session_with_source("export const unused = 1;\n");
1960 assert!(!session.is_cancelled());
1961 session
1962 .analyze_dead_code()
1963 .expect("a session without a token analyzes");
1964 }
1965
1966 const PARSE_LOOP_FILES: usize = 400;
1970
1971 fn parse_loop_project() -> tempfile::TempDir {
1972 let project = tempfile::tempdir().expect("project");
1973 let src = project.path().join("src");
1974 std::fs::create_dir_all(&src).expect("src dir");
1975 for module in 0..PARSE_LOOP_FILES {
1976 let mut source = String::new();
1977 for symbol in 0..20 {
1978 let _ = writeln!(
1979 source,
1980 "export const helper{symbol} = (input: number): number => {{\n \
1981 if (input > {symbol}) {{\n return input * {symbol};\n }}\n \
1982 return input - {symbol};\n}};"
1983 );
1984 }
1985 std::fs::write(src.join(format!("mod{module}.ts")), source).expect("module");
1986 }
1987 project
1988 }
1989
1990 #[cfg(unix)]
1997 #[test]
1998 fn a_refresh_drops_modules_whose_fingerprints_need_a_content_check() {
1999 let (_project, mut session) = session_with_source("export const kept = 1;\n");
2000 drop(session.parse_modules(false, None));
2001
2002 assert!(!session.refresh_discovery(), "the file set is the same");
2003 assert!(
2004 session.parsed_cache.lock().expect("parse cache").is_some(),
2005 "fingerprints with a known ctime keep the modules for the next run"
2006 );
2007
2008 if let Some(cache) = session
2009 .parsed_cache
2010 .get_mut()
2011 .expect("parse cache")
2012 .as_mut()
2013 {
2014 for fingerprint in &mut cache.fingerprints {
2015 fingerprint.ctime_ns = 0;
2016 }
2017 }
2018 assert!(!session.refresh_discovery(), "the file set is the same");
2019 assert!(
2020 session.parsed_cache.lock().expect("parse cache").is_none(),
2021 "the next run parses through the persisted cache, which checks the content"
2022 );
2023 }
2024
2025 #[cfg(unix)]
2029 #[test]
2030 fn a_flush_stores_an_unsettled_fingerprint_without_its_ctime() {
2031 let (project, mut session) = session_with_source("export const kept = 1;\n");
2032 drop(session.parse_modules(false, None));
2033 let path = project.path().join("src/index.ts");
2034 let stored_ctime = |session: &AnalysisSession| {
2035 let _ = std::fs::remove_dir_all(&session.config.cache_dir);
2036 session.disk_cache_stale.store(true, Ordering::SeqCst);
2037 session.flush_parse_cache();
2038 let store = fallow_extract::cache::CacheStore::load(
2039 &session.config.cache_dir,
2040 &session.config.root,
2041 session.config.cache_config_hash,
2042 crate::project_config::resolve_cache_max_size_bytes(&session.config),
2043 )
2044 .expect("flush writes the parse cache");
2045 store
2046 .get_by_path_only(&path)
2047 .expect("flushed module")
2048 .ctime_ns
2049 };
2050
2051 let set_read_started = |session: &mut AnalysisSession, offset: u64| {
2054 if let Some(cache) = session
2055 .parsed_cache
2056 .get_mut()
2057 .expect("parse cache")
2058 .as_mut()
2059 {
2060 let ctime = cache.fingerprints[0].ctime_ns;
2061 assert!(ctime > 0, "the platform reports a ctime");
2062 cache.read_started_ns = ctime.saturating_add(offset);
2063 }
2064 };
2065
2066 set_read_started(&mut session, 0);
2067 assert_eq!(
2068 stored_ctime(&session),
2069 0,
2070 "a fingerprint inside the window is not settled"
2071 );
2072
2073 set_read_started(
2074 &mut session,
2075 fallow_types::source_fingerprint::TIMESTAMP_SETTLE_WINDOW_NS,
2076 );
2077 assert!(
2078 stored_ctime(&session) > 0,
2079 "a settled fingerprint keeps its ctime"
2080 );
2081 }
2082
2083 #[cfg(unix)]
2087 #[test]
2088 fn a_same_tick_rewrite_does_not_reuse_the_kept_module() {
2089 let (project, mut session) = session_with_source("export const alpha = 1;\n");
2090 drop(session.parse_modules(false, None));
2091
2092 let path = project.path().join("src/index.ts");
2093 std::fs::write(&path, "export const bravo = 1;\n").expect("rewrite source");
2094 let same_tick = SourceFingerprint::from_metadata(
2095 &std::fs::metadata(&path).expect("metadata after rewrite"),
2096 );
2097 if let Some(cache) = session
2098 .parsed_cache
2099 .get_mut()
2100 .expect("parse cache")
2101 .as_mut()
2102 {
2103 cache.fingerprints = vec![same_tick];
2104 }
2105
2106 let modules = session.parse_modules(false, None).modules;
2107 let exports: Vec<String> = modules
2108 .iter()
2109 .flat_map(|module| module.exports.iter())
2110 .map(|export| export.name.to_string())
2111 .collect();
2112 assert_eq!(exports, vec!["bravo".to_string()]);
2113 }
2114
2115 fn uncached_session(root: &Path) -> AnalysisSession {
2118 let mut project_config = crate::project_config::default_project_config(root);
2119 project_config.config.no_cache = true;
2120 AnalysisSession::from_config(project_config)
2121 }
2122
2123 #[test]
2132 fn a_cancelled_parse_stops_partway_and_leaves_no_truncated_cache_behind() {
2133 let project = parse_loop_project();
2134 let root = project.path();
2135
2136 let token = Arc::new(AtomicBool::new(true));
2139 let session = uncached_session(root).with_cancellation(Arc::clone(&token));
2140 let stopped = session.parse_modules(false, Some(&token));
2141 assert!(stopped.modules.is_empty(), "the loop never read the token");
2142 assert!(
2143 session.parsed_cache.lock().expect("parse cache").is_none(),
2144 "a truncated parse must not be retained as this session's warm cache"
2145 );
2146
2147 drop(uncached_session(root).parse_modules(false, None));
2149 let session = uncached_session(root);
2150 let started = Instant::now();
2151 let full_count = session.parse_modules(false, None).modules.len();
2152 let full_parse = started.elapsed();
2153 assert_eq!(
2154 full_count, PARSE_LOOP_FILES,
2155 "the fixture must parse every generated module"
2156 );
2157
2158 let mut shorter_than = None::<Duration>;
2163 let mut longer_than = Duration::ZERO;
2164 let mut delay = full_parse / 2;
2165 let mut stopped_part_way = false;
2166 for _ in 0..16 {
2167 let token = Arc::new(AtomicBool::new(false));
2168 let session = uncached_session(root).with_cancellation(Arc::clone(&token));
2171 let watchdog = {
2172 let token = Arc::clone(&token);
2173 std::thread::spawn(move || {
2174 std::thread::sleep(delay);
2175 token.store(true, Ordering::SeqCst);
2176 })
2177 };
2178 let cancelled = session.parse_modules(false, Some(&token));
2179 watchdog.join().expect("watchdog thread");
2180
2181 let parsed = cancelled.modules.len();
2182 if parsed == full_count {
2183 shorter_than = Some(delay);
2184 } else if parsed == 0 {
2185 longer_than = delay;
2186 } else {
2187 stopped_part_way = true;
2188 break;
2189 }
2190 delay = match shorter_than {
2191 Some(upper) => (longer_than + upper) / 2,
2192 None => delay * 2,
2193 };
2194 }
2195 assert!(
2196 stopped_part_way,
2197 "no attempt in 16 stopped the parse part way through"
2198 );
2199
2200 let recovered = uncached_session(root).parse_modules(false, None);
2201 assert_eq!(
2202 recovered.modules.len(),
2203 full_count,
2204 "a later uncancelled parse must still see the whole project"
2205 );
2206 }
2207
2208 #[test]
2209 fn session_retains_workspace_metadata_from_config_load() {
2210 let project = tempfile::tempdir().expect("project");
2211 let root = project.path();
2212 std::fs::write(
2213 root.join("package.json"),
2214 r#"{"name":"root","workspaces":["packages/*"]}"#,
2215 )
2216 .expect("write root package");
2217 std::fs::create_dir_all(root.join("packages/a")).expect("create workspace");
2218 std::fs::write(
2219 root.join("packages/a/package.json"),
2220 r#"{"name":"pkg-a","type":"module"}"#,
2221 )
2222 .expect("write workspace package");
2223
2224 let session = AnalysisSession::load(root, None).expect("session loads");
2225
2226 assert!(
2227 session
2228 .workspaces()
2229 .iter()
2230 .any(|workspace| workspace.name == "pkg-a"),
2231 "session must retain workspace metadata discovered during config load"
2232 );
2233 }
2234
2235 #[test]
2236 fn finding_ignore_filters_results_without_removing_graph_inputs() {
2237 let project = tempfile::tempdir().expect("project");
2238 let root = project.path();
2239 std::fs::create_dir(root.join("src")).expect("create source directory");
2240 std::fs::write(
2241 root.join("package.json"),
2242 r#"{"name":"finding-ignore","devDependencies":{"vitest":"latest"}}"#,
2243 )
2244 .expect("write package manifest");
2245 std::fs::write(
2246 root.join("vitest.config.ts"),
2247 "import './src/feature';\nexport default {};\n",
2248 )
2249 .expect("write vitest config");
2250 std::fs::write(
2251 root.join("src/feature.ts"),
2252 "export const feature = true;\n",
2253 )
2254 .expect("write reachable source");
2255 std::fs::write(root.join("src/hidden.ts"), "export const hidden = true;\n")
2256 .expect("write hidden source");
2257
2258 let unfiltered = AnalysisSession::load(root, None)
2259 .expect("unfiltered session loads")
2260 .analyze_dead_code()
2261 .expect("unfiltered analysis succeeds");
2262 assert!(
2263 unfiltered
2264 .results
2265 .unused_files
2266 .iter()
2267 .any(|finding| finding.file.path.ends_with("src/hidden.ts"))
2268 );
2269
2270 std::fs::write(
2271 root.join(".fallowrc.json"),
2272 r#"{"ignoreFindings":["src/hidden.ts"]}"#,
2273 )
2274 .expect("write fallow config");
2275 let session = AnalysisSession::load(root, None).expect("filtered session loads");
2276 let hidden_path = root.join("src/hidden.ts");
2277 assert!(session.files().iter().any(|file| file.path == hidden_path));
2278
2279 let filtered = session
2280 .analyze_dead_code_with_artifacts(false, true)
2281 .expect("filtered analysis succeeds");
2282 assert!(
2283 filtered
2284 .results
2285 .unused_files
2286 .iter()
2287 .all(|finding| finding.file.path != hidden_path)
2288 );
2289 assert!(
2290 filtered
2291 .graph
2292 .as_ref()
2293 .is_some_and(|graph| graph.module_count() == session.files().len())
2294 );
2295 }
2296
2297 #[test]
2298 fn finding_ignore_normalizes_separators_and_rejects_outside_paths() {
2299 use fallow_types::output_dead_code::UnusedFileFinding;
2300 use fallow_types::results::UnusedFile;
2301
2302 let project = tempfile::tempdir().expect("project");
2303 let config = serde_json::from_str::<fallow_config::FallowConfig>(
2304 r#"{"ignoreFindings":["**/*.ts"]}"#,
2305 )
2306 .expect("config parses")
2307 .resolve(
2308 project.path().to_path_buf(),
2309 fallow_config::OutputFormat::Human,
2310 1,
2311 true,
2312 true,
2313 None,
2314 );
2315 let outside = project
2316 .path()
2317 .parent()
2318 .expect("project has parent")
2319 .join("outside.ts");
2320 let mut results = AnalysisResults {
2321 unused_files: vec![
2322 UnusedFileFinding::with_actions(UnusedFile {
2323 path: PathBuf::from(r"src\hidden.ts"),
2324 }),
2325 UnusedFileFinding::with_actions(UnusedFile {
2326 path: outside.clone(),
2327 }),
2328 ],
2329 ..AnalysisResults::default()
2330 };
2331
2332 crate::dead_code::filter_configured_ignored_findings(&mut results, &config);
2333
2334 assert_eq!(results.unused_files.len(), 1);
2335 assert_eq!(results.unused_files[0].file.path, outside);
2336 }
2337
2338 #[cfg(unix)]
2341 fn warm_store_project() -> tempfile::TempDir {
2342 let project = tempfile::tempdir().expect("project");
2343 let root = project.path();
2344 std::fs::create_dir(root.join("src")).expect("create source directory");
2345 std::fs::write(root.join("src/index.ts"), "export const entry = 1;\n").expect("entry");
2346 std::fs::write(root.join("src/other.ts"), "export const other = 2;\n").expect("other");
2347 project
2348 }
2349
2350 #[cfg(unix)]
2351 fn warm_session(root: &Path, store: &Arc<WarmParseStore>) -> AnalysisSession {
2352 AnalysisSession::load_default(root).with_warm_parse(Some(Arc::clone(store)))
2353 }
2354
2355 #[cfg(unix)]
2356 fn exported_names(modules: &[ModuleInfo]) -> Vec<String> {
2357 let mut names: Vec<String> = modules
2358 .iter()
2359 .flat_map(|module| module.exports.iter().map(|export| export.name.to_string()))
2360 .collect();
2361 names.sort();
2362 names
2363 }
2364
2365 #[cfg(unix)]
2366 #[test]
2367 fn a_warm_store_serves_a_new_session_without_parse_work() {
2368 let project = warm_store_project();
2369 let store = Arc::new(WarmParseStore::new(
2370 crate::warm_parse::WarmParseLimits::default(),
2371 ));
2372
2373 let first = warm_session(project.path(), &store).parse_modules(false, None);
2374 let second = warm_session(project.path(), &store).parse_modules(false, None);
2375
2376 assert!(Arc::ptr_eq(&first.modules, &second.modules));
2377 assert_eq!(second.metrics.cache_hits + second.metrics.cache_misses, 0);
2378 let counts = store.counts();
2379 assert_eq!(counts.parse_runs, 1);
2380 assert_eq!(counts.modules_parsed, 2);
2381 assert_eq!(counts.modules_reused, 2);
2382 }
2383
2384 #[cfg(unix)]
2385 #[test]
2386 fn a_warm_store_serves_the_health_parse_of_a_new_session() {
2387 let project = warm_store_project();
2388 let store = Arc::new(WarmParseStore::new(
2389 crate::warm_parse::WarmParseLimits::default(),
2390 ));
2391
2392 drop(warm_session(project.path(), &store).parse_modules(false, None));
2393 let health = warm_session(project.path(), &store).parsed_parts_uncached(true);
2394
2395 assert_eq!(health.modules.len(), 2);
2396 assert_eq!(health.cache_hits + health.cache_misses, 0);
2397 assert_eq!(
2398 store.counts().parse_runs,
2399 1,
2400 "the first parse computed complexity"
2401 );
2402 }
2403
2404 #[cfg(unix)]
2405 #[test]
2406 fn an_edit_or_a_new_file_makes_the_next_session_parse_again() {
2407 let project = warm_store_project();
2408 let root = project.path();
2409 let store = Arc::new(WarmParseStore::new(
2410 crate::warm_parse::WarmParseLimits::default(),
2411 ));
2412 drop(warm_session(root, &store).parse_modules(false, None));
2413
2414 std::fs::write(root.join("src/other.ts"), "export const renamed = 22;\n").expect("edit");
2415 let edited = warm_session(root, &store).parse_modules(false, None);
2416 assert_eq!(exported_names(&edited.modules), ["entry", "renamed"]);
2417 assert_eq!(
2418 edited.metrics.cache_misses, 1,
2419 "only the edited file is parsed"
2420 );
2421
2422 std::fs::write(root.join("src/added.ts"), "export const added = 3;\n").expect("add");
2423 let added = warm_session(root, &store).parse_modules(false, None);
2424 assert_eq!(
2425 exported_names(&added.modules),
2426 ["added", "entry", "renamed"]
2427 );
2428
2429 let counts = store.counts();
2430 assert_eq!(counts.parse_runs, 3);
2431 assert_eq!(counts.modules_reused, 0);
2432 assert_eq!(store.len(), 2, "each file list keeps its latest parse only");
2433 }
2434
2435 #[cfg(unix)]
2436 #[test]
2437 fn a_session_without_the_persisted_cache_does_not_use_the_store() {
2438 let project = warm_store_project();
2439 let store = Arc::new(WarmParseStore::new(
2440 crate::warm_parse::WarmParseLimits::default(),
2441 ));
2442
2443 drop(
2444 uncached_session(project.path())
2445 .with_warm_parse(Some(Arc::clone(&store)))
2446 .parse_modules(false, None),
2447 );
2448
2449 assert_eq!(
2450 store.counts(),
2451 crate::warm_parse::WarmParseCounts::default()
2452 );
2453 assert!(store.is_empty());
2454 }
2455
2456 #[cfg(unix)]
2460 #[test]
2461 fn a_kept_parse_records_its_read_failures_again() {
2462 let project = warm_store_project();
2463 let root = project.path();
2464 std::fs::write(root.join("src/broken.ts"), [0xff, 0xfe, 0x00]).expect("invalid UTF-8");
2465 let store = Arc::new(WarmParseStore::new(
2466 crate::warm_parse::WarmParseLimits::default(),
2467 ));
2468 let read_failures = |session: &AnalysisSession| {
2469 session
2470 .current_workspace_diagnostics()
2471 .into_iter()
2472 .filter(|diagnostic| {
2473 matches!(
2474 diagnostic.kind,
2475 fallow_types::workspace::WorkspaceDiagnosticKind::SourceReadFailure { .. }
2476 )
2477 })
2478 .count()
2479 };
2480
2481 let first = warm_session(root, &store);
2482 drop(first.parse_modules(false, None));
2483 assert_eq!(read_failures(&first), 1);
2484
2485 drop(fallow_config::record_source_read_failures(root, &[]));
2486 let second = warm_session(root, &store);
2487 drop(second.parse_modules(false, None));
2488 assert_eq!(store.counts().modules_reused, 2);
2489 assert_eq!(read_failures(&second), 1);
2490 }
2491
2492 #[test]
2493 fn warm_parse_cache_reuses_module_storage() {
2494 let (_project, session) = session_with_source("export function value() { return 1; }\n");
2495 let first = session.parse_modules(true, None);
2496 let second = session.parse_modules(false, None);
2497
2498 assert!(
2499 Arc::ptr_eq(&first.modules, &second.modules),
2500 "warm session queries must share parsed module storage"
2501 );
2502 }
2503
2504 #[test]
2505 fn warm_styling_cache_reuses_artifact_allocation() {
2506 let project = tempfile::tempdir().expect("project");
2507 let root = project.path();
2508 std::fs::write(root.join("styles.css"), ".button { color: red; }\n")
2509 .expect("write stylesheet");
2510 let session = AnalysisSession::load_default(root);
2511
2512 let first = session.styling_analysis_artifacts();
2513 let second = session.styling_analysis_artifacts();
2514
2515 assert!(
2516 Arc::ptr_eq(&first, &second),
2517 "warm styling queries must share the cached artifact allocation"
2518 );
2519 }
2520
2521 #[test]
2522 fn shared_parsed_modules_reuse_public_session_storage() {
2523 let (_project, session) = session_with_source("export const value = 1;\n");
2524 let first = session.shared_parsed_modules(true);
2525 let second = session.shared_parsed_modules(false);
2526
2527 assert!(Arc::ptr_eq(&first, &second));
2528 }
2529
2530 #[test]
2531 fn shared_parsed_parts_reuse_public_session_storage() {
2532 let (_project, session) = session_with_source("export const value = 1;\n");
2533 let cached = session.shared_parsed_modules(true);
2534 let parts = session.shared_parsed_parts(false);
2535
2536 assert!(Arc::ptr_eq(&cached, &parts.modules));
2537 }
2538
2539 #[test]
2540 fn warm_complexity_artifacts_reuse_cached_module_storage() {
2541 let (_project, session) = session_with_source("export function value() { return 1; }\n");
2542 let cached = session.parse_modules(true, None);
2543 let artifacts = session
2544 .analyze_dead_code_with_reuse_artifacts(true, true, false)
2545 .expect("analysis succeeds");
2546 let retained = artifacts.modules.expect("complexity modules retained");
2547
2548 assert!(
2549 Arc::ptr_eq(&cached.modules, &retained),
2550 "warm complexity artifacts must share parsed module storage"
2551 );
2552 }
2553
2554 #[test]
2555 fn shared_and_owned_artifacts_preserve_output_bytes() {
2556 let (_project, session) = session_with_source(
2557 "export const used = 1;\nexport const unused = 2;\nconsole.log(used);\n",
2558 );
2559 let owned = session
2560 .analyze_dead_code_with_artifacts(true, true)
2561 .expect("owned analysis succeeds");
2562 let shared = session
2563 .analyze_dead_code_with_shared_artifacts(true, true)
2564 .expect("shared analysis succeeds");
2565
2566 assert_eq!(
2567 serde_json::to_vec(&owned.results).expect("serialize owned results"),
2568 serde_json::to_vec(&shared.results).expect("serialize shared results")
2569 );
2570 assert_eq!(owned.file_hashes, shared.file_hashes);
2571 assert_eq!(
2572 owned
2573 .modules
2574 .as_deref()
2575 .unwrap_or_default()
2576 .iter()
2577 .map(|module| module.content_hash)
2578 .collect::<Vec<_>>(),
2579 shared
2580 .modules
2581 .as_deref()
2582 .unwrap_or_default()
2583 .iter()
2584 .map(|module| module.content_hash)
2585 .collect::<Vec<_>>()
2586 );
2587 }
2588
2589 #[test]
2590 fn route_loader_whole_use_matches_across_cold_and_warm_sessions() {
2591 let project = tempfile::tempdir().expect("project");
2592 let root = project.path();
2593 std::fs::create_dir_all(root.join("app/routes")).expect("create route directory");
2594 std::fs::write(
2595 root.join("package.json"),
2596 r#"{"name":"route-cache-parity","dependencies":{"react-router":"latest"}}"#,
2597 )
2598 .expect("write package manifest");
2599 std::fs::write(
2600 root.join("app/routes/home.tsx"),
2601 r#"
2602import { useLoaderData } from "react-router";
2603export function loader() { return { opaque: "value" }; }
2604export default function Home() {
2605 const data = useLoaderData<typeof loader>();
2606 const copy = { ...data };
2607 return JSON.stringify(copy);
2608}
2609"#,
2610 )
2611 .expect("write route module");
2612
2613 let cold_session = AnalysisSession::load(root, None).expect("cold session loads");
2614 let cold_parse = cold_session.parsed_parts(false);
2615 assert_eq!(cold_parse.cache_hits, 0, "first parse must be cold");
2616 let cold = cold_session
2617 .analyze_dead_code()
2618 .expect("cold analysis succeeds");
2619
2620 let warm_session = AnalysisSession::load(root, None).expect("warm session loads");
2621 let warm_parse = warm_session.parsed_parts(false);
2622 assert!(
2623 warm_parse.cache_hits > 0,
2624 "second session must use disk cache"
2625 );
2626 let warm = warm_session
2627 .analyze_dead_code()
2628 .expect("warm analysis succeeds");
2629
2630 assert!(
2631 cold.results.unused_load_data_keys.is_empty(),
2632 "cold analysis must abstain for an opaque route-loader use"
2633 );
2634 assert_eq!(
2635 serde_json::to_vec(&cold.results).expect("serialize cold results"),
2636 serde_json::to_vec(&warm.results).expect("serialize warm results"),
2637 "warm route-loader analysis must match cold analysis"
2638 );
2639 }
2640
2641 #[test]
2642 fn replaced_module_coverage_matches_across_cold_and_warm_graph_cache() {
2643 let project = tempfile::tempdir().expect("project");
2644 let root = project.path();
2645 std::fs::create_dir(root.join("src")).expect("create source directory");
2646 std::fs::write(
2647 root.join("package.json"),
2648 r#"{"name":"mock-cache-parity","main":"src/index.ts","devDependencies":{"vitest":"latest"}}"#,
2649 )
2650 .expect("write package manifest");
2651 std::fs::write(
2652 root.join("src/dependency.ts"),
2653 "export function dependency() { return 'real'; }\n",
2654 )
2655 .expect("write dependency");
2656 std::fs::write(
2657 root.join("src/wrapper.ts"),
2658 "import { dependency } from './dependency';\nexport function wrapper() { return dependency(); }\n",
2659 )
2660 .expect("write wrapper");
2661 std::fs::write(
2662 root.join("src/index.ts"),
2663 "export { wrapper } from './wrapper';\n",
2664 )
2665 .expect("write entry point");
2666 std::fs::write(
2667 root.join("src/wrapper.test.ts"),
2668 r#"
2669import { vi } from "vitest";
2670vi.mock("./dependency", () => ({ dependency: () => "mock" }));
2671import { wrapper } from "./wrapper";
2672wrapper();
2673"#,
2674 )
2675 .expect("write test");
2676
2677 let cold_session = AnalysisSession::load(root, None).expect("cold session loads");
2678 let dependency_id = cold_session
2679 .files()
2680 .iter()
2681 .find(|file| file.path == root.join("src/dependency.ts"))
2682 .expect("dependency discovered")
2683 .id;
2684 let cold = cold_session
2685 .analyze_dead_code_with_artifacts(false, true)
2686 .expect("cold analysis succeeds");
2687 let cold_exports = crate::module_graph::module_value_exports(
2688 cold.graph.as_ref().expect("cold graph retained"),
2689 );
2690 assert!(
2691 fallow_graph::cache::GraphCacheStore::load(&cold_session.config().cache_dir).is_ok(),
2692 "cold analysis must persist the graph cache"
2693 );
2694
2695 let warm_session = AnalysisSession::load(root, None).expect("warm session loads");
2696 let warm = warm_session
2697 .analyze_dead_code_with_artifacts(false, true)
2698 .expect("warm analysis succeeds");
2699 let warm_exports = crate::module_graph::module_value_exports(
2700 warm.graph.as_ref().expect("warm graph retained"),
2701 );
2702
2703 let dependency = cold_exports
2704 .iter()
2705 .find(|export| export.file_id == dependency_id && export.name == "dependency")
2706 .expect("dependency export retained");
2707 assert!(!dependency.test_referenced);
2708 assert_eq!(warm_exports, cold_exports);
2709 }
2710
2711 #[test]
2712 fn session_parse_surfaces_removed_source_with_sparse_file_ids() {
2713 let project = tempfile::tempdir().expect("project");
2714 let root = project.path();
2715 std::fs::create_dir(root.join("src")).expect("create source directory");
2716 std::fs::write(root.join("package.json"), r#"{"name":"read-failure"}"#)
2717 .expect("write package manifest");
2718 for name in ["a.ts", "b.ts", "c.ts"] {
2719 std::fs::write(
2720 root.join("src").join(name),
2721 format!("export const {} = 1;\n", name.replace('.', "_")),
2722 )
2723 .expect("write source");
2724 }
2725 let session = AnalysisSession::load(root, None).expect("session loads");
2726 let removed_path = root.join("src/b.ts");
2727 let removed_id = session
2728 .files()
2729 .iter()
2730 .find(|file| file.path == removed_path)
2731 .expect("removed source discovered")
2732 .id;
2733 std::fs::remove_file(&removed_path).expect("remove source after discovery");
2734
2735 let parts = session.parsed_parts(false);
2736
2737 assert!(
2738 parts
2739 .modules
2740 .iter()
2741 .all(|module| module.file_id != removed_id),
2742 "unreadable file must not receive a placeholder module"
2743 );
2744 let diagnostic = parts
2745 .workspace_diagnostics
2746 .iter()
2747 .find(|diagnostic| diagnostic.kind.id() == "source-read-failure")
2748 .expect("parsed session parts carry source read failure");
2749 assert_eq!(diagnostic.path, removed_path);
2750 assert!(
2751 session
2752 .current_workspace_diagnostics()
2753 .iter()
2754 .any(|diagnostic| {
2755 diagnostic.kind.id() == "source-read-failure" && diagnostic.path == removed_path
2756 }),
2757 "session output carries parse-time source diagnostics"
2758 );
2759 }
2760
2761 const MALFORMED_PNPM_WORKSPACE_YAML: &str =
2762 "catalog:\n react: ^18.2.0\n{this is\nnot: valid: yaml: at: all\n";
2763 const VALID_PNPM_WORKSPACE_YAML: &str = "catalog:\n react: ^18.2.0\n";
2764
2765 fn has_diagnostic_kind(diagnostics: &[WorkspaceDiagnostic], id: &str) -> bool {
2766 diagnostics
2767 .iter()
2768 .any(|diagnostic| diagnostic.kind.id() == id)
2769 }
2770
2771 fn write_single_source_project(root: &Path, manifest: &str) {
2772 std::fs::create_dir(root.join("src")).expect("create source directory");
2773 std::fs::write(root.join("package.json"), manifest).expect("write package manifest");
2774 std::fs::write(root.join("src/index.ts"), "export const value = 1;\n")
2775 .expect("write source");
2776 }
2777
2778 #[test]
2784 fn later_session_drops_stale_analysis_stage_diagnostic_after_cause_is_fixed() {
2785 let project = tempfile::tempdir().expect("project");
2786 let root = project.path();
2787 write_single_source_project(
2788 root,
2789 r#"{"name":"issue-2366-engine-session","private":true}"#,
2790 );
2791 std::fs::write(
2792 root.join("pnpm-workspace.yaml"),
2793 MALFORMED_PNPM_WORKSPACE_YAML,
2794 )
2795 .expect("write malformed workspace yaml");
2796
2797 let broken = AnalysisSession::load(root, None).expect("session loads");
2798 broken
2799 .analyze_dead_code()
2800 .expect("analysis on the malformed yaml succeeds");
2801 assert!(
2802 has_diagnostic_kind(
2803 &broken.current_workspace_diagnostics(),
2804 "malformed-pnpm-workspace-yaml"
2805 ),
2806 "the first session surfaces the malformed yaml: {:?}",
2807 broken.current_workspace_diagnostics()
2808 );
2809
2810 std::fs::write(root.join("pnpm-workspace.yaml"), VALID_PNPM_WORKSPACE_YAML)
2811 .expect("fix workspace yaml");
2812
2813 let fixed = AnalysisSession::load(root, None).expect("session loads");
2814 fixed
2815 .analyze_dead_code()
2816 .expect("analysis on the fixed yaml succeeds");
2817 let current = fixed.current_workspace_diagnostics();
2818 assert!(
2819 !has_diagnostic_kind(¤t, "malformed-pnpm-workspace-yaml"),
2820 "a later session must not keep the stale analysis-stage entry (#2366): {current:?}"
2821 );
2822 }
2823
2824 #[test]
2831 fn watch_style_rerun_drops_bun_lockb_skip_once_text_lockfile_exists() {
2832 let project = tempfile::tempdir().expect("project");
2833 let root = project.path();
2834 write_single_source_project(
2835 root,
2836 r#"{"name":"issue-2366-watch-rerun","private":true,"overrides":{"ws":"^8.21.0"}}"#,
2837 );
2838 std::fs::write(root.join("bun.lockb"), b"placeholder binary lockfile")
2839 .expect("write bun.lockb placeholder");
2840 let config = fallow_config::FallowConfig::default().resolve(
2841 root.to_path_buf(),
2842 fallow_config::OutputFormat::Json,
2843 1,
2844 true,
2845 true,
2846 None,
2847 );
2848 let reload_config = || {
2849 let (_, diagnostics) =
2850 fallow_config::discover_workspaces_with_diagnostics(root, &config.ignore_patterns)
2851 .expect("workspace discovery succeeds");
2852 fallow_config::stash_workspace_diagnostics(root, diagnostics);
2853 };
2854
2855 reload_config();
2856 let first =
2857 AnalysisSession::from_resolved_config(config.clone()).expect("first session loads");
2858 first
2859 .analyze_dead_code()
2860 .expect("analysis with bun.lockb only succeeds");
2861 assert!(
2862 has_diagnostic_kind(
2863 &first.current_workspace_diagnostics(),
2864 "bun-lockb-override-resolution-skipped"
2865 ),
2866 "the first run surfaces the bun.lockb skip: {:?}",
2867 first.current_workspace_diagnostics()
2868 );
2869
2870 std::fs::write(
2871 root.join("bun.lock"),
2872 r#"{"lockfileVersion":1,"workspaces":{"":{"name":"issue-2366-watch-rerun"}},"packages":{"ws":["ws@8.21.3","",{},"sha512-20"]}}"#,
2873 )
2874 .expect("write text bun.lock");
2875
2876 reload_config();
2877 let rerun =
2878 AnalysisSession::from_resolved_config(config.clone()).expect("rerun session loads");
2879 rerun
2880 .analyze_dead_code()
2881 .expect("analysis with the text bun.lock succeeds");
2882 let current = rerun.current_workspace_diagnostics();
2883 assert!(
2884 !has_diagnostic_kind(¤t, "bun-lockb-override-resolution-skipped"),
2885 "the rerun drops the skip once a text bun.lock exists (#2366): {current:?}"
2886 );
2887 }
2888
2889 #[test]
2902 fn session_keeps_its_own_walk_skips_and_ignores_another_walks_registry_write() {
2903 let project = tempfile::tempdir().expect("project");
2904 let root = project.path();
2905 write_single_source_project(
2906 root,
2907 r#"{"name":"issue-2366-parallel-walks","private":true}"#,
2908 );
2909 std::fs::write(root.join("src/huge.ts"), "// filler\n".repeat(400))
2910 .expect("write oversized source");
2911 let mut config = fallow_config::FallowConfig::default().resolve(
2912 root.to_path_buf(),
2913 fallow_config::OutputFormat::Json,
2914 1,
2915 true,
2916 true,
2917 None,
2918 );
2919 config.max_file_size_bytes = Some(1024);
2920
2921 let session = AnalysisSession::from_resolved_config(config).expect("session loads");
2922
2923 fallow_config::append_workspace_diagnostics(
2928 root,
2929 vec![WorkspaceDiagnostic::new(
2930 root,
2931 root.join("src/other-walk-only.ts"),
2932 fallow_types::workspace::WorkspaceDiagnosticKind::SkippedLargeFile {
2933 size_bytes: 4096,
2934 },
2935 )],
2936 );
2937
2938 let current = session.current_workspace_diagnostics();
2939 let skipped: Vec<&Path> = current
2940 .iter()
2941 .filter(|diagnostic| diagnostic.kind.id() == "skipped-large-file")
2942 .map(|diagnostic| diagnostic.path.as_path())
2943 .collect();
2944 assert_eq!(
2945 skipped.len(),
2946 1,
2947 "the session reports its own walk's skips only: {skipped:?}"
2948 );
2949 assert!(
2950 skipped[0].ends_with("src/huge.ts"),
2951 "the surviving skip is this walk's own: {skipped:?}"
2952 );
2953 }
2954
2955 #[test]
2963 fn config_reload_after_the_analyze_pass_keeps_the_bun_lockb_skip_readable() {
2964 let project = tempfile::tempdir().expect("project");
2965 let root = project.path();
2966 write_single_source_project(
2967 root,
2968 r#"{"name":"issue-2366-reload-preserve","private":true,"overrides":{"ws":"^8.21.0"}}"#,
2969 );
2970 std::fs::write(root.join("bun.lockb"), b"placeholder binary lockfile")
2971 .expect("write bun.lockb placeholder");
2972 let config = fallow_config::FallowConfig::default().resolve(
2973 root.to_path_buf(),
2974 fallow_config::OutputFormat::Json,
2975 1,
2976 true,
2977 true,
2978 None,
2979 );
2980 let reload_config = || {
2981 let (_, diagnostics) =
2982 fallow_config::discover_workspaces_with_diagnostics(root, &config.ignore_patterns)
2983 .expect("workspace discovery succeeds");
2984 fallow_config::stash_workspace_diagnostics(root, diagnostics);
2985 };
2986
2987 reload_config();
2988 let analyzing =
2989 AnalysisSession::from_resolved_config(config.clone()).expect("session loads");
2990 analyzing
2991 .analyze_dead_code()
2992 .expect("analysis with bun.lockb only succeeds");
2993
2994 reload_config();
2997
2998 let later = AnalysisSession::from_resolved_config(config.clone()).expect("session loads");
2999 let current = later.current_workspace_diagnostics();
3000 assert!(
3001 has_diagnostic_kind(¤t, "bun-lockb-override-resolution-skipped"),
3002 "the reload must preserve the analysis-stage entry the pass recorded (#2366): \
3003 {current:?}"
3004 );
3005 }
3006}
3007
3008#[cfg(all(test, unix, not(miri)))]
3009#[path = "session_shared_state_tests.rs"]
3010mod shared_state_tests;
3011
3012#[cfg(all(test, unix, not(miri)))]
3013#[path = "session_call_facts_tests.rs"]
3014mod call_facts_tests;