Skip to main content

aft_parse/callgraph_store/
method_call_facts.rs

1//! What method-call resolution reads about one file: its [`FileFacts`].
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use serde::{Deserialize, Serialize};
6
7use crate::callgraph_store::join::{
8    self,
9    dispatch::{
10        dependency, DispatchFacts, FieldHint, MethodHint, ReturnHint, StaticFacts, TypeHint,
11    },
12    BlobImport, ParseBlob,
13};
14
15/// The import fields method-call resolution reads.
16#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
17pub struct ImportFact {
18    module_path: String,
19    names: Vec<String>,
20    default_import: Option<String>,
21}
22
23/// Everything method-call resolution reads about one file, apart from its
24/// call sites. Positions are left out, so an edit that only moves code keeps
25/// a file's facts, and the resolutions that read them, unchanged.
26#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
27pub struct FileFacts {
28    pub language: String,
29    #[serde(default)]
30    go_package: Option<String>,
31    types: Vec<TypeHint>,
32    methods: Vec<MethodHint>,
33    fields: Vec<FieldHint>,
34    returns: Vec<ReturnHint>,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    static_facts: Option<Box<StaticFacts>>,
37    imports: Vec<ImportFact>,
38    default_export_symbol: Option<String>,
39    /// Target file of each resolved import, by module path.
40    pub import_targets: BTreeMap<String, String>,
41    /// Target file and symbol of each Rust receiver type name.
42    pub type_targets: BTreeMap<String, (String, String)>,
43}
44
45#[derive(Default, PartialEq)]
46struct NamedFacts<'a> {
47    types: Vec<&'a TypeHint>,
48    target: Option<&'a (String, String)>,
49    imports: Vec<(&'a str, Vec<&'a str>, bool, Option<&'a String>)>,
50}
51
52fn grouped<'a, T, K: Ord>(items: &'a [T], key: impl Fn(&'a T) -> K) -> BTreeMap<K, Vec<&'a T>> {
53    let mut groups = BTreeMap::<K, Vec<&T>>::new();
54    for item in items {
55        groups.entry(key(item)).or_default().push(item);
56    }
57    groups
58}
59
60fn changed_groups<K: Ord, V: PartialEq>(
61    old: &BTreeMap<K, V>,
62    new: &BTreeMap<K, V>,
63    mut emit: impl FnMut(&K),
64) {
65    for key in old.keys().chain(new.keys()) {
66        if old.get(key) != new.get(key) {
67            emit(key);
68        }
69    }
70}
71
72impl FileFacts {
73    pub fn new(parse: &ParseBlob) -> Self {
74        Self {
75            language: parse.language.clone(),
76            go_package: parse.dispatch.go_package.clone(),
77            types: parse.dispatch.types.clone(),
78            methods: parse.dispatch.methods.clone(),
79            fields: parse.dispatch.fields.clone(),
80            returns: parse.dispatch.returns.clone(),
81            static_facts: parse.dispatch.static_facts.clone(),
82            imports: if parse.language == "python" {
83                join::dispatch::python_reexports(parse)
84                    .into_iter()
85                    .map(|(module_path, names)| ImportFact {
86                        module_path,
87                        names,
88                        default_import: None,
89                    })
90                    .collect()
91            } else {
92                parse
93                    .imports
94                    .iter()
95                    .map(|import| ImportFact {
96                        module_path: import.module_path.clone(),
97                        names: import.names.clone(),
98                        default_import: import.default_import.clone(),
99                    })
100                    .collect()
101            },
102            default_export_symbol: parse.default_export_symbol.clone(),
103            import_targets: BTreeMap::new(),
104            type_targets: BTreeMap::new(),
105        }
106    }
107
108    /// A parse blob carrying only what [`Resolver`] reads. Fields the resolver
109    /// never reads (symbols, references, AST nodes, import positions, sites)
110    /// are left empty.
111    pub fn resolver_parse(&self) -> ParseBlob {
112        ParseBlob {
113            entry_point_symbols: Vec::new(),
114            dispatch: DispatchFacts {
115                go_package: self.go_package.clone(),
116                types: self.types.clone(),
117                methods: self.methods.clone(),
118                sites: Vec::new(),
119                fields: self.fields.clone(),
120                returns: self.returns.clone(),
121                static_facts: self.static_facts.clone(),
122            },
123            extractor_version: String::new(),
124            language: self.language.clone(),
125            ast_nodes: Vec::new(),
126            symbols: Vec::new(),
127            default_export_symbol: self.default_export_symbol.clone(),
128            exported_symbols: Vec::new(),
129            callable_symbols: Vec::new(),
130            python_bindings: Vec::new(),
131            imports: self
132                .imports
133                .iter()
134                .map(|import| BlobImport {
135                    ordinal: 0,
136                    module_path: import.module_path.clone(),
137                    names: import.names.clone(),
138                    default_import: import.default_import.clone(),
139                    namespace_import: None,
140                    byte_start: 0,
141                    byte_end: 0,
142                    raw_text: String::new(),
143                    type_only: false,
144                    side_effect: false,
145                })
146                .collect(),
147            refs: Vec::new(),
148        }
149    }
150
151    /// The keys of every resolution that may read this file's facts, when the
152    /// facts change from `old` to `new` (either side may be absent).
153    pub fn changed_keys(
154        path: &str,
155        old: Option<&Self>,
156        new: Option<&Self>,
157        keys: &mut BTreeSet<String>,
158    ) {
159        if old == new {
160            return;
161        }
162        keys.insert(dependency::file(path));
163        keys.insert(dependency::directory(path));
164        for facts in old.into_iter().chain(new) {
165            StaticFacts::changed_keys(
166                path,
167                &facts.language,
168                None,
169                facts.static_facts.as_deref(),
170                keys,
171            );
172            // A resolution that found this file through a method name recorded
173            // only that name, so every method name of the file is affected.
174            keys.extend(
175                facts
176                    .methods
177                    .iter()
178                    .map(|method| dependency::method(&method.name)),
179            );
180            if facts.language == "go" {
181                keys.insert(dependency::GO_INTERFACES.to_string());
182            }
183        }
184    }
185
186    /// Diff name-addressed reads when the file keeps its identity and language.
187    /// Go interface checks read whole method sets, so Go retains the coarse diff.
188    pub fn changed_keys_by_method(
189        path: &str,
190        old: Option<&Self>,
191        new: Option<&Self>,
192        keys: &mut BTreeSet<String>,
193    ) {
194        if old == new {
195            return;
196        }
197        let (Some(old), Some(new)) = (old, new) else {
198            return Self::changed_keys(path, old, new, keys);
199        };
200        if old.language == "go" || old.language != new.language || old.go_package != new.go_package
201        {
202            return Self::changed_keys(path, Some(old), Some(new), keys);
203        }
204        let mut named = Vec::new();
205        StaticFacts::changed_keys(
206            path,
207            &new.language,
208            old.static_facts.as_deref(),
209            new.static_facts.as_deref(),
210            keys,
211        );
212        changed_groups(
213            &grouped(&old.methods, |m| m.name.as_str()),
214            &grouped(&new.methods, |m| m.name.as_str()),
215            |name| named.push(dependency::method(name)),
216        );
217        let (old_named, new_named) = (old.named_facts(), new.named_facts());
218        changed_groups(&old_named, &new_named, |name| {
219            named.push(dependency::type_name(path, name));
220        });
221        if old.default_export_symbol != new.default_export_symbol {
222            named.push(dependency::type_name(path, "@default"));
223        }
224        changed_groups(
225            &grouped(&old.types, |t| t.name.as_str()),
226            &grouped(&new.types, |t| t.name.as_str()),
227            |name| named.push(dependency::directory_type(path, name)),
228        );
229        changed_groups(
230            &grouped(&old.fields, |f| (f.owner.as_str(), f.name.as_str())),
231            &grouped(&new.fields, |f| (f.owner.as_str(), f.name.as_str())),
232            |(owner, name)| named.push(dependency::field(path, owner, name)),
233        );
234        changed_groups(
235            &grouped(&old.returns, |r| r.symbol.as_str()),
236            &grouped(&new.returns, |r| r.symbol.as_str()),
237            |symbol| named.push(dependency::return_hint(path, symbol)),
238        );
239        // The facts differ, so something a resolution may read changed. If no
240        // name above accounts for it (for example the target of an import that
241        // binds no local name), fall back to the whole-file keys rather than
242        // invalidate nothing.
243        if named.is_empty()
244            && (old.static_facts == new.static_facts
245                || old.imports != new.imports
246                || old.import_targets != new.import_targets)
247        {
248            return Self::changed_keys(path, Some(old), Some(new), keys);
249        }
250        keys.extend(named);
251    }
252
253    fn named_facts(&self) -> BTreeMap<&str, NamedFacts<'_>> {
254        let mut names = BTreeMap::<&str, NamedFacts<'_>>::new();
255        for ty in &self.types {
256            names.entry(&ty.name).or_default().types.push(ty);
257        }
258        for (name, target) in &self.type_targets {
259            names.entry(name).or_default().target = Some(target);
260        }
261        for import in &self.imports {
262            let mut locals = BTreeMap::<&str, Vec<&str>>::new();
263            for specifier in &import.names {
264                locals
265                    .entry(crate::imports::specifier_local_name(specifier))
266                    .or_default()
267                    .push(specifier);
268            }
269            if let Some(default) = &import.default_import {
270                locals.entry(default).or_default();
271            }
272            for (name, specifiers) in locals {
273                names.entry(name).or_default().imports.push((
274                    &import.module_path,
275                    specifiers,
276                    import.default_import.as_deref() == Some(name),
277                    self.import_targets.get(&import.module_path),
278                ));
279            }
280        }
281        names
282    }
283}
284aft_store::heap_bytes_of_fields!(ImportFact {
285    module_path,
286    names,
287    default_import,
288});
289aft_store::heap_bytes_of_fields!(FileFacts {
290    language,
291    go_package,
292    types,
293    methods,
294    fields,
295    returns,
296    static_facts,
297    imports,
298    default_export_symbol,
299    import_targets,
300    type_targets,
301});