use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::{Flm, FlmGroupType};
use crate::model::element::element_value;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{
ARG_SLOT, ENVIRONMENT as LATEX_ENVIRONMENT, MACRO, RAW,
};
use crate::stdlib::backends::latex::{
LatexArgShape, LatexEnvironmentPayload, LatexMacroPayload, LatexRawPayload, packages,
preamble,
};
use crate::stdlib::backends::latex_recomposed::BACKEND;
use crate::stdlib::backends::lowering::{copy_subtree_verbatim, stage_verbatim_content};
use crate::stdlib::backends::pres::{BODY_SLOT, VerbatimKind};
use super::{CONTENT_ARG, ENVIRONMENT, LANG_ARG, MACRO as VERBATIM_MACRO, VerbatimCallable};
pub const MACRO_LATEX_RULE: &str = "flm.verbatim.macro.lower.latex-recomposed";
pub const ENVIRONMENT_LATEX_RULE: &str = "flm.verbatim.environment.lower.latex-recomposed";
fn require_verbatim(lw: &mut dyn Lowerer) {
lw.require(&Name::from(packages::FVEXTRA));
lw.require(&Name::from(preamble::VERBATIM));
}
fn escverb(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
kind: VerbatimKind,
content: Vec<BuildId>,
) -> Result<BuildId, LowerError> {
let options = lw.pres_with(
cx,
&ElementName::from(RAW),
LatexRawPayload::new(preamble::escverb_options(kind)),
Vec::new(),
)?;
lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(preamble::ESCVERB, [LatexArgShape::Optional, LatexArgShape::EscVerb]),
vec![(String::from(ARG_SLOT), vec![options]), (String::from(ARG_SLOT), content)],
)
}
#[derive(Debug, Default, Clone, Copy)]
pub struct MacroLatexRule;
impl Lower for MacroLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let value = element_value::<VerbatimCallable>(&node)
.ok_or_else(|| LowerError::structure("a verbatim node without its element's data"))?;
let content = match node.argument_content_nodes_named(CONTENT_ARG) {
Ok(Some(content)) => stage_verbatim_content(&node, content, cx, lw)?,
_ => Vec::new(),
};
require_verbatim(lw);
Ok(Lowering::Emit(vec![escverb(cx, lw, value.kind, content)?]))
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct EnvironmentLatexRule;
impl Lower for EnvironmentLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let value = element_value::<VerbatimCallable>(&node)
.ok_or_else(|| LowerError::structure("a verbatim node without its element's data"))?;
let mut content = Vec::new();
if let Some(body) = node.body() {
for child in body.iter() {
if child.group_type() == Some(FlmGroupType::Verbatim) {
content.extend(stage_verbatim_content(&node, child.children(), cx, lw)?);
} else {
content.push(copy_subtree_verbatim(cx, child)?);
}
}
}
require_verbatim(lw);
if !value.block {
return Ok(Lowering::Emit(vec![escverb(cx, lw, value.kind, content)?]));
}
let shapes = vec![LatexArgShape::Optional];
let mut slots = Vec::new();
let lang = language_slot(&node, cx, lw)?;
slots.push((String::from(ARG_SLOT), lang));
slots.push((String::from(BODY_SLOT), content));
let block = lw.pres_slots_with(
cx,
&ElementName::from(LATEX_ENVIRONMENT),
LatexEnvironmentPayload::new(preamble::VERBATIM_CODE_ENVIRONMENT, shapes).verbatim(),
slots,
)?;
Ok(Lowering::Emit(vec![block]))
}
}
fn language_slot(
node: &NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Vec<BuildId>, LowerError> {
let Ok(Some(content)) = node.argument_content_nodes_named(LANG_ARG) else {
return Ok(Vec::new());
};
if content.iter().all(|child| child.chars().is_some()) {
return match super::language_of(node) {
Some(lang) => Ok(vec![lw.text(cx, &lang)?]),
None => Ok(Vec::new()),
};
}
lw.lower_nodes(cx, content)
}
pub fn latex_rules() -> Vec<LoweringRule> {
let decl = || LoweringDecl::new().produces(MACRO).produces(LATEX_ENVIRONMENT).produces(RAW);
let on_this_backend = || DefaultMark::OnBackends(vec![BACKEND.into()]);
vec![
LoweringRule::new(
MACRO_LATEX_RULE,
VERBATIM_MACRO,
decl(),
Arc::new(MacroLatexRule),
on_this_backend(),
)
.docs(
"a verbatim macro lowers to `\\EscVerb` over its content, in the encoding \
`\\EscVerb` reads",
),
LoweringRule::new(
ENVIRONMENT_LATEX_RULE,
ENVIRONMENT,
decl(),
Arc::new(EnvironmentLatexRule),
on_this_backend(),
)
.docs(
"an inline verbatim environment lowers to `\\EscVerb` over its content; a block \
lowers to the `flmVerbatimCode` environment over its content",
),
]
}
pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the recomposition rules of the verbatim \
commands are the default",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro construct, which the recomposition rules of the verbatim \
commands stage",
)?;
b.peer_element::<LatexEnvironmentPayload>(
LATEX_ENVIRONMENT,
"the LaTeX family's environment construct, which the recomposition rules of the \
verbatim commands stage",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw construct, which the recomposition rules of the verbatim \
commands stage",
)?;
for rule in latex_rules() {
b.lowering_rule(rule)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn both_rules_are_the_default_on_the_recomposed_backend_only() {
let rules = latex_rules();
assert_eq!(rules[0].name, MACRO_LATEX_RULE);
assert_eq!(rules[0].element, VERBATIM_MACRO);
assert_eq!(rules[1].name, ENVIRONMENT_LATEX_RULE);
assert_eq!(rules[1].element, ENVIRONMENT);
for rule in &rules {
assert!(rule.default.is_specific_to(&BACKEND.into()));
assert_eq!(rule.decl.produces.len(), 3);
}
}
}