use std::sync::{Arc, LazyLock};
use techy::core::node::{NodeRef, NodeSlice};
use crate::lang::mint::{ArgDef, ArgStdKind, TackOnField, field_name};
use crate::lang::text::collapse_whitespace;
use crate::lang::{Flm, FlmCallableType};
use crate::model::aspects::{
AcceptedRefTypes, AnchorPolicy, ApartFromText, BlockRole, BlockRoleAspect, ContentRef,
FixedBlockRole, Label, RefDisplayOptions, RefPoint, RefSite, Referenceable, Referencing,
};
use crate::model::element::{ElementSpec, element_value};
use crate::model::names::RefKind;
use crate::stdlib::backends::pres::spelling_identity;
use crate::stdlib::features::refs;
pub const DEFTERM: &str = "flm.defterm";
pub const TERM: &str = "flm.term";
pub const TERM_ARG: &str = "term";
pub const ALIAS_FIELD: &str = "aliasterm";
pub const ALIAS_ARG: &str = "term";
pub const REF_ARG: &str = "ref";
pub const SHOWN_ARG: &str = "shown";
pub const DEFINED_TERM_ARG_ROLE: &str = "flm.defterm.defined-term";
pub const TARGET_ARG_ROLE: &str = "flm.defterm.target";
pub const DEFINITION_KIND: &str = "defterm";
pub const LABEL_TYPES: [&str; 2] = ["term", "topic"];
pub(crate) const COMPUTED_TYPE: &str = "defterm";
fn computed_label(identity: String) -> Option<Label> {
(!identity.is_empty()).then(|| Label::new(COMPUTED_TYPE, identity))
}
pub(super) fn holds_placeholder<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> bool {
nodes.into_iter().any(|node| {
std::iter::once(node)
.chain(node.descendants())
.any(|inner| inner.callable_type() == Some(FlmCallableType::Placeholder))
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeftermElement;
pub(super) fn computed_labels(node: &NodeRef<'_, Flm>) -> Vec<Label> {
if element_value::<DeftermElement>(node).is_none() {
return Vec::new();
}
let mut labels = Vec::new();
let term = node.argument_content_nodes_named(TERM_ARG).ok().flatten();
if let Some(label) = term.and_then(|content| computed_label(declared_identity(content.iter()))) {
labels.push(label);
}
let fields = node.argument_content_nodes_named(refs::FIELDS_ARG).ok().flatten();
for field in fields.iter().flat_map(|fields| fields.iter()) {
if field_name(&field).is_none_or(|name| name != ALIAS_FIELD) {
continue;
}
let alias = field.argument_content_nodes_named(ALIAS_ARG).ok().flatten();
if let Some(label) = alias.and_then(|content| computed_label(declared_identity(content.iter())))
{
if !labels.contains(&label) {
labels.push(label);
}
}
}
labels
}
fn declared_identity<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>> + Clone) -> String {
if !holds_placeholder(nodes.clone()) {
return spelling_identity(nodes);
}
let written: String = nodes
.into_iter()
.filter(|node| !node.is_comment())
.map(|node| node.span_content())
.collect();
collapse_whitespace(&written)
}
fn defines(node: &NodeRef<'_, Flm>, target: &Label) -> bool {
computed_labels(node).iter().any(|label| label == target)
}
impl Referenceable for DeftermElement {
fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
let mut labels = computed_labels(node);
let computed = labels.len();
let (written, mut malformed) = refs::point_labels(&refs::label_uses(node));
labels.extend(written);
for text in &mut malformed {
text.position += computed;
}
vec![RefPoint {
kind: RefKind::from(DEFINITION_KIND),
labels,
computed,
malformed,
anchor: AnchorPolicy::FromFirstLabel,
number: None,
content: Some(ContentRef::ArgumentNamed(TERM_ARG.to_string())),
accepts: AcceptedRefTypes::these(LABEL_TYPES),
}]
}
}
impl ApartFromText for DeftermElement {
fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
vec![ContentRef::ArgumentNamed(refs::FIELDS_ARG.to_string())]
}
}
static DEFTERM_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
Arc::new(
ElementSpec::new(DEFTERM)
.docs(
"The definition of a term (the `defterm` environment), the target of the term \
links to that term.",
)
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block)))
.with::<dyn Referenceable>(Arc::new(DeftermElement))
.with::<dyn ApartFromText>(Arc::new(DeftermElement))
.with_value(Arc::new(DeftermElement)),
)
});
pub fn defterm_element() -> Arc<ElementSpec> {
Arc::clone(&DEFTERM_ELEMENT)
}
pub fn defterm_args() -> Vec<ArgDef> {
let alias = TackOnField::new(
ALIAS_FIELD,
vec![ArgDef::named(ALIAS_ARG, ArgStdKind::Mandatory).docs("The alias.").role(DEFINED_TERM_ARG_ROLE)],
)
.repeatable()
.docs("Declares another way of writing the term, by which term links find it too.");
let fields = ArgStdKind::TackOn { fields: vec![refs::label_field(), alias] };
vec![
ArgDef::named(TERM_ARG, ArgStdKind::Mandatory)
.docs("The term being defined.")
.role(DEFINED_TERM_ARG_ROLE),
ArgDef::named(refs::FIELDS_ARG, fields)
.docs(
"The `\\label{…}` and `\\aliasterm{…}` fields written after the term: they \
label the term definition.",
),
]
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TermElement;
pub fn term_target(node: &NodeRef<'_, Flm>) -> Option<Label> {
let written = written_term(node)?;
if holds_placeholder(written.iter()) {
return None;
}
computed_label(spelling_identity(written.iter()))
}
pub(super) fn written_term<'t>(node: &NodeRef<'t, Flm>) -> Option<NodeSlice<'t, Flm>> {
element_value::<TermElement>(node)?;
let named = |name: &str| node.argument_content_nodes_named(name).ok().flatten();
named(REF_ARG)
.filter(|content| holds_placeholder(content.iter()) || !spelling_identity(content.iter()).is_empty())
.or_else(|| named(SHOWN_ARG))
}
pub fn in_own_definition(node: &NodeRef<'_, Flm>, target: &Label) -> bool {
let mut current = node.parent();
while let Some(ancestor) = current {
if defines(&ancestor, target) {
return true;
}
current = ancestor.parent();
}
false
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct TermDecision {
pub(super) target: Label,
pub(super) in_own_definition: bool,
}
pub(super) fn decide_term(node: &NodeRef<'_, Flm>) -> Option<TermDecision> {
let target = term_target(node)?;
let in_own_definition = in_own_definition(node, &target);
Some(TermDecision { target, in_own_definition })
}
impl Referencing for TermElement {
fn sites(&self, node: &NodeRef<'_, Flm>) -> Vec<RefSite> {
term_target(node)
.map(|target| RefSite {
target,
display: RefDisplayOptions { variant: None, with_prefix: false },
shown: true,
})
.into_iter()
.collect()
}
}
impl ApartFromText for TermElement {
fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
vec![ContentRef::ArgumentNamed(REF_ARG.to_string())]
}
}
static TERM_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
Arc::new(
ElementSpec::new(TERM)
.docs("A link to the definition of a term, showing the text written for it.")
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
.with::<dyn Referencing>(Arc::new(TermElement))
.with::<dyn ApartFromText>(Arc::new(TermElement))
.with_value(Arc::new(TermElement)),
)
});
pub fn term_element() -> Arc<ElementSpec> {
Arc::clone(&TERM_ELEMENT)
}
pub fn term_args() -> Vec<ArgDef> {
vec![
ArgDef::named(REF_ARG, ArgStdKind::Optional)
.docs("The term linked to, where it is not the text shown.")
.role(TARGET_ARG_ROLE),
ArgDef::named(SHOWN_ARG, ArgStdKind::Mandatory).docs("The text shown."),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_two_elements_carry_their_aspects() {
assert!(defterm_element().has_aspect::<dyn Referenceable>());
assert!(defterm_element().has_aspect::<dyn ApartFromText>());
assert!(term_element().has_aspect::<dyn Referencing>());
assert!(term_element().has_aspect::<dyn ApartFromText>());
assert!(!ElementSpec::same_value(&defterm_element(), &term_element()));
}
#[test]
fn the_empty_identity_names_no_term() {
assert_eq!(computed_label(String::new()), None);
assert_eq!(
computed_label("entropy".to_string()),
Some(Label::new(COMPUTED_TYPE, "entropy"))
);
}
}