Skip to main content

aft_parse/callgraph_store/dispatch/
projected.rs

1//! Method-call resolution split in two: what each file's sites and
2//! declarations mean, worked out in file order, and the matching of sites
3//! to declarations, which then reads only the records written here.
4//!
5//! [`Resolver::project_type`] is the only rule that reads a file's imports,
6//! fields, return types, type and import targets, or its directory, and
7//! Python's method resolution order is the only rule that follows imports
8//! across files. Both are answered here once per file, with the dependency
9//! keys they recorded. A resolver over a source with
10//! [`DispatchFiles::projections`] replays these answers and reads each file
11//! only for its language, Go package, types and methods (the method rows
12//! and the type graph), so it may run in any order: every other rule runs
13//! the same code on the same facts and records the same keys.
14//!
15//! What pass 4 asks [`Resolver::project_type`] of each file `F`:
16//! - each site's receiver, from the calling file;
17//! - each method's owner and trait, from `F`;
18//! - each base of every type `F` declares, from `F`;
19//! - each base of a method's owner type, again from the method's file `F`
20//!   (the unknown-receiver rule projects them from there, even when the
21//!   owner type is declared elsewhere);
22//! - for a Rust file with typed sites, the last segment of a trait or owner
23//!   name, from the calling file. Those names are not known in file order,
24//!   so every name such a file can resolve is projected, and any other name
25//!   gets [`Recorded::NotProjectable`], whose answer and keys are fixed (see
26//!   [`Resolver::replay_projection`]).
27
28use std::collections::{BTreeMap, BTreeSet};
29
30use super::{dependency, DispatchFacts, MethodHint, ParseBlob, Resolver, SiteHint, TypeHint};
31
32/// The answer for one type lookup in a file. Static import keys carry the
33/// class declaration's position in the static facts rather than its nominal type.
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct ProjectedType {
36    #[cfg(any(test, feature = "test-support"))]
37    /// The file declaring the type and the type's position among that
38    /// file's types, or `None` when the name names no project type.
39    pub found: Option<(String, u32)>,
40    #[cfg(not(any(test, feature = "test-support")))]
41    /// The file declaring the type and the type's position among that
42    /// file's types, or `None` when the name names no project type.
43    found: Option<(String, u32)>,
44    #[cfg(any(test, feature = "test-support"))]
45    /// The keys the lookup recorded.
46    pub dependencies: Box<[String]>,
47    #[cfg(not(any(test, feature = "test-support")))]
48    /// The keys the lookup recorded.
49    dependencies: Box<[String]>,
50}
51
52/// The method resolution order a Python `super()` call reads for its owner
53/// type, with the keys computing it recorded. The owner's own projection is
54/// recorded separately, as a [`ProjectedType`].
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct ProjectedMro {
57    #[cfg(any(test, feature = "test-support"))]
58    pub mro: Option<Vec<(String, String)>>,
59    #[cfg(not(any(test, feature = "test-support")))]
60    mro: Option<Vec<(String, String)>>,
61    #[cfg(any(test, feature = "test-support"))]
62    pub dependencies: Box<[String]>,
63    #[cfg(not(any(test, feature = "test-support")))]
64    dependencies: Box<[String]>,
65}
66
67/// One method-call site in `bound_dispatch_sites()` order, with what the
68/// pass-4 driver reads about it from its file besides the site itself.
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub struct SiteRecord {
71    pub site: SiteHint,
72    /// Whether the file's reference with the site's ordinal is a Rust
73    /// associated-function call. The resolver applies it to Rust files only.
74    pub associated: bool,
75    /// Whether pass 2 already linked the site's reference with an ordinary
76    /// edge that Rust spells as an associated or `self.` call: such a Rust
77    /// site with no project receiver is left out of the file's sites.
78    pub keeps_ordinary_edge: bool,
79}
80
81/// Everything pass 4 reads about one file once receivers are projected.
82#[derive(Clone, Debug, PartialEq, Eq)]
83pub struct FileRecord {
84    #[cfg(any(test, feature = "test-support"))]
85    /// The file's language, Go package, types and methods; everything else
86    /// is left empty.
87    pub facts: ParseBlob,
88    #[cfg(not(any(test, feature = "test-support")))]
89    /// The file's language, Go package, types and methods; everything else
90    /// is left empty.
91    facts: ParseBlob,
92    #[cfg(any(test, feature = "test-support"))]
93    /// Every name pass 4 asks [`Resolver::project_type`] of this file, with
94    /// its answer.
95    pub projections: BTreeMap<String, ProjectedType>,
96    #[cfg(not(any(test, feature = "test-support")))]
97    /// Every name pass 4 asks [`Resolver::project_type`] of this file, with
98    /// its answer.
99    projections: BTreeMap<String, ProjectedType>,
100    #[cfg(any(test, feature = "test-support"))]
101    /// For each owner of a Python `super()` site of this file, the owner
102    /// type's resolution order.
103    pub mro: BTreeMap<String, ProjectedMro>,
104    #[cfg(not(any(test, feature = "test-support")))]
105    /// For each owner of a Python `super()` site of this file, the owner
106    /// type's resolution order.
107    mro: BTreeMap<String, ProjectedMro>,
108    #[cfg(any(test, feature = "test-support"))]
109    /// Set for a Rust file whose every resolvable name is in
110    /// `projections`, so any other name has the fixed miss answer.
111    pub complete_names: bool,
112    #[cfg(not(any(test, feature = "test-support")))]
113    /// Set for a Rust file whose every resolvable name is in
114    /// `projections`, so any other name has the fixed miss answer.
115    complete_names: bool,
116    #[cfg(any(test, feature = "test-support"))]
117    /// How many of `projections` are there only because `complete_names`
118    /// is set, for measurement.
119    pub resolvable_name_projections: u32,
120    #[cfg(not(any(test, feature = "test-support")))]
121    /// How many of `projections` are there only because `complete_names`
122    /// is set, for measurement.
123    resolvable_name_projections: u32,
124    #[cfg(any(test, feature = "test-support"))]
125    pub sites: Vec<SiteRecord>,
126    #[cfg(not(any(test, feature = "test-support")))]
127    sites: Vec<SiteRecord>,
128    #[cfg(any(test, feature = "test-support"))]
129    /// Sorted ordinals of the sites whose `associated` is set.
130    pub associated: Vec<u32>,
131    #[cfg(not(any(test, feature = "test-support")))]
132    /// Sorted ordinals of the sites whose `associated` is set.
133    associated: Vec<u32>,
134}
135
136/// A record looked up by name.
137pub enum Recorded<'r, T> {
138    Found(&'r T),
139    /// A name of a Rust file the file cannot resolve to a type.
140    NotProjectable,
141    /// No record: the records are incomplete, which fails the build.
142    Missing,
143}
144
145/// Recorded projections, as a source serving them hands them to the
146/// resolver.
147pub trait Projections {
148    fn projected_type(&self, file: &str, name: &str) -> Recorded<'_, ProjectedType>;
149    fn projected_mro(&self, file: &str, owner: &str) -> Recorded<'_, ProjectedMro>;
150    /// Notes a record the resolver needed and did not find; the pass fails.
151    fn missing(&self, what: String);
152}
153
154impl FileRecord {
155    pub fn facts(&self) -> &ParseBlob {
156        &self.facts
157    }
158
159    pub fn sites(&self) -> &[SiteRecord] {
160        &self.sites
161    }
162
163    /// How many projected answers and resolution orders the record keeps,
164    /// how many of those answer a Rust file's resolvable names only, and
165    /// the heap they hold.
166    pub fn projection_census(&self, seen: &mut aft_store::heap::Seen) -> (usize, usize, usize) {
167        use aft_store::heap::HeapBytes as _;
168        (
169            self.projections.len() + self.mro.len(),
170            self.resolvable_name_projections as usize,
171            self.projections.heap_bytes(seen) + self.mro.heap_bytes(seen),
172        )
173    }
174
175    pub fn associated(&self, ordinal: u32) -> bool {
176        self.associated.binary_search(&ordinal).is_ok()
177    }
178
179    pub fn projected_type(&self, name: &str) -> Recorded<'_, ProjectedType> {
180        match self.projections.get(name) {
181            Some(found) => Recorded::Found(found),
182            None if self.complete_names && !name.starts_with('@') => Recorded::NotProjectable,
183            None => Recorded::Missing,
184        }
185    }
186
187    pub fn projected_mro(&self, owner: &str) -> Recorded<'_, ProjectedMro> {
188        self.mro
189            .get(owner)
190            .map_or(Recorded::Missing, Recorded::Found)
191    }
192
193    /// The names of the methods the file declares, in name order.
194    pub fn method_names(&self) -> BTreeSet<&str> {
195        self.facts
196            .dispatch
197            .methods
198            .iter()
199            .map(|method| method.name.as_str())
200            .collect()
201    }
202
203    /// For a Go file, the names of the methods its interfaces require.
204    pub fn go_required(&self) -> BTreeSet<&str> {
205        if self.facts.language != "go" {
206            return BTreeSet::new();
207        }
208        let dispatch = &self.facts.dispatch;
209        dispatch
210            .methods
211            .iter()
212            .filter(|method| {
213                dispatch
214                    .types
215                    .iter()
216                    .any(|ty| ty.interface && ty.name == method.owner)
217            })
218            .map(|method| method.name.as_str())
219            .collect()
220    }
221}
222
223test_support_visibility! {
224/// The first byte of every scratch-encoded record (see
225/// [`FileRecord::encode_scratch`]). The encoding lives only in one build's
226/// scratch folder and is read back by the same process, so it needs no
227/// version history; the byte only catches bytes that are not a record.
228const SCRATCH_FORMAT: u8 = 1;
229}
230
231/// Appends the scratch encoding's parts: counts and lengths as
232/// little-endian `u32`, flags as one byte, text as its length and bytes.
233struct ScratchWriter<'o>(&'o mut Vec<u8>);
234
235impl ScratchWriter<'_> {
236    fn byte(&mut self, value: u8) {
237        self.0.push(value);
238    }
239
240    fn flag(&mut self, value: bool) {
241        self.0.push(u8::from(value));
242    }
243
244    fn number(&mut self, value: u32) {
245        self.0.extend(value.to_le_bytes());
246    }
247
248    fn count(&mut self, count: usize) -> Result<(), String> {
249        let count = u32::try_from(count)
250            .map_err(|_| "a pass-4 record part has 4 billion or more items".to_string())?;
251        self.number(count);
252        Ok(())
253    }
254
255    fn text(&mut self, text: &str) -> Result<(), String> {
256        self.count(text.len())?;
257        self.0.extend_from_slice(text.as_bytes());
258        Ok(())
259    }
260
261    fn optional(&mut self, text: Option<&str>) -> Result<(), String> {
262        match text {
263            None => self.byte(0),
264            Some(text) => {
265                self.byte(1);
266                self.text(text)?;
267            }
268        }
269        Ok(())
270    }
271
272    fn texts(&mut self, texts: &[String]) -> Result<(), String> {
273        self.count(texts.len())?;
274        for text in texts {
275            self.text(text)?;
276        }
277        Ok(())
278    }
279}
280
281/// Reads what [`ScratchWriter`] wrote, failing on anything it could not
282/// have written.
283struct ScratchReader<'b> {
284    bytes: &'b [u8],
285    at: usize,
286}
287
288impl<'b> ScratchReader<'b> {
289    fn take(&mut self, len: usize) -> Result<&'b [u8], String> {
290        let end = self
291            .at
292            .checked_add(len)
293            .filter(|end| *end <= self.bytes.len())
294            .ok_or_else(|| "a truncated pass-4 record".to_string())?;
295        let taken = &self.bytes[self.at..end];
296        self.at = end;
297        Ok(taken)
298    }
299
300    fn byte(&mut self) -> Result<u8, String> {
301        Ok(self.take(1)?[0])
302    }
303
304    fn flag(&mut self) -> Result<bool, String> {
305        match self.byte()? {
306            0 => Ok(false),
307            1 => Ok(true),
308            other => Err(format!("a pass-4 record flag reads {other}")),
309        }
310    }
311
312    fn number(&mut self) -> Result<u32, String> {
313        let bytes = self.take(4)?;
314        Ok(u32::from_le_bytes(bytes.try_into().expect("four bytes")))
315    }
316
317    /// A count of items, each at least one byte long, so a damaged count
318    /// cannot ask for more memory than the record's bytes.
319    fn count(&mut self) -> Result<usize, String> {
320        let count = self.number()? as usize;
321        if count > self.bytes.len() - self.at {
322            return Err(format!("a pass-4 record counts {count} items past its end"));
323        }
324        Ok(count)
325    }
326
327    fn text(&mut self) -> Result<String, String> {
328        let len = self.number()? as usize;
329        String::from_utf8(self.take(len)?.to_vec())
330            .map_err(|_| "a pass-4 record holds text that is not UTF-8".to_string())
331    }
332
333    fn optional(&mut self) -> Result<Option<String>, String> {
334        match self.byte()? {
335            0 => Ok(None),
336            1 => self.text().map(Some),
337            other => Err(format!("a pass-4 record option reads {other}")),
338        }
339    }
340
341    fn texts(&mut self) -> Result<Vec<String>, String> {
342        let count = self.count()?;
343        (0..count).map(|_| self.text()).collect()
344    }
345}
346
347impl ProjectedType {
348    fn encode_scratch(&self, out: &mut ScratchWriter<'_>) -> Result<(), String> {
349        let Self {
350            found,
351            dependencies,
352        } = self;
353        match found {
354            None => out.byte(0),
355            Some((file, index)) => {
356                out.byte(1);
357                out.text(file)?;
358                out.number(*index);
359            }
360        }
361        out.texts(dependencies)
362    }
363
364    fn decode_scratch(input: &mut ScratchReader<'_>) -> Result<Self, String> {
365        let found = match input.byte()? {
366            0 => None,
367            1 => Some((input.text()?, input.number()?)),
368            other => return Err(format!("a projected type reads {other}")),
369        };
370        Ok(Self {
371            found,
372            dependencies: input.texts()?.into_boxed_slice(),
373        })
374    }
375}
376
377impl ProjectedMro {
378    fn encode_scratch(&self, out: &mut ScratchWriter<'_>) -> Result<(), String> {
379        let Self { mro, dependencies } = self;
380        match mro {
381            None => out.byte(0),
382            Some(order) => {
383                out.byte(1);
384                out.count(order.len())?;
385                for (file, name) in order {
386                    out.text(file)?;
387                    out.text(name)?;
388                }
389            }
390        }
391        out.texts(dependencies)
392    }
393
394    fn decode_scratch(input: &mut ScratchReader<'_>) -> Result<Self, String> {
395        let mro = match input.byte()? {
396            0 => None,
397            1 => {
398                let count = input.count()?;
399                Some(
400                    (0..count)
401                        .map(|_| Ok((input.text()?, input.text()?)))
402                        .collect::<Result<Vec<_>, String>>()?,
403                )
404            }
405            other => return Err(format!("a resolution order reads {other}")),
406        };
407        Ok(Self {
408            mro,
409            dependencies: input.texts()?.into_boxed_slice(),
410        })
411    }
412}
413
414impl FileRecord {
415    /// Appends the record's scratch encoding to `out`: what a cold build
416    /// writes to its scratch folder, and [`Self::decode_scratch`] reads back
417    /// equal. Never published.
418    ///
419    /// # Errors
420    ///
421    /// When a part has 4 billion or more items or bytes.
422    pub fn encode_scratch(&self, out: &mut Vec<u8>) -> Result<(), String> {
423        // Named in full, so a field added to the record must be added here.
424        let Self {
425            facts,
426            projections,
427            mro,
428            complete_names,
429            resolvable_name_projections,
430            sites,
431            associated,
432        } = self;
433        debug_assert!(
434            *facts == declarations(facts),
435            "a record keeps only the facts `declarations` keeps"
436        );
437        let mut out = ScratchWriter(out);
438        out.byte(SCRATCH_FORMAT);
439        out.text(&facts.language)?;
440        out.optional(facts.dispatch.go_package.as_deref())?;
441        out.count(facts.dispatch.types.len())?;
442        for TypeHint {
443            name,
444            bases,
445            interface,
446            closed,
447        } in &facts.dispatch.types
448        {
449            out.text(name)?;
450            out.texts(bases)?;
451            out.flag(*interface);
452            out.flag(*closed);
453        }
454        out.count(facts.dispatch.methods.len())?;
455        for MethodHint {
456            owner,
457            trait_name,
458            name,
459            symbol,
460            has_body,
461            shape,
462            private,
463        } in &facts.dispatch.methods
464        {
465            out.text(owner)?;
466            out.optional(trait_name.as_deref())?;
467            out.text(name)?;
468            out.text(symbol)?;
469            out.flag(*has_body);
470            out.text(shape)?;
471            out.flag(*private);
472        }
473        out.count(projections.len())?;
474        for (name, projected) in projections {
475            out.text(name)?;
476            projected.encode_scratch(&mut out)?;
477        }
478        out.count(mro.len())?;
479        for (owner, order) in mro {
480            out.text(owner)?;
481            order.encode_scratch(&mut out)?;
482        }
483        out.flag(*complete_names);
484        out.number(*resolvable_name_projections);
485        out.count(sites.len())?;
486        for SiteRecord {
487            site,
488            associated,
489            keeps_ordinary_edge,
490        } in sites
491        {
492            let SiteHint {
493                ordinal,
494                caller,
495                line,
496                member,
497                receiver,
498                dynamic,
499            } = site;
500            out.number(*ordinal);
501            out.optional(caller.as_deref())?;
502            out.number(*line);
503            out.optional(member.as_deref())?;
504            out.optional(receiver.as_deref())?;
505            out.flag(*dynamic);
506            out.flag(*associated);
507            out.flag(*keeps_ordinary_edge);
508        }
509        out.count(associated.len())?;
510        for ordinal in associated {
511            out.number(*ordinal);
512        }
513        if let Some(static_facts) = &facts.dispatch.static_facts {
514            out.0.extend(static_facts.encode());
515        }
516        Ok(())
517    }
518
519    /// The record [`Self::encode_scratch`] encoded as `bytes`.
520    ///
521    /// # Errors
522    ///
523    /// When `bytes` is not exactly one record's scratch encoding.
524    pub fn decode_scratch(bytes: &[u8]) -> Result<Self, String> {
525        let mut input = ScratchReader { bytes, at: 0 };
526        let format = input.byte()?;
527        if format != SCRATCH_FORMAT {
528            return Err(format!("not a pass-4 record (it starts with {format})"));
529        }
530        let language = input.text()?;
531        let go_package = input.optional()?;
532        let count = input.count()?;
533        let mut types = Vec::with_capacity(count);
534        for _ in 0..count {
535            types.push(TypeHint {
536                name: input.text()?,
537                bases: input.texts()?,
538                interface: input.flag()?,
539                closed: input.flag()?,
540            });
541        }
542        let count = input.count()?;
543        let mut methods = Vec::with_capacity(count);
544        for _ in 0..count {
545            methods.push(MethodHint {
546                owner: input.text()?,
547                trait_name: input.optional()?,
548                name: input.text()?,
549                symbol: input.text()?,
550                has_body: input.flag()?,
551                shape: input.text()?,
552                private: input.flag()?,
553            });
554        }
555        let mut projections = BTreeMap::new();
556        for _ in 0..input.count()? {
557            let name = input.text()?;
558            projections.insert(name, ProjectedType::decode_scratch(&mut input)?);
559        }
560        let mut mro = BTreeMap::new();
561        for _ in 0..input.count()? {
562            let owner = input.text()?;
563            mro.insert(owner, ProjectedMro::decode_scratch(&mut input)?);
564        }
565        let complete_names = input.flag()?;
566        let resolvable_name_projections = input.number()?;
567        let count = input.count()?;
568        let mut sites = Vec::with_capacity(count);
569        for _ in 0..count {
570            sites.push(SiteRecord {
571                site: SiteHint {
572                    ordinal: input.number()?,
573                    caller: input.optional()?,
574                    line: input.number()?,
575                    member: input.optional()?,
576                    receiver: input.optional()?,
577                    dynamic: input.flag()?,
578                },
579                associated: input.flag()?,
580                keeps_ordinary_edge: input.flag()?,
581            });
582        }
583        let count = input.count()?;
584        let associated = (0..count)
585            .map(|_| input.number())
586            .collect::<Result<Vec<_>, _>>()?;
587        let mut facts = declarations_of(language, go_package, types, methods);
588        if input.at != bytes.len() {
589            facts.dispatch.static_facts = Some(Box::new(
590                super::StaticFacts::decode(&bytes[input.at..])
591                    .map_err(|error| error.to_string())?,
592            ));
593        }
594        Ok(Self {
595            facts,
596            projections,
597            mro,
598            complete_names,
599            resolvable_name_projections,
600            sites,
601            associated,
602        })
603    }
604}
605
606/// `parse` reduced to what the resolver reads once projections are
607/// recorded: language, Go package, types and methods.
608fn declarations(parse: &ParseBlob) -> ParseBlob {
609    let mut facts = declarations_of(
610        parse.language.clone(),
611        parse.dispatch.go_package.clone(),
612        parse.dispatch.types.clone(),
613        parse.dispatch.methods.clone(),
614    );
615    facts.dispatch.static_facts = parse.dispatch.static_facts.clone();
616    facts
617}
618
619test_support_visibility! {
620/// The facts a [`FileRecord`] keeps, from their parts: every other field
621/// of the parse is left empty.
622fn declarations_of(
623    language: String,
624    go_package: Option<String>,
625    types: Vec<TypeHint>,
626    methods: Vec<MethodHint>,
627) -> ParseBlob {
628    ParseBlob {
629        entry_point_symbols: Vec::new(),
630        dispatch: DispatchFacts {
631            go_package,
632            types,
633            methods,
634            ..DispatchFacts::default()
635        },
636        extractor_version: String::new(),
637        language,
638        ast_nodes: Vec::new(),
639        symbols: Vec::new(),
640        default_export_symbol: None,
641        exported_symbols: Vec::new(),
642        callable_symbols: Vec::new(),
643        imports: Vec::new(),
644        python_bindings: Vec::new(),
645        refs: Vec::new(),
646    }
647}
648}
649
650/// Every name a Rust file's [`Resolver::project_type`] can answer other than
651/// with the fixed miss: the types it declares, its receiver type targets,
652/// and the names its imports bind (read as `File::imports_naming` reads
653/// them).
654fn rust_resolvable_names(
655    parse: &ParseBlob,
656    type_target_names: &mut dyn Iterator<Item = &str>,
657) -> BTreeSet<String> {
658    let mut names = parse
659        .dispatch
660        .types
661        .iter()
662        .map(|ty| ty.name.clone())
663        .collect::<BTreeSet<_>>();
664    names.extend(type_target_names.map(str::to_string));
665    for import in &parse.imports {
666        names.extend(
667            import
668                .names
669                .iter()
670                .filter_map(|name| name.split_whitespace().last())
671                .map(str::to_string),
672        );
673        names.extend(import.default_import.clone());
674    }
675    names
676}
677
678impl<'a> Resolver<'a> {
679    /// The source's recorded projections, when it serves them.
680    pub(super) fn projections(&self) -> Option<&'a (dyn Projections + 'a)> {
681        self.source.and_then(|source| source.projections())
682    }
683
684    /// [`Resolver::project_type`] answered from `projections`, recording the
685    /// keys the recorded lookup recorded.
686    pub(super) fn replay_projection(
687        &self,
688        projections: &'a (dyn Projections + 'a),
689        file: &str,
690        name: &str,
691    ) -> Option<(String, &'a TypeHint)> {
692        match projections.projected_type(file, name) {
693            Recorded::Found(projected) => {
694                for key in projected.dependencies.iter() {
695                    self.depend(key.clone());
696                }
697                let (type_file, index) = projected.found.as_ref()?;
698                let ty = self
699                    .lookup(type_file)
700                    .and_then(|parse| parse.dispatch.types.get(usize::try_from(*index).ok()?));
701                if ty.is_none() {
702                    projections.missing(format!(
703                        "type {index} of {type_file}, which {name} names in {file}"
704                    ));
705                }
706                Some((type_file.clone(), ty?))
707            }
708            // A Rust file's lookup of a name it neither declares, targets
709            // nor imports reads its facts, the name's target and the
710            // name's local declaration and imports, and finds nothing.
711            Recorded::NotProjectable => {
712                self.depend(dependency::file(file));
713                self.depend(dependency::type_name(file, name));
714                None
715            }
716            Recorded::Missing => {
717                projections.missing(format!("the projection of {name} in {file}"));
718                None
719            }
720        }
721    }
722
723    pub(super) fn replay_static_import(
724        &self,
725        projections: &'a (dyn Projections + 'a),
726        file: &str,
727        key: &str,
728    ) -> Option<(String, u32)> {
729        if let Recorded::Found(projected) = projections.projected_type(file, key) {
730            for dependency in &projected.dependencies {
731                self.depend(dependency.clone());
732            }
733            projected.found.clone()
734        } else {
735            projections.missing(format!("the static import projection of {key} in {file}"));
736            None
737        }
738    }
739
740    /// `owner`'s resolution order as `file`'s Python `super()` call reads
741    /// it, from `projections`, recording the keys computing it recorded.
742    pub(super) fn replay_mro(
743        &self,
744        projections: &'a (dyn Projections + 'a),
745        file: &str,
746        owner: &str,
747    ) -> Option<Vec<(String, String)>> {
748        match projections.projected_mro(file, owner) {
749            Recorded::Found(projected) => {
750                for key in projected.dependencies.iter() {
751                    self.depend(key.clone());
752                }
753                projected.mro.clone()
754            }
755            Recorded::NotProjectable | Recorded::Missing => {
756                projections.missing(format!("the resolution order of {owner} in {file}"));
757                None
758            }
759        }
760    }
761
762    /// [`Resolver::project_type`] for `name` in `file` with the keys it
763    /// recorded, leaving the keys recorded so far as they were.
764    fn record_projection(&self, file: &str, name: &str) -> ProjectedType {
765        let outer = self.take_dependencies();
766        let found = if name.starts_with(super::STATIC_IMPORT_PREFIX) {
767            self.static_import_projection(file, name)
768        } else {
769            self.project_type(file, name).and_then(|(type_file, ty)| {
770                let index = self
771                    .lookup(&type_file)?
772                    .dispatch
773                    .types
774                    .iter()
775                    .position(|candidate| std::ptr::eq(candidate, ty))?;
776                Some((type_file, u32::try_from(index).ok()?))
777            })
778        };
779        let dependencies = self.take_dependencies();
780        *self.dependencies.borrow_mut() = outer;
781        ProjectedType {
782            found,
783            dependencies: dependencies.into_iter().collect(),
784        }
785    }
786
787    /// The resolution order `python_super` reads for `owner` in `file`,
788    /// with the keys computing it recorded. `None` when `owner` names no
789    /// project type, so `python_super` reads no order.
790    fn record_mro(&self, file: &str, owner: &str) -> Option<ProjectedMro> {
791        let outer = self.take_dependencies();
792        let projected = self.project_type(file, owner);
793        // The owner's projection is recorded on its own.
794        self.take_dependencies();
795        let mro = projected.map(|(owner_file, ty)| {
796            let mro = self.python_mro(&owner_file, ty, &mut BTreeSet::new(), &mut BTreeMap::new());
797            ProjectedMro {
798                mro,
799                dependencies: self.take_dependencies().into_iter().collect(),
800            }
801        });
802        *self.dependencies.borrow_mut() = outer;
803        mro
804    }
805
806    /// The pass-4 record of `path`, a file this resolver reads from files:
807    /// its declarations, every projection pass 4 asks of it, and `sites`
808    /// (its `bound_dispatch_sites()`), each with whether its ordinal is an
809    /// associated-function call and whether it keeps an ordinary edge.
810    /// `None` when `path` has no facts.
811    pub fn project_file(
812        &self,
813        path: &str,
814        sites: Vec<SiteHint>,
815        type_target_names: &mut dyn Iterator<Item = &str>,
816        associated: &dyn Fn(u32) -> bool,
817        keeps_ordinary_edge: &dyn Fn(u32) -> bool,
818    ) -> Option<FileRecord> {
819        let parse = self.lookup(path)?;
820        let mut projections = BTreeMap::new();
821        let inserted = std::cell::Cell::new(0u32);
822        let mut project = |name: &str| -> Option<(String, u32)> {
823            if let Some(found) = projections.get(name) {
824                let found: &ProjectedType = found;
825                return found.found.clone();
826            }
827            let projected = self.record_projection(path, name);
828            let found = projected.found.clone();
829            projections.insert(name.to_string(), projected);
830            inserted.set(inserted.get() + 1);
831            found
832        };
833        for ty in &parse.dispatch.types {
834            for base in &ty.bases {
835                project(base);
836            }
837        }
838        for method in &parse.dispatch.methods {
839            if let Some((owner_file, index)) = project(&method.owner) {
840                let owner = self
841                    .lookup(&owner_file)
842                    .and_then(|owner| owner.dispatch.types.get(index as usize));
843                for base in owner.into_iter().flat_map(|owner| &owner.bases) {
844                    project(base);
845                }
846            }
847            if let Some(trait_name) = &method.trait_name {
848                project(trait_name);
849            }
850        }
851        let language = parse.language.as_str();
852        if super::typescript::supported(language) {
853            if let Some(static_facts) = &parse.dispatch.static_facts {
854                for name in static_facts.projection_names() {
855                    project(name);
856                }
857                for (name, _) in static_facts.import_receivers() {
858                    project(&format!("{}{name}", super::STATIC_IMPORT_PREFIX));
859                }
860            }
861        }
862        let mut mro = BTreeMap::new();
863        let mut typed_rust = false;
864        let mut records = Vec::with_capacity(sites.len());
865        let mut associated_ordinals = Vec::new();
866        for site in sites {
867            let record = SiteRecord {
868                associated: associated(site.ordinal),
869                keeps_ordinary_edge: keeps_ordinary_edge(site.ordinal),
870                site,
871            };
872            if record.associated {
873                associated_ordinals.push(record.site.ordinal);
874            }
875            let site = &record.site;
876            // The projections `Resolver::resolve` makes from the calling
877            // file, on the paths that reach one.
878            let typed = !site.dynamic
879                && site.member.is_some()
880                && !(language == "go" && parse.dispatch.go_package.is_none())
881                && language != "cpp";
882            match site.receiver.as_deref() {
883                Some(receiver)
884                    if typed
885                        && !(language == "rust"
886                            && receiver.starts_with(super::TEMPLATE_SELF_RECEIVER)) =>
887                {
888                    match receiver.strip_prefix("@super:") {
889                        Some(owner) if language == "python" => {
890                            project(owner);
891                            if !mro.contains_key(owner) {
892                                if let Some(order) = self.record_mro(path, owner) {
893                                    mro.insert(owner.to_string(), order);
894                                }
895                            }
896                        }
897                        _ => {
898                            let projection = super::receiver_projection(
899                                language,
900                                receiver,
901                                site.member.as_deref().expect("typed site has a member"),
902                            );
903                            project(&projection);
904                            typed_rust |= language == "rust";
905                        }
906                    }
907                }
908                _ => {}
909            }
910            records.push(record);
911        }
912        let mut complete_names = false;
913        let before = inserted.get();
914        if typed_rust {
915            for name in rust_resolvable_names(parse, type_target_names) {
916                project(&name);
917            }
918            complete_names = true;
919        }
920        let resolvable_name_projections = inserted.get() - before;
921        associated_ordinals.sort_unstable();
922        associated_ordinals.dedup();
923        Some(FileRecord {
924            facts: declarations(parse),
925            projections,
926            mro,
927            complete_names,
928            resolvable_name_projections,
929            sites: records,
930            associated: associated_ordinals,
931        })
932    }
933}
934
935aft_store::heap_bytes_of_fields!(ProjectedType {
936    found,
937    dependencies
938});
939aft_store::heap_bytes_of_fields!(ProjectedMro { mro, dependencies });
940aft_store::heap_bytes_of_fields!(SiteRecord {
941    site,
942    associated,
943    keeps_ordinary_edge,
944});
945aft_store::heap_bytes_of_fields!(FileRecord {
946    facts,
947    projections,
948    mro,
949    complete_names,
950    resolvable_name_projections,
951    sites,
952    associated,
953});
954
955#[cfg(any(test, feature = "test-support"))]
956impl FileRecord {
957    /// A record whose parts all depend on `index`, declaring methods named
958    /// `m{index % 3}` and `shared`, for tests of where records are kept.
959    pub fn sample(index: u32) -> Self {
960        let method = |name: String| MethodHint {
961            owner: format!("Type{index}"),
962            trait_name: None,
963            name,
964            symbol: format!("Type{index}::method"),
965            has_body: index % 2 == 0,
966            shape: "x".repeat(index as usize % 40),
967            private: false,
968        };
969        FileRecord {
970            facts: declarations_of(
971                "typescript".to_string(),
972                None,
973                vec![TypeHint {
974                    name: format!("Type{index}"),
975                    bases: vec![format!("Base{}", index / 2)],
976                    interface: false,
977                    closed: false,
978                }],
979                vec![
980                    method(format!("m{}", index % 3)),
981                    method("shared".to_string()),
982                ],
983            ),
984            projections: BTreeMap::from([(
985                format!("Base{}", index / 2),
986                ProjectedType {
987                    found: (index % 2 == 0).then(|| (format!("src/{index}.ts"), index)),
988                    dependencies: vec![format!("t:src/{index}.ts\tBase")].into_boxed_slice(),
989                },
990            )]),
991            mro: BTreeMap::new(),
992            complete_names: false,
993            resolvable_name_projections: 0,
994            sites: (0..index % 5)
995                .map(|ordinal| SiteRecord {
996                    site: SiteHint {
997                        ordinal,
998                        caller: Some(format!("caller{index}")),
999                        line: ordinal + index,
1000                        member: Some("shared".to_string()),
1001                        receiver: None,
1002                        dynamic: false,
1003                    },
1004                    associated: false,
1005                    keeps_ordinary_edge: false,
1006                })
1007                .collect(),
1008            associated: Vec::new(),
1009        }
1010    }
1011}