1use std::sync::Arc;
18
19use techy::core::node::{BuildId, NodeRef, NodeTree};
20use techy::serialize::SerialValue;
21
22use crate::core::data::store::StageOut;
23use crate::core::data::table::TableHandle;
24use crate::core::lowering::{
25 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
26};
27use crate::core::piece::{Piece, PieceDecl, PiecePlace};
28use crate::core::plan::PlanCx;
29use crate::core::registry::{BuildError, FeatureBuilder, FlmRegistry};
30use crate::core::run::StageCx;
31use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
32use crate::lang::copy::{copy_pieces_into_value, SynthesizedPiece, ValueContent, ValuePiece};
33use crate::lang::mint::{ElementDef, FlmSynthesizedSpec, SyntaxDef};
34use crate::lang::{Flm, PresPayload};
35use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
36use crate::model::element::ElementSpec;
37use crate::model::names::{ElementName, FeatureName, Name};
38use crate::stdlib::backends::lowering::lower_blocks_with_edges;
39use crate::stdlib::backends::pieces;
40use crate::stdlib::backends::pres::{
41 self, BlockPayload, DocRole, DroppedPayload, HeadingPayload, ListPayload, SpanPayload, ITEM_SLOT,
42 LABEL_SLOT, LIST_LABELED, LIST_NUMBERED,
43};
44use crate::stdlib::features::numbering::{format_many, CounterValue, FormatOptions, NumberedValue};
45
46use super::config::{CitationPlacement, MarkForm};
47use super::entries::{CitationEntries, ENTRIES};
48use super::mark::MarkSettings;
49use super::numbers::{stage_failed, CitedWorks, CITATIONS};
50use super::providers::CitationEntry;
51
52pub const BIBLIOGRAPHY: &str = "flm.citations.bibliography";
57
58pub const BIBLIOGRAPHY_ENTRY: &str = "flm.citations.bibliography.entry";
62
63pub const BUILD_BIBLIOGRAPHY: &str = "flm.citations.build-bibliography";
67
68pub const ENTRY_NUMBER_ROLE: &str = "flm.citations.entry.number";
72
73pub const KIND_CITATIONS: &str = "citations";
77
78pub const BIBLIOGRAPHY_RULE: &str = "flm.citations.bibliography.lower.default";
82
83pub const BIBLIOGRAPHY_ENTRY_RULE: &str = "flm.citations.bibliography.entry.lower.default";
88
89pub fn bibliography_table() -> TableHandle<Piece> {
92 TableHandle::new(BIBLIOGRAPHY)
93}
94
95#[derive(Debug, Clone, Copy)]
99pub struct ListedWork<'w> {
100 pub key: &'w str,
102 pub number: usize,
104 pub identifier: &'w str,
106 pub entry: Option<&'w CitationEntry>,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct ListedEntry {
116 pub key: String,
118 pub number: usize,
120 pub identifier: String,
122 pub missing: bool,
124}
125
126impl PresPayload for ListedEntry {
127 fn project(&self) -> SerialValue {
128 let mut entries = vec![
129 ("key".to_string(), SerialValue::Str(self.key.clone())),
130 ("number".to_string(), SerialValue::Int(self.number as i64)),
131 ("id".to_string(), SerialValue::Str(self.identifier.clone())),
132 ];
133 if self.missing {
134 entries.push(("missing".to_string(), SerialValue::Bool(true)));
135 }
136 SerialValue::Map(entries)
137 }
138}
139
140impl ListedEntry {
141 pub fn of<'n>(node: &'n NodeRef<'_, Flm>) -> Option<&'n ListedEntry> {
144 node.ext().payload.as_deref()?.downcast_ref::<ListedEntry>()
145 }
146}
147
148pub fn build_list(
176 works: &[ListedWork<'_>],
177 registry: &FlmRegistry,
178 anchor: &NodeRef<'_, Flm>,
179) -> Result<Arc<NodeTree<Flm>>, String> {
180 let spec = |name: &str| match registry.element_value(name) {
181 Ok(Some(element)) => Ok(Arc::new(FlmSynthesizedSpec::new(Arc::clone(element)))),
182 Ok(None) => Err(format!("missing element ‘{name}’ in the registry")),
183 Err(error) => Err(error.to_string()),
184 };
185 let (list_spec, entry_spec) = (spec(BIBLIOGRAPHY)?, spec(BIBLIOGRAPHY_ENTRY)?);
186 let contents: Vec<Vec<NodeRef<'_, Flm>>> = works
187 .iter()
188 .map(|work| work.entry.map_or_else(Vec::new, |entry| entry.content.root().children().iter().collect()))
189 .collect();
190 let entries: Vec<SynthesizedPiece<'_, '_>> = works
191 .iter()
192 .zip(&contents)
193 .map(|(work, content)| SynthesizedPiece {
194 spec: Arc::clone(&entry_spec),
195 slot: pres::BODY_SLOT,
196 span: anchor.span().clone(),
197 state: Arc::clone(anchor.parsing_state()),
198 body: content.iter().copied().map(ValuePiece::Node).collect(),
199 payload: Some(Arc::new(ListedEntry {
200 key: work.key.to_string(),
201 number: work.number,
202 identifier: work.identifier.to_string(),
203 missing: work.entry.is_none(),
204 })),
205 })
206 .collect();
207 let list = SynthesizedPiece {
208 spec: list_spec,
209 slot: pres::BODY_SLOT,
210 span: anchor.span().clone(),
211 state: Arc::clone(anchor.parsing_state()),
212 body: entries.iter().map(ValuePiece::Synthesized).collect(),
213 payload: None,
214 };
215 copy_pieces_into_value(&[ValuePiece::Synthesized(&list)], anchor, ValueContent::Own, registry.lang().guard())
216 .map_err(|error| error.to_string())
217}
218
219#[derive(Debug)]
228pub(super) struct BuildBibliography {
229 pub(super) placement: CitationPlacement,
230}
231
232impl BuildBibliography {
233 fn build(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) -> Option<Arc<NodeTree<Flm>>> {
236 if self.placement == CitationPlacement::InPlace {
237 return None;
238 }
239 let (citations, entries): (&CitedWorks, Option<&CitationEntries>) =
240 match (cx.get(CITATIONS), cx.get(ENTRIES)) {
241 (Ok(Some(citations)), Ok(entries)) => (citations, entries),
242 (Err(error), _) | (_, Err(error)) => {
243 stage_failed(out, BUILD_BIBLIOGRAPHY, error);
244 return None;
245 }
246 (Ok(None), _) => return None,
247 };
248 if citations.is_empty() {
249 return None;
250 }
251 let works: Vec<ListedWork<'_>> = citations
252 .works()
253 .map(|(key, work)| ListedWork {
254 key,
255 number: work.number,
256 identifier: &work.identifier,
257 entry: entries.and_then(|entries| entries.entry(key)),
258 })
259 .collect();
260 let (_, tree) = cx.trees().next()?;
263 match build_list(&works, cx.registry(), &tree.root()) {
264 Ok(value) => Some(value),
265 Err(detail) => {
266 stage_failed(out, BUILD_BIBLIOGRAPHY, detail);
267 None
268 }
269 }
270 }
271}
272
273impl Stage for BuildBibliography {
274 fn decl(&self) -> StageDecl {
275 StageDecl::new(BUILD_BIBLIOGRAPHY, Effect::Compute, Scope::Document)
276 .writes(bibliography_table())
277 .docs(
278 "Builds the list of the cited works, in the order of their numbers, each with its \
279 citation entry, into the piece `flm.citations.bibliography`.",
280 )
281 }
282
283 fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
284 Needs::new().reads(CITATIONS).reads(ENTRIES)
285 }
286
287 fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
288 let content = self.build(cx, out);
289 match out.table(&bibliography_table()) {
290 Ok(table) => *table = Piece { content },
291 Err(error) => stage_failed(out, BUILD_BIBLIOGRAPHY, error),
292 }
293 }
294}
295
296#[derive(Debug)]
331pub struct BibliographyRule {
332 settings: Arc<MarkSettings>,
333}
334
335impl BibliographyRule {
336 fn label(&self, cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, number: usize) -> Result<BuildId, LowerError> {
338 let style = self.settings.style()?;
339 let value = CounterValue::new(number as i64);
340 let numbered = [NumberedValue::new(&value)];
341 let options = match self.settings.config().mark {
342 MarkForm::Bracketed => FormatOptions::new().without_word(),
343 MarkForm::Superscript => FormatOptions::new().without_word().without_delimiters(),
344 };
345 let segments = format_many(style, &numbered, &options)
346 .map_err(|error| LowerError::structure(error.to_string()))?;
347 let mut body = Vec::new();
348 for segment in &segments {
349 body.extend(lw.splice(cx, segment.content())?);
350 }
351 let payload = SpanPayload { role: Some(Name::from(ENTRY_NUMBER_ROLE)), ..SpanPayload::default() };
352 lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)
353 }
354}
355
356impl Lower for BibliographyRule {
357 fn lower(
358 &self,
359 node: NodeRef<'_, Flm>,
360 cx: &mut LowerCx<'_>,
361 lw: &mut dyn Lowerer,
362 ) -> Result<Lowering, LowerError> {
363 let entries: Vec<NodeRef<'_, Flm>> = node
364 .children()
365 .iter()
366 .filter(|child| child.ext().element.name.as_str() == BIBLIOGRAPHY_ENTRY)
367 .collect();
368 let mut slots: Vec<(String, Vec<BuildId>)> = Vec::with_capacity(2 * entries.len());
369 let mut entry_anchors = Vec::with_capacity(entries.len());
370 for entry in &entries {
371 let Some(listed) = ListedEntry::of(entry) else { continue };
372 let label = self.label(cx, lw, listed.number)?;
373 let item = if listed.missing {
374 let dropped = DroppedPayload {
375 condition: Name::from("flm.citations.no-entry"),
376 detail: "bibliography entry".to_string(),
377 };
378 let mark = lw.pres_with(cx, &ElementName::from(pres::DROPPED), dropped, Vec::new())?;
379 lower_blocks_with_edges(cx, lw, &[], Vec::new(), vec![mark])?
380 } else {
381 let content: Vec<NodeRef<'_, Flm>> = entry.children().iter().collect();
382 lower_blocks_with_edges(cx, lw, &content, Vec::new(), Vec::new())?
383 };
384 slots.push((LABEL_SLOT.to_string(), vec![label]));
385 slots.push((ITEM_SLOT.to_string(), item));
386 entry_anchors.push(Some(listed.identifier.clone()));
387 }
388 let list = ListPayload {
389 kinds: vec![Name::from(LIST_NUMBERED), Name::from(KIND_CITATIONS), Name::from(LIST_LABELED)],
390 anchor: None,
391 entry_anchors,
392 entry_levels: Vec::new(),
393 };
394 let list = lw.pres_slots_with(cx, &ElementName::from(pres::LIST), list, slots)?;
395 let mut body = Vec::with_capacity(2);
396 if let Some(title) = self.settings.heading_title()? {
397 let title = lw.splice(cx, title)?;
398 let level = self.settings.config().heading_level;
399 let heading =
400 HeadingPayload { name: Name::from(KIND_CITATIONS), level, in_toc: false, anchor: None, number: None };
401 body.push(lw.pres_with(cx, &ElementName::from(pres::BLOCK_HEADING), heading, title)?);
402 }
403 body.push(list);
404 let block = BlockPayload {
405 role: Some(Name::from(BIBLIOGRAPHY)),
406 kinds: vec![Name::from(KIND_CITATIONS)],
407 anchor: None,
408 doc_role: Some(DocRole::Bibliography),
409 };
410 Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block, body)?]))
411 }
412}
413
414#[derive(Debug, Default)]
419struct EntryOutsideList;
420
421impl Lower for EntryOutsideList {
422 fn lower(
423 &self,
424 _node: NodeRef<'_, Flm>,
425 _cx: &mut LowerCx<'_>,
426 _lw: &mut dyn Lowerer,
427 ) -> Result<Lowering, LowerError> {
428 Err(LowerError::structure("an entry of a list of cited works must be inside its list"))
429 }
430}
431
432pub(super) fn declare(
439 b: &mut FeatureBuilder<'_>,
440 owner: &FeatureName,
441 settings: &Arc<MarkSettings>,
442) -> Result<(), BuildError> {
443 let block = || Arc::new(FixedBlockRole(BlockRole::Block)) as Arc<dyn BlockRoleAspect>;
444 b.element(
445 ElementDef::new(
446 owner.clone(),
447 Vec::<&str>::new(),
448 SyntaxDef::Synthesized,
449 Arc::new(ElementSpec::new(BIBLIOGRAPHY).docs("A list of cited works.").with(block())),
450 )
451 .docs("A list of cited works. An author never writes it: a stage builds it."),
452 )?;
453 b.element(
454 ElementDef::new(
455 owner.clone(),
456 Vec::<&str>::new(),
457 SyntaxDef::Synthesized,
458 Arc::new(ElementSpec::new(BIBLIOGRAPHY_ENTRY).docs("One entry of a list of cited works.").with(block())),
459 )
460 .docs("One entry of a list of cited works. An author never writes it: a stage builds it."),
461 )?;
462 b.element_type_text(BIBLIOGRAPHY, "The list of the works a document cites, one entry per work.")?;
463 b.element_type_text(
464 BIBLIOGRAPHY_ENTRY,
465 "One entry of the list of cited works: the mark of one work and its reference.",
466 )?;
467 b.lowering_rule(
468 LoweringRule::new(
469 BIBLIOGRAPHY_RULE,
470 BIBLIOGRAPHY,
471 LoweringDecl::new()
472 .produces(pres::BLOCK)
473 .produces(pres::BLOCK_HEADING)
474 .produces(pres::LIST)
475 .produces(pres::SPAN)
476 .produces(pres::PAR)
477 .produces(pres::DROPPED),
478 Arc::new(BibliographyRule { settings: Arc::clone(settings) }),
479 DefaultMark::Everywhere,
480 )
481 .docs(
482 "a list of cited works lowers to a `flm.pres.block` holding the title as a \
483 `flm.pres.block-heading` and a labeled `flm.pres.list` with one entry per work, its \
484 number as the label",
485 ),
486 )?;
487 b.lowering_rule(
488 LoweringRule::new(
489 BIBLIOGRAPHY_ENTRY_RULE,
490 BIBLIOGRAPHY_ENTRY,
491 LoweringDecl::new(),
492 Arc::new(EntryOutsideList),
493 DefaultMark::Everywhere,
494 )
495 .docs("an entry of a list of cited works is lowered by its list's rule; lowered on its own, it fails"),
496 )?;
497 b.table_named::<Piece>(
498 BIBLIOGRAPHY,
499 "The list of the cited works of the document, as a synthesized value, or nothing to place.",
500 )?;
501 b.stage(Arc::new(BuildBibliography { placement: settings.config().placement }))?;
502 b.peer_slot(
505 pieces::SLOT,
506 Arc::new(PieceDecl::new(
507 BIBLIOGRAPHY,
508 PiecePlace::AfterContent,
509 "the list of the cited works, placed after the document's content",
510 )),
511 )?;
512 Ok(())
513}