use std::collections::BTreeMap;
use techy::error::Diagnostic;
use techy::serialize::SerialValue;
use crate::core::data::store::StageOut;
use crate::core::data::table::{PieceClass, ProjectCx, Table, TableName};
use crate::core::plan::PlanCx;
use crate::core::run::StageCx;
use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
use crate::model::addr::NodeAddr;
use crate::model::aspects::{Label, Referencing};
use crate::model::element::element_of;
use crate::lang::{nowhere, FlmOrigin};
use super::elements::reference_targets;
use super::latex::{RefsRecomposeOptions, SafeLabelMode};
use super::stages::StageFailed;
use super::tables::REF_RESOLUTIONS;
use crate::stdlib::features::index::ELEMENT_INDEX;
use crate::stdlib::features::refpoints::{REFPOINTS, RefPointRecord, node_key};
pub const STAGE: &str = "flm.refs.safe-labels";
pub const SAFE_LABELS: TableName<SafeLabels> = TableName::new("flm.labels.safe");
pub const REF_DOMAIN: &str = "ref";
pub fn label_key(text: &str, label: Option<&Label>) -> String {
match label {
Some(label) => label.to_string(),
None => String::from(text),
}
}
#[derive(Debug, Clone, Default)]
pub struct SafeLabels {
pub by_label: BTreeMap<String, BTreeMap<String, String>>,
pub by_name: BTreeMap<String, BTreeMap<String, String>>,
pub allocated: u32,
}
impl SafeLabels {
pub fn safe_name(&self, domain: &str, key: &str) -> Option<&str> {
self.by_label.get(domain)?.get(key).map(String::as_str)
}
pub fn label_of(&self, domain: &str, name: &str) -> Option<&str> {
self.by_name.get(domain)?.get(name).map(String::as_str)
}
pub fn allocate(&mut self, domain: &str, key: &str) -> &str {
let names = self.by_label.entry(String::from(domain)).or_default();
if !names.contains_key(key) {
self.allocated += 1;
let name = format!("{domain}{}", self.allocated);
self.by_name
.entry(String::from(domain))
.or_default()
.insert(name.clone(), String::from(key));
names.insert(String::from(key), name);
}
names.get(key).map(String::as_str).unwrap_or_default()
}
}
impl Table for SafeLabels {
fn absorb(&mut self, piece: SafeLabels) {
for (domain, names) in piece.by_label {
let mine = self.by_label.entry(domain).or_default();
for (key, name) in names {
mine.entry(key).or_insert(name);
}
}
for (domain, labels) in piece.by_name {
let mine = self.by_name.entry(domain).or_default();
for (name, label) in labels {
mine.entry(name).or_insert(label);
}
}
self.allocated = self.allocated.max(piece.allocated);
}
fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
SerialValue::Map(
self.by_label
.iter()
.map(|(domain, names)| {
let labels = names
.iter()
.map(|(key, name)| (key.clone(), SerialValue::Str(name.clone())))
.collect();
let reverse = self
.by_name
.get(domain)
.into_iter()
.flatten()
.map(|(name, key)| (name.clone(), SerialValue::Str(key.clone())))
.collect();
(
domain.clone(),
SerialValue::Map(vec![
(String::from("labels"), SerialValue::Map(labels)),
(String::from("names"), SerialValue::Map(reverse)),
]),
)
})
.collect(),
)
}
fn piece_class(&self) -> PieceClass {
if self.by_label.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct SafeLabelsStage;
impl Stage for SafeLabelsStage {
fn decl(&self) -> StageDecl {
StageDecl::new(STAGE, Effect::Compute, Scope::Document).writes(SAFE_LABELS).docs(
"For the recomposed LaTeX: allocates the safe label (`ref1`, `ref2`, …) of every \
label a reference point carries and of every reference target, resolved or not, \
in the order the document first mentions it, into `flm.labels.safe`.",
)
}
fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
Needs::new().reads(REFPOINTS).option::<RefsRecomposeOptions>()
}
fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
let options = match cx.option::<RefsRecomposeOptions>() {
Ok(options) => options,
Err(error) => {
out.diags.push(Diagnostic::error(
StageFailed { stage: String::from(STAGE), detail: error.to_string() },
nowhere(FlmOrigin::none()),
));
return;
}
};
let points = match cx.get(REFPOINTS) {
Ok(Some(points)) => points,
Ok(None) => {
out.diags.push(Diagnostic::error(
StageFailed {
stage: String::from(STAGE),
detail: format!("missing table ‘{}’", REFPOINTS.name()),
},
nowhere(FlmOrigin::none()),
));
return;
}
Err(error) => {
out.diags.push(Diagnostic::error(
StageFailed { stage: String::from(STAGE), detail: error.to_string() },
nowhere(FlmOrigin::none()),
));
return;
}
};
let mut by_node: BTreeMap<NodeAddr, Vec<&RefPointRecord>> = BTreeMap::new();
for record in points.records() {
by_node.entry(record.id.addr).or_default().push(record);
}
let mut table = SafeLabels::default();
let raw = |label: Option<&Label>| {
label.is_some_and(|label| {
options.safe_label_types.get(&label.ref_type) == Some(&SafeLabelMode::Raw)
})
};
for (addr, node) in cx.walk() {
let mentions = by_node
.get(&addr)
.into_iter()
.flatten()
.flat_map(|record| record.mentions());
for (text, label) in mentions {
if !raw(label) {
table.allocate(REF_DOMAIN, &label_key(&text, label));
}
}
let sites = element_of(&node)
.aspect::<dyn Referencing>()
.map(|referencing| referencing.sites(&node))
.unwrap_or_default();
for site in sites {
if !raw(Some(&site.target)) {
table.allocate(REF_DOMAIN, &label_key("", Some(&site.target)));
}
}
let unspelled = reference_targets(&node).into_iter().flatten();
for target in unspelled.filter(|target| target.label.is_none()) {
table.allocate(REF_DOMAIN, &label_key(&target.text, None));
}
}
match out.table(SAFE_LABELS) {
Ok(written) => *written = table,
Err(error) => out.diags.push(Diagnostic::error(
StageFailed { stage: String::from(STAGE), detail: error.to_string() },
nowhere(FlmOrigin::none()),
)),
}
}
}
pub const VALUE_STAGE: &str = "flm.refs.value-safe-labels";
pub const VALUE_SAFE_LABELS: TableName<ValueSafeLabels> = TableName::new("flm.labels.safe.value");
pub fn value_name(domain: &str, number: u32) -> String {
format!("{domain}-v{number}")
}
#[derive(Debug, Clone, Default)]
pub struct ValueSafeLabels {
pub by_node: BTreeMap<NodeAddr, BTreeMap<String, String>>,
}
impl ValueSafeLabels {
pub fn safe_name(&self, at: NodeAddr, key: &str) -> Option<&str> {
self.by_node.get(&at)?.get(key).map(String::as_str)
}
}
impl Table for ValueSafeLabels {
fn absorb(&mut self, piece: ValueSafeLabels) {
for (addr, names) in piece.by_node {
self.by_node.entry(addr).or_default().extend(names);
}
}
fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
SerialValue::Map(
self.by_node
.iter()
.map(|(addr, names)| {
let names = names
.iter()
.map(|(key, name)| (key.clone(), SerialValue::Str(name.clone())))
.collect();
(node_key(cx, *addr), SerialValue::Map(names))
})
.collect(),
)
}
fn piece_class(&self) -> PieceClass {
if self.by_node.is_empty() { PieceClass::Empty } else { PieceClass::NodeKeyed }
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct ValueSafeLabelsStage;
impl Stage for ValueSafeLabelsStage {
fn decl(&self) -> StageDecl {
StageDecl::new(VALUE_STAGE, Effect::Compute, Scope::PerTree)
.writes(VALUE_SAFE_LABELS)
.docs(
"For the recomposed LaTeX, over a synthesized value spliced at lowering: gives \
every target its references mention that has no safe label in \
`flm.labels.safe` a value name, `ref-v1`, `ref-v2`, … in the order the value \
first mentions it, into `flm.labels.safe.value`; writes nothing over a \
document tree.",
)
}
fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
Needs::new()
.reads(SAFE_LABELS)
.reads(ELEMENT_INDEX)
.reads(REF_RESOLUTIONS)
.option::<RefsRecomposeOptions>()
}
fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
let (Some(id), Some(tree)) = (cx.tree_id(), cx.my_tree()) else { return };
if !id.is_value() {
return;
}
let (Ok(Some(document)), Ok(Some(index)), Ok(options)) =
(cx.get(SAFE_LABELS), cx.get(ELEMENT_INDEX), cx.option::<RefsRecomposeOptions>())
else {
return;
};
let raw = |label: &Label| {
options.safe_label_types.get(&label.ref_type) == Some(&SafeLabelMode::Raw)
};
let mut named: BTreeMap<String, String> = BTreeMap::new();
let mut table = ValueSafeLabels::default();
for (addr, node, referencing) in
index.nodes_with::<dyn Referencing>(cx.registry(), id, &tree)
{
let sites = referencing.sites(&node).into_iter().map(|site| site.target);
let keys = sites
.filter(|target| !raw(target))
.map(|target| label_key("", Some(&target)))
.chain(
reference_targets(&node)
.into_iter()
.flatten()
.filter(|target| target.label.is_none())
.map(|target| label_key(&target.text, None)),
);
for key in keys {
if document.safe_name(REF_DOMAIN, &key).is_some() {
continue;
}
let next = named.len() + 1;
let name = named
.entry(key.clone())
.or_insert_with(|| value_name(REF_DOMAIN, u32::try_from(next).unwrap_or(u32::MAX)))
.clone();
table.by_node.entry(addr).or_default().insert(key, name);
}
}
if let Ok(written) = out.table(VALUE_SAFE_LABELS) {
*written = table;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_are_allocated_once_per_label_across_domains() {
let mut table = SafeLabels::default();
let a = Label::new("sec", "a").to_string();
let b = Label::new("eq", "b").to_string();
assert_eq!(table.allocate(REF_DOMAIN, &a), "ref1");
assert_eq!(table.allocate("cite", &b), "cite2");
assert_eq!(table.allocate(REF_DOMAIN, &a), "ref1");
assert_eq!(table.allocate(REF_DOMAIN, &b), "ref3");
assert_eq!(table.safe_name(REF_DOMAIN, &b), Some("ref3"));
assert_eq!(table.safe_name("cite", &a), None);
assert_eq!(table.label_of("cite", "cite2"), Some("eq:b"));
assert_eq!(table.allocated, 3);
assert_eq!(table.piece_class(), PieceClass::DocumentFact);
assert_eq!(SafeLabels::default().piece_class(), PieceClass::Empty);
}
#[test]
fn a_label_with_no_type_is_keyed_by_its_text_and_named_like_any_other() {
assert_eq!(label_key("sec : intro", Label::parse("sec : intro").as_ref()), "sec:intro");
assert_eq!(label_key("intro", None), "intro");
let mut table = SafeLabels::default();
assert_eq!(table.allocate(REF_DOMAIN, &label_key("sec:a", Label::parse("sec:a").as_ref())), "ref1");
assert_eq!(table.allocate(REF_DOMAIN, &label_key("a_b", None)), "ref2");
assert_eq!(table.safe_name(REF_DOMAIN, "a_b"), Some("ref2"));
assert_eq!(table.label_of(REF_DOMAIN, "ref2"), Some("a_b"));
}
#[test]
fn a_value_name_holds_a_hyphen_no_document_name_holds() {
assert_eq!(value_name(REF_DOMAIN, 3), "ref-v3");
let mut table = SafeLabels::default();
assert!(!table.allocate(REF_DOMAIN, "sec:a").contains('-'));
assert_eq!(ValueSafeLabels::default().piece_class(), PieceClass::Empty);
}
#[test]
fn the_value_stage_is_per_tree_and_writes_its_table() {
let decl = ValueSafeLabelsStage.decl();
assert_eq!(decl.name, VALUE_STAGE);
assert_eq!(decl.scope, Scope::PerTree);
assert_eq!(decl.writes.len(), 1);
}
#[test]
fn the_stage_is_of_document_scope_and_writes_the_table() {
let decl = SafeLabelsStage.decl();
assert_eq!(decl.name, STAGE);
assert_eq!(decl.scope, Scope::Document);
assert_eq!(decl.effect, Effect::Compute);
assert_eq!(decl.writes.len(), 1);
}
}