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