use super::ast::*;
use super::dispatch::{classify_command, matrix_style, pile_align, EqCommandClass};
use super::symbols::{
self, is_big_operator, is_function, is_structure_command, lookup_function, lookup_symbol,
FontStyleKind, DECORATIONS, FONT_STYLES,
};
use super::tokenizer::{tokenize, Token, TokenType};
#[path = "parser_commands.rs"]
mod commands;
#[path = "parser_fractions.rs"]
mod fractions;
#[path = "parser_structures.rs"]
mod structures;
#[path = "parser_groups.rs"]
mod groups;
#[path = "parser_atoms.rs"]
mod atoms;
#[path = "parser_root.rs"]
mod root;
#[path = "parser_negation.rs"]
mod negation;
#[path = "parser_alignment.rs"]
mod alignment;
#[path = "parser_attached_scripts.rs"]
mod attached_scripts;
#[path = "parser_script_operand.rs"]
mod script_operand;
#[path = "parser_terms.rs"]
mod terms;
#[path = "parser_left_scripts.rs"]
mod left_scripts;
pub(super) const MAX_EQ_DEPTH: u32 = 64;
pub struct EqParser {
tokens: Vec<Token>,
pos: usize,
depth: u32,
paren_match: Vec<usize>,
document_terms: bool,
legacy_display: bool,
term_limit: usize,
invalid_document_script: bool,
stopped_document_input: bool,
font_state: Option<FontStyleKind>,
last_element: Option<(usize, Option<FontStyleKind>)>,
}
impl EqParser {
pub fn new(mut tokens: Vec<Token>) -> Self {
super::brace_recovery::retain_owned_closing_braces(&mut tokens);
let paren_match = Self::compute_paren_match(&tokens);
let term_limit = tokens.len();
Self {
tokens,
pos: 0,
depth: 0,
paren_match,
document_terms: false,
legacy_display: false,
term_limit,
invalid_document_script: false,
stopped_document_input: false,
font_state: None,
last_element: None,
}
}
fn styled_literal(&self, node: EqNode, roman_literal: bool) -> EqNode {
if roman_literal {
return atoms::literal_font(node, true);
}
match self.font_state {
Some(style) => EqNode::FontStyle {
style,
body: Box::new(node),
},
None => node,
}
}
pub(crate) fn for_document(tokens: Vec<Token>) -> Self {
Self {
document_terms: true,
..Self::new(tokens)
}
}
pub(crate) fn for_equation(
tokens: Vec<Token>,
equation: &crate::model::control::Equation,
) -> Self {
Self {
legacy_display: equation.uses_legacy_display(),
..Self::for_document(tokens)
}
}
fn compute_paren_match(tokens: &[Token]) -> Vec<usize> {
let n = tokens.len();
let mut m = vec![n; n];
let mut stack: Vec<usize> = Vec::new();
for (i, t) in tokens.iter().enumerate() {
match t.ty {
TokenType::LParen => stack.push(i),
TokenType::RParen => {
if let Some(open) = stack.pop() {
m[open] = i;
}
}
_ => {}
}
}
m
}
fn current(&self) -> Option<&Token> {
if self.stopped_document_input {
return None;
}
self.tokens.get(self.pos).filter(|t| t.ty != TokenType::Eof)
}
fn current_type(&self) -> TokenType {
if self.stopped_document_input {
return TokenType::Eof;
}
self.tokens
.get(self.pos)
.map(|t| t.ty)
.unwrap_or(TokenType::Eof)
}
fn current_value(&self) -> &str {
self.tokens
.get(self.pos)
.map(|t| t.value.as_str())
.unwrap_or("")
}
fn at_end(&self) -> bool {
self.stopped_document_input
|| self.pos >= self.tokens.len()
|| self.current_type() == TokenType::Eof
}
fn advance(&mut self) -> Option<&Token> {
if self.at_end() {
return None;
}
let tok = &self.tokens[self.pos];
self.pos += 1;
Some(tok)
}
fn expect(&mut self, ty: TokenType) -> bool {
if self.current_type() == ty {
self.pos += 1;
true
} else {
false
}
}
fn cmd_eq(val: &str, target: &str) -> bool {
val.eq_ignore_ascii_case(target)
}
fn has_toplevel_over(tokens: &[Token]) -> bool {
let mut brace_depth = 0i32;
let mut lr_depth = 0i32;
for t in tokens {
match t.ty {
TokenType::LBrace => brace_depth += 1,
TokenType::RBrace => brace_depth -= 1,
TokenType::Command => {
if Self::cmd_eq(&t.value, "LEFT") {
lr_depth += 1;
} else if Self::cmd_eq(&t.value, "RIGHT") {
lr_depth -= 1;
} else if Self::cmd_eq(&t.value, "OVER") && brace_depth == 0 && lr_depth == 0 {
return true;
}
}
_ => {}
}
}
false
}
pub fn parse(&mut self) -> EqNode {
let result = self.parse_expression();
if self.document_terms && self.invalid_document_script {
EqNode::Empty
} else {
result
}
}
fn try_consume_infix_over_atop(
&mut self,
children: &mut Vec<EqNode>,
over_run: &mut u32,
) -> bool {
if self.current_type() != TokenType::Command {
*over_run = 0; return false;
}
let val = self.current_value();
let is_over = Self::cmd_eq(val, "OVER");
let is_atop = Self::cmd_eq(val, "ATOP");
let is_choose = Self::cmd_eq(val, "CHOOSE");
if !is_over && !is_atop && !is_choose {
*over_run = 0; return false;
}
if *over_run >= MAX_EQ_DEPTH {
return false;
}
*over_run += 1;
self.pos += 1;
let mut top = children.pop().unwrap_or(EqNode::Empty);
let numer = self.last_element.take();
let state_before_numer = numer.map_or(self.font_state, |(_, state)| state);
let state_after_numer = self.font_state;
self.font_state = state_before_numer;
let bottom = self.parse_element();
let state_after_denom = self.font_state;
let numer_changed = state_after_numer != state_before_numer;
if let Some((start, _)) = numer {
if !numer_changed && state_after_denom != state_before_numer {
let after_denom = self.pos;
self.pos = start;
let reread = self.parse_element();
let stopped_at_infix = self.current_type() == TokenType::Command
&& ["OVER", "ATOP", "CHOOSE"]
.iter()
.any(|name| Self::cmd_eq(self.current_value(), name));
if stopped_at_infix {
top = reread;
}
self.pos = after_denom;
}
}
self.font_state = if numer_changed {
state_after_numer
} else {
state_after_denom
};
self.last_element = None;
children.push(if is_choose {
EqNode::Binomial {
top: Box::new(top),
bottom: Box::new(bottom),
}
} else if is_atop {
EqNode::Atop {
top: Box::new(top),
bottom: Box::new(bottom),
}
} else {
EqNode::Fraction {
numer: Box::new(top),
denom: Box::new(bottom),
}
});
true
}
fn parse_expression(&mut self) -> EqNode {
let mut children = Vec::new();
let mut over_run = 0u32;
while !self.at_end() {
if self.current_type() == TokenType::RBrace {
break;
}
if self.current_type() == TokenType::Command
&& Self::cmd_eq(self.current_value(), "RIGHT")
{
break;
}
if self.try_consume_infix_over_atop(&mut children, &mut over_run) {
continue;
}
children.push(self.parse_element());
}
EqNode::Row(children).simplify()
}
fn finish_command_atom(&mut self, node: EqNode, attach_scripts: bool) -> EqNode {
if attach_scripts {
self.try_parse_scripts(node)
} else {
node
}
}
fn parse_big_op(&mut self, symbol: String) -> EqNode {
let (sub, sup) = self.parse_operator_scripts();
EqNode::BigOp { symbol, sub, sup }
}
fn parse_limit(&mut self, is_upper: bool) -> EqNode {
let mut sub = None;
if self.current_type() == TokenType::Subscript {
self.pos += 1;
sub = Some(Box::new(self.parse_script_operand(false)));
}
EqNode::Limit { is_upper, sub }
}
fn parse_left_right(&mut self) -> EqNode {
let left = self.read_bracket_char();
let body = self.parse_expression();
if self.current_type() == TokenType::Command && Self::cmd_eq(self.current_value(), "RIGHT")
{
self.pos += 1;
}
let right = self.read_bracket_char();
EqNode::Paren {
left,
right,
body: Box::new(body),
}
}
fn read_bracket_char(&mut self) -> String {
if self.at_end() {
return String::new();
}
let ty = self.current_type();
let val = self.current_value().to_string();
match ty {
TokenType::LParen
| TokenType::RParen
| TokenType::LBracket
| TokenType::RBracket
| TokenType::LBrace
| TokenType::RBrace => {
self.pos += 1;
val
}
TokenType::Symbol if val == "|" || val == "." => {
self.pos += 1;
if val == "." {
String::new() } else {
val
}
}
TokenType::Command => {
if let Some(sym) = lookup_symbol(&val) {
self.pos += 1;
sym.to_string()
} else {
String::new()
}
}
_ => String::new(),
}
}
fn find_right_pos(&self) -> usize {
let mut depth = 1i32;
let mut pos = self.pos;
while pos < self.tokens.len() {
let t = &self.tokens[pos];
if t.ty == TokenType::Command {
if Self::cmd_eq(&t.value, "LEFT") {
depth += 1;
} else if Self::cmd_eq(&t.value, "RIGHT") {
depth -= 1;
if depth == 0 {
return pos;
}
}
}
pos += 1;
}
self.tokens.len()
}
fn parse_fraction_in_range(&mut self, end: usize) -> EqNode {
let mut before_nodes = Vec::new();
while self.pos < end && !self.at_end() {
if self.current_type() == TokenType::Command
&& Self::cmd_eq(self.current_value(), "OVER")
{
self.pos += 1;
break;
}
before_nodes.push(self.parse_element());
}
let (pre_nodes, numer) = if before_nodes.len() > 1 {
let numer = before_nodes.pop().unwrap();
(before_nodes, numer)
} else {
(Vec::new(), EqNode::Row(before_nodes).simplify())
};
let denom = if self.pos < end && !self.at_end() {
self.parse_element()
} else {
EqNode::Empty
};
let mut after_nodes = Vec::new();
while self.pos < end && !self.at_end() {
if self.current_type() == TokenType::Command
&& Self::cmd_eq(self.current_value(), "RIGHT")
{
break;
}
after_nodes.push(self.parse_element());
}
let fraction = EqNode::Fraction {
numer: Box::new(numer),
denom: Box::new(denom),
};
if pre_nodes.is_empty() && after_nodes.is_empty() {
fraction
} else {
let mut all = pre_nodes;
all.push(fraction);
all.extend(after_nodes);
EqNode::Row(all).simplify()
}
}
fn parse_color(&mut self) -> EqNode {
if !self.expect(TokenType::LBrace) {
let _color_argument = self.parse_element();
return self.parse_element();
}
let mut rgb = [0u8; 3];
for i in 0..3 {
if self.current_type() == TokenType::Number {
rgb[i] = self.current_value().parse().unwrap_or(0);
self.pos += 1;
}
if self.current_type() == TokenType::Symbol && self.current_value() == "," {
self.pos += 1;
}
}
self.expect(TokenType::RBrace);
let body = self.parse_single_or_group();
EqNode::Color {
r: rgb[0],
g: rgb[1],
b: rgb[2],
body: Box::new(body),
}
}
}
pub fn parse(script: &str) -> EqNode {
let tokens = tokenize(script);
let mut parser = EqParser::new(tokens);
parser.parse()
}
#[cfg(test)]
mod tests {
use super::symbols::{DecoKind, FontStyleKind};
use super::*;
#[test]
fn left_right_group_binds_trailing_script() {
let ast = parse("left | x right | ^3");
let s = format!("{:?}", ast);
assert!(
s.contains("Superscript") && s.contains("Paren") && !s.contains("base: Empty"),
"|x|^3 의 ^3 가 Paren 그룹에 결합돼야 함(orphan 금지): {s}"
);
let sub = format!("{:?}", parse("left | x right | _3"));
assert!(
sub.contains("Subscript") && sub.contains("Paren") && !sub.contains("base: Empty"),
"|x|_3 의 _3 가 Paren 그룹에 결합돼야 함: {sub}"
);
let x2 = format!("{:?}", parse("x^2"));
assert!(x2.contains("Superscript"), "x^2 정상: {x2}");
}
#[test]
fn test_simple_fraction() {
let ast = parse("1 over 2");
match &ast {
EqNode::Fraction { numer, denom } => {
assert!(matches!(numer.as_ref(), EqNode::Number(n) if n == "1"));
assert!(matches!(denom.as_ref(), EqNode::Number(n) if n == "2"));
}
_ => panic!("Expected Fraction, got {:?}", ast),
}
}
#[test]
fn test_task1122_over_followed_by_number_parses_as_fraction() {
for (script, expected_numer, expected_denom) in [
("11 over20", "11", "20"),
("3 over5", "3", "5"),
("7 OVER10", "7", "10"),
("{8} over {13}", "8", "13"),
] {
let ast = parse(script);
match &ast {
EqNode::Fraction { numer, denom } => {
assert!(
matches!(numer.as_ref(), EqNode::Number(n) if n == expected_numer),
"unexpected numerator for {script:?}: {ast:?}"
);
assert!(
matches!(denom.as_ref(), EqNode::Number(n) if n == expected_denom),
"unexpected denominator for {script:?}: {ast:?}"
);
}
_ => panic!("Expected Fraction for {script:?}, got {:?}", ast),
}
}
}
#[test]
fn test_task1122_over_prefix_non_numeric_identifiers_parse_as_text() {
let ast = parse("overlap");
assert!(matches!(ast, EqNode::Text(ref t) if t == "overlap"));
let ast = parse(r"\overline{AB}");
assert!(
matches!(
ast,
EqNode::Decoration {
kind: DecoKind::Overline,
..
}
),
r"Expected Decoration(Overline), got {:?}",
ast
);
}
#[test]
fn test_atop() {
let ast = parse("a atop b");
match &ast {
EqNode::Atop { top, bottom } => {
assert!(matches!(top.as_ref(), EqNode::Text(t) if t == "a"));
assert!(matches!(bottom.as_ref(), EqNode::Text(t) if t == "b"));
}
_ => panic!("Expected Atop, got {:?}", ast),
}
}
#[test]
fn test_superscript() {
let ast = parse("E=mc^2");
match &ast {
EqNode::Row(children) => {
assert!(children.len() >= 3);
assert!(matches!(&children[2], EqNode::Superscript { .. }));
}
_ => panic!("Expected Row, got {:?}", ast),
}
}
#[test]
fn test_sqrt() {
let ast = parse("SQRT x");
match &ast {
EqNode::Sqrt { index, body } => {
assert!(index.is_none());
assert!(matches!(body.as_ref(), EqNode::Text(t) if t == "x"));
}
_ => panic!("Expected Sqrt, got {:?}", ast),
}
}
#[test]
fn test_sqrt_with_index() {
let ast = parse("SQRT(3) of x");
match &ast {
EqNode::Sqrt { index, body } => {
assert!(index.is_some());
assert!(matches!(body.as_ref(), EqNode::Text(t) if t == "x"));
}
_ => panic!("Expected Sqrt with index, got {:?}", ast),
}
}
#[test]
fn test_greek() {
let ast = parse("alpha + beta");
match &ast {
EqNode::Row(children) => {
assert!(matches!(&children[0], EqNode::MathSymbol(s) if s == "α"));
assert!(matches!(&children[1], EqNode::Symbol(s) if s == "+"));
assert!(matches!(&children[2], EqNode::MathSymbol(s) if s == "β"));
}
_ => panic!("Expected Row, got {:?}", ast),
}
}
#[test]
fn test_integral() {
let ast = parse("INT_0^{inf}");
match &ast {
EqNode::SubSup { base, sub, sup } => {
assert!(matches!(base.as_ref(), EqNode::MathSymbol(s) if s == "∫"));
}
_ => panic!("Expected SubSup, got {:?}", ast),
}
}
#[test]
fn test_sum() {
let ast = parse("SUM_{i=0}^n");
match &ast {
EqNode::BigOp { symbol, sub, sup } => {
assert_eq!(symbol, "∑");
assert!(sub.is_some());
assert!(sup.is_some());
}
_ => panic!("Expected BigOp, got {:?}", ast),
}
}
#[test]
fn test_limit() {
let ast = parse("lim_{x->0}");
match &ast {
EqNode::Limit { is_upper, sub } => {
assert!(!is_upper);
assert!(sub.is_some());
}
_ => panic!("Expected Limit, got {:?}", ast),
}
}
#[test]
fn test_matrix() {
let ast = parse("matrix{a & b # c & d}");
match &ast {
EqNode::Matrix { rows, style } => {
assert_eq!(*style, MatrixStyle::Plain);
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].len(), 2);
assert_eq!(rows[1].len(), 2);
}
_ => panic!("Expected Matrix, got {:?}", ast),
}
}
#[test]
fn test_left_right() {
let ast = parse("LEFT ( a over b RIGHT )");
match &ast {
EqNode::Paren { left, right, body } => {
assert_eq!(left, "(");
assert_eq!(right, ")");
assert!(matches!(body.as_ref(), EqNode::Fraction { .. }));
}
_ => panic!("Expected Paren, got {:?}", ast),
}
}
#[test]
fn test_decoration() {
let ast = parse("hat x");
match &ast {
EqNode::Decoration { kind, body } => {
assert_eq!(*kind, DecoKind::Hat);
assert!(matches!(body.as_ref(), EqNode::Text(t) if t == "x"));
}
_ => panic!("Expected Decoration, got {:?}", ast),
}
}
#[test]
fn test_font_style() {
let ast = parse("rm abc");
match &ast {
EqNode::FontStyle { style, body } => {
assert_eq!(*style, FontStyleKind::Roman);
}
_ => panic!("Expected FontStyle, got {:?}", ast),
}
}
#[test]
fn test_font_style_body_decoration_not_leaked() {
let ast = parse("rm bar {F prime F}");
let s = format!("{:?}", ast);
assert!(
s.contains("Decoration"),
"bar 가 Decoration 으로 파싱돼야 함: {s}"
);
assert!(
!s.contains(r#"Text("bar")"#),
"bar 가 텍스트로 leak 되면 안 됨: {s}"
);
}
#[test]
fn test_uppercase_font_and_deco_commands() {
let s = format!("{:?}", parse("RM {vec{EC}}"));
assert!(!s.contains(r#"Text("RM")"#), "RM 이 leak 되면 안 됨: {s}");
assert!(
s.contains("FontStyle"),
"RM 이 FontStyle 로 인식돼야 함: {s}"
);
let s2 = format!("{:?}", parse("BAR {AB}"));
assert!(
s2.contains("Decoration"),
"BAR 가 Decoration 으로 인식돼야 함: {s2}"
);
}
#[test]
fn test_root_glued_digit_parses_as_sqrt() {
let ast = parse("root3 y");
let s = format!("{:?}", ast);
assert!(s.contains("Sqrt"), "root3 이 Sqrt 로 파싱돼야 함: {s}");
assert!(
!s.contains(r#"Text("root3")"#),
"root3 이 텍스트로 leak 되면 안 됨: {s}"
);
}
#[test]
fn test_cases() {
let ast = parse("CASES{ 1 & x>0 # -1 & x<0 }");
match &ast {
EqNode::Cases { rows } => {
assert_eq!(rows.len(), 2);
}
_ => panic!("Expected Cases, got {:?}", ast),
}
}
#[test]
fn test_sample_eq01_script() {
let script =
"평점=입찰가격평가~배점한도 TIMES LEFT ( {최저입찰가격} over {해당입찰가격} RIGHT )";
let ast = parse(script);
match &ast {
EqNode::Row(children) => {
assert!(children.len() > 1);
let has_paren = children.iter().any(|c| matches!(c, EqNode::Paren { .. }));
assert!(has_paren, "Should contain Paren node");
}
_ => {} }
}
#[test]
fn test_cos_fraction_with_left_right() {
let script = " cos ` left({ pi} over {2}+ theta right)=`-{1} over {5}`";
let ast = parse(script);
eprintln!("AST: {:#?}", ast);
let ast_str = format!("{:?}", ast);
assert!(ast_str.contains("cos"), "cos가 있어야 함");
assert!(ast_str.contains("Paren"), "Paren이 있어야 함");
assert!(
ast_str.contains("Fraction { numer: Number(\"1\"), denom: Number(\"5\")"),
"Fraction{{1,5}}가 있어야 함: {}",
ast_str
);
}
#[test]
fn test_latex_frac() {
let ast = parse(r"\frac{1}{2}");
match &ast {
EqNode::Fraction { numer, denom } => {
assert!(matches!(numer.as_ref(), EqNode::Number(n) if n == "1"));
assert!(matches!(denom.as_ref(), EqNode::Number(n) if n == "2"));
}
_ => panic!("Expected Fraction, got {:?}", ast),
}
}
#[test]
fn test_latex_quadratic_slice() {
let ast = parse(r"x=\frac{-b \pm \sqrt{b^2}}{2a}");
let ast_str = format!("{:?}", ast);
assert!(
ast_str.contains("Fraction"),
"Fraction이 있어야 함: {}",
ast_str
);
assert!(
ast_str.contains("MathSymbol(\"±\")"),
"± 기호가 있어야 함: {}",
ast_str
);
assert!(ast_str.contains("Sqrt"), "Sqrt가 있어야 함: {}", ast_str);
}
#[test]
fn test_latex_sqrt_with_bracket_index() {
let ast = parse(r"\sqrt[3]{x}");
match &ast {
EqNode::Sqrt { index, body } => {
assert!(index.is_some(), "sqrt index가 있어야 함");
assert!(matches!(body.as_ref(), EqNode::Text(t) if t == "x"));
}
_ => panic!("Expected indexed Sqrt, got {:?}", ast),
}
}
}
#[cfg(test)]
#[test]
fn test_lim_fraction() {
let script = " lim _{h ``rarrow`` 0} {f left(2+h right)-f left(2 right)} over {h}`";
let ast = parse(script);
eprintln!("LIM AST: {:#?}", ast);
let ast_str = format!("{:?}", ast);
assert!(ast_str.contains("Limit"), "Limit가 있어야 함: {}", ast_str);
assert!(
ast_str.contains("Fraction"),
"Fraction이 있어야 함: {}",
ast_str
);
}
#[cfg(test)]
#[test]
fn test_bar_rm_it() {
let script = "bar {{rm{AB}} it }< bar {{rm{AC}} it }`";
let ast = parse(script);
eprintln!("BAR AST: {:#?}", ast);
let ast_str = format!("{:?}", ast);
assert!(ast_str.contains("Decoration"), "Decoration이 있어야 함");
assert!(
!ast_str.contains(r#"Text("}")"#),
"brace가 텍스트로 나오면 안 됨"
);
}
#[cfg(test)]
#[test]
fn test_cases_double_amp() {
let script = "{cases{eqalign{``x^{3}#}&&eqalign{~LEFT(x LEQ 0 RIGHT)#}#``f LEFT(x RIGHT)&&~LEFT(x>0 RIGHT)}}";
let ast = parse(script);
eprintln!("CASES AST: {:#?}", ast);
let s = format!("{:?}", ast);
assert!(s.contains("Tab"), "Tab이 있어야 함: {}", s);
}
#[cfg(test)]
#[test]
fn test_rm_p_left() {
let script = "{rm{P}} it left(A``|` B` right)";
let ast = parse(script);
eprintln!("RM_P AST: {:#?}", ast);
let s = format!("{:?}", ast);
assert!(s.contains("Paren"), "Paren이 있어야 함: {}", s);
}
#[cfg(test)]
#[path = "parser_latex_compat_tests.rs"]
mod latex_compat_tests;