use techy::core::node::{BuildId, NodeRef};
use techy::latexlike::{InvocationSyntaxData, MathGroupForm};
use crate::core::lowering::{Lower, LowerCx, LowerError, Lowerer, Lowering};
use crate::lang::Flm;
use crate::lang::mint::is_math_text_command;
use crate::model::element::{element_of, element_value};
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::lowering::{copy_subtree_verbatim, lower_run};
use crate::stdlib::backends::pres::{
self, MathDisplay, MathPassthroughPayload, MathTextPayload, recompose_source,
};
use crate::stdlib::features::math::MathEnvironment;
use crate::stdlib::features::math::ensuremath::ENSUREMATH;
use crate::stdlib::features::math::frame::{formula_display, line_frames, stage_tag_content};
use crate::stdlib::features::math::html::FORMULA_ROLE;
use crate::stdlib::features::math::latex::NewlineRule;
use crate::stdlib::features::numbering::COUNTERS;
use crate::stdlib::features::refs::ANCHORS;
fn formula_payload(display: MathDisplay, env: Option<String>) -> MathPassthroughPayload {
MathPassthroughPayload { display, env, role: Some(Name::from(FORMULA_ROLE)) }
}
fn enclosing_display(node: &NodeRef<'_, Flm>) -> MathDisplay {
let mut ancestor = node.parent();
while let Some(up) = ancestor {
if let Some(form) = up.math_form() {
return match form {
MathGroupForm::Display => MathDisplay::Display,
_ => MathDisplay::Inline,
};
}
ancestor = up.parent();
}
MathDisplay::Inline
}
#[derive(Debug, Default)]
pub struct OpaqueRule;
impl Lower for OpaqueRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let display = enclosing_display(&node);
let body = vec![copy_subtree_verbatim(cx, node)?];
let payload = formula_payload(display, None);
let math = lw.pres_with(cx, &ElementName::from(pres::MATH_PASSTHROUGH), payload, body)?;
Ok(Lowering::Emit(vec![math]))
}
}
pub(crate) fn stage_source(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
nodes: &[NodeRef<'_, Flm>],
) -> Result<Vec<BuildId>, LowerError> {
let mut body = Vec::with_capacity(nodes.len());
for node in nodes {
stage_node(cx, lw, *node, &mut body)?;
}
Ok(body)
}
fn stage_node(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
node: NodeRef<'_, Flm>,
body: &mut Vec<BuildId>,
) -> Result<(), LowerError> {
if is_math_text_command(&node) {
body.extend(lower_run(cx, lw, std::slice::from_ref(&node))?);
return Ok(());
}
if let Some((open, close)) = node.group_delimiters() {
body.push(lw.text(cx, open)?);
body.extend(stage_source(cx, lw, &children_of(&node))?);
body.push(lw.text(cx, close)?);
return Ok(());
}
if node.is_list() {
body.extend(stage_source(cx, lw, &children_of(&node))?);
return Ok(());
}
if let Some(inner) = node.body() {
let name = node.name().unwrap_or_default();
body.push(lw.text(cx, &format!("\\begin{{{name}}}"))?);
stage_arguments(cx, lw, &node, body)?;
let inner: Vec<NodeRef<'_, Flm>> = inner.iter().collect();
body.extend(stage_source(cx, lw, &inner)?);
body.push(lw.text(cx, &format!("\\end{{{name}}}"))?);
return Ok(());
}
if element_of(&node).name == ENSUREMATH {
let content: Vec<NodeRef<'_, Flm>> =
node.argument_content_nodes(0).map(|slice| slice.iter().collect()).unwrap_or_default();
body.extend(stage_source(cx, lw, &content)?);
return Ok(());
}
if node.callable().is_some_and(|callable| !callable.arguments.is_empty()) {
body.push(lw.text(cx, ¯o_call(&node))?);
return stage_arguments(cx, lw, &node, body);
}
body.push(copy_subtree_verbatim(cx, node)?);
Ok(())
}
fn children_of<'t>(node: &NodeRef<'t, Flm>) -> Vec<NodeRef<'t, Flm>> {
node.children().iter().collect()
}
fn macro_call(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 stage_arguments(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
node: &NodeRef<'_, Flm>,
body: &mut Vec<BuildId>,
) -> Result<(), LowerError> {
let count = node.callable().map_or(0, |callable| callable.arguments.len());
for index in 0..count {
if let Some(region) = node.argument_nodes(index) {
let nodes: Vec<NodeRef<'_, Flm>> = region.iter().collect();
body.extend(stage_source(cx, lw, &nodes)?);
}
}
Ok(())
}
fn stage_tag(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
content: Vec<BuildId>,
) -> Result<Vec<BuildId>, LowerError> {
if content.is_empty() {
return Ok(Vec::new());
}
let payload = MathTextPayload { command: None, anchor: None, at_tag: true };
let text = lw.pres_with(cx, &ElementName::from(pres::MATH_TEXT), payload, content)?;
Ok(vec![lw.text(cx, "\\tag*{")?, text, lw.text(cx, "}")?])
}
fn needs_walk(node: &NodeRef<'_, Flm>) -> bool {
let walked =
|node: &NodeRef<'_, Flm>| is_math_text_command(node) || element_of(node).name == ENSUREMATH;
walked(node) || node.descendants().any(|descendant| walked(&descendant))
}
enum LinePart<'t> {
Text(String),
Comment(NodeRef<'t, Flm>),
Walked(NodeRef<'t, Flm>),
}
fn stage_line_content(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
content: &[NodeRef<'_, Flm>],
rule: &mut NewlineRule,
body: &mut Vec<BuildId>,
) -> Result<String, LowerError> {
let mut parts = Vec::new();
let mut run: Vec<NodeRef<'_, Flm>> = Vec::new();
for node in content {
if node.is_comment() || needs_walk(node) {
if !run.is_empty() {
parts.push(LinePart::Text(recompose_source(&run)));
run.clear();
}
parts.push(if node.is_comment() { LinePart::Comment(*node) } else { LinePart::Walked(*node) });
} else {
run.push(*node);
}
}
if !run.is_empty() {
parts.push(LinePart::Text(recompose_source(&run)));
}
let count = parts.len();
let mut trailing = String::new();
for (index, part) in parts.into_iter().enumerate() {
match part {
LinePart::Text(text) => {
let line = rule.text(&text, index + 1 == count);
if !line.text.is_empty() {
body.push(lw.text(cx, &line.text)?);
}
trailing = line.trailing;
}
LinePart::Comment(node) => {
rule.written(&recompose_source(&[node]));
body.push(copy_subtree_verbatim(cx, node)?);
}
LinePart::Walked(node) => {
stage_node(cx, lw, node, body)?;
rule.piece(false);
}
}
}
Ok(trailing)
}
#[derive(Debug, Default, Clone, Copy)]
pub struct EnvironmentRule;
impl Lower for EnvironmentRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let value = element_value::<MathEnvironment>(&node)
.ok_or_else(|| LowerError::structure("a math environment without its value"))?;
let frames = line_frames(lw.get(ANCHORS)?, lw.get(COUNTERS)?, lw.addr(), &node)
.map_err(|error| LowerError::structure(error.to_string()))?;
let mut body = Vec::new();
let mut rule = NewlineRule::default();
for frame in &frames {
if let Some(anchor) = frame.anchor.clone() {
let payload =
MathTextPayload { command: None, anchor: Some(anchor), at_tag: false };
body.push(lw.pres_with(
cx,
&ElementName::from(pres::MATH_TEXT),
payload,
Vec::new(),
)?);
}
let trailing = stage_line_content(cx, lw, &frame.line.content, &mut rule, &mut body)?;
let content = stage_tag_content(cx, lw, frame)?;
let tag = stage_tag(cx, lw, content)?;
let closed = !tag.is_empty() || frame.line.linebreak.is_some();
body.extend(tag);
if let Some(brk) = &frame.line.linebreak {
body.push(copy_subtree_verbatim(cx, brk.node)?);
}
rule.line_end(closed, &trailing);
if !trailing.is_empty() {
body.push(lw.text(cx, &trailing)?);
}
}
let payload = formula_payload(MathDisplay::Display, Some(value.name.to_string()));
let math = lw.pres_with(cx, &ElementName::from(pres::MATH_PASSTHROUGH), payload, body)?;
Ok(Lowering::Emit(vec![math]))
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct MathRule;
impl Lower for MathRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let display =
if formula_display(&node) { MathDisplay::Display } else { MathDisplay::Inline };
let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
let body = stage_source(cx, lw, &children)?;
let payload = formula_payload(display, None);
let math = lw.pres_with(cx, &ElementName::from(pres::MATH_PASSTHROUGH), payload, body)?;
Ok(Lowering::Emit(vec![math]))
}
}