Skip to main content

fallow_engine/
source.rs

1//! Source parsing contracts owned by the engine boundary.
2
3use std::sync::atomic::AtomicBool;
4
5use fallow_types::discover::DiscoveredFile;
6#[cfg(test)]
7pub use fallow_types::extract::{ExportName, MemberKind, VisibilityTag};
8pub use fallow_types::extract::{ModuleInfo, ParseResult, SourceReadFailure};
9
10type CacheStore = fallow_extract::cache::CacheStore;
11
12/// Parse the `fallow-ignore-next-line` and `fallow-ignore-file` comments of
13/// the raw source text of the file at `path`. Unknown tokens are dropped. A
14/// marker inside a string or template literal of the file's scripts has no
15/// effect.
16#[must_use]
17pub fn suppressions_from_text(
18    path: &std::path::Path,
19    source: &str,
20) -> Vec<fallow_types::suppress::Suppression> {
21    fallow_extract::parse_suppressions_for_file(path, source).suppressions
22}
23
24/// On-demand, transient function extraction for local similar-code inference.
25pub mod similar_code {
26    use std::path::Path;
27
28    pub use fallow_types::similar_code::{
29        ExtractedSimilarCodeFunction, SIMILAR_CODE_EXTRACTION_SEMANTICS_VERSION,
30        SimilarCodeExtraction, SimilarCodeExtractionLimits, SimilarCodeExtractionSkip,
31        SimilarCodeExtractionSkipReason, SimilarCodeFunctionKind, SimilarCodeFunctionLocation,
32        SimilarCodeSideEffectHint, SimilarCodeSourceDigest,
33    };
34
35    /// Extract bounded named functions without touching the normal parse cache.
36    #[must_use]
37    pub fn extract(
38        path: &Path,
39        source: &str,
40        limits: SimilarCodeExtractionLimits,
41    ) -> SimilarCodeExtraction {
42        fallow_extract::extract_similar_code_functions(path, source, limits)
43    }
44}
45
46/// Source inventory walking for coverage and upload surfaces.
47pub mod inventory {
48    use std::path::Path;
49
50    use rustc_hash::FxHashMap;
51
52    /// A single static-inventory entry for one function.
53    ///
54    /// This is the engine-owned inventory contract exposed to CLI upload
55    /// surfaces. The extractor owns AST traversal; the engine owns the public
56    /// shape that downstream crates construct and upload.
57    #[derive(Debug, Clone, PartialEq, Eq)]
58    pub struct InventoryEntry {
59        /// Beacon-compatible function name.
60        pub name: String,
61        /// 1-based source line of the function declaration.
62        pub line: u32,
63        /// 1-indexed UTF-16 column of the function node start.
64        pub start_column: u32,
65        /// 1-based source line where the function node ends.
66        pub end_line: u32,
67        /// 1-indexed UTF-16 column of the function node end.
68        pub end_column: u32,
69        /// Content digest of the function's full-span source slice. `None`
70        /// for a function with too many nested functions below it.
71        pub source_hash: Option<String>,
72        /// Whether the name came from the callee of the call this function is
73        /// passed to (`arr.map(cb)` -> `map`) rather than from a declaration,
74        /// a binding, or a property key.
75        pub is_callback: bool,
76    }
77
78    impl From<fallow_extract::inventory::InventoryEntry> for InventoryEntry {
79        fn from(entry: fallow_extract::inventory::InventoryEntry) -> Self {
80            Self {
81                name: entry.name,
82                line: entry.line,
83                start_column: entry.start_column,
84                end_line: entry.end_line,
85                end_column: entry.end_column,
86                source_hash: entry.source_hash,
87                is_callback: entry.is_callback,
88            }
89        }
90    }
91
92    /// Per-function static complexity collected alongside the inventory walk.
93    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
94    pub struct InventoryComplexity {
95        /// `McCabe` cyclomatic complexity (1 + decision points).
96        pub cyclomatic: u16,
97        /// `SonarSource` cognitive complexity (structural + nesting penalty).
98        pub cognitive: u16,
99    }
100
101    impl From<fallow_extract::inventory::InventoryComplexity> for InventoryComplexity {
102        fn from(complexity: fallow_extract::inventory::InventoryComplexity) -> Self {
103            Self {
104                cyclomatic: complexity.cyclomatic,
105                cognitive: complexity.cognitive,
106            }
107        }
108    }
109
110    /// Walk source and emit engine-owned function inventory entries.
111    #[must_use]
112    pub fn walk_source(path: &Path, source: &str) -> Vec<InventoryEntry> {
113        fallow_extract::inventory::walk_source(path, source)
114            .into_iter()
115            .map(InventoryEntry::from)
116            .collect()
117    }
118
119    /// Walk source once and emit inventory entries plus static complexity by source hash.
120    #[must_use]
121    pub fn walk_source_with_complexity(
122        path: &Path,
123        source: &str,
124    ) -> (Vec<InventoryEntry>, FxHashMap<String, InventoryComplexity>) {
125        let (entries, complexity) =
126            fallow_extract::inventory::walk_source_with_complexity(path, source);
127        let entries = entries.into_iter().map(InventoryEntry::from).collect();
128        let complexity = complexity
129            .into_iter()
130            .map(|(hash, metrics)| (hash, InventoryComplexity::from(metrics)))
131            .collect();
132        (entries, complexity)
133    }
134}
135
136/// Parse discovered source files into typed module facts.
137///
138/// Keeping parsing behind the engine boundary lets sessions and future
139/// incremental runners choose cache policy without exposing the extract crate
140/// as the public orchestration layer.
141///
142/// `cancellation`, when set mid-parse, turns every remaining file into a no-op
143/// and truncates the returned modules; see
144/// [`fallow_extract::parse_all_files_cancellable`]. `flag_patterns` are the
145/// user flag patterns of the config the cache is keyed on.
146#[must_use]
147pub(crate) fn parse_all_files(
148    files: &[DiscoveredFile],
149    cache: Option<&CacheStore>,
150    needs: fallow_extract::ParseNeeds,
151    cancellation: Option<&AtomicBool>,
152    flag_patterns: &fallow_types::extract::FlagPatterns,
153    mode: fallow_types::shared_state::ExtractionMode,
154) -> ParseResult {
155    fallow_extract::parse_all_files_with_mode(
156        files,
157        cache,
158        needs,
159        cancellation,
160        flag_patterns,
161        mode,
162    )
163}