Skip to main content

fallow_core/plugins/
trace_provenance.rs

1//! What the plugin run knows about files, dependencies and exports beyond
2//! the module graph, collected once per analysis for the trace output.
3
4use std::path::Path;
5
6use fallow_types::extract::ExportName;
7use fallow_types::trace::{PluginExportCredit, TraceProvenance};
8
9use super::{
10    AggregatedPluginResult, CONFIG_ONLY_EXPORT_NAMES, CompiledPathRule, PluginUsedExportRule,
11    federation_trace_provenance, push_tooling_trace_credits,
12};
13use crate::discover::DiscoveredFile;
14use crate::extract::ModuleInfo;
15
16/// Which plugin export credits the trace provenance records.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ExportCredits {
19    /// Record no export credit. A run without a retained module graph gives
20    /// no trace, so it skips the match of each rule against each module.
21    Skip,
22    /// Record the plugin `used_exports` credits and, when
23    /// `include_entry_exports` is on, the config-file export credits, the
24    /// same as in the unused-export analysis.
25    Collect { include_entry_exports: bool },
26}
27
28impl ExportCredits {
29    /// The credits of a run: a trace needs the retained module graph.
30    #[must_use]
31    pub fn for_run(retain_graph: bool, config: &fallow_config::ResolvedConfig) -> Self {
32        if retain_graph {
33            Self::Collect {
34                include_entry_exports: config.include_entry_exports
35                    || config.workspace_settings.any_include_entry_exports(),
36            }
37        } else {
38            Self::Skip
39        }
40    }
41}
42
43/// Collect the trace provenance of one analysis, with the seeds of the
44/// peer-dependency closures.
45#[must_use]
46pub fn build_trace_provenance(
47    root: &Path,
48    files: &[DiscoveredFile],
49    workspaces: &[fallow_config::WorkspaceInfo],
50    modules: &[ModuleInfo],
51    plugin_result: &AggregatedPluginResult,
52    export_credits: ExportCredits,
53) -> TraceProvenance {
54    let mut provenance =
55        federation_trace_provenance(root, files, &plugin_result.federation_sources, modules);
56    push_tooling_trace_credits(&mut provenance, root, workspaces, plugin_result);
57    push_config_export_provenance(&mut provenance, root, files, modules, plugin_result);
58    if let ExportCredits::Collect {
59        include_entry_exports,
60    } = export_credits
61    {
62        push_plugin_export_credits(
63            &mut provenance,
64            root,
65            files,
66            modules,
67            plugin_result,
68            include_entry_exports,
69        );
70    }
71    provenance.with_peer_seeds(crate::analyze::peer_closure_seeds(plugin_result))
72}
73
74/// Record each export that a plugin rule marks as used.
75///
76/// The rules are the plugin `used_exports` rules and, under
77/// `includeEntryExports`, the config-file export credits. A rule matches the
78/// export names that it lists, or every export for `*`.
79fn push_plugin_export_credits(
80    provenance: &mut TraceProvenance,
81    root: &Path,
82    files: &[DiscoveredFile],
83    modules: &[ModuleInfo],
84    plugin_result: &AggregatedPluginResult,
85    include_entry_exports: bool,
86) {
87    let config_credits: &[PluginUsedExportRule] = if include_entry_exports {
88        &plugin_result.config_export_credits
89    } else {
90        &[]
91    };
92    let rules: Vec<(CompiledPathRule, &PluginUsedExportRule)> = plugin_result
93        .used_exports
94        .iter()
95        .chain(config_credits)
96        .filter_map(|rule| {
97            let compiled = CompiledPathRule::for_used_export_rule(
98                &rule.rule.path,
99                "plugin export credit pattern",
100            )?;
101            Some((compiled, rule))
102        })
103        .collect();
104    if rules.is_empty() {
105        return;
106    }
107    for module in modules {
108        let Some(file) = files.get(module.file_id.0 as usize) else {
109            continue;
110        };
111        let relative = file.path.strip_prefix(root).unwrap_or(&file.path);
112        let relative_str = relative.to_string_lossy().replace('\\', "/");
113        let mut credits = Vec::new();
114        for (compiled, rule) in &rules {
115            if !compiled.matches(&relative_str) {
116                continue;
117            }
118            for name in export_names(module) {
119                if rule.rule.exports.iter().any(|e| e == "*" || e == name) {
120                    credits.push((
121                        name.to_owned(),
122                        PluginExportCredit {
123                            plugin: rule.plugin_name.clone(),
124                            pattern: rule.rule.path.pattern.clone(),
125                        },
126                    ));
127                }
128            }
129        }
130        if !credits.is_empty() {
131            provenance.push_export_credits(relative.to_path_buf(), credits);
132        }
133    }
134}
135
136/// The names that a module exports: its own exports and its named
137/// re-exports. The graph gives a named re-export its own export, so a plugin
138/// rule credits it in the analysis too.
139fn export_names(module: &ModuleInfo) -> impl Iterator<Item = &str> {
140    let own = module.exports.iter().map(|export| match &export.name {
141        ExportName::Named(name) => name.as_str(),
142        ExportName::Default => "default",
143    });
144    let re_exported = module
145        .re_exports
146        .iter()
147        .map(|re_export| re_export.exported_name.as_str())
148        .filter(|name| *name != "*");
149    own.chain(re_exported)
150}
151
152/// Record each export that a plugin `used_exports` rule names for its file
153/// and that is in [`CONFIG_ONLY_EXPORT_NAMES`]. Only modules that declare such
154/// a name pay for the glob match.
155fn push_config_export_provenance(
156    provenance: &mut TraceProvenance,
157    root: &Path,
158    files: &[DiscoveredFile],
159    modules: &[ModuleInfo],
160    plugin_result: &AggregatedPluginResult,
161) {
162    let rules: Vec<(CompiledPathRule, Vec<&str>)> = plugin_result
163        .used_exports
164        .iter()
165        .filter_map(|rule| {
166            let names: Vec<&str> = rule
167                .rule
168                .exports
169                .iter()
170                .map(String::as_str)
171                .filter(|name| CONFIG_ONLY_EXPORT_NAMES.contains(name))
172                .collect();
173            if names.is_empty() {
174                return None;
175            }
176            let compiled =
177                CompiledPathRule::for_used_export_rule(&rule.rule.path, "used_exports pattern")?;
178            Some((compiled, names))
179        })
180        .collect();
181    if rules.is_empty() {
182        return;
183    }
184    for module in modules {
185        let config_names: Vec<String> = module
186            .exports
187            .iter()
188            .filter_map(|export| match &export.name {
189                ExportName::Named(name)
190                    if !export.is_type_only
191                        && CONFIG_ONLY_EXPORT_NAMES.contains(&name.as_str()) =>
192                {
193                    Some(name.clone())
194                }
195                _ => None,
196            })
197            .collect();
198        if config_names.is_empty() {
199            continue;
200        }
201        let Some(file) = files.get(module.file_id.0 as usize) else {
202            continue;
203        };
204        let relative = file.path.strip_prefix(root).unwrap_or(&file.path);
205        let relative_str = relative.to_string_lossy().replace('\\', "/");
206        for name in config_names {
207            if rules
208                .iter()
209                .any(|(rule, names)| names.contains(&name.as_str()) && rule.matches(&relative_str))
210            {
211                provenance.push_config_export(relative.to_path_buf(), name);
212            }
213        }
214    }
215}