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