use std::sync::{Arc, LazyLock};
use techy::core::node::NodeRef;
use techy::extract::split_at_chars_drop_annotations;
use crate::core::lowering::{spelling_at_lowering, LowerError};
use crate::lang::mint::{is_field_named, ArgDef, ArgStdKind, TackOnField};
use crate::lang::{Flm, FlmSpan};
use crate::model::aspects::{
ApartFromText, BlockRole, BlockRoleAspect, ContentRef, FixedBlockRole, InlineSpacing,
};
use crate::model::element::{element_value, ElementSpec};
use crate::stdlib::backends::pres::spelling_identity;
pub const CITE: &str = "flm.citations.cite";
pub const REFCITE: &str = "flm.citations.refcite";
pub const NOTE_ARG: &str = "note";
pub const KEYS_ARG: &str = "keys";
pub const KEY_ARG_ROLE: &str = "flm.citations.key";
pub const MORE_ARG: &str = "more";
pub const CITE_FIELD: &str = "cite";
pub const FLAGS_ARG: &str = "flags";
pub const CITATION_ARG: &str = "citation";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CitationElement {
Cite,
RefCite,
}
impl ApartFromText for CitationElement {
fn apart_from_text(&self, node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
let mut apart: Vec<ContentRef> = calls(node)
.iter()
.filter_map(|call| call.argument_content_nodes_named(KEYS_ARG).ok().flatten())
.flat_map(|keys| keys.iter().map(|key| ContentRef::Node(key.id())).collect::<Vec<_>>())
.collect();
if *self == CitationElement::RefCite {
apart.push(ContentRef::ArgumentNamed(FLAGS_ARG.to_string()));
}
apart
}
}
fn call_args() -> Vec<ArgDef> {
vec![
ArgDef::named(NOTE_ARG, ArgStdKind::Optional)
.docs("A note shown after the numbers, `[1; Thm 4]`; it belongs to every citation key of the call."),
ArgDef::named(KEYS_ARG, ArgStdKind::Mandatory)
.docs(
"The citation keys of the cited works, separated by commas; a citation key is FLM code, kept as typed, and a comma inside braces belongs to it.",
)
.role(KEY_ARG_ROLE)
.with_opaque_wrapper(),
]
}
fn more_field() -> TackOnField {
TackOnField::new(CITE_FIELD, call_args())
.repeatable()
.docs("A further call of the citation chunk, `\\cite[note]{keys}`; may be repeated.")
}
fn more_arg() -> ArgDef {
ArgDef::named(MORE_ARG, ArgStdKind::TackOn { fields: vec![more_field()] })
.docs("Further `\\cite` calls written directly after this one, read with it as one citation chunk.")
}
pub fn cite_args() -> Vec<ArgDef> {
let mut args = call_args();
args.push(more_arg());
args
}
pub fn refcite_args() -> Vec<ArgDef> {
let mut field_args = call_args();
field_args.push(more_arg());
let field = TackOnField::new(CITE_FIELD, field_args)
.docs("The citation that `\\R` writes as a noun: `\\cite[note]{keys}`, with its further calls.");
vec![
ArgDef::named(FLAGS_ARG, ArgStdKind::Optional)
.docs("Flags: `S` writes the capitalized word before the citation mark (`Refs.~`), `I` writes no word.")
.with_opaque_wrapper(),
ArgDef::named(CITATION_ARG, ArgStdKind::TackOn { fields: vec![field] })
.docs("The citation written directly after `\\R`."),
]
}
static CITE_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
let role = BlockRole::Inline(InlineSpacing { absorb_before: true, absorb_after: false });
Arc::new(
ElementSpec::new(CITE)
.docs("A citation chunk, `\\cite[note]{keys}`, attached to the content before it.")
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(role)))
.with::<dyn ApartFromText>(Arc::new(CitationElement::Cite))
.with_value(Arc::new(CitationElement::Cite)),
)
});
pub fn cite_element() -> Arc<ElementSpec> {
Arc::clone(&CITE_ELEMENT)
}
static REFCITE_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
Arc::new(
ElementSpec::new(REFCITE)
.docs("A citation chunk written as a noun, `\\R\\cite{keys}`, after a word, `ref.~` or `refs.~` by default.")
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
.with::<dyn ApartFromText>(Arc::new(CitationElement::RefCite))
.with_value(Arc::new(CitationElement::RefCite)),
)
});
pub fn refcite_element() -> Arc<ElementSpec> {
Arc::clone(&REFCITE_ELEMENT)
}
fn fields_in<'t>(node: &NodeRef<'t, Flm>, arg: &str) -> Vec<NodeRef<'t, Flm>> {
match node.argument_content_nodes_named(arg) {
Ok(Some(content)) => content.iter().filter(|field| is_field_named(field, CITE_FIELD)).collect(),
_ => Vec::new(),
}
}
pub fn leading_call<'t>(node: &NodeRef<'t, Flm>) -> Option<NodeRef<'t, Flm>> {
match element_value::<CitationElement>(node)? {
CitationElement::Cite => Some(*node),
CitationElement::RefCite => fields_in(node, CITATION_ARG).into_iter().next(),
}
}
pub fn calls<'t>(node: &NodeRef<'t, Flm>) -> Vec<NodeRef<'t, Flm>> {
let Some(leader) = leading_call(node) else { return Vec::new() };
let mut out = vec![leader];
out.extend(fields_in(&leader, MORE_ARG));
out
}
#[derive(Debug, Clone)]
pub struct CitationItem<'t> {
pub key: String,
pub note: Option<Vec<NodeRef<'t, Flm>>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChunkMistake {
NoKey {
span: FlmSpan,
},
}
#[derive(Debug, Clone, Default)]
pub struct Chunk<'t> {
pub items: Vec<CitationItem<'t>>,
pub mistakes: Vec<ChunkMistake>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reading {
AtLowering,
InStage,
}
pub fn read_chunk<'t>(node: &NodeRef<'t, Flm>, reading: Reading) -> Result<Chunk<'t>, LowerError> {
let mut chunk = Chunk::default();
for call in calls(node) {
read_call(&call, reading, &mut chunk)?;
}
Ok(chunk)
}
pub(super) fn read_call<'t>(call: &NodeRef<'t, Flm>, reading: Reading, chunk: &mut Chunk<'t>) -> Result<(), LowerError> {
let keys = match call.argument_content_nodes_named(KEYS_ARG) {
Ok(Some(content)) => Some(content),
_ => None,
};
if let Some(keys) = keys {
let known = spelling_at_lowering(keys.iter());
match reading {
Reading::AtLowering => known?,
Reading::InStage => {
if known.is_err() {
return Ok(());
}
}
}
}
let note: Option<Vec<NodeRef<'t, Flm>>> = match call.argument_content_nodes_named(NOTE_ARG) {
Ok(Some(content)) => Some(content.iter().collect()),
_ => None,
};
let before = chunk.items.len();
if let Some(Ok(segments)) = keys.map(|keys| split_at_chars_drop_annotations(keys, ",")) {
for segment in segments.segments() {
let key = spelling_identity(segment.iter());
if !key.is_empty() {
chunk.items.push(CitationItem { key, note: note.clone() });
}
}
}
if chunk.items.len() == before {
chunk.mistakes.push(ChunkMistake::NoKey { span: call.span().clone() });
}
Ok(())
}