texlang_stdlib/
mathchardef.rs

1//! The `\mathchardef` primitive.
2use texlang::prelude as txl;
3use texlang::traits::*;
4use texlang::*;
5
6/// Get the `\mathchardef` command.
7pub fn get_mathchardef<S: TexlangState>() -> command::BuiltIn<S> {
8    command::BuiltIn::new_execution(mathchardef_primitive_fn)
9}
10
11fn mathchardef_primitive_fn<S: TexlangState>(
12    _: token::Token,
13    input: &mut vm::ExecutionInput<S>,
14) -> txl::Result<()> {
15    let scope = TexlangState::variable_assignment_scope_hook(input.state_mut());
16    let (cmd_ref_or, _, c) = <(
17        Option<token::CommandRef>,
18        parse::OptionalEquals,
19        types::MathCode,
20    )>::parse(input)?;
21    if let Some(cmd_ref) = cmd_ref_or {
22        input
23            .commands_map_mut()
24            .insert(cmd_ref, command::Command::MathCharacter(c), scope);
25    }
26    Ok(())
27}
28
29#[cfg(test)]
30mod test {
31    use super::*;
32    use crate::the;
33    use std::collections::HashMap;
34    use texlang_testing::*;
35
36    fn built_in_commands() -> HashMap<&'static str, command::BuiltIn<State>> {
37        HashMap::from([
38            ("mathchardef", get_mathchardef()),
39            ("the", the::get_the()),
40            ("i", TestingComponent::get_integer()),
41        ])
42    }
43
44    test_suite![
45        expansion_equality_tests(
46            (
47                basic_case,
48                r"\mathchardef\Hello = `\+ \Hello",
49                "MathCode(43)"
50            ),
51            (
52                basic_case_with_the,
53                r"\mathchardef\Hello = 123 \the\Hello",
54                "123"
55            ),
56            (
57                parsable_as_number,
58                r"\mathchardef\Hello = 13 \i=\Hello x\the\i",
59                "x13"
60            ),
61            (
62                parsable_as_number_negative,
63                r"\mathchardef\Hello = 13 \i=-\Hello x\the\i",
64                "x-13"
65            ),
66        ),
67        serde_tests((basic_case, r"\mathchardef\Hello = `\+ ", r"\Hello"),),
68    ];
69}