use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef, NodeTree};
use techy::serialize::SerialValue;
use crate::core::data::store::StageOut;
use crate::core::data::table::TableHandle;
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::piece::{Piece, PieceDecl, PiecePlace};
use crate::core::plan::PlanCx;
use crate::core::registry::{BuildError, FeatureBuilder, FlmRegistry};
use crate::core::run::StageCx;
use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
use crate::lang::copy::{copy_pieces_into_value, SynthesizedPiece, ValueContent, ValuePiece};
use crate::lang::mint::{ElementDef, FlmSynthesizedSpec, SyntaxDef};
use crate::lang::{Flm, PresPayload};
use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
use crate::model::element::ElementSpec;
use crate::model::names::{ElementName, FeatureName, Name};
use crate::stdlib::backends::lowering::lower_blocks_with_edges;
use crate::stdlib::backends::pieces;
use crate::stdlib::backends::pres::{
self, BlockPayload, DocRole, DroppedPayload, HeadingPayload, ListPayload, SpanPayload, ITEM_SLOT,
LABEL_SLOT, LIST_LABELED, LIST_NUMBERED,
};
use crate::stdlib::features::numbering::{format_many, CounterValue, FormatOptions, NumberedValue};
use super::config::{CitationPlacement, MarkForm};
use super::entries::{CitationEntries, ENTRIES};
use super::mark::MarkSettings;
use super::numbers::{stage_failed, CitedWorks, CITATIONS};
use super::providers::CitationEntry;
pub const BIBLIOGRAPHY: &str = "flm.citations.bibliography";
pub const BIBLIOGRAPHY_ENTRY: &str = "flm.citations.bibliography.entry";
pub const BUILD_BIBLIOGRAPHY: &str = "flm.citations.build-bibliography";
pub const ENTRY_NUMBER_ROLE: &str = "flm.citations.entry.number";
pub const KIND_CITATIONS: &str = "citations";
pub const BIBLIOGRAPHY_RULE: &str = "flm.citations.bibliography.lower.default";
pub const BIBLIOGRAPHY_ENTRY_RULE: &str = "flm.citations.bibliography.entry.lower.default";
pub fn bibliography_table() -> TableHandle<Piece> {
TableHandle::new(BIBLIOGRAPHY)
}
#[derive(Debug, Clone, Copy)]
pub struct ListedWork<'w> {
pub key: &'w str,
pub number: usize,
pub identifier: &'w str,
pub entry: Option<&'w CitationEntry>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListedEntry {
pub key: String,
pub number: usize,
pub identifier: String,
pub missing: bool,
}
impl PresPayload for ListedEntry {
fn project(&self) -> SerialValue {
let mut entries = vec![
("key".to_string(), SerialValue::Str(self.key.clone())),
("number".to_string(), SerialValue::Int(self.number as i64)),
("id".to_string(), SerialValue::Str(self.identifier.clone())),
];
if self.missing {
entries.push(("missing".to_string(), SerialValue::Bool(true)));
}
SerialValue::Map(entries)
}
}
impl ListedEntry {
pub fn of<'n>(node: &'n NodeRef<'_, Flm>) -> Option<&'n ListedEntry> {
node.ext().payload.as_deref()?.downcast_ref::<ListedEntry>()
}
}
pub fn build_list(
works: &[ListedWork<'_>],
registry: &FlmRegistry,
anchor: &NodeRef<'_, Flm>,
) -> Result<Arc<NodeTree<Flm>>, String> {
let spec = |name: &str| match registry.element_value(name) {
Ok(Some(element)) => Ok(Arc::new(FlmSynthesizedSpec::new(Arc::clone(element)))),
Ok(None) => Err(format!("missing element ‘{name}’ in the registry")),
Err(error) => Err(error.to_string()),
};
let (list_spec, entry_spec) = (spec(BIBLIOGRAPHY)?, spec(BIBLIOGRAPHY_ENTRY)?);
let contents: Vec<Vec<NodeRef<'_, Flm>>> = works
.iter()
.map(|work| work.entry.map_or_else(Vec::new, |entry| entry.content.root().children().iter().collect()))
.collect();
let entries: Vec<SynthesizedPiece<'_, '_>> = works
.iter()
.zip(&contents)
.map(|(work, content)| SynthesizedPiece {
spec: Arc::clone(&entry_spec),
slot: pres::BODY_SLOT,
span: anchor.span().clone(),
state: Arc::clone(anchor.parsing_state()),
body: content.iter().copied().map(ValuePiece::Node).collect(),
payload: Some(Arc::new(ListedEntry {
key: work.key.to_string(),
number: work.number,
identifier: work.identifier.to_string(),
missing: work.entry.is_none(),
})),
})
.collect();
let list = SynthesizedPiece {
spec: list_spec,
slot: pres::BODY_SLOT,
span: anchor.span().clone(),
state: Arc::clone(anchor.parsing_state()),
body: entries.iter().map(ValuePiece::Synthesized).collect(),
payload: None,
};
copy_pieces_into_value(&[ValuePiece::Synthesized(&list)], anchor, ValueContent::Own, registry.lang().guard())
.map_err(|error| error.to_string())
}
#[derive(Debug)]
pub(super) struct BuildBibliography {
pub(super) placement: CitationPlacement,
}
impl BuildBibliography {
fn build(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) -> Option<Arc<NodeTree<Flm>>> {
if self.placement == CitationPlacement::InPlace {
return None;
}
let (citations, entries): (&CitedWorks, Option<&CitationEntries>) =
match (cx.get(CITATIONS), cx.get(ENTRIES)) {
(Ok(Some(citations)), Ok(entries)) => (citations, entries),
(Err(error), _) | (_, Err(error)) => {
stage_failed(out, BUILD_BIBLIOGRAPHY, error);
return None;
}
(Ok(None), _) => return None,
};
if citations.is_empty() {
return None;
}
let works: Vec<ListedWork<'_>> = citations
.works()
.map(|(key, work)| ListedWork {
key,
number: work.number,
identifier: &work.identifier,
entry: entries.and_then(|entries| entries.entry(key)),
})
.collect();
let (_, tree) = cx.trees().next()?;
match build_list(&works, cx.registry(), &tree.root()) {
Ok(value) => Some(value),
Err(detail) => {
stage_failed(out, BUILD_BIBLIOGRAPHY, detail);
None
}
}
}
}
impl Stage for BuildBibliography {
fn decl(&self) -> StageDecl {
StageDecl::new(BUILD_BIBLIOGRAPHY, Effect::Compute, Scope::Document)
.writes(bibliography_table())
.docs(
"Builds the list of the cited works, in the order of their numbers, each with its \
citation entry, into the piece `flm.citations.bibliography`.",
)
}
fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
Needs::new().reads(CITATIONS).reads(ENTRIES)
}
fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
let content = self.build(cx, out);
match out.table(&bibliography_table()) {
Ok(table) => *table = Piece { content },
Err(error) => stage_failed(out, BUILD_BIBLIOGRAPHY, error),
}
}
}
#[derive(Debug)]
pub struct BibliographyRule {
settings: Arc<MarkSettings>,
}
impl BibliographyRule {
fn label(&self, cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, number: usize) -> Result<BuildId, LowerError> {
let style = self.settings.style()?;
let value = CounterValue::new(number as i64);
let numbered = [NumberedValue::new(&value)];
let options = match self.settings.config().mark {
MarkForm::Bracketed => FormatOptions::new().without_word(),
MarkForm::Superscript => FormatOptions::new().without_word().without_delimiters(),
};
let segments = format_many(style, &numbered, &options)
.map_err(|error| LowerError::structure(error.to_string()))?;
let mut body = Vec::new();
for segment in &segments {
body.extend(lw.splice(cx, segment.content())?);
}
let payload = SpanPayload { role: Some(Name::from(ENTRY_NUMBER_ROLE)), ..SpanPayload::default() };
lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)
}
}
impl Lower for BibliographyRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let entries: Vec<NodeRef<'_, Flm>> = node
.children()
.iter()
.filter(|child| child.ext().element.name.as_str() == BIBLIOGRAPHY_ENTRY)
.collect();
let mut slots: Vec<(String, Vec<BuildId>)> = Vec::with_capacity(2 * entries.len());
let mut entry_anchors = Vec::with_capacity(entries.len());
for entry in &entries {
let Some(listed) = ListedEntry::of(entry) else { continue };
let label = self.label(cx, lw, listed.number)?;
let item = if listed.missing {
let dropped = DroppedPayload {
condition: Name::from("flm.citations.no-entry"),
detail: "bibliography entry".to_string(),
};
let mark = lw.pres_with(cx, &ElementName::from(pres::DROPPED), dropped, Vec::new())?;
lower_blocks_with_edges(cx, lw, &[], Vec::new(), vec![mark])?
} else {
let content: Vec<NodeRef<'_, Flm>> = entry.children().iter().collect();
lower_blocks_with_edges(cx, lw, &content, Vec::new(), Vec::new())?
};
slots.push((LABEL_SLOT.to_string(), vec![label]));
slots.push((ITEM_SLOT.to_string(), item));
entry_anchors.push(Some(listed.identifier.clone()));
}
let list = ListPayload {
kinds: vec![Name::from(LIST_NUMBERED), Name::from(KIND_CITATIONS), Name::from(LIST_LABELED)],
anchor: None,
entry_anchors,
entry_levels: Vec::new(),
};
let list = lw.pres_slots_with(cx, &ElementName::from(pres::LIST), list, slots)?;
let mut body = Vec::with_capacity(2);
if let Some(title) = self.settings.heading_title()? {
let title = lw.splice(cx, title)?;
let level = self.settings.config().heading_level;
let heading =
HeadingPayload { name: Name::from(KIND_CITATIONS), level, in_toc: false, anchor: None, number: None };
body.push(lw.pres_with(cx, &ElementName::from(pres::BLOCK_HEADING), heading, title)?);
}
body.push(list);
let block = BlockPayload {
role: Some(Name::from(BIBLIOGRAPHY)),
kinds: vec![Name::from(KIND_CITATIONS)],
anchor: None,
doc_role: Some(DocRole::Bibliography),
};
Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block, body)?]))
}
}
#[derive(Debug, Default)]
struct EntryOutsideList;
impl Lower for EntryOutsideList {
fn lower(
&self,
_node: NodeRef<'_, Flm>,
_cx: &mut LowerCx<'_>,
_lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
Err(LowerError::structure("an entry of a list of cited works must be inside its list"))
}
}
pub(super) fn declare(
b: &mut FeatureBuilder<'_>,
owner: &FeatureName,
settings: &Arc<MarkSettings>,
) -> Result<(), BuildError> {
let block = || Arc::new(FixedBlockRole(BlockRole::Block)) as Arc<dyn BlockRoleAspect>;
b.element(
ElementDef::new(
owner.clone(),
Vec::<&str>::new(),
SyntaxDef::Synthesized,
Arc::new(ElementSpec::new(BIBLIOGRAPHY).docs("A list of cited works.").with(block())),
)
.docs("A list of cited works. An author never writes it: a stage builds it."),
)?;
b.element(
ElementDef::new(
owner.clone(),
Vec::<&str>::new(),
SyntaxDef::Synthesized,
Arc::new(ElementSpec::new(BIBLIOGRAPHY_ENTRY).docs("One entry of a list of cited works.").with(block())),
)
.docs("One entry of a list of cited works. An author never writes it: a stage builds it."),
)?;
b.element_type_text(BIBLIOGRAPHY, "The list of the works a document cites, one entry per work.")?;
b.element_type_text(
BIBLIOGRAPHY_ENTRY,
"One entry of the list of cited works: the mark of one work and its reference.",
)?;
b.lowering_rule(
LoweringRule::new(
BIBLIOGRAPHY_RULE,
BIBLIOGRAPHY,
LoweringDecl::new()
.produces(pres::BLOCK)
.produces(pres::BLOCK_HEADING)
.produces(pres::LIST)
.produces(pres::SPAN)
.produces(pres::PAR)
.produces(pres::DROPPED),
Arc::new(BibliographyRule { settings: Arc::clone(settings) }),
DefaultMark::Everywhere,
)
.docs(
"a list of cited works lowers to a `flm.pres.block` holding the title as a \
`flm.pres.block-heading` and a labeled `flm.pres.list` with one entry per work, its \
number as the label",
),
)?;
b.lowering_rule(
LoweringRule::new(
BIBLIOGRAPHY_ENTRY_RULE,
BIBLIOGRAPHY_ENTRY,
LoweringDecl::new(),
Arc::new(EntryOutsideList),
DefaultMark::Everywhere,
)
.docs("an entry of a list of cited works is lowered by its list's rule; lowered on its own, it fails"),
)?;
b.table_named::<Piece>(
BIBLIOGRAPHY,
"The list of the cited works of the document, as a synthesized value, or nothing to place.",
)?;
b.stage(Arc::new(BuildBibliography { placement: settings.config().placement }))?;
b.peer_slot(
pieces::SLOT,
Arc::new(PieceDecl::new(
BIBLIOGRAPHY,
PiecePlace::AfterContent,
"the list of the cited works, placed after the document's content",
)),
)?;
Ok(())
}