use super::dispatch::{classify_command, EqCommandClass};
use super::tokenizer::{self, Token, TokenType};
pub(crate) fn parse(equation: &crate::model::control::Equation) -> super::ast::EqNode {
let tokens = tokenize_with_display(&equation.script, equation.uses_legacy_display());
super::parser::EqParser::for_equation(tokens, equation).parse()
}
pub(crate) fn tokenize(script: &str) -> Vec<Token> {
tokenize_with_display(script, false)
}
fn tokenize_with_display(script: &str, legacy_display: bool) -> Vec<Token> {
let normalized = super::legacy_hwpeq::normalize(script);
let script = normalized.as_deref().unwrap_or(script);
let lexer = if legacy_display {
tokenizer::Tokenizer::for_legacy_document(script)
} else {
tokenizer::Tokenizer::for_document(script)
};
let mut tokens = lexer.tokenize();
let chars: Vec<char> = script.chars().collect();
let mut roman_literal = false;
for token in &mut tokens {
if token.ty == TokenType::Text && chars.get(token.pos) == Some(&'\\') {
roman_literal = true;
} else if token.ty == TokenType::Command && token.value.eq_ignore_ascii_case("IT") {
roman_literal = false;
}
token.roman_literal = roman_literal;
if token.ty != TokenType::Command {
continue;
}
match token.value.as_str() {
"LEFTARROW" => token.value = "Leftarrow".to_owned(),
"RIGHTARROW" => token.value = "Rightarrow".to_owned(),
_ if token.value.eq_ignore_ascii_case("LINE") => {
token.ty = TokenType::Symbol;
token.value = "|".to_owned();
continue;
}
_ => {}
}
let class = classify_command(&token.value);
let mixed_root = class == EqCommandClass::Sqrt
&& token.value != token.value.to_ascii_uppercase()
&& token.value != token.value.to_ascii_lowercase();
if mixed_root
|| matches!(
class,
EqCommandClass::LatexFraction
| EqCommandClass::RomanText
| EqCommandClass::LatexSpacing
| EqCommandClass::BeginEnv
| EqCommandClass::EndEnv
)
|| token.value.eq_ignore_ascii_case("STACKREL")
{
token.ty = TokenType::Text;
}
}
retain_escaped_underline_brace(tokens, &chars)
}
fn retain_escaped_underline_brace(mut tokens: Vec<Token>, chars: &[char]) -> Vec<Token> {
let mut closers = vec![None; tokens.len()];
let mut opens = Vec::new();
for (index, token) in tokens.iter().enumerate() {
match token.ty {
TokenType::LBrace => opens.push(index),
TokenType::RBrace => {
if let Some(open) = opens.pop() {
closers[open] = Some(index);
}
}
_ => {}
}
}
let mut removed_closers = vec![false; tokens.len()];
for index in 0..tokens.len() {
if tokens[index].ty != TokenType::Text
|| !tokens[index].value.eq_ignore_ascii_case("UNDERLINE")
|| chars.get(tokens[index].pos) != Some(&'\\')
|| tokens.get(index + 1).map(|token| token.ty) != Some(TokenType::LBrace)
{
continue;
}
if let Some(close) = closers[index + 1] {
tokens[index + 1].ty = TokenType::Symbol;
removed_closers[close] = true;
}
}
tokens
.into_iter()
.enumerate()
.filter_map(|(index, token)| (!removed_closers[index]).then_some(token))
.collect()
}