1use std::sync::Arc;
27
28use techy::core::node::{BuildId, NodeRef};
29use techy::error::Diagnostic;
30
31use crate::core::lowering::{
32 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
33};
34use crate::core::registry::{BuildError, FeatureBuilder};
35use crate::core::run::MissingEntry;
36use crate::lang::mint::{ElementDef, SyntaxDef};
37use crate::lang::Flm;
38use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
39use crate::model::element::ElementSpec;
40use crate::model::names::{CapName, ElementName, Name};
41use crate::stdlib::backends::pres::{
42 self, BlockPayload, DocRole, LinkPayload, ListPayload, SpanPayload, ITEM_SLOT, LABEL_SLOT,
43 LIST_UNNUMBERED,
44};
45use crate::stdlib::features::numbering::{Counters, FormatOptions, COUNTERS};
46use crate::stdlib::features::refs::{Anchors, ANCHORS};
47
48use super::{TocEntryPayload, ENTRY, KIND_TOC, LIST, NUMBER_ROLE, PIECE, STYLE};
49
50pub const LINK_KIND: &str = "toc";
52
53pub fn rule_name(element: &str) -> String {
56 format!("{element}.lower.default")
57}
58
59#[derive(Debug, Default, Clone, Copy)]
72pub struct RootRule;
73
74impl Lower for RootRule {
75 fn lower(
76 &self,
77 node: NodeRef<'_, Flm>,
78 cx: &mut LowerCx<'_>,
79 lw: &mut dyn Lowerer,
80 ) -> Result<Lowering, LowerError> {
81 lw.require(&Name::from(STYLE));
82 let content = lw.lower_children(cx, &node)?;
83 let block = BlockPayload {
84 role: Some(Name::from(PIECE)),
85 kinds: vec![Name::from(KIND_TOC)],
86 anchor: None,
87 doc_role: Some(DocRole::Toc),
88 };
89 Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block, content)?]))
90 }
91}
92
93#[derive(Debug, Default, Clone, Copy)]
109pub struct ListRule;
110
111impl Lower for ListRule {
112 fn lower(
113 &self,
114 node: NodeRef<'_, Flm>,
115 cx: &mut LowerCx<'_>,
116 lw: &mut dyn Lowerer,
117 ) -> Result<Lowering, LowerError> {
118 let mut slots: Vec<(String, Vec<BuildId>)> = Vec::new();
119 let mut entry_levels: Vec<Option<u32>> = Vec::new();
120 for one in each_child(&node)? {
121 let Some(entry) = one.first().filter(|child| child.ext().element.name.as_str() == ENTRY) else {
122 continue;
123 };
124 entry_levels.push(TocEntryPayload::of(&entry).map(|payload| payload.level));
125 slots.push((LABEL_SLOT.to_string(), Vec::new()));
126 slots.push((ITEM_SLOT.to_string(), lw.lower_nodes(cx, one)?));
127 }
128 let payload = ListPayload {
129 kinds: vec![Name::from(LIST_UNNUMBERED), Name::from(KIND_TOC)],
130 anchor: None,
131 entry_anchors: Vec::new(),
132 entry_levels,
133 };
134 Ok(Lowering::Emit(vec![lw.pres_slots_with(cx, &ElementName::from(pres::LIST), payload, slots)?]))
135 }
136}
137
138fn each_child<'t>(node: &NodeRef<'t, Flm>) -> Result<Vec<techy::core::node::NodeSlice<'t, Flm>>, LowerError> {
141 let children = node.children();
142 let start = children.range().start;
143 (0u32..)
144 .zip(children.iter())
145 .map(|(index, _)| {
146 node.tree()
147 .slice(start + index..start + index + 1)
148 .ok_or_else(|| LowerError::structure("a child outside its parent's children"))
149 })
150 .collect()
151}
152
153#[derive(Debug, Default, Clone, Copy)]
182pub struct EntryRule;
183
184impl Lower for EntryRule {
185 fn lower(
186 &self,
187 node: NodeRef<'_, Flm>,
188 cx: &mut LowerCx<'_>,
189 lw: &mut dyn Lowerer,
190 ) -> Result<Lowering, LowerError> {
191 let point = TocEntryPayload::of(&node).and_then(|payload| payload.point);
192 let segments = match (point, lw.get(COUNTERS)?) {
195 (Some(point), Some(counters)) => number(counters, point)?,
196 _ => Vec::new(),
197 };
198 let anchor = match point {
199 Some(point) => anchor(&node, point, lw)?,
200 None => None,
201 };
202 let mut shown = Vec::new();
203 if !segments.is_empty() {
204 let mut number = Vec::new();
205 for segment in &segments {
206 number.extend(lw.splice(cx, segment.content())?);
207 }
208 let span = SpanPayload { role: Some(Name::from(NUMBER_ROLE)), ..SpanPayload::default() };
209 shown.push(lw.pres_with(cx, &ElementName::from(pres::SPAN), span, number)?);
210 shown.push(lw.text(cx, " ")?);
211 }
212 let paragraph = Arc::clone(&lw.lang().structural().paragraph);
213 let mut lists = Vec::new();
214 for (one, child) in each_child(&node)?.into_iter().zip(node.children().iter()) {
215 let name = &child.ext().element.name;
216 if name.as_str() == LIST {
217 lists.push(one);
218 } else if *name == paragraph.name {
219 shown.extend(lw.lower_children(cx, &child)?);
220 } else {
221 shown.extend(lw.lower_nodes(cx, one)?);
222 }
223 }
224 let mut staged = match anchor {
225 Some(anchor) => {
226 let link = LinkPayload {
227 href: format!("#{anchor}"),
228 kind: Name::from(LINK_KIND),
229 doc_role: None,
230 label: None,
231 shows_target: true,
232 };
233 vec![lw.pres_with(cx, &ElementName::from(pres::LINK), link, shown)?]
234 }
235 None => shown,
236 };
237 for one in lists {
238 staged.extend(lw.lower_nodes(cx, one)?);
239 }
240 Ok(Lowering::Emit(staged))
241 }
242}
243
244fn number(counters: &Counters, point: crate::model::aspects::PointId) -> Result<Vec<crate::stdlib::features::numbering::NumberSegment>, LowerError> {
247 let options = FormatOptions::new().without_word().without_delimiters();
248 match counters.format(point, &options) {
249 None => Ok(Vec::new()),
250 Some(result) => result.map_err(|error| LowerError::structure(error.to_string())),
251 }
252}
253
254fn anchor(
259 node: &NodeRef<'_, Flm>,
260 point: crate::model::aspects::PointId,
261 lw: &mut dyn Lowerer,
262) -> Result<Option<String>, LowerError> {
263 let found: Option<Option<String>> = match lw.get(ANCHORS)? {
264 None => return Ok(None),
265 Some(anchors) => anchors.lookup(point).map(|entry| entry.map(String::from)),
266 };
267 match found {
268 Some(anchor) => Ok(anchor),
269 None => {
270 let table = CapName::from(ANCHORS.name());
271 let producer =
272 lw.producer_of(&table).map(|stage| stage.to_string()).unwrap_or_else(|| "nobody".to_string());
273 lw.diagnose(Diagnostic::error(
274 MissingEntry { table: table.to_string(), producer, element: ENTRY.to_string() },
275 node.span().clone(),
276 ));
277 Ok(None)
278 }
279 }
280}
281
282pub(super) fn decl() -> LoweringDecl {
286 LoweringDecl::new()
287 .reads_opt(COUNTERS)
288 .reads_opt(ANCHORS)
289 .produces(pres::BLOCK)
290 .produces(pres::LIST)
291 .produces(pres::SPAN)
292 .produces(pres::LINK)
293 .produces(pres::PAR)
294}
295
296fn declare_peers(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
302 b.peer_table::<Counters>(COUNTERS.name(), "the numbering feature's counter table: each entry's number")?;
303 b.peer_table::<Anchors>(ANCHORS.name(), "the references feature's anchors table: each entry's link target")?;
304 b.peer_element::<BlockPayload>(pres::BLOCK, "the table of contents")?;
305 b.peer_element::<ListPayload>(pres::LIST, "a list of entries of the table of contents")?;
306 b.peer_element::<SpanPayload>(pres::SPAN, "the number of an entry of the table of contents")?;
307 b.peer_element::<LinkPayload>(pres::LINK, "the link from an entry of the table of contents to its heading")?;
308 b.peer_element::<pres::ParPayload>(pres::PAR, "a paragraph inside an entry's title")
309}
310
311pub(super) fn declare(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
314 let owner = b.feature().clone();
315 let elements = [
316 (
317 PIECE,
318 "The table of contents: one list of entries.",
319 "The table of contents of the document, built from its headings.",
320 ),
321 (
322 LIST,
323 "A list of entries of the table of contents.",
324 "A list of entries of the table of contents: the headings of one level, under one \
325 heading or at the top.",
326 ),
327 (
328 ENTRY,
329 "One entry of the table of contents: the title, then the list of its sub-entries.",
330 "One entry of the table of contents: one heading's title, then the entries of the \
331 headings under it.",
332 ),
333 ];
334 for (name, docs, type_docs) in elements {
335 b.element_type_text(name, type_docs)?;
336 let role = Arc::new(FixedBlockRole(BlockRole::Block)) as Arc<dyn BlockRoleAspect>;
337 b.element(
338 ElementDef::new(
339 owner.clone(),
340 Vec::<&str>::new(),
341 SyntaxDef::Synthesized,
342 Arc::new(ElementSpec::new(name).docs(docs).with(role)),
343 )
344 .docs(format!("{docs} No document can write it: a stage builds it from the headings.")),
345 )?;
346 }
347 declare_peers(b)?;
348 let rules: [(&str, Arc<dyn Lower>, &str); 3] = [
349 (
350 PIECE,
351 Arc::new(RootRule),
352 "the table of contents lowers to a `flm.pres.block` of role `flm.toc` and document role \
353 `toc`, holding its list",
354 ),
355 (
356 LIST,
357 Arc::new(ListRule),
358 "a list of entries lowers to an unlabeled `flm.pres.list` of kinds `unnumbered` and `toc`",
359 ),
360 (
361 ENTRY,
362 Arc::new(EntryRule),
363 "an entry lowers to its number and its title inside a link to its heading, then its \
364 sub-list",
365 ),
366 ];
367 for (element, rule, docs) in rules {
368 b.lowering_rule(
369 LoweringRule::new(rule_name(element), element, decl(), rule, DefaultMark::Everywhere).docs(docs),
370 )?;
371 }
372 Ok(())
373}