use std::sync::Arc;
use std::sync::LazyLock;
use techy::core::node::{BuildId, NodeRef};
use techy::error::{Diagnostic, DiagnosticInfo};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::Flm;
use crate::lang::text::{is_space, read_chars};
use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, SyntaxDef};
use crate::model::aspects::{
ApartFromText, BlockRole, BlockRoleAspect, ContentRef, FixedBlockRole, Label, RefDisplayOptions,
RefSite, Referencing,
};
use crate::model::element::{ElementSpec, element_value};
use crate::model::names::{ElementName, FeatureName, Name};
use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
use crate::stdlib::backends::latex::{LatexArgShape, LatexMacroPayload, packages};
use crate::stdlib::backends::latex_recomposed::BACKEND as LATEX_BACKEND;
use crate::stdlib::backends::pres;
use crate::stdlib::features::numbering::COUNTERS;
use crate::stdlib::features::refs::{
LabelSpelling, REF_RESOLUTIONS, RefResolutions, RefTargetText, SAFE_LABELS, TARGET_ARG,
TARGET_ARG_ROLE, VALUE_SAFE_LABELS, ValueSafeLabels, lower_reference, read_target_at_lowering,
stage_spelling, target_spelling,
};
use super::LABEL_TYPES;
pub const EQREF: &str = "flm.math.eqref";
pub const RULE: &str = "flm.math.eqref.lower.default";
pub const LATEX_RULE: &str = "flm.math.eqref.lower.latex-recomposed";
pub const LATEX_COMMAND: &str = "eqref";
pub const TARGET_TYPE: &str = LABEL_TYPES[0];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EqrefElement;
pub fn eqref_target(node: &NodeRef<'_, Flm>) -> Option<RefTargetText> {
element_value::<EqrefElement>(node)?;
let text = match node.argument_content_nodes_named(TARGET_ARG) {
Ok(Some(content)) => match read_chars(content.iter()) {
Ok(read) if read.has_placeholder() => return None,
Ok(read) => read.text().unwrap_or_default().trim_matches(is_space).to_string(),
Err(_) => String::new(),
},
_ => String::new(),
};
let label = Label::parse(&text);
Some(RefTargetText { text, label })
}
fn names_an_equation(target: &RefTargetText) -> bool {
target.label.as_ref().is_some_and(|label| label.ref_type == TARGET_TYPE)
}
impl Referencing for EqrefElement {
fn sites(&self, node: &NodeRef<'_, Flm>) -> Vec<RefSite> {
let Some(target) = eqref_target(node).filter(names_an_equation) else {
return Vec::new();
};
let Some(label) = target.label else { return Vec::new() };
vec![RefSite {
target: label,
display: RefDisplayOptions { variant: None, with_prefix: false },
shown: true,
}]
}
}
impl ApartFromText for EqrefElement {
fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
vec![ContentRef::ArgumentNamed(TARGET_ARG.to_string())]
}
}
static EQREF_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
Arc::new(
ElementSpec::new(EQREF)
.docs("A reference to an equation line that shows its number in parentheses.")
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
.with::<dyn ApartFromText>(Arc::new(EqrefElement))
.with::<dyn Referencing>(Arc::new(EqrefElement))
.with_value(Arc::new(EqrefElement)),
)
});
pub fn element() -> Arc<ElementSpec> {
Arc::clone(&EQREF_ELEMENT)
}
pub fn args() -> Vec<ArgDef> {
vec![
ArgDef::named(TARGET_ARG, ArgStdKind::CharsGroup)
.docs("The equation's label, `eq:label`.")
.role(TARGET_ARG_ROLE),
]
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.math.eqref-not-an-equation",
message = "`\\eqref` refers to equations: the label `{label}` must begin with `{expected}:`"
)]
pub struct NotAnEquation {
pub label: String,
pub expected: String,
}
#[derive(Debug, Default, Clone, Copy)]
pub struct EqrefRule;
impl Lower for EqrefRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let mut target = eqref_target(&node)
.ok_or_else(|| LowerError::structure("an `\\eqref` without its element's data"))?;
let names_equation = names_an_equation(&target);
if !names_equation {
let condition = NotAnEquation {
label: target.text.clone(),
expected: String::from(TARGET_TYPE),
};
lw.diagnose(Diagnostic::error(condition, node.span().clone()));
}
if !names_equation || lw.get(REF_RESOLUTIONS)?.is_none() {
target.label = None;
}
let display = RefDisplayOptions { variant: None, with_prefix: false };
let items = lower_reference(cx, lw, &node, std::slice::from_ref(&target), &display)?;
Ok(Lowering::Emit(items.into_iter().flatten().collect()))
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct EqrefLatexRule;
impl Lower for EqrefLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
read_target_at_lowering(&node)?;
lw.require(&Name::from(packages::AMSMATH));
let target = eqref_target(&node).unwrap_or(RefTargetText {
text: String::new(),
label: None,
});
let spelling = if names_an_equation(&target) {
target_spelling(lw, &target.text, target.label.as_ref())?
} else {
let condition = NotAnEquation {
label: target.text.clone(),
expected: String::from(TARGET_TYPE),
};
lw.diagnose(Diagnostic::error(condition, node.span().clone()));
LabelSpelling::Raw(target.text.clone())
};
let key = stage_spelling(cx, lw, &spelling)?;
Ok(Lowering::Emit(vec![eqref_command(cx, lw, key)?]))
}
}
fn eqref_command(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
key: Vec<BuildId>,
) -> Result<BuildId, LowerError> {
lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(LATEX_COMMAND, [LatexArgShape::Mandatory]),
vec![(String::from(ARG_SLOT), key)],
)
}
pub fn rules() -> Vec<LoweringRule> {
vec![
LoweringRule::new(
RULE,
EQREF,
LoweringDecl::new()
.reads_opt(REF_RESOLUTIONS)
.reads_opt(COUNTERS)
.produces(pres::LINK)
.produces(pres::SPAN),
Arc::new(EqrefRule),
DefaultMark::Everywhere,
)
.docs(
"an `\\eqref` lowers to what `\\ref[noprefix]` lowers to for the same label: the \
line's number in parentheses, inside a link to the equation line",
),
LoweringRule::new(
LATEX_RULE,
EQREF,
LoweringDecl::new()
.reads_opt(SAFE_LABELS)
.reads_opt(VALUE_SAFE_LABELS)
.produces(MACRO)
.produces(RAW),
Arc::new(EqrefLatexRule),
DefaultMark::OnBackends(vec![LATEX_BACKEND.into()]),
)
.docs("an `\\eqref` lowers to the LaTeX `\\eqref` around its label's safe label"),
]
}
pub fn register(b: &mut FeatureBuilder<'_>, owner: &FeatureName) -> Result<(), BuildError> {
b.peer_table::<RefResolutions>(
REF_RESOLUTIONS.name(),
"the references feature's resolutions table, which the `\\eqref` rule reads for the \
reference point its label refers to",
)?;
b.peer_table::<ValueSafeLabels>(
VALUE_SAFE_LABELS.name(),
"the references feature's value names table (`flm.labels.safe.value`), which the \
`\\eqref` recomposition rule reads for the safe label of a label that appears only inside a synthesized value",
)?;
b.peer_argument_role(TARGET_ARG_ROLE)?;
b.element(
ElementDef::new(owner.clone(), ["eqref"], SyntaxDef::Macro { args: args() }, element())
.docs(
"Refers to an equation line and shows its number in parentheses. The label has \
the label type `eq`.",
),
)?;
b.element_type_text(
EQREF,
"A reference to an equation line, shown as the line's number in parentheses.",
)?;
for rule in rules() {
b.lowering_rule(rule)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_element_carries_the_referencing_aspect_and_is_one_shared_value() {
let element = element();
assert!(element.has_aspect::<dyn Referencing>());
assert!(element.value_as::<EqrefElement>().is_some());
assert!(ElementSpec::same_value(&super::element(), &super::element()));
}
#[test]
fn only_a_label_of_the_equation_type_names_an_equation() {
let target = |text: &str| RefTargetText {
text: String::from(text),
label: Label::parse(text),
};
assert!(names_an_equation(&target("eq:euler")));
assert!(!names_an_equation(&target("sec:intro")));
assert!(!names_an_equation(&target("euler")));
assert!(!names_an_equation(&target("")));
}
}