use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use techy::latexlike::InvocationSyntaxData;
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::{structural, Flm};
use crate::model::element::element_value;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{DEFINITION, RAW};
use crate::stdlib::backends::latex::{
packages, LatexDefinitionKind, LatexDefinitionPayload, LatexRawPayload,
};
use crate::stdlib::backends::latex_recomposed::BACKEND;
use crate::stdlib::backends::lowering::lower_run;
use crate::stdlib::backends::pres::BODY_SLOT;
use super::config::{AnnotationsRenderOptions, Annotator};
use super::parser::{delimiters_of, form_of, Form};
use super::{AnnotationElement, ANNOTATION, FEATURE, TEXT_ARG};
pub const LATEX_RULE: &str = "flm.annotations.annotation.lower.latex-recomposed";
pub const MAKE_COMMAND: &str = "phfMakeCommentingCommand";
#[derive(Debug, Clone)]
pub struct AnnotationLatexRule {
annotators: Arc<[Annotator]>,
}
impl AnnotationLatexRule {
pub fn new(annotators: impl Into<Arc<[Annotator]>>) -> AnnotationLatexRule {
AnnotationLatexRule { annotators: annotators.into() }
}
fn declarations(&self, cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer) -> Result<Vec<BuildId>, LowerError> {
let mut staged = Vec::with_capacity(self.annotators.len());
for annotator in self.annotators.iter() {
let command = annotator.command.as_str();
let body = match annotator.initials.as_deref() {
Some(initials) => vec![
raw(cx, lw, &format!("\\{MAKE_COMMAND}[initials={{"))?,
lw.text(cx, initials)?,
raw(cx, lw, &format!("}}]{{{command}}}"))?,
],
None => vec![raw(cx, lw, &format!("\\{MAKE_COMMAND}[formatinitials=hide]{{{command}}}"))?],
};
let payload = LatexDefinitionPayload::new(LatexDefinitionKind::Declaration, command, 0)
.of_feature(FEATURE);
staged.push(lw.pres_slots_with(
cx,
&ElementName::from(DEFINITION),
payload,
vec![(String::from(BODY_SLOT), body)],
)?);
}
Ok(staged)
}
}
impl Lower for AnnotationLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
if element_value::<AnnotationElement>(&node).is_none() {
return Err(LowerError::structure("an annotation without its element's data"));
}
let form = form_of(&node).ok_or_else(|| LowerError::structure("an annotation without its argument"))?;
if lw.option::<AnnotationsRenderOptions>()?.hidden {
return Ok(Lowering::Emit(match form {
Form::Highlight => lw.lower_arg_named(cx, &node, TEXT_ARG)?,
Form::Comment => paragraph_breaks(&node, cx, lw)?,
}));
}
let (open, close) =
delimiters_of(&node).ok_or_else(|| LowerError::structure("an annotation without its argument"))?;
lw.require(&Name::from(packages::PHFCC));
let mut staged = self.declarations(cx, lw)?;
staged.push(raw(cx, lw, &command_as_written(&node))?);
staged.extend(before_group(&node, cx, lw)?);
if !open.is_empty() {
staged.push(raw(cx, lw, open)?);
}
staged.extend(lw.lower_arg_named(cx, &node, TEXT_ARG)?);
if !close.is_empty() {
staged.push(raw(cx, lw, close)?);
}
Ok(Lowering::Emit(staged))
}
}
fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<BuildId, LowerError> {
lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
}
fn command_as_written(node: &NodeRef<'_, Flm>) -> String {
let name = node.name().unwrap_or_default();
match node.invocation_syntax() {
Some(InvocationSyntaxData::Macro { escape_char, post_space }) => {
format!("{escape_char}{name}{}", post_space.resolve(node.span().source()))
}
_ => format!("\\{name}"),
}
}
fn before_group(node: &NodeRef<'_, Flm>, cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer) -> Result<Vec<BuildId>, LowerError> {
let Some(region) = node.arguments().and_then(|arguments| arguments.get_named(TEXT_ARG)?.region.as_ref())
else {
return Ok(Vec::new());
};
let group = region.content_parent();
let noise: Vec<NodeRef<'_, Flm>> = node
.argument_nodes_named(TEXT_ARG)
.ok()
.flatten()
.map(|nodes| nodes.iter().take_while(|written| written.id() != group).collect())
.unwrap_or_default();
lower_run(cx, lw, &noise)
}
fn paragraph_breaks(node: &NodeRef<'_, Flm>, cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer) -> Result<Vec<BuildId>, LowerError> {
let Some(content) = node.argument_content_nodes_named(TEXT_ARG).ok().flatten() else {
return Ok(Vec::new());
};
let mut staged = Vec::new();
for written in content.iter() {
if written.ext().element.name.as_str() == structural::PARBREAK {
staged.extend(lower_run(cx, lw, std::slice::from_ref(&written))?);
}
}
Ok(staged)
}
pub fn latex_rule(annotators: impl Into<Arc<[Annotator]>>) -> LoweringRule {
LoweringRule::new(
LATEX_RULE,
ANNOTATION,
LoweringDecl::new()
.option::<AnnotationsRenderOptions>()
.produces(DEFINITION)
.produces(RAW),
Arc::new(AnnotationLatexRule::new(annotators)),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"an annotation lowers to its invocation as written (the command, the opening delimiter, \
the content and the closing delimiter), one invocation even across a paragraph break, \
since the backend lowers the tree before the block-structure pass; it requires the \
`phfcc` package, and the style file makes every configured annotator's command with \
`\\phfMakeCommentingCommand`, guarded on its name; when annotations are hidden \
(`hidden`), a highlight lowers to its passage alone and a comment to its paragraph \
breaks",
)
}
pub(super) fn register(b: &mut FeatureBuilder<'_>, annotators: &[Annotator]) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the annotation's rule \
`flm.annotations.annotation.lower.latex-recomposed` is the default",
)?;
b.peer_element::<LatexDefinitionPayload>(
DEFINITION,
"the LaTeX family's definition construct, which the annotation's rule stages for the \
declaration of each annotator's command",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw construct, in which the annotation's rule writes the command and \
the delimiters as written",
)?;
b.lowering_rule(latex_rule(annotators.to_vec()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_rule_is_the_default_on_the_latex_recomposed_backend_only() {
let rule = latex_rule(vec![Annotator::new("phf")]);
assert_eq!(rule.element, ANNOTATION);
assert!(rule.default.is_specific_to(&BACKEND.into()));
}
}