use crate::parsing::source::Source;
use crate::planning::execution_plan::ExecutionPlan;
use crate::planning::instance_list::RowStore;
use crate::planning::semantics::{
DataDefinition, DataPath, LemmaType, ListKey, RowBinding, RowInstance, SpecIdentity,
};
use indexmap::IndexMap;
use std::sync::Arc;
#[derive(Debug, Clone, Default)]
pub struct Writes {
instances: IndexMap<Vec<String>, Vec<Write>>,
rekeyed: Vec<(Vec<String>, DataPath)>,
copies: Vec<Copy>,
lists: Vec<(Vec<String>, DataPath, Arc<RowStore>)>,
row_writes: Vec<(DataPath, Arc<RowInstance>)>,
rows: RowSets,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct RowSets {
pub(crate) written: std::collections::HashSet<usize>,
pub(crate) copies: std::collections::HashSet<usize>,
pub(crate) filled: std::collections::HashSet<usize>,
pub(crate) rekeyed: std::collections::HashSet<usize>,
}
impl RowSets {
pub(crate) fn extend(&mut self, other: &RowSets) {
self.written.extend(&other.written);
self.copies.extend(&other.copies);
self.filled.extend(&other.filled);
self.rekeyed.extend(&other.rekeyed);
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct WritesIndex {
by_spec: std::collections::HashMap<SpecIdentity, Writes>,
pub(crate) rows: RowSets,
copies: std::collections::HashMap<usize, (usize, Arc<RowInstance>)>,
}
impl WritesIndex {
pub(crate) fn new(by_spec: std::collections::HashMap<SpecIdentity, Writes>) -> Self {
let mut rows = RowSets::default();
let mut copies = std::collections::HashMap::new();
for writes in by_spec.values() {
rows.extend(writes.rows());
for copy in &writes.copies {
copies.insert(
address(©.copy),
(copy.path.len(), Arc::clone(©.source)),
);
}
}
Self {
by_spec,
rows,
copies,
}
}
pub(crate) fn copy(&self, row: &RowInstance) -> Option<&(usize, Arc<RowInstance>)> {
self.copies.get(&address(row))
}
pub(crate) fn copies(&self) -> impl Iterator<Item = (&usize, &(usize, Arc<RowInstance>))> {
self.copies.iter()
}
pub(crate) fn get(&self, identity: &SpecIdentity) -> Option<&Writes> {
self.by_spec.get(identity)
}
pub(crate) fn is_empty(&self) -> bool {
self.by_spec.is_empty()
}
}
pub(crate) fn address(row: &RowInstance) -> usize {
std::ptr::from_ref(row) as usize
}
#[derive(Debug, Clone)]
struct Copy {
path: Vec<String>,
copy: Arc<RowInstance>,
alias: String,
source: Arc<RowInstance>,
}
#[derive(Debug, Clone)]
pub(crate) struct Write {
pub(crate) field: DataPath,
pub(crate) binding: RowBinding,
pub(crate) spec: SpecIdentity,
pub(crate) source: Source,
}
impl Writes {
pub(crate) fn has_instances(&self) -> bool {
!self.instances.is_empty()
}
pub(crate) fn is_empty(&self) -> bool {
self.instances.is_empty()
&& self.rekeyed.is_empty()
&& self.copies.is_empty()
&& self.lists.is_empty()
&& self.row_writes.is_empty()
}
pub(crate) fn get(&self, instance: &[String], field: &DataPath) -> Option<&RowBinding> {
self.instances
.get(instance)?
.iter()
.find(|write| write.field == *field)
.map(|write| &write.binding)
}
pub(crate) fn rows(&self) -> &RowSets {
&self.rows
}
pub(crate) fn rekey(&mut self, holder: Vec<String>, list: DataPath, holder_row: &RowInstance) {
self.rows.rekeyed.insert(address(holder_row));
if !self.rekeyed.iter().any(|(h, l)| *h == holder && *l == list) {
self.rekeyed.push((holder, list));
}
}
pub(crate) fn is_rekeyed(&self, holder: &[String], list: &DataPath) -> bool {
self.rekeyed.iter().any(|(h, l)| h == holder && l == list)
}
pub(crate) fn writes_rows_of(&self, holder: &[String], list: &DataPath) -> bool {
self.instances.keys().any(|instance| {
instance.len() > holder.len()
&& instance.starts_with(holder)
&& instance[holder.len()] == list.data
})
}
pub(crate) fn copy(
&mut self,
path: Vec<String>,
copy: &Arc<RowInstance>,
alias: &str,
source: Arc<RowInstance>,
) {
self.rows.copies.insert(address(copy));
self.copies.push(Copy {
path,
copy: Arc::clone(copy),
alias: alias.to_string(),
source,
});
}
pub(crate) fn copy_of(&self, path: &[String], row: &RowInstance) -> Option<&Arc<RowInstance>> {
self.copy_record(path, row).map(|copy| ©.source)
}
pub(crate) fn copy_rows(&self) -> impl Iterator<Item = (usize, usize, &Arc<RowInstance>)> {
self.copies
.iter()
.map(|copy| (address(©.copy), copy.path.len(), ©.source))
}
pub(crate) fn copy_alias(&self, path: &[String], row: &RowInstance) -> Option<&str> {
self.copy_record(path, row).map(|copy| copy.alias.as_str())
}
fn copy_record(&self, path: &[String], row: &RowInstance) -> Option<&Copy> {
self.copies
.iter()
.find(|copy| copy.path == path && std::ptr::eq(copy.copy.as_ref(), row))
}
pub(crate) fn lists(&self) -> impl Iterator<Item = (&[String], &DataPath, &Arc<RowStore>)> {
self.lists
.iter()
.map(|(holder, list, rows)| (holder.as_slice(), list, rows))
}
pub(crate) fn fill_list(
&mut self,
holder: Vec<String>,
holder_row: &RowInstance,
list: DataPath,
rows: Arc<RowStore>,
) {
self.rows.filled.insert(address(holder_row));
self.lists.push((holder, list, rows));
}
pub(crate) fn list(&self, holder: &[String], list: &DataPath) -> Option<&Arc<RowStore>> {
self.lists
.iter()
.find(|(h, l, _)| h == holder && l == list)
.map(|(_, _, rows)| rows)
}
pub(crate) fn write_rows(&mut self, list: DataPath, row: Arc<RowInstance>) {
self.row_writes.retain(|(written, _)| *written != list);
self.row_writes.push((list, row));
}
pub(crate) fn rows_write(&self, list: &str) -> Option<&Arc<RowInstance>> {
self.row_writes
.iter()
.find(|(written, _)| written.data == list)
.map(|(_, row)| row)
}
pub(crate) fn insert(
&mut self,
instance: Vec<String>,
write: Write,
rows: &[Arc<RowInstance>],
) {
for row in rows {
self.rows.written.insert(address(row));
}
self.instances.entry(instance).or_default().push(write);
}
pub(crate) fn iter(&self) -> impl Iterator<Item = (&[String], &Write)> {
self.instances.iter().flat_map(|(instance, writes)| {
writes.iter().map(move |write| (instance.as_slice(), write))
})
}
}
pub(crate) struct Reached {
pub(crate) template: Arc<ExecutionPlan>,
pub(crate) row: Arc<RowInstance>,
pub(crate) field: DataPath,
pub(crate) written: bool,
pub(crate) keys_list: Option<(Arc<ExecutionPlan>, DataPath, Arc<RowInstance>)>,
}
pub(crate) enum Reach {
Fields(Vec<Reached>),
Global { slot: usize },
}
#[derive(Clone)]
struct Walk {
template: Arc<ExecutionPlan>,
row: Arc<RowInstance>,
holders: Vec<(Arc<ExecutionPlan>, Vec<String>)>,
listed: Option<(Arc<ExecutionPlan>, DataPath, Arc<RowInstance>)>,
copied: Option<(Arc<RowInstance>, Vec<String>)>,
from_writer: Vec<String>,
}
pub(crate) fn reach(
template: Arc<ExecutionPlan>,
row: Arc<RowInstance>,
path: &[String],
field: &str,
templates: &Templates,
writer: (&Writes, &[String]),
) -> Result<Reach, String> {
if let Some(slot) = through_global(&template, path, templates) {
return Ok(Reach::Global { slot });
}
let mut walks = vec![(
Walk {
template,
row,
holders: Vec::new(),
listed: None,
copied: None,
from_writer: writer.1.to_vec(),
},
0usize,
)];
let mut reached = Vec::new();
while let Some((walk, at)) = walks.pop() {
let Some(name) = path.get(at) else {
reached.push(reach_field(&walk, field, writer.0)?);
continue;
};
let slot = DataPath::local(name.clone());
match walk.template.data.get(&slot) {
Some(DataDefinition::Import {
row,
pin,
candidates,
..
}) => {
let bodies: Vec<&Arc<RowInstance>> = match pin {
Some(_) => candidates.values().collect(),
None => vec![row],
};
for body in bodies {
walks.push((
step(
&walk,
Arc::clone(body),
template_of(templates, &body.identity),
&[name],
None,
),
at + 1,
));
}
}
Some(DataDefinition::InstanceList { .. }) => {
let source = walk
.template
.instance_lists
.get(&slot)
.expect("BUG: an instance list has a source");
let number = path.get(at + 1).and_then(|n| n.parse::<usize>().ok());
let Some(number) = number else {
return Err(format!(
"`{name}` is a list; write a row of it as `{name}.<row>.<field>`"
));
};
let (writes, from) = std::iter::once((writer.0, walk.from_writer.clone()))
.chain(
walk.holders
.iter()
.map(|(holder, path)| (&holder.writes, path.clone())),
)
.find(|(writes, from)| writes.list(from, &slot).is_some())
.map_or((None, Vec::new()), |(writes, from)| (Some(writes), from));
let rows = writes
.and_then(|writes| writes.list(&from, &slot))
.unwrap_or(&source.store);
let Some(listed) = number.checked_sub(1).and_then(|i| rows.rows.get(i)) else {
return Err(format!(
"'{name}' has {} spec-written row(s); rows are numbered from 1",
rows.rows.len()
));
};
let row_path: Vec<String> = from
.iter()
.cloned()
.chain([name.clone(), number.to_string()])
.collect();
let recorder_path: Vec<String> = match writes {
Some(_) => walk.from_writer[..walk.from_writer.len() - from.len()].to_vec(),
None => walk.from_writer.clone(),
};
let recorder = writes.unwrap_or(&walk.template.writes);
let copied = recorder.copy_of(&row_path, listed).cloned().map(|source| {
let alias = recorder
.copy_alias(&row_path, listed)
.expect("BUG: a copy record has an alias")
.to_string();
let mut at = recorder_path.clone();
at.push(alias);
(source, at)
});
let row_template = if source.identity == walk.template.identity {
Arc::clone(&walk.template)
} else {
template_of(templates, &source.identity)
};
let mut next = step(
&walk,
Arc::clone(listed),
row_template,
&[name, &number.to_string()],
Some((
Arc::clone(&walk.template),
slot.clone(),
Arc::clone(&walk.row),
)),
);
next.copied = copied;
walks.push((next, at + 2));
}
Some(_) => {
return Err(format!(
"`{name}` of `{}` is no `uses` instance or list",
walk.template.identity.spec
))
}
None => {
return Err(format!(
"`{}` has no data field `{name}`",
walk.template.identity.spec
))
}
}
}
Ok(Reach::Fields(reached))
}
pub(crate) fn reach_instance(
template: Arc<ExecutionPlan>,
path: &[String],
templates: &Templates,
) -> Result<Arc<ExecutionPlan>, String> {
let mut current = template;
let mut at = 0;
while let Some(name) = path.get(at) {
let slot = DataPath::local(name.clone());
match current.data.get(&slot) {
Some(DataDefinition::Import { row, .. }) => {
current = template_of(templates, &row.identity);
at += 1;
}
Some(DataDefinition::InstanceList { .. }) => {
let source = ¤t.instance_lists[&slot];
let next = if source.identity == current.identity {
Arc::clone(¤t)
} else {
template_of(templates, &source.identity)
};
current = next;
at += 2;
}
Some(_) => {
return Err(format!(
"`{name}` of `{}` is no `uses` instance or list",
current.identity.spec
))
}
None => {
return Err(format!(
"`{}` has no data field `{name}`",
current.identity.spec
))
}
}
}
Ok(current)
}
fn through_global(
template: &Arc<ExecutionPlan>,
path: &[String],
templates: &Templates,
) -> Option<usize> {
let mut current = Arc::clone(template);
let mut at = 0;
while let Some(name) = path.get(at) {
match current.data.get(&DataPath::local(name.clone()))? {
DataDefinition::Import {
global: Some(_), ..
} => return Some(at),
DataDefinition::Import { row, .. } => {
current = template_of(templates, &row.identity);
at += 1;
}
_ => return None,
}
}
None
}
pub(crate) type Templates = std::collections::BTreeMap<SpecIdentity, Arc<ExecutionPlan>>;
fn template_of(templates: &Templates, identity: &SpecIdentity) -> Arc<ExecutionPlan> {
Arc::clone(
templates.get(identity).unwrap_or_else(|| {
panic!("BUG: template of `{identity}` is recorded with its importer")
}),
)
}
fn step(
walk: &Walk,
row: Arc<RowInstance>,
template: Arc<ExecutionPlan>,
parts: &[&String],
listed: Option<(Arc<ExecutionPlan>, DataPath, Arc<RowInstance>)>,
) -> Walk {
let mut holders = walk.holders.clone();
holders.push((Arc::clone(&walk.template), Vec::new()));
for (_, path) in &mut holders {
path.extend(parts.iter().map(|part| (*part).clone()));
}
let mut from_writer = walk.from_writer.clone();
from_writer.extend(parts.iter().map(|part| (*part).clone()));
Walk {
template,
row,
holders,
listed,
copied: None,
from_writer,
}
}
fn reach_field(walk: &Walk, field: &str, writer: &Writes) -> Result<Reached, String> {
let path = DataPath::local(field.to_string());
let Some((slot, _, definition)) = walk.template.data.get_full(&path) else {
return Err(format!(
"`{}` has no data field `{field}`",
walk.template.identity.spec
));
};
if matches!(definition, DataDefinition::Import { .. }) {
return Err(format!("cannot bind import alias '{field}' as a value"));
}
let by_row = walk.row.bindings[slot].is_some()
|| walk.copied.as_ref().is_some_and(|(copied, at)| {
copied.bindings[slot].is_some() || writer.get(at, &path).is_some()
})
|| walk.listed.as_ref().is_some_and(|(holder, list, _)| {
holder.instance_lists[list]
.row_writes
.as_ref()
.is_some_and(|written| written.bindings[slot].is_some())
});
let by_holder = walk
.holders
.iter()
.rev()
.skip(1)
.any(|(holder, instance)| holder.writes.get(instance, &path).is_some());
let keys_list = walk.listed.as_ref().filter(|(holder, list, _)| {
matches!(
&holder.instance_lists[list].key,
ListKey::Fields(fields) if fields.iter().any(|key| key.path == path)
)
});
let by_fill = walk
.holders
.iter()
.any(|(holder, instance)| holder.writes.list(instance, &path).is_some());
Ok(Reached {
template: Arc::clone(&walk.template),
row: Arc::clone(&walk.row),
keys_list: keys_list.cloned(),
field: path,
written: by_row || by_holder || by_fill,
})
}
pub(crate) fn unit_not_held(field: &LemmaType, source: &LemmaType) -> Option<String> {
if !field.same_measure_family(source) {
return None;
}
let held = field.measure_units_table();
source
.measure_units_table()?
.iter()
.find(|unit| unit.is_dynamic() && held.is_none_or(|units| units.get(&unit.name).is_err()))
.map(|unit| unit.name.clone())
}
pub(crate) fn bounded_at_other_than_zero(lemma_type: &LemmaType) -> bool {
let crate::planning::semantics::TypeSpecification::Measure {
minimum, maximum, ..
} = &lemma_type.specifications
else {
return false;
};
[minimum, maximum]
.into_iter()
.flatten()
.any(|(magnitude, _)| !crate::computation::rational::rational_is_zero(magnitude))
}