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/// Whether the file at `path` with the text `source` is generated code: a
47/// generator writes it again on its next run, so an edit of it does not last.
48#[must_use]
49pub fn is_generated_file(path: &std::path::Path, source: &str) -> bool {
50    fallow_extract::is_generated_file(path, source)
51}
52
53/// Source inventory walking for coverage and upload surfaces.
54pub mod inventory {
55    use std::path::Path;
56
57    use rustc_hash::FxHashMap;
58
59    /// A single static-inventory entry for one function.
60    ///
61    /// This is the engine-owned inventory contract exposed to CLI upload
62    /// surfaces. The extractor owns AST traversal; the engine owns the public
63    /// shape that downstream crates construct and upload.
64    #[derive(Debug, Clone, PartialEq, Eq)]
65    pub struct InventoryEntry {
66        /// Beacon-compatible function name.
67        pub name: String,
68        /// 1-based source line of the function declaration.
69        pub line: u32,
70        /// 1-indexed UTF-16 column of the function node start.
71        pub start_column: u32,
72        /// 1-based source line where the function node ends.
73        pub end_line: u32,
74        /// 1-indexed UTF-16 column of the function node end.
75        pub end_column: u32,
76        /// Content digest of the function's full-span source slice. `None`
77        /// for a function with too many nested functions below it.
78        pub source_hash: Option<String>,
79        /// Whether the name came from the callee of the call this function is
80        /// passed to (`arr.map(cb)` -> `map`) rather than from a declaration,
81        /// a binding, or a property key.
82        pub is_callback: bool,
83    }
84
85    impl From<fallow_extract::inventory::InventoryEntry> for InventoryEntry {
86        fn from(entry: fallow_extract::inventory::InventoryEntry) -> Self {
87            Self {
88                name: entry.name,
89                line: entry.line,
90                start_column: entry.start_column,
91                end_line: entry.end_line,
92                end_column: entry.end_column,
93                source_hash: entry.source_hash,
94                is_callback: entry.is_callback,
95            }
96        }
97    }
98
99    /// Per-function static complexity collected alongside the inventory walk.
100    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
101    pub struct InventoryComplexity {
102        /// `McCabe` cyclomatic complexity (1 + decision points).
103        pub cyclomatic: u16,
104        /// `SonarSource` cognitive complexity (structural + nesting penalty).
105        pub cognitive: u16,
106    }
107
108    impl From<fallow_extract::inventory::InventoryComplexity> for InventoryComplexity {
109        fn from(complexity: fallow_extract::inventory::InventoryComplexity) -> Self {
110            Self {
111                cyclomatic: complexity.cyclomatic,
112                cognitive: complexity.cognitive,
113            }
114        }
115    }
116
117    /// Walk source and emit engine-owned function inventory entries.
118    #[must_use]
119    pub fn walk_source(path: &Path, source: &str) -> Vec<InventoryEntry> {
120        fallow_extract::inventory::walk_source(path, source)
121            .into_iter()
122            .map(InventoryEntry::from)
123            .collect()
124    }
125
126    /// Walk source once and emit inventory entries plus static complexity by source hash.
127    #[must_use]
128    pub fn walk_source_with_complexity(
129        path: &Path,
130        source: &str,
131    ) -> (Vec<InventoryEntry>, FxHashMap<String, InventoryComplexity>) {
132        let (entries, complexity) =
133            fallow_extract::inventory::walk_source_with_complexity(path, source);
134        let entries = entries.into_iter().map(InventoryEntry::from).collect();
135        let complexity = complexity
136            .into_iter()
137            .map(|(hash, metrics)| (hash, InventoryComplexity::from(metrics)))
138            .collect();
139        (entries, complexity)
140    }
141}
142
143/// Parse discovered source files into typed module facts.
144///
145/// Keeping parsing behind the engine boundary lets sessions and future
146/// incremental runners choose cache policy without exposing the extract crate
147/// as the public orchestration layer.
148///
149/// `cancellation`, when set mid-parse, turns every remaining file into a no-op
150/// and truncates the returned modules; see
151/// [`fallow_extract::parse_all_files_cancellable`]. `flag_patterns` are the
152/// user flag patterns of the config the cache is keyed on.
153#[must_use]
154pub(crate) fn parse_all_files(
155    files: &[DiscoveredFile],
156    cache: Option<&CacheStore>,
157    needs: fallow_extract::ParseNeeds,
158    cancellation: Option<&AtomicBool>,
159    flag_patterns: &fallow_types::extract::FlagPatterns,
160    mode: fallow_types::shared_state::ExtractionMode,
161) -> ParseResult {
162    fallow_extract::parse_all_files_with_mode(
163        files,
164        cache,
165        needs,
166        cancellation,
167        flag_patterns,
168        mode,
169    )
170}