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, ToolingCredit, TraceProvenance};
8
9use super::{
10    AggregatedPluginResult, CONFIG_ONLY_EXPORT_NAMES, PathRuleIndex, PluginUsedExportRule,
11    federation_trace_provenance, module_specifiers, 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(crate) 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_virtual_module_trace_credits(&mut provenance, root, files, modules, plugin_result);
58    push_config_export_provenance(&mut provenance, root, files, modules, plugin_result);
59    if let ExportCredits::Collect {
60        include_entry_exports,
61    } = export_credits
62    {
63        push_plugin_export_credits(
64            &mut provenance,
65            root,
66            files,
67            modules,
68            plugin_result,
69            include_entry_exports,
70        );
71    }
72    provenance.with_peer_seeds(crate::analyze::peer_closure_seeds(plugin_result))
73}
74
75/// Record, for each package behind a virtual module of a plugin, the first
76/// file in path order that imports one of its modules, and the first such
77/// specifier of that file. The analysis
78/// credits the package for the same import, through the same
79/// [`VirtualModuleProviderRule::matches`].
80///
81/// [`VirtualModuleProviderRule::matches`]: super::VirtualModuleProviderRule::matches
82fn push_virtual_module_trace_credits(
83    provenance: &mut TraceProvenance,
84    root: &Path,
85    files: &[DiscoveredFile],
86    modules: &[ModuleInfo],
87    plugin_result: &AggregatedPluginResult,
88) {
89    if plugin_result.virtual_module_providers.is_empty() {
90        return;
91    }
92    let mut paths: Vec<(&Path, &ModuleInfo)> = modules
93        .iter()
94        .filter_map(|module| {
95            let file = files.get(module.file_id.0 as usize)?;
96            Some((file.path.as_path(), module))
97        })
98        .collect();
99    paths.sort_unstable_by_key(|(path, _)| *path);
100    // The first credit of a package wins, so the path order decides.
101    for (path, module) in paths {
102        for specifier in module_specifiers(module) {
103            for rule in &plugin_result.virtual_module_providers {
104                if !rule.matches(root, path, specifier) {
105                    continue;
106                }
107                provenance.push_tooling_credit(
108                    rule.package.clone(),
109                    ToolingCredit {
110                        reason: "virtual-module-import".to_owned(),
111                        plugin: Some(rule.plugin.clone()),
112                        config: Some(path.strip_prefix(root).unwrap_or(path).to_path_buf()),
113                        reference: Some(specifier.to_owned()),
114                    },
115                );
116            }
117        }
118    }
119}
120
121/// Record each export that a plugin rule marks as used.
122///
123/// The rules are the plugin `used_exports` rules and, under
124/// `includeEntryExports`, the config-file export credits. A rule matches the
125/// export names that it lists, or every export for `*`.
126fn push_plugin_export_credits(
127    provenance: &mut TraceProvenance,
128    root: &Path,
129    files: &[DiscoveredFile],
130    modules: &[ModuleInfo],
131    plugin_result: &AggregatedPluginResult,
132    include_entry_exports: bool,
133) {
134    let config_credits: &[PluginUsedExportRule] = if include_entry_exports {
135        &plugin_result.config_export_credits
136    } else {
137        &[]
138    };
139    let rules: PathRuleIndex<&PluginUsedExportRule> = PathRuleIndex::build(
140        plugin_result
141            .used_exports
142            .iter()
143            .chain(config_credits)
144            .map(|rule| (&rule.rule.path, rule)),
145        "plugin export credit pattern",
146    );
147    if rules.is_empty() {
148        return;
149    }
150    for module in modules {
151        let Some(file) = files.get(module.file_id.0 as usize) else {
152            continue;
153        };
154        let relative = file.path.strip_prefix(root).unwrap_or(&file.path);
155        let relative_str = relative.to_string_lossy().replace('\\', "/");
156        let mut credits = Vec::new();
157        for rule in rules.matching(&relative_str) {
158            for name in export_names(module) {
159                if rule.rule.exports.iter().any(|e| e == "*" || e == name) {
160                    credits.push((
161                        name.to_owned(),
162                        PluginExportCredit {
163                            plugin: rule.plugin_name.clone(),
164                            pattern: rule.rule.path.pattern.clone(),
165                        },
166                    ));
167                }
168            }
169        }
170        if !credits.is_empty() {
171            provenance.push_export_credits(relative.to_path_buf(), credits);
172        }
173    }
174}
175
176/// The names that a module exports: its own exports and its named
177/// re-exports. The graph gives a named re-export its own export, so a plugin
178/// rule credits it in the analysis too.
179fn export_names(module: &ModuleInfo) -> impl Iterator<Item = &str> {
180    let own = module.exports.iter().map(|export| match &export.name {
181        ExportName::Named(name) => name.as_str(),
182        ExportName::Default => "default",
183    });
184    let re_exported = module
185        .re_exports
186        .iter()
187        .map(|re_export| re_export.exported_name.as_str())
188        .filter(|name| *name != "*");
189    own.chain(re_exported)
190}
191
192/// Record each export that a plugin `used_exports` rule names for its file
193/// and that is in [`CONFIG_ONLY_EXPORT_NAMES`]. Only modules that declare such
194/// a name pay for the glob match.
195fn push_config_export_provenance(
196    provenance: &mut TraceProvenance,
197    root: &Path,
198    files: &[DiscoveredFile],
199    modules: &[ModuleInfo],
200    plugin_result: &AggregatedPluginResult,
201) {
202    let rules: PathRuleIndex<Vec<&str>> = PathRuleIndex::build(
203        plugin_result.used_exports.iter().filter_map(|rule| {
204            let names: Vec<&str> = rule
205                .rule
206                .exports
207                .iter()
208                .map(String::as_str)
209                .filter(|name| CONFIG_ONLY_EXPORT_NAMES.contains(name))
210                .collect();
211            (!names.is_empty()).then_some((&rule.rule.path, names))
212        }),
213        "used_exports pattern",
214    );
215    if rules.is_empty() {
216        return;
217    }
218    for module in modules {
219        let config_names: Vec<String> = module
220            .exports
221            .iter()
222            .filter_map(|export| match &export.name {
223                ExportName::Named(name)
224                    if !export.is_type_only
225                        && CONFIG_ONLY_EXPORT_NAMES.contains(&name.as_str()) =>
226                {
227                    Some(name.clone())
228                }
229                _ => None,
230            })
231            .collect();
232        if config_names.is_empty() {
233            continue;
234        }
235        let Some(file) = files.get(module.file_id.0 as usize) else {
236            continue;
237        };
238        let relative = file.path.strip_prefix(root).unwrap_or(&file.path);
239        let relative_str = relative.to_string_lossy().replace('\\', "/");
240        let matching = rules.matching(&relative_str);
241        for name in config_names {
242            if matching.iter().any(|names| names.contains(&name.as_str())) {
243                provenance.push_config_export(relative.to_path_buf(), name);
244            }
245        }
246    }
247}