use super::*;
use crate::{
ast::{Program, Stmt},
database::DeclarationIdentities,
exports::ExportTable,
};
use std::{borrow::Cow, collections::BTreeMap, sync::Arc};
pub(super) type Unit = (SourceId, Vec<String>, Program);
#[derive(Clone, Debug, Default)]
pub(crate) struct ModuleCache {
graph: ModuleGraph,
host: String,
scripts: BTreeMap<String, String>,
identities: DeclarationIdentities,
pub(super) units: Arc<[Unit]>,
pub(super) first: Pass,
pub(super) second: Pass,
}
impl ModuleCache {
pub(super) fn prepare(
&mut self,
units: &[Unit],
syntax: &ProjectSyntax,
graph: &ModuleGraph,
host: String,
) {
let compatible =
self.graph == *graph
&& self.host == host
&& self.scripts == syntax.scripts
&& self.identities.same_bindings(&syntax.identities)
&& self.units.len() == units.len()
&& self.units.iter().zip(units).all(
|((source, path, old), (next, module, new))| {
source == next && path == module && same_declarations(old, new)
},
);
self.first.units.resize(units.len(), None);
self.second.units.resize(units.len(), None);
for (i, (_, _, program)) in units.iter().enumerate() {
if !compatible || self.units[i].2 != *program {
self.first.units[i] = None;
self.second.units[i] = None;
}
}
self.graph.clone_from(graph);
self.host = host;
self.scripts.clone_from(&syntax.scripts);
self.identities = syntax.identities.clone();
}
}
fn same_declarations(old: &Program, new: &Program) -> bool {
old.language_declaration_spans == new.language_declaration_spans
&& old.statements.len() == new.statements.len()
&& old.statements.iter().zip(&new.statements).all(|(a, b)| {
a == b || function_header(a).is_some_and(|header| Some(header) == function_header(b))
})
}
fn function_header(stmt: &Stmt) -> Option<impl PartialEq + '_> {
let Stmt::Function {
visibility,
attributes,
name,
name_span,
generic_parameters,
parameters,
return_type,
body,
span,
} = stmt
else {
return None;
};
Some((
visibility,
attributes,
name,
name_span,
generic_parameters,
parameters,
return_type,
span.source,
span.start,
body.span.start,
))
}
#[derive(Clone, Debug, Default)]
pub(super) struct Pass {
exports: ExportTable,
units: Vec<Option<Arc<DocumentAnalysis>>>,
}
impl Pass {
pub(super) fn for_exports(&mut self, exports: &ExportTable) -> &mut Self {
if self.exports != *exports {
self.units.fill(None);
self.exports.clone_from(exports);
}
self
}
pub(super) fn analyze(
cache: Option<&mut Self>,
index: usize,
build: impl FnOnce() -> DocumentAnalysis,
) -> Cow<'_, DocumentAnalysis> {
match cache {
Some(pass) => Cow::Borrowed(pass.units[index].get_or_insert_with(|| Arc::new(build()))),
None => Cow::Owned(build()),
}
}
}