use std::collections::{BTreeMap, BTreeSet};
use super::{dependency, DispatchFacts, MethodHint, ParseBlob, Resolver, SiteHint, TypeHint};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProjectedType {
#[cfg(any(test, feature = "test-support"))]
pub found: Option<(String, u32)>,
#[cfg(not(any(test, feature = "test-support")))]
found: Option<(String, u32)>,
#[cfg(any(test, feature = "test-support"))]
pub dependencies: Box<[String]>,
#[cfg(not(any(test, feature = "test-support")))]
dependencies: Box<[String]>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProjectedMro {
#[cfg(any(test, feature = "test-support"))]
pub mro: Option<Vec<(String, String)>>,
#[cfg(not(any(test, feature = "test-support")))]
mro: Option<Vec<(String, String)>>,
#[cfg(any(test, feature = "test-support"))]
pub dependencies: Box<[String]>,
#[cfg(not(any(test, feature = "test-support")))]
dependencies: Box<[String]>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SiteRecord {
pub site: SiteHint,
pub associated: bool,
pub keeps_ordinary_edge: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileRecord {
#[cfg(any(test, feature = "test-support"))]
pub facts: ParseBlob,
#[cfg(not(any(test, feature = "test-support")))]
facts: ParseBlob,
#[cfg(any(test, feature = "test-support"))]
pub projections: BTreeMap<String, ProjectedType>,
#[cfg(not(any(test, feature = "test-support")))]
projections: BTreeMap<String, ProjectedType>,
#[cfg(any(test, feature = "test-support"))]
pub mro: BTreeMap<String, ProjectedMro>,
#[cfg(not(any(test, feature = "test-support")))]
mro: BTreeMap<String, ProjectedMro>,
#[cfg(any(test, feature = "test-support"))]
pub complete_names: bool,
#[cfg(not(any(test, feature = "test-support")))]
complete_names: bool,
#[cfg(any(test, feature = "test-support"))]
pub resolvable_name_projections: u32,
#[cfg(not(any(test, feature = "test-support")))]
resolvable_name_projections: u32,
#[cfg(any(test, feature = "test-support"))]
pub sites: Vec<SiteRecord>,
#[cfg(not(any(test, feature = "test-support")))]
sites: Vec<SiteRecord>,
#[cfg(any(test, feature = "test-support"))]
pub associated: Vec<u32>,
#[cfg(not(any(test, feature = "test-support")))]
associated: Vec<u32>,
}
pub enum Recorded<'r, T> {
Found(&'r T),
NotProjectable,
Missing,
}
pub trait Projections {
fn projected_type(&self, file: &str, name: &str) -> Recorded<'_, ProjectedType>;
fn projected_mro(&self, file: &str, owner: &str) -> Recorded<'_, ProjectedMro>;
fn missing(&self, what: String);
}
impl FileRecord {
pub fn facts(&self) -> &ParseBlob {
&self.facts
}
pub fn sites(&self) -> &[SiteRecord] {
&self.sites
}
pub fn projection_census(&self, seen: &mut aft_store::heap::Seen) -> (usize, usize, usize) {
use aft_store::heap::HeapBytes as _;
(
self.projections.len() + self.mro.len(),
self.resolvable_name_projections as usize,
self.projections.heap_bytes(seen) + self.mro.heap_bytes(seen),
)
}
pub fn associated(&self, ordinal: u32) -> bool {
self.associated.binary_search(&ordinal).is_ok()
}
pub fn projected_type(&self, name: &str) -> Recorded<'_, ProjectedType> {
match self.projections.get(name) {
Some(found) => Recorded::Found(found),
None if self.complete_names && !name.starts_with('@') => Recorded::NotProjectable,
None => Recorded::Missing,
}
}
pub fn projected_mro(&self, owner: &str) -> Recorded<'_, ProjectedMro> {
self.mro
.get(owner)
.map_or(Recorded::Missing, Recorded::Found)
}
pub fn method_names(&self) -> BTreeSet<&str> {
self.facts
.dispatch
.methods
.iter()
.map(|method| method.name.as_str())
.collect()
}
pub fn go_required(&self) -> BTreeSet<&str> {
if self.facts.language != "go" {
return BTreeSet::new();
}
let dispatch = &self.facts.dispatch;
dispatch
.methods
.iter()
.filter(|method| {
dispatch
.types
.iter()
.any(|ty| ty.interface && ty.name == method.owner)
})
.map(|method| method.name.as_str())
.collect()
}
}
test_support_visibility! {
const SCRATCH_FORMAT: u8 = 1;
}
struct ScratchWriter<'o>(&'o mut Vec<u8>);
impl ScratchWriter<'_> {
fn byte(&mut self, value: u8) {
self.0.push(value);
}
fn flag(&mut self, value: bool) {
self.0.push(u8::from(value));
}
fn number(&mut self, value: u32) {
self.0.extend(value.to_le_bytes());
}
fn count(&mut self, count: usize) -> Result<(), String> {
let count = u32::try_from(count)
.map_err(|_| "a pass-4 record part has 4 billion or more items".to_string())?;
self.number(count);
Ok(())
}
fn text(&mut self, text: &str) -> Result<(), String> {
self.count(text.len())?;
self.0.extend_from_slice(text.as_bytes());
Ok(())
}
fn optional(&mut self, text: Option<&str>) -> Result<(), String> {
match text {
None => self.byte(0),
Some(text) => {
self.byte(1);
self.text(text)?;
}
}
Ok(())
}
fn texts(&mut self, texts: &[String]) -> Result<(), String> {
self.count(texts.len())?;
for text in texts {
self.text(text)?;
}
Ok(())
}
}
struct ScratchReader<'b> {
bytes: &'b [u8],
at: usize,
}
impl<'b> ScratchReader<'b> {
fn take(&mut self, len: usize) -> Result<&'b [u8], String> {
let end = self
.at
.checked_add(len)
.filter(|end| *end <= self.bytes.len())
.ok_or_else(|| "a truncated pass-4 record".to_string())?;
let taken = &self.bytes[self.at..end];
self.at = end;
Ok(taken)
}
fn byte(&mut self) -> Result<u8, String> {
Ok(self.take(1)?[0])
}
fn flag(&mut self) -> Result<bool, String> {
match self.byte()? {
0 => Ok(false),
1 => Ok(true),
other => Err(format!("a pass-4 record flag reads {other}")),
}
}
fn number(&mut self) -> Result<u32, String> {
let bytes = self.take(4)?;
Ok(u32::from_le_bytes(bytes.try_into().expect("four bytes")))
}
fn count(&mut self) -> Result<usize, String> {
let count = self.number()? as usize;
if count > self.bytes.len() - self.at {
return Err(format!("a pass-4 record counts {count} items past its end"));
}
Ok(count)
}
fn text(&mut self) -> Result<String, String> {
let len = self.number()? as usize;
String::from_utf8(self.take(len)?.to_vec())
.map_err(|_| "a pass-4 record holds text that is not UTF-8".to_string())
}
fn optional(&mut self) -> Result<Option<String>, String> {
match self.byte()? {
0 => Ok(None),
1 => self.text().map(Some),
other => Err(format!("a pass-4 record option reads {other}")),
}
}
fn texts(&mut self) -> Result<Vec<String>, String> {
let count = self.count()?;
(0..count).map(|_| self.text()).collect()
}
}
impl ProjectedType {
fn encode_scratch(&self, out: &mut ScratchWriter<'_>) -> Result<(), String> {
let Self {
found,
dependencies,
} = self;
match found {
None => out.byte(0),
Some((file, index)) => {
out.byte(1);
out.text(file)?;
out.number(*index);
}
}
out.texts(dependencies)
}
fn decode_scratch(input: &mut ScratchReader<'_>) -> Result<Self, String> {
let found = match input.byte()? {
0 => None,
1 => Some((input.text()?, input.number()?)),
other => return Err(format!("a projected type reads {other}")),
};
Ok(Self {
found,
dependencies: input.texts()?.into_boxed_slice(),
})
}
}
impl ProjectedMro {
fn encode_scratch(&self, out: &mut ScratchWriter<'_>) -> Result<(), String> {
let Self { mro, dependencies } = self;
match mro {
None => out.byte(0),
Some(order) => {
out.byte(1);
out.count(order.len())?;
for (file, name) in order {
out.text(file)?;
out.text(name)?;
}
}
}
out.texts(dependencies)
}
fn decode_scratch(input: &mut ScratchReader<'_>) -> Result<Self, String> {
let mro = match input.byte()? {
0 => None,
1 => {
let count = input.count()?;
Some(
(0..count)
.map(|_| Ok((input.text()?, input.text()?)))
.collect::<Result<Vec<_>, String>>()?,
)
}
other => return Err(format!("a resolution order reads {other}")),
};
Ok(Self {
mro,
dependencies: input.texts()?.into_boxed_slice(),
})
}
}
impl FileRecord {
pub fn encode_scratch(&self, out: &mut Vec<u8>) -> Result<(), String> {
let Self {
facts,
projections,
mro,
complete_names,
resolvable_name_projections,
sites,
associated,
} = self;
debug_assert!(
*facts == declarations(facts),
"a record keeps only the facts `declarations` keeps"
);
let mut out = ScratchWriter(out);
out.byte(SCRATCH_FORMAT);
out.text(&facts.language)?;
out.optional(facts.dispatch.go_package.as_deref())?;
out.count(facts.dispatch.types.len())?;
for TypeHint {
name,
bases,
interface,
closed,
} in &facts.dispatch.types
{
out.text(name)?;
out.texts(bases)?;
out.flag(*interface);
out.flag(*closed);
}
out.count(facts.dispatch.methods.len())?;
for MethodHint {
owner,
trait_name,
name,
symbol,
has_body,
shape,
private,
} in &facts.dispatch.methods
{
out.text(owner)?;
out.optional(trait_name.as_deref())?;
out.text(name)?;
out.text(symbol)?;
out.flag(*has_body);
out.text(shape)?;
out.flag(*private);
}
out.count(projections.len())?;
for (name, projected) in projections {
out.text(name)?;
projected.encode_scratch(&mut out)?;
}
out.count(mro.len())?;
for (owner, order) in mro {
out.text(owner)?;
order.encode_scratch(&mut out)?;
}
out.flag(*complete_names);
out.number(*resolvable_name_projections);
out.count(sites.len())?;
for SiteRecord {
site,
associated,
keeps_ordinary_edge,
} in sites
{
let SiteHint {
ordinal,
caller,
line,
member,
receiver,
dynamic,
} = site;
out.number(*ordinal);
out.optional(caller.as_deref())?;
out.number(*line);
out.optional(member.as_deref())?;
out.optional(receiver.as_deref())?;
out.flag(*dynamic);
out.flag(*associated);
out.flag(*keeps_ordinary_edge);
}
out.count(associated.len())?;
for ordinal in associated {
out.number(*ordinal);
}
if let Some(static_facts) = &facts.dispatch.static_facts {
out.0.extend(static_facts.encode());
}
Ok(())
}
pub fn decode_scratch(bytes: &[u8]) -> Result<Self, String> {
let mut input = ScratchReader { bytes, at: 0 };
let format = input.byte()?;
if format != SCRATCH_FORMAT {
return Err(format!("not a pass-4 record (it starts with {format})"));
}
let language = input.text()?;
let go_package = input.optional()?;
let count = input.count()?;
let mut types = Vec::with_capacity(count);
for _ in 0..count {
types.push(TypeHint {
name: input.text()?,
bases: input.texts()?,
interface: input.flag()?,
closed: input.flag()?,
});
}
let count = input.count()?;
let mut methods = Vec::with_capacity(count);
for _ in 0..count {
methods.push(MethodHint {
owner: input.text()?,
trait_name: input.optional()?,
name: input.text()?,
symbol: input.text()?,
has_body: input.flag()?,
shape: input.text()?,
private: input.flag()?,
});
}
let mut projections = BTreeMap::new();
for _ in 0..input.count()? {
let name = input.text()?;
projections.insert(name, ProjectedType::decode_scratch(&mut input)?);
}
let mut mro = BTreeMap::new();
for _ in 0..input.count()? {
let owner = input.text()?;
mro.insert(owner, ProjectedMro::decode_scratch(&mut input)?);
}
let complete_names = input.flag()?;
let resolvable_name_projections = input.number()?;
let count = input.count()?;
let mut sites = Vec::with_capacity(count);
for _ in 0..count {
sites.push(SiteRecord {
site: SiteHint {
ordinal: input.number()?,
caller: input.optional()?,
line: input.number()?,
member: input.optional()?,
receiver: input.optional()?,
dynamic: input.flag()?,
},
associated: input.flag()?,
keeps_ordinary_edge: input.flag()?,
});
}
let count = input.count()?;
let associated = (0..count)
.map(|_| input.number())
.collect::<Result<Vec<_>, _>>()?;
let mut facts = declarations_of(language, go_package, types, methods);
if input.at != bytes.len() {
facts.dispatch.static_facts = Some(Box::new(
super::StaticFacts::decode(&bytes[input.at..])
.map_err(|error| error.to_string())?,
));
}
Ok(Self {
facts,
projections,
mro,
complete_names,
resolvable_name_projections,
sites,
associated,
})
}
}
fn declarations(parse: &ParseBlob) -> ParseBlob {
let mut facts = declarations_of(
parse.language.clone(),
parse.dispatch.go_package.clone(),
parse.dispatch.types.clone(),
parse.dispatch.methods.clone(),
);
facts.dispatch.static_facts = parse.dispatch.static_facts.clone();
facts
}
test_support_visibility! {
fn declarations_of(
language: String,
go_package: Option<String>,
types: Vec<TypeHint>,
methods: Vec<MethodHint>,
) -> ParseBlob {
ParseBlob {
entry_point_symbols: Vec::new(),
dispatch: DispatchFacts {
go_package,
types,
methods,
..DispatchFacts::default()
},
extractor_version: String::new(),
language,
ast_nodes: Vec::new(),
symbols: Vec::new(),
default_export_symbol: None,
exported_symbols: Vec::new(),
callable_symbols: Vec::new(),
imports: Vec::new(),
python_bindings: Vec::new(),
refs: Vec::new(),
}
}
}
fn rust_resolvable_names(
parse: &ParseBlob,
type_target_names: &mut dyn Iterator<Item = &str>,
) -> BTreeSet<String> {
let mut names = parse
.dispatch
.types
.iter()
.map(|ty| ty.name.clone())
.collect::<BTreeSet<_>>();
names.extend(type_target_names.map(str::to_string));
for import in &parse.imports {
names.extend(
import
.names
.iter()
.filter_map(|name| name.split_whitespace().last())
.map(str::to_string),
);
names.extend(import.default_import.clone());
}
names
}
impl<'a> Resolver<'a> {
pub(super) fn projections(&self) -> Option<&'a (dyn Projections + 'a)> {
self.source.and_then(|source| source.projections())
}
pub(super) fn replay_projection(
&self,
projections: &'a (dyn Projections + 'a),
file: &str,
name: &str,
) -> Option<(String, &'a TypeHint)> {
match projections.projected_type(file, name) {
Recorded::Found(projected) => {
for key in projected.dependencies.iter() {
self.depend(key.clone());
}
let (type_file, index) = projected.found.as_ref()?;
let ty = self
.lookup(type_file)
.and_then(|parse| parse.dispatch.types.get(usize::try_from(*index).ok()?));
if ty.is_none() {
projections.missing(format!(
"type {index} of {type_file}, which {name} names in {file}"
));
}
Some((type_file.clone(), ty?))
}
Recorded::NotProjectable => {
self.depend(dependency::file(file));
self.depend(dependency::type_name(file, name));
None
}
Recorded::Missing => {
projections.missing(format!("the projection of {name} in {file}"));
None
}
}
}
pub(super) fn replay_static_import(
&self,
projections: &'a (dyn Projections + 'a),
file: &str,
key: &str,
) -> Option<(String, u32)> {
if let Recorded::Found(projected) = projections.projected_type(file, key) {
for dependency in &projected.dependencies {
self.depend(dependency.clone());
}
projected.found.clone()
} else {
projections.missing(format!("the static import projection of {key} in {file}"));
None
}
}
pub(super) fn replay_mro(
&self,
projections: &'a (dyn Projections + 'a),
file: &str,
owner: &str,
) -> Option<Vec<(String, String)>> {
match projections.projected_mro(file, owner) {
Recorded::Found(projected) => {
for key in projected.dependencies.iter() {
self.depend(key.clone());
}
projected.mro.clone()
}
Recorded::NotProjectable | Recorded::Missing => {
projections.missing(format!("the resolution order of {owner} in {file}"));
None
}
}
}
fn record_projection(&self, file: &str, name: &str) -> ProjectedType {
let outer = self.take_dependencies();
let found = if name.starts_with(super::STATIC_IMPORT_PREFIX) {
self.static_import_projection(file, name)
} else {
self.project_type(file, name).and_then(|(type_file, ty)| {
let index = self
.lookup(&type_file)?
.dispatch
.types
.iter()
.position(|candidate| std::ptr::eq(candidate, ty))?;
Some((type_file, u32::try_from(index).ok()?))
})
};
let dependencies = self.take_dependencies();
*self.dependencies.borrow_mut() = outer;
ProjectedType {
found,
dependencies: dependencies.into_iter().collect(),
}
}
fn record_mro(&self, file: &str, owner: &str) -> Option<ProjectedMro> {
let outer = self.take_dependencies();
let projected = self.project_type(file, owner);
self.take_dependencies();
let mro = projected.map(|(owner_file, ty)| {
let mro = self.python_mro(&owner_file, ty, &mut BTreeSet::new(), &mut BTreeMap::new());
ProjectedMro {
mro,
dependencies: self.take_dependencies().into_iter().collect(),
}
});
*self.dependencies.borrow_mut() = outer;
mro
}
pub fn project_file(
&self,
path: &str,
sites: Vec<SiteHint>,
type_target_names: &mut dyn Iterator<Item = &str>,
associated: &dyn Fn(u32) -> bool,
keeps_ordinary_edge: &dyn Fn(u32) -> bool,
) -> Option<FileRecord> {
let parse = self.lookup(path)?;
let mut projections = BTreeMap::new();
let inserted = std::cell::Cell::new(0u32);
let mut project = |name: &str| -> Option<(String, u32)> {
if let Some(found) = projections.get(name) {
let found: &ProjectedType = found;
return found.found.clone();
}
let projected = self.record_projection(path, name);
let found = projected.found.clone();
projections.insert(name.to_string(), projected);
inserted.set(inserted.get() + 1);
found
};
for ty in &parse.dispatch.types {
for base in &ty.bases {
project(base);
}
}
for method in &parse.dispatch.methods {
if let Some((owner_file, index)) = project(&method.owner) {
let owner = self
.lookup(&owner_file)
.and_then(|owner| owner.dispatch.types.get(index as usize));
for base in owner.into_iter().flat_map(|owner| &owner.bases) {
project(base);
}
}
if let Some(trait_name) = &method.trait_name {
project(trait_name);
}
}
let language = parse.language.as_str();
if super::typescript::supported(language) {
if let Some(static_facts) = &parse.dispatch.static_facts {
for name in static_facts.projection_names() {
project(name);
}
for (name, _) in static_facts.import_receivers() {
project(&format!("{}{name}", super::STATIC_IMPORT_PREFIX));
}
}
}
let mut mro = BTreeMap::new();
let mut typed_rust = false;
let mut records = Vec::with_capacity(sites.len());
let mut associated_ordinals = Vec::new();
for site in sites {
let record = SiteRecord {
associated: associated(site.ordinal),
keeps_ordinary_edge: keeps_ordinary_edge(site.ordinal),
site,
};
if record.associated {
associated_ordinals.push(record.site.ordinal);
}
let site = &record.site;
let typed = !site.dynamic
&& site.member.is_some()
&& !(language == "go" && parse.dispatch.go_package.is_none())
&& language != "cpp";
match site.receiver.as_deref() {
Some(receiver)
if typed
&& !(language == "rust"
&& receiver.starts_with(super::TEMPLATE_SELF_RECEIVER)) =>
{
match receiver.strip_prefix("@super:") {
Some(owner) if language == "python" => {
project(owner);
if !mro.contains_key(owner) {
if let Some(order) = self.record_mro(path, owner) {
mro.insert(owner.to_string(), order);
}
}
}
_ => {
let projection = super::receiver_projection(
language,
receiver,
site.member.as_deref().expect("typed site has a member"),
);
project(&projection);
typed_rust |= language == "rust";
}
}
}
_ => {}
}
records.push(record);
}
let mut complete_names = false;
let before = inserted.get();
if typed_rust {
for name in rust_resolvable_names(parse, type_target_names) {
project(&name);
}
complete_names = true;
}
let resolvable_name_projections = inserted.get() - before;
associated_ordinals.sort_unstable();
associated_ordinals.dedup();
Some(FileRecord {
facts: declarations(parse),
projections,
mro,
complete_names,
resolvable_name_projections,
sites: records,
associated: associated_ordinals,
})
}
}
aft_store::heap_bytes_of_fields!(ProjectedType {
found,
dependencies
});
aft_store::heap_bytes_of_fields!(ProjectedMro { mro, dependencies });
aft_store::heap_bytes_of_fields!(SiteRecord {
site,
associated,
keeps_ordinary_edge,
});
aft_store::heap_bytes_of_fields!(FileRecord {
facts,
projections,
mro,
complete_names,
resolvable_name_projections,
sites,
associated,
});
#[cfg(any(test, feature = "test-support"))]
impl FileRecord {
pub fn sample(index: u32) -> Self {
let method = |name: String| MethodHint {
owner: format!("Type{index}"),
trait_name: None,
name,
symbol: format!("Type{index}::method"),
has_body: index % 2 == 0,
shape: "x".repeat(index as usize % 40),
private: false,
};
FileRecord {
facts: declarations_of(
"typescript".to_string(),
None,
vec![TypeHint {
name: format!("Type{index}"),
bases: vec![format!("Base{}", index / 2)],
interface: false,
closed: false,
}],
vec![
method(format!("m{}", index % 3)),
method("shared".to_string()),
],
),
projections: BTreeMap::from([(
format!("Base{}", index / 2),
ProjectedType {
found: (index % 2 == 0).then(|| (format!("src/{index}.ts"), index)),
dependencies: vec![format!("t:src/{index}.ts\tBase")].into_boxed_slice(),
},
)]),
mro: BTreeMap::new(),
complete_names: false,
resolvable_name_projections: 0,
sites: (0..index % 5)
.map(|ordinal| SiteRecord {
site: SiteHint {
ordinal,
caller: Some(format!("caller{index}")),
line: ordinal + index,
member: Some("shared".to_string()),
receiver: None,
dynamic: false,
},
associated: false,
keeps_ordinary_edge: false,
})
.collect(),
associated: Vec::new(),
}
}
}