use std::sync::{Arc, OnceLock};
use techy::core::node::{BuildId, NodeRef, NodeTree};
use crate::core::lowering::{
chars_at_lowering, DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl,
LoweringRule,
};
use crate::core::registry::{LateInit, LateInitError};
use crate::lang::rewrites::userdefs::template::{PlaceholderVocabulary, TemplateLanguage};
use crate::lang::text::is_space;
use crate::lang::{BuiltLang, Flm, FlmDiagnostics, FlmSpan};
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::lowering::stage_trimmed;
use crate::stdlib::backends::pres::{
self, DocRole, DroppedPayload, LinkPayload, SpanPayload, SpanStyle, spelling_identity,
};
use crate::stdlib::features::numbering::{
compile_text, format_many, instantiate_fixed, CounterStyle, CounterValue, FormatOptions,
JoinText, NumberedValue,
};
use super::config::{CitationPlacement, CitationsConfig, MarkForm, CAPITAL_VARIANT};
use super::diagnostics::{NoCitation, NoKey, Uncollected, UnknownFlag};
use super::html::STYLE;
use super::elements::{
leading_call, read_chunk, Chunk, ChunkMistake, Reading, CITE, FLAGS_ARG,
REFCITE,
};
use super::entries::{CitationEntries, ENTRIES};
use super::numbers::{CitedWorks, CITATIONS};
pub const MARK_ROLE: &str = "flm.citations.mark";
pub const WORD_ROLE: &str = "flm.citations.word";
pub const SPACE_ROLE: &str = "flm.citations.space";
pub const ATTACHED: &str = "attached";
pub const STANDALONE: &str = "standalone";
pub const IN_PLACE: &str = "in-place";
pub const LINK_KIND: &str = "cite";
pub const CITE_RULE: &str = "flm.citations.cite.lower.default";
pub const REFCITE_RULE: &str = "flm.citations.refcite.lower.default";
pub const CAPITAL_FLAG: char = 'S';
pub const INLINE_FLAG: char = 'I';
pub const NO_BREAK_SPACE: &str = "\u{a0}";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Standing {
Attached,
Standalone,
}
impl Standing {
pub fn kind_token(self) -> &'static str {
match self {
Standing::Attached => ATTACHED,
Standing::Standalone => STANDALONE,
}
}
}
#[derive(Debug)]
pub struct MarkSettings {
config: CitationsConfig,
compiled: OnceLock<Compiled>,
}
struct Compiled {
style: CounterStyle,
separator: Arc<NodeTree<Flm>>,
title: Option<Arc<NodeTree<Flm>>>,
}
impl std::fmt::Debug for Compiled {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Compiled").field("style", &self.style).finish_non_exhaustive()
}
}
impl MarkSettings {
pub(super) fn new(config: CitationsConfig) -> MarkSettings {
MarkSettings { config, compiled: OnceLock::new() }
}
pub fn config(&self) -> &CitationsConfig {
&self.config
}
fn compiled(&self) -> Result<&Compiled, LowerError> {
self.compiled
.get()
.ok_or_else(|| LowerError::structure("the citation settings were not compiled"))
}
pub fn style(&self) -> Result<&CounterStyle, LowerError> {
Ok(&self.compiled()?.style)
}
pub fn heading_title(&self) -> Result<Option<&Arc<NodeTree<Flm>>>, LowerError> {
Ok(self.compiled()?.title.as_ref())
}
}
pub(super) struct CompileSettings {
pub(super) settings: Arc<MarkSettings>,
}
fn compile_fixed(lang: &BuiltLang, text: &str, what: &str) -> Result<Arc<NodeTree<Flm>>, LateInitError> {
let failed = |error: &dyn std::fmt::Display| LateInitError::new(format!("{what} is set to `{text}`, which is not valid FLM text: {error}"));
let language = TemplateLanguage::new(lang).map_err(|errors| {
failed(&errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "))
})?;
let template = compile_text(text, what, &PlaceholderVocabulary::new(0), lang, &language)
.map_err(|error| failed(&error))?;
instantiate_fixed(&template).map_err(|error| failed(&error))
}
impl LateInit for CompileSettings {
fn late_init(&self, lang: &BuiltLang, _diags: &mut FlmDiagnostics) -> Result<(), LateInitError> {
let config = &self.settings.config;
let style = config.style.compile(lang).map_err(|error| {
LateInitError::new(format!("the option `style` of the feature `citations` is not a valid counter style: {error}"))
})?;
let separator = compile_fixed(lang, &config.note_separator, "the option `note_separator` of the feature `citations`")?;
let title = config
.heading_title
.as_deref()
.map(|title| compile_fixed(lang, title, "the option `heading_title` of the feature `citations`"))
.transpose()?;
let _ = self.settings.compiled.set(Compiled { style, separator, title });
Ok(())
}
}
pub fn space_before(config: &CitationsConfig) -> Option<&'static str> {
match (config.placement, config.mark) {
(CitationPlacement::InPlace, _) | (CitationPlacement::Listed, MarkForm::Bracketed) => {
Some(NO_BREAK_SPACE)
}
(CitationPlacement::Listed, MarkForm::Superscript) => None,
}
}
#[derive(Debug, Clone)]
pub struct StagedMark {
pub node: BuildId,
pub shown: usize,
}
struct Group<'t> {
identity: Option<String>,
note: Option<Vec<NodeRef<'t, Flm>>>,
works: Vec<(usize, String)>,
}
pub fn report_mistakes(lw: &mut dyn Lowerer, chunk: &Chunk<'_>) {
for mistake in &chunk.mistakes {
match mistake {
ChunkMistake::NoKey { span } => lw.error(NoKey, span.clone()),
}
}
}
pub fn stage_mark(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
chunk: &Chunk<'_>,
settings: &MarkSettings,
standing: Standing,
span: &FlmSpan,
) -> Result<StagedMark, LowerError> {
let compiled = settings.compiled()?;
let form = settings.config.mark;
let found: Vec<Option<(usize, String)>> = {
let citations: Option<&CitedWorks> = lw.get(CITATIONS)?;
chunk
.items
.iter()
.map(|item| {
let work = citations?.work(&item.key)?;
Some((work.number, work.identifier.clone()))
})
.collect()
};
let mut groups: Vec<Group<'_>> = vec![Group { identity: None, note: None, works: Vec::new() }];
let mut uncollected = false;
for (item, work) in chunk.items.iter().zip(found) {
let Some(work) = work else {
lw.error(Uncollected { key: item.key.clone() }, span.clone());
uncollected = true;
continue;
};
let identity = item.note.as_ref().map(|note| spelling_identity(note.iter().copied()));
let at = match groups.iter().position(|group| group.identity == identity) {
Some(at) => at,
None => {
groups.push(Group { identity, note: item.note.clone(), works: Vec::new() });
groups.len() - 1
}
};
if !groups[at].works.iter().any(|(number, _)| *number == work.0) {
groups[at].works.push(work);
}
}
groups.retain(|group| !group.works.is_empty());
let shown: usize = groups.iter().map(|group| group.works.len()).sum();
if shown == 0 {
let node = stage_dropped(cx, lw, chunk, uncollected)?;
return Ok(StagedMark { node, shown: 0 });
}
let style = &compiled.style;
if settings.config.placement == CitationPlacement::InPlace {
return stage_in_place(cx, lw, chunk, compiled, standing, shown);
}
let delimited = form == MarkForm::Bracketed;
let mut children = Vec::new();
for (index, group) in groups.iter().enumerate() {
if index > 0 && !delimited {
children.extend(lw.splice(cx, style.join().text(JoinText::ListMid))?);
}
if delimited {
children.extend(lw.splice(cx, style.open())?);
}
children.extend(stage_numbers(cx, lw, style, &group.works)?);
if let Some(note) = &group.note {
children.extend(lw.splice(cx, &compiled.separator)?);
children.extend(stage_trimmed(cx, lw, note, |_| false)?);
}
if delimited {
children.extend(lw.splice(cx, style.close())?);
}
}
let raised = form == MarkForm::Superscript && standing == Standing::Attached;
let payload = SpanPayload {
style: raised.then_some(SpanStyle::Superscript),
role: Some(Name::from(MARK_ROLE)),
kinds: vec![Name::from(standing.kind_token())],
..SpanPayload::default()
};
let node = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, children)?;
Ok(StagedMark { node, shown })
}
pub(super) fn stage_dropped(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
chunk: &Chunk<'_>,
uncollected: bool,
) -> Result<BuildId, LowerError> {
let condition = if uncollected {
"flm.citations.uncollected"
} else {
match chunk.mistakes.first() {
Some(ChunkMistake::NoKey { .. }) => "flm.citations.no-key",
None => "flm.citations.no-citation",
}
};
let mark = DroppedPayload { condition: Name::from(condition), detail: "citation".to_string() };
lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())
}
type Note<'t> = Option<Vec<NodeRef<'t, Flm>>>;
fn stage_in_place(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
chunk: &Chunk<'_>,
compiled: &Compiled,
standing: Standing,
shown: usize,
) -> Result<StagedMark, LowerError> {
let items: Vec<(Option<Arc<NodeTree<Flm>>>, &Note<'_>)> = {
let citations: Option<&CitedWorks> = lw.get(CITATIONS)?;
let entries: Option<&CitationEntries> = lw.get(ENTRIES)?;
chunk
.items
.iter()
.filter(|item| citations.is_some_and(|citations| citations.work(&item.key).is_some()))
.map(|item| {
let entry = entries.and_then(|entries| entries.entry(&item.key));
(entry.map(|entry| Arc::clone(&entry.content)), &item.note)
})
.collect()
};
let style = &compiled.style;
let mut children = Vec::new();
for (entry, note) in items {
children.extend(lw.splice(cx, style.open())?);
match entry {
Some(content) => children.extend(lw.splice(cx, &content)?),
None => {
let mark = DroppedPayload {
condition: Name::from("flm.citations.no-entry"),
detail: "bibliography entry".to_string(),
};
children.push(lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())?);
}
}
if let Some(note) = note {
children.extend(lw.splice(cx, &compiled.separator)?);
children.extend(stage_trimmed(cx, lw, note, |_| false)?);
}
children.extend(lw.splice(cx, style.close())?);
}
let payload = SpanPayload {
role: Some(Name::from(MARK_ROLE)),
kinds: vec![Name::from(standing.kind_token()), Name::from(IN_PLACE)],
..SpanPayload::default()
};
let node = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, children)?;
Ok(StagedMark { node, shown })
}
fn stage_numbers(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
style: &CounterStyle,
works: &[(usize, String)],
) -> Result<Vec<BuildId>, LowerError> {
let values: Vec<CounterValue> =
works.iter().map(|(number, _)| CounterValue::new(*number as i64)).collect();
let numbered: Vec<NumberedValue<'_>> = values.iter().map(NumberedValue::new).collect();
let options = FormatOptions::new().without_word().without_delimiters();
let segments = format_many(style, &numbered, &options)
.map_err(|error| LowerError::structure(error.to_string()))?;
let mut staged = Vec::new();
for segment in &segments {
let body = lw.splice(cx, segment.content())?;
match segment.link().and_then(|position| works.get(position)) {
Some((_, identifier)) => {
let payload = LinkPayload {
href: format!("#{identifier}"),
kind: Name::from(LINK_KIND),
doc_role: Some(DocRole::BiblioRef),
label: None,
shows_target: false,
};
staged.push(lw.pres_with(cx, &ElementName::from(pres::LINK), payload, body)?);
}
None => staged.extend(body),
}
}
Ok(staged)
}
pub(super) struct Flags {
pub(super) capital: bool,
pub(super) word: bool,
}
pub(super) fn read_flags(node: &NodeRef<'_, Flm>, lw: &mut dyn Lowerer) -> Result<Flags, LowerError> {
let mut flags = Flags { capital: false, word: true };
let Ok(Some(content)) = node.argument_content_nodes_named(FLAGS_ARG) else {
return Ok(flags);
};
let text = match chars_at_lowering(content.iter())? {
Ok(text) => text,
Err(_) => {
let flag = crate::lang::text::plain_text_of(content.iter());
lw.error(UnknownFlag { flag }, node.span().clone());
return Ok(flags);
}
};
for flag in text.chars().filter(|flag| !is_space(*flag)) {
match flag {
CAPITAL_FLAG => flags.capital = true,
INLINE_FLAG => flags.word = false,
other => lw.error(UnknownFlag { flag: other.to_string() }, node.span().clone()),
}
}
Ok(flags)
}
#[derive(Debug)]
pub struct CiteRule {
settings: Arc<MarkSettings>,
}
impl CiteRule {
pub(super) fn new(settings: &Arc<MarkSettings>) -> CiteRule {
CiteRule { settings: Arc::clone(settings) }
}
}
impl Lower for CiteRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
lw.require(&Name::from(STYLE));
let chunk = read_chunk(&node, Reading::AtLowering)?;
report_mistakes(lw, &chunk);
let mut out = Vec::with_capacity(2);
if let Some(space) = space_before(&self.settings.config) {
let body = vec![lw.text(cx, space)?];
let payload = SpanPayload { role: Some(Name::from(SPACE_ROLE)), ..SpanPayload::default() };
out.push(lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?);
}
let mark = stage_mark(cx, lw, &chunk, &self.settings, Standing::Attached, node.span())?;
out.push(mark.node);
Ok(Lowering::Emit(out))
}
}
#[derive(Debug)]
pub struct RefCiteRule {
settings: Arc<MarkSettings>,
}
impl RefCiteRule {
pub(super) fn new(settings: &Arc<MarkSettings>) -> RefCiteRule {
RefCiteRule { settings: Arc::clone(settings) }
}
}
impl Lower for RefCiteRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
lw.require(&Name::from(STYLE));
let flags = read_flags(&node, lw)?;
if leading_call(&node).is_none() {
lw.error(NoCitation, node.span().clone());
}
let chunk = read_chunk(&node, Reading::AtLowering)?;
report_mistakes(lw, &chunk);
let mark = stage_mark(cx, lw, &chunk, &self.settings, Standing::Standalone, node.span())?;
let mut out = Vec::with_capacity(2);
if flags.word && mark.shown > 0 {
let variant = flags.capital.then_some(CAPITAL_VARIANT);
let style = self.settings.style()?;
if let Some(word) = style.word_text(mark.shown, variant) {
let body = lw.splice(cx, word)?;
let payload = SpanPayload { role: Some(Name::from(WORD_ROLE)), ..SpanPayload::default() };
out.push(lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?);
}
}
out.push(mark.node);
Ok(Lowering::Emit(out))
}
}
pub(super) fn decl() -> LoweringDecl {
LoweringDecl::new()
.reads(CITATIONS)
.reads(ENTRIES)
.produces(pres::SPAN)
.produces(pres::LINK)
.produces(pres::DROPPED)
}
pub(super) fn rules(settings: &Arc<MarkSettings>) -> Vec<LoweringRule> {
vec![
LoweringRule::new(
CITE_RULE,
CITE,
decl(),
Arc::new(CiteRule::new(settings)),
DefaultMark::Everywhere,
)
.docs(
"a citation chunk lowers to the space its form calls for and a `flm.pres.span` of \
role `flm.citations.mark`, kind token `attached`, holding its numbers as links of kind \
`cite`",
),
LoweringRule::new(
REFCITE_RULE,
REFCITE,
decl(),
Arc::new(RefCiteRule::new(settings)),
DefaultMark::Everywhere,
)
.docs(
"a citation chunk written with `\\R` lowers to the citation counter style's word in a \
`flm.pres.span` of role `flm.citations.word`, then the citation mark, kind token \
`standalone`, shown inline",
),
]
}