Custom Parsers and Extensions
Extend MathHook's parser for domain-specific mathematical notation. Add custom functions, operators, preprocessors, and grammar modifications.
Code Examples
Adding Custom Functions
Register domain-specific functions
use mathhook::parser::ParserBuilder;
let parser = ParserBuilder::new()
.add_function("erf", "error_function")
.add_function("Si", "sine_integral")
.add_function("Ci", "cosine_integral")
.build();
let expr = parser.parse("erf(x) + Si(x)")?;
// Parsed as: error_function(x) + sine_integral(x)
Adding Custom Operators
Define new infix operators with precedence
use mathhook::parser::ParserBuilder;
use mathhook::parser::Precedence;
let parser = ParserBuilder::new()
.add_operator("ร", "*") // Cross product symbol
.add_operator("โ", "tensor") // Tensor product
.add_operator_with_precedence(
"โ",
"direct_sum",
Precedence::Addition
)
.build();
let expr = parser.parse("A โ B")?;
// Parsed as: tensor(A, B)
Preprocessor Transformations
Transform input before parsing
use mathhook::parser::ParserBuilder;
let parser = ParserBuilder::new()
.add_preprocessor(|input| {
input.replace("โ", "->") // Arrow notation
.replace("ร", "*") // Cross product
.replace("รท", "/") // Division symbol
})
.build();
let expr = parser.parse("x โ โ")?;
// Preprocessed to: x -> โ
// Then parsed normally
Domain-Specific Parser (Chemistry)
Complete chemistry equation parser
use mathhook::parser::ParserBuilder;
fn create_chemistry_parser() -> Parser {
ParserBuilder::new()
.add_operator("โ", "yields")
.add_operator("โ", "equilibrium")
.add_operator("+", "plus")
.add_preprocessor(|input| {
// H2O โ H_2*O
expand_chemical_formulas(input)
})
.add_postprocessor(|expr| {
balance_equation(expr)
})
.build()
}
let parser = create_chemistry_parser();
let reaction = parser.parse("Hโ + Oโ โ HโO")?;
let balanced = reaction.balance(); // 2Hโ + Oโ โ 2HโO
Custom LaTeX Macros
Expand LaTeX macros before parsing
use mathhook::parser::LatexParserBuilder;
let parser = LatexParserBuilder::new()
.add_macro(r"\RR", r"\mathbb{R}") // Real numbers
.add_macro(r"\CC", r"\mathbb{C}") // Complex numbers
.add_macro(r"\NN", r"\mathbb{N}") // Natural numbers
.add_macro(r"\dd", r"\mathrm{d}") // Differential d
.build();
let expr = parser.parse(r"f: \RR \to \CC")?;
// Expands to: f: \mathbb{R} \to \mathbb{C}