use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use techy::error::Diagnostic;
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::core::run::MissingEntry;
use crate::lang::mint::{ElementDef, SyntaxDef};
use crate::lang::Flm;
use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
use crate::model::element::ElementSpec;
use crate::model::names::{CapName, ElementName, Name};
use crate::stdlib::backends::pres::{
self, BlockPayload, DocRole, LinkPayload, ListPayload, SpanPayload, ITEM_SLOT, LABEL_SLOT,
LIST_UNNUMBERED,
};
use crate::stdlib::features::numbering::{Counters, FormatOptions, COUNTERS};
use crate::stdlib::features::refs::{Anchors, ANCHORS};
use super::{TocEntryPayload, ENTRY, KIND_TOC, LIST, NUMBER_ROLE, PIECE, STYLE};
pub const LINK_KIND: &str = "toc";
pub fn rule_name(element: &str) -> String {
format!("{element}.lower.default")
}
#[derive(Debug, Default, Clone, Copy)]
pub struct RootRule;
impl Lower for RootRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
lw.require(&Name::from(STYLE));
let content = lw.lower_children(cx, &node)?;
let block = BlockPayload {
role: Some(Name::from(PIECE)),
kinds: vec![Name::from(KIND_TOC)],
anchor: None,
doc_role: Some(DocRole::Toc),
};
Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block, content)?]))
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct ListRule;
impl Lower for ListRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let mut slots: Vec<(String, Vec<BuildId>)> = Vec::new();
let mut entry_levels: Vec<Option<u32>> = Vec::new();
for one in each_child(&node)? {
let Some(entry) = one.first().filter(|child| child.ext().element.name.as_str() == ENTRY) else {
continue;
};
entry_levels.push(TocEntryPayload::of(&entry).map(|payload| payload.level));
slots.push((LABEL_SLOT.to_string(), Vec::new()));
slots.push((ITEM_SLOT.to_string(), lw.lower_nodes(cx, one)?));
}
let payload = ListPayload {
kinds: vec![Name::from(LIST_UNNUMBERED), Name::from(KIND_TOC)],
anchor: None,
entry_anchors: Vec::new(),
entry_levels,
};
Ok(Lowering::Emit(vec![lw.pres_slots_with(cx, &ElementName::from(pres::LIST), payload, slots)?]))
}
}
fn each_child<'t>(node: &NodeRef<'t, Flm>) -> Result<Vec<techy::core::node::NodeSlice<'t, Flm>>, LowerError> {
let children = node.children();
let start = children.range().start;
(0u32..)
.zip(children.iter())
.map(|(index, _)| {
node.tree()
.slice(start + index..start + index + 1)
.ok_or_else(|| LowerError::structure("a child outside its parent's children"))
})
.collect()
}
#[derive(Debug, Default, Clone, Copy)]
pub struct EntryRule;
impl Lower for EntryRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let point = TocEntryPayload::of(&node).and_then(|payload| payload.point);
let segments = match (point, lw.get(COUNTERS)?) {
(Some(point), Some(counters)) => number(counters, point)?,
_ => Vec::new(),
};
let anchor = match point {
Some(point) => anchor(&node, point, lw)?,
None => None,
};
let mut shown = Vec::new();
if !segments.is_empty() {
let mut number = Vec::new();
for segment in &segments {
number.extend(lw.splice(cx, segment.content())?);
}
let span = SpanPayload { role: Some(Name::from(NUMBER_ROLE)), ..SpanPayload::default() };
shown.push(lw.pres_with(cx, &ElementName::from(pres::SPAN), span, number)?);
shown.push(lw.text(cx, " ")?);
}
let paragraph = Arc::clone(&lw.lang().structural().paragraph);
let mut lists = Vec::new();
for (one, child) in each_child(&node)?.into_iter().zip(node.children().iter()) {
let name = &child.ext().element.name;
if name.as_str() == LIST {
lists.push(one);
} else if *name == paragraph.name {
shown.extend(lw.lower_children(cx, &child)?);
} else {
shown.extend(lw.lower_nodes(cx, one)?);
}
}
let mut staged = match anchor {
Some(anchor) => {
let link = LinkPayload {
href: format!("#{anchor}"),
kind: Name::from(LINK_KIND),
doc_role: None,
label: None,
shows_target: true,
};
vec![lw.pres_with(cx, &ElementName::from(pres::LINK), link, shown)?]
}
None => shown,
};
for one in lists {
staged.extend(lw.lower_nodes(cx, one)?);
}
Ok(Lowering::Emit(staged))
}
}
fn number(counters: &Counters, point: crate::model::aspects::PointId) -> Result<Vec<crate::stdlib::features::numbering::NumberSegment>, LowerError> {
let options = FormatOptions::new().without_word().without_delimiters();
match counters.format(point, &options) {
None => Ok(Vec::new()),
Some(result) => result.map_err(|error| LowerError::structure(error.to_string())),
}
}
fn anchor(
node: &NodeRef<'_, Flm>,
point: crate::model::aspects::PointId,
lw: &mut dyn Lowerer,
) -> Result<Option<String>, LowerError> {
let found: Option<Option<String>> = match lw.get(ANCHORS)? {
None => return Ok(None),
Some(anchors) => anchors.lookup(point).map(|entry| entry.map(String::from)),
};
match found {
Some(anchor) => Ok(anchor),
None => {
let table = CapName::from(ANCHORS.name());
let producer =
lw.producer_of(&table).map(|stage| stage.to_string()).unwrap_or_else(|| "nobody".to_string());
lw.diagnose(Diagnostic::error(
MissingEntry { table: table.to_string(), producer, element: ENTRY.to_string() },
node.span().clone(),
));
Ok(None)
}
}
}
pub(super) fn decl() -> LoweringDecl {
LoweringDecl::new()
.reads_opt(COUNTERS)
.reads_opt(ANCHORS)
.produces(pres::BLOCK)
.produces(pres::LIST)
.produces(pres::SPAN)
.produces(pres::LINK)
.produces(pres::PAR)
}
fn declare_peers(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
b.peer_table::<Counters>(COUNTERS.name(), "the numbering feature's counter table: each entry's number")?;
b.peer_table::<Anchors>(ANCHORS.name(), "the references feature's anchors table: each entry's link target")?;
b.peer_element::<BlockPayload>(pres::BLOCK, "the table of contents")?;
b.peer_element::<ListPayload>(pres::LIST, "a list of entries of the table of contents")?;
b.peer_element::<SpanPayload>(pres::SPAN, "the number of an entry of the table of contents")?;
b.peer_element::<LinkPayload>(pres::LINK, "the link from an entry of the table of contents to its heading")?;
b.peer_element::<pres::ParPayload>(pres::PAR, "a paragraph inside an entry's title")
}
pub(super) fn declare(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
let owner = b.feature().clone();
let elements = [
(
PIECE,
"The table of contents: one list of entries.",
"The table of contents of the document, built from its headings.",
),
(
LIST,
"A list of entries of the table of contents.",
"A list of entries of the table of contents: the headings of one level, under one \
heading or at the top.",
),
(
ENTRY,
"One entry of the table of contents: the title, then the list of its sub-entries.",
"One entry of the table of contents: one heading's title, then the entries of the \
headings under it.",
),
];
for (name, docs, type_docs) in elements {
b.element_type_text(name, type_docs)?;
let role = Arc::new(FixedBlockRole(BlockRole::Block)) as Arc<dyn BlockRoleAspect>;
b.element(
ElementDef::new(
owner.clone(),
Vec::<&str>::new(),
SyntaxDef::Synthesized,
Arc::new(ElementSpec::new(name).docs(docs).with(role)),
)
.docs(format!("{docs} No document can write it: a stage builds it from the headings.")),
)?;
}
declare_peers(b)?;
let rules: [(&str, Arc<dyn Lower>, &str); 3] = [
(
PIECE,
Arc::new(RootRule),
"the table of contents lowers to a `flm.pres.block` of role `flm.toc` and document role \
`toc`, holding its list",
),
(
LIST,
Arc::new(ListRule),
"a list of entries lowers to an unlabeled `flm.pres.list` of kinds `unnumbered` and `toc`",
),
(
ENTRY,
Arc::new(EntryRule),
"an entry lowers to its number and its title inside a link to its heading, then its \
sub-list",
),
];
for (element, rule, docs) in rules {
b.lowering_rule(
LoweringRule::new(rule_name(element), element, decl(), rule, DefaultMark::Everywhere).docs(docs),
)?;
}
Ok(())
}