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;
use crate::model::element::{element_of, element_value};
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
use crate::stdlib::backends::latex::{
LatexArgShape, LatexMacroPayload, LatexRawPayload, packages, preamble,
};
use crate::stdlib::backends::lowering::{lower_arg_or_nothing, lower_run};
use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
use crate::stdlib::features::refs::{SAFE_LABELS, SafeLabels, stage_label, stage_label_group};
use crate::stdlib::features::userdefs::kept::{MathPiece, write_math_run};
use super::ensuremath::ENSUREMATH;
use super::frame::{LineFrame, formula_display};
use super::lines::{LINEBREAK_COMMAND, NONUMBER_COMMAND, TAG_COMMAND};
use super::text::{MathTextCommand, TEXT};
use super::MathEnvironment;
pub const TEXT_LATEX_RULE: &str = "flm.math.text.lower.latex-recomposed";
pub const FLM_MATH_ENVIRONMENT: &str = "flmMathEnvironment";
pub const KERNEL_ENVIRONMENT: &str = "equation";
pub const AMSMATH_COMMAND: &str = "text";
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct MathRecomposeOptions {
pub surround_display_math: (String, String),
pub emit_flm_math_environment_macro: bool,
}
#[derive(Debug, Default, Clone, Copy)]
pub struct TextLatexRule;
impl Lower for TextLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let value = element_value::<MathTextCommand>(&node)
.ok_or_else(|| LowerError::structure("a math text command without its element's data"))?;
if value.command == AMSMATH_COMMAND {
lw.require(&Name::from(packages::AMSMATH));
}
let argument = lower_arg_or_nothing(cx, lw, &node, 0)?;
let call = lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(value.command.as_str(), [LatexArgShape::Mandatory]),
vec![(String::from(ARG_SLOT), argument)],
)?;
Ok(Lowering::Emit(vec![call]))
}
}
pub fn text_rule() -> LoweringRule {
LoweringRule::new(
TEXT_LATEX_RULE,
TEXT,
LoweringDecl::new().produces(MACRO),
Arc::new(TextLatexRule),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a text command of math mode lowers to the LaTeX macro of the same name, over its \
argument lowered as document text",
)
}
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 environment_name(node: &NodeRef<'_, Flm>) -> Result<String, LowerError> {
element_value::<MathEnvironment>(node)
.map(|value| value.name.to_string())
.ok_or_else(|| LowerError::structure("a math environment without its element's data"))
}
pub fn environment_opening(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
node: &NodeRef<'_, Flm>,
) -> Result<Vec<BuildId>, LowerError> {
let name = environment_name(node)?;
let options = lw.option::<MathRecomposeOptions>()?.clone();
if name != KERNEL_ENVIRONMENT {
lw.require(&Name::from(packages::AMSMATH));
}
let mut nodes = Vec::with_capacity(2);
let (before, _) = &options.surround_display_math;
if !before.is_empty() {
nodes.push(raw(cx, lw, before)?);
}
let opening = if options.emit_flm_math_environment_macro {
lw.require(&Name::from(preamble::MATH_ENVIRONMENT));
format!("\\{FLM_MATH_ENVIRONMENT}{{{name}}}{{}}{{")
} else {
format!("\\begin{{{name}}}")
};
nodes.push(raw(cx, lw, &opening)?);
Ok(nodes)
}
pub fn line_closing(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
frame: &LineFrame<'_>,
) -> Result<Vec<BuildId>, LowerError> {
let line = &frame.line;
let mut pieces = Vec::new();
if let Some(tag) = &line.tag {
let mut argument = Vec::new();
if tag.parenthesized() {
argument.push(lw.text(cx, "(")?);
}
argument.extend(lower_run(cx, lw, &tag.content)?);
if tag.parenthesized() {
argument.push(lw.text(cx, ")")?);
}
pieces.push(lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(TAG_COMMAND, [LatexArgShape::Star, LatexArgShape::Mandatory]),
vec![(String::from(ARG_SLOT), argument)],
)?);
}
let written = lw.get(SAFE_LABELS)?.is_some()
|| !lw.option::<LatexRecomposedRenderOptions>()?.drop_math_labels_without_refs;
if written {
let mut group = Vec::new();
for label in &line.labels {
group.push(stage_label(cx, lw, &label.text, label.label.as_ref())?);
}
pieces.extend(stage_label_group(cx, lw, group, false)?);
}
if line.nonumber {
pieces.push(lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(NONUMBER_COMMAND, []),
Vec::new(),
)?);
}
if let Some(brk) = &line.linebreak {
let mut text = format!("\\{LINEBREAK_COMMAND}");
if let Some(spacing) = &brk.spacing {
text.push('[');
text.push_str(spacing);
text.push(']');
}
pieces.push(raw(cx, lw, &text)?);
}
Ok(pieces)
}
pub fn environment_closing(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
node: &NodeRef<'_, Flm>,
) -> Result<Vec<BuildId>, LowerError> {
let name = environment_name(node)?;
let options = lw.option::<MathRecomposeOptions>()?.clone();
let closing = if options.emit_flm_math_environment_macro {
String::from("}")
} else {
format!("\\end{{{name}}}")
};
let mut nodes = vec![raw(cx, lw, &closing)?];
let (_, after) = &options.surround_display_math;
if !after.is_empty() {
nodes.push(raw(cx, lw, after)?);
}
Ok(nodes)
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct NormalizedLine {
pub text: String,
pub trailing: String,
}
fn is_run_char(ch: char) -> bool {
matches!(ch, ' ' | '\t' | '\n')
}
pub fn normalize_line_newlines(content: &str, after_line_end: bool, inner: bool) -> NormalizedLine {
let mut line = NormalizedLine::default();
let mut rest = content;
let mut at = 0;
while !rest.is_empty() {
let run_end = rest.find(|ch: char| !is_run_char(ch)).unwrap_or(rest.len());
let run = &rest[..run_end];
match run.rfind('\n') {
None => line.text.push_str(run),
Some(last) => {
let normalized = &run[last..];
if at == 0 {
if !after_line_end {
line.text.push_str(normalized);
}
} else if run_end == rest.len() && !inner {
line.trailing.push_str(normalized);
} else {
line.text.push_str(normalized);
}
}
}
rest = &rest[run_end..];
at += run_end;
let text_end = rest.find(is_run_char).unwrap_or(rest.len());
line.text.push_str(&rest[..text_end]);
rest = &rest[text_end..];
at += text_end;
}
line
}
fn ends_line(text: &str, after_line_end: bool) -> bool {
let only_blanks = |text: &str| text.chars().all(|ch| matches!(ch, ' ' | '\t'));
match text.rsplit_once('\n') {
Some((_, last)) => only_blanks(last),
None => after_line_end && only_blanks(text),
}
}
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct NewlineRule {
after_line_end: bool,
}
impl NewlineRule {
pub(crate) fn text(&mut self, text: &str, last: bool) -> NormalizedLine {
let line = normalize_line_newlines(text, self.after_line_end, !last);
self.after_line_end = ends_line(&line.text, self.after_line_end);
line
}
pub(crate) fn written(&mut self, written: &str) {
self.after_line_end = ends_line(written, self.after_line_end);
}
pub(crate) fn piece(&mut self, ends_line: bool) {
self.after_line_end = ends_line;
}
pub(crate) fn line_end(&mut self, closed: bool, trailing: &str) {
if closed {
self.after_line_end = false;
}
if !trailing.is_empty() {
self.after_line_end = true;
}
}
}
pub fn stage_lines(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
frames: &[LineFrame<'_>],
) -> Result<Vec<BuildId>, LowerError> {
let drop_comments = lw.option::<LatexRecomposedRenderOptions>()?.drop_comments;
let mut rule = NewlineRule::default();
let mut nodes = Vec::new();
for frame in frames {
let pieces = write_math_run(cx, lw, &frame.line.content)?;
let count = pieces.len();
let mut trailing = String::new();
for (index, piece) in pieces.into_iter().enumerate() {
match piece {
MathPiece::Text(text) => {
let line = rule.text(&text, index + 1 == count);
if !line.text.is_empty() {
nodes.push(raw(cx, lw, &line.text)?);
}
trailing = line.trailing;
}
MathPiece::Comment(id) => {
nodes.push(id);
if !drop_comments {
rule.piece(true);
}
}
MathPiece::Node(id) => {
nodes.push(id);
rule.piece(false);
}
}
}
let closing = line_closing(cx, lw, frame)?;
rule.line_end(!closing.is_empty(), &trailing);
nodes.extend(closing);
if !trailing.is_empty() {
nodes.push(raw(cx, lw, &trailing)?);
}
}
Ok(nodes)
}
fn ensuremath_formula(node: &NodeRef<'_, Flm>) -> bool {
node.parent().is_some_and(|parent| element_of(&parent).name == ENSUREMATH)
}
pub fn group_opening(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
node: &NodeRef<'_, Flm>,
) -> Result<Vec<BuildId>, LowerError> {
let options = lw.option::<MathRecomposeOptions>()?.clone();
if !formula_display(node) {
let opening = if ensuremath_formula(node) { "\\ensuremath{" } else { "\\(" };
return Ok(vec![raw(cx, lw, opening)?]);
}
let mut nodes = Vec::with_capacity(2);
let (before, _) = &options.surround_display_math;
if !before.is_empty() {
nodes.push(raw(cx, lw, before)?);
}
nodes.push(raw(cx, lw, "\\[")?);
Ok(nodes)
}
pub fn group_closing(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
node: &NodeRef<'_, Flm>,
) -> Result<Vec<BuildId>, LowerError> {
let options = lw.option::<MathRecomposeOptions>()?.clone();
if !formula_display(node) {
let closing = if ensuremath_formula(node) { "}" } else { "\\)" };
return Ok(vec![raw(cx, lw, closing)?]);
}
let mut nodes = vec![raw(cx, lw, "\\]")?];
let (_, after) = &options.surround_display_math;
if !after.is_empty() {
nodes.push(raw(cx, lw, after)?);
}
Ok(nodes)
}
pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the recomposition rules of the text commands \
and of `\\eqref` are the default",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro construct, which the recomposition rules of the text \
commands and of `\\eqref` stage",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw construct, which the recomposition rule of `\\eqref` stages",
)?;
b.peer_table::<SafeLabels>(
SAFE_LABELS.name(),
"the references feature's safe-labels table, which the recomposition rule of \
`\\eqref` reads for the safe label of the label it refers to",
)?;
b.lowering_rule(text_rule())
}
#[cfg(test)]
mod tests {
use super::*;
fn normalized(content: &str, after_line_end: bool, inner: bool) -> (String, String) {
let line = normalize_line_newlines(content, after_line_end, inner);
(line.text, line.trailing)
}
#[test]
fn every_newline_run_becomes_one_newline_and_the_last_indentation() {
assert_eq!(normalized("\n \n x &= 0.\n", false, false), ("\n x &= 0.".into(), "\n".into()));
assert_eq!(normalized("a\n\n\n\tb c\n", false, false), ("a\n\tb c".into(), "\n".into()));
assert_eq!(normalized("x = 1 \n", false, false), ("x = 1".into(), "\n".into()));
assert_eq!(normalized("x = 1 ", false, false), ("x = 1 ".into(), String::new()));
assert_eq!(normalized("a \t b", false, false), ("a \t b".into(), String::new()));
assert_eq!(normalized("", false, false), (String::new(), String::new()));
assert_eq!(normalized(" ", false, false), (" ".into(), String::new()));
}
#[test]
fn the_run_that_begins_a_part_is_dropped_only_after_a_line_end() {
assert_eq!(normalized("\n b &= 2 \n", false, false), ("\n b &= 2".into(), "\n".into()));
assert_eq!(normalized("\n b &= 2 \n", true, false), ("b &= 2".into(), "\n".into()));
assert_eq!(normalized("\n ", false, false), ("\n ".into(), String::new()));
assert_eq!(normalized("\n ", true, false), (String::new(), String::new()));
}
#[test]
fn a_part_that_is_not_the_last_keeps_its_run_in_place() {
assert_eq!(normalized("a %% c\n ", false, true), ("a %% c\n ".into(), String::new()));
assert_eq!(normalized("a %% c\n \n ", false, true), ("a %% c\n ".into(), String::new()));
}
#[test]
fn whether_written_text_ends_a_line() {
assert!(ends_line("a\n ", false));
assert!(ends_line("a\n", false));
assert!(!ends_line("a\n b", false));
assert!(!ends_line("a", true));
assert!(ends_line(" ", true));
assert!(!ends_line(" ", false));
assert!(!ends_line("", false));
assert!(ends_line("", true));
}
fn written_line(rule: &mut NewlineRule, parts: &[Option<&str>], closed: bool) -> (String, String) {
let mut text = String::new();
let mut trailing = String::new();
for (index, part) in parts.iter().enumerate() {
match part {
Some(part) => {
let line = rule.text(part, index + 1 == parts.len());
text.push_str(&line.text);
trailing = line.trailing;
}
None => {
text.push_str("%c\n ");
rule.piece(true);
}
}
}
rule.line_end(closed, &trailing);
(text, trailing)
}
#[test]
fn the_rule_follows_the_line_ends_across_lines_and_comments() {
let mut rule = NewlineRule::default();
assert_eq!(written_line(&mut rule, &[Some("\n a &= b\n \n ")], true), ("\n a &= b".into(), "\n ".into()));
assert_eq!(written_line(&mut rule, &[Some("\n c &= d\n \n")], false), ("c &= d".into(), "\n".into()));
let mut rule = NewlineRule::default();
assert_eq!(written_line(&mut rule, &[Some("\n a &= b ")], true), ("\n a &= b ".into(), String::new()));
assert_eq!(
written_line(&mut rule, &[Some(" "), None, Some("\n c &= d\n")], false),
(" %c\n c &= d".into(), "\n".into())
);
let mut rule = NewlineRule::default();
rule.piece(true);
rule.piece(false);
assert_eq!(rule.text("\n x", false).text, "\n x");
let mut rule = NewlineRule::default();
rule.written("%c");
assert_eq!(rule.text("\n\n x", true).text, "\n x");
rule.written("%c\n ");
assert_eq!(rule.text("\n y", true).text, "y");
}
#[test]
fn the_text_rule_is_the_default_on_the_recomposed_backend_only() {
let rule = text_rule();
assert_eq!(rule.name, TEXT_LATEX_RULE);
assert_eq!(rule.element, TEXT);
assert!(rule.default.is_specific_to(&BACKEND.into()));
assert_eq!(rule.decl.produces, [ElementName::from(MACRO)]);
}
}