use std::sync::Arc;
use techy::core::constructs::{
scan_argument_noise, stage_pre_space, ArgumentParser, ChildStateSpec, ConstructParserResult,
GroupArgumentParser, ParseContext, ParsedArgumentNodes,
};
use techy::core::node::{ContentNodes, NodeRef};
use techy::core::specs::ArgumentSpec;
use techy::core::token::{GroupRule, TokenEdge, TokenKind};
use techy::latexlike::{MathGroupForm, Mode};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::mint::{ArgDef, ArgStdKind, DefinitionShape, ElementDef, FlmArgumentParser, SyntaxDef};
use crate::lang::{Flm, FlmGroupType};
use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
use crate::model::element::ElementSpec;
use crate::model::names::FeatureName;
use crate::stdlib::backends::lowering::lower_arg_or_nothing;
pub const COMMAND: &str = "ensuremath";
pub const ENSUREMATH: &str = "flm.math.ensuremath";
pub const RULE: &str = "flm.math.ensuremath.lower.default";
pub const FORMULA_ARG: &str = "formula";
#[derive(Debug)]
struct FormulaArgument {
rule: Arc<GroupRule<Flm>>,
missing: GroupArgumentParser<Flm>,
}
impl FormulaArgument {
fn new() -> FormulaArgument {
FormulaArgument {
rule: Arc::new(GroupRule {
group_type: FlmGroupType::Math(MathGroupForm::Inline),
open: String::from("{"),
close: String::from("}"),
}),
missing: GroupArgumentParser::new(FlmGroupType::Content).with_expression_fallback(false),
}
}
}
impl ArgumentParser<Flm> for FormulaArgument {
fn parse_argument(
&self,
cx: &mut ParseContext<'_, '_, Flm>,
spec: &ArgumentSpec<Flm>,
) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
let noise = scan_argument_noise(cx)?;
let open = noise.next.clone().filter(|token| {
matches!(cx.tokens.token_kind(token), TokenKind::GroupOpen { rule, .. }
if rule.group_type == FlmGroupType::Content && rule.open == self.rule.open)
});
let Some(open) = open else {
noise.rewind(cx);
return self.missing.parse_argument(cx, spec);
};
let mut nodes = noise.nodes;
stage_pre_space(cx, &mut nodes, &open)?;
cx.tokens.move_to(&open, TokenEdge::EndPastPostSpace);
let base = Arc::clone(&cx.state);
let (group, _) =
cx.parse_group(base, &open, Arc::clone(&self.rule), ChildStateSpec::inherit(), None)?;
let index = u32::try_from(nodes.len()).unwrap_or(u32::MAX);
nodes.push(group);
Ok(Some(ParsedArgumentNodes::new(
nodes,
ContentNodes::InRegion(index..index.saturating_add(1)),
(),
)))
}
fn can_match_empty(&self) -> bool {
false
}
}
impl FlmArgumentParser for FormulaArgument {
fn identity(&self) -> Vec<u8> {
b"flm.math.ensuremath.formula".to_vec()
}
fn definition_shape(&self) -> DefinitionShape {
DefinitionShape::NoShape { token: "formula" }
}
fn description(&self) -> String {
String::from("a `{…}` group read as an inline formula")
}
}
fn element(mode: Mode) -> Arc<ElementSpec> {
let docs = match mode {
Mode::Text => "`\\ensuremath{…}` in text: an inline formula, as `\\(…\\)`.",
_ => "`\\ensuremath{…}` inside mathematics: its argument, as if written in its place.",
};
Arc::new(
ElementSpec::new(ENSUREMATH)
.docs(docs)
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT))),
)
}
fn text_def(owner: &FeatureName) -> ElementDef {
ElementDef::new(
owner.clone(),
[COMMAND],
SyntaxDef::Macro {
args: vec![ArgDef::named(
FORMULA_ARG,
Arc::new(FormulaArgument::new()) as Arc<dyn FlmArgumentParser>,
)
.docs("The formula, in braces: its content is mathematics.")],
},
element(Mode::Text),
)
.modes([Mode::Text])
.docs(
"Writes an inline formula, as `\\(…\\)` does. The braces are required; their \
content is read in math mode.",
)
}
fn math_def(owner: &FeatureName) -> ElementDef {
ElementDef::new(
owner.clone(),
[COMMAND],
SyntaxDef::Macro {
args: vec![ArgDef::named(FORMULA_ARG, ArgStdKind::Mandatory)
.docs("The mathematics, as if written in place of the command.")],
},
element(Mode::Math),
)
.modes([Mode::Math])
.docs("Inside mathematics, writes its argument as if it were written in place of the command.")
}
#[derive(Debug, Default, Clone, Copy)]
pub struct EnsureMathRule;
impl Lower for EnsureMathRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
Ok(Lowering::Emit(lower_arg_or_nothing(cx, lw, &node, 0)?))
}
}
pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
let owner: FeatureName = b.feature().clone();
b.element(text_def(&owner))?;
b.element(math_def(&owner))?;
b.element_type_text(
ENSUREMATH,
"Mathematics that holds whether `\\ensuremath` is written in text or inside a formula: \
in text, an inline formula; inside mathematics, the mathematics it holds.",
)?;
b.lowering_rule(
LoweringRule::new(
RULE,
ENSUREMATH,
LoweringDecl::new(),
Arc::new(EnsureMathRule),
DefaultMark::Everywhere,
)
.docs(
"`\\ensuremath` lowers to its argument lowered through the rules: in text an inline \
formula, inside mathematics the mathematics it holds",
),
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_command_is_declared_once_per_mode_with_one_argument() {
let owner = FeatureName::from("math");
let text = text_def(&owner);
assert_eq!(text.modes, vec![Mode::Text]);
let math = math_def(&owner);
assert_eq!(math.modes, vec![Mode::Math]);
for def in [text, math] {
let SyntaxDef::Macro { args } = &def.syntax else { panic!("a macro") };
assert_eq!(args.len(), 1);
assert_eq!(args[0].name.as_deref(), Some(FORMULA_ARG));
assert_eq!(args[0].mode, None, "the mode comes from the group or the formula");
}
}
#[test]
fn both_declarations_carry_the_one_element_type() {
assert_eq!(element(Mode::Text).name, ENSUREMATH);
assert_eq!(element(Mode::Math).name, ENSUREMATH);
}
}