use super::{EqNode, EqParser, TokenType};
impl EqParser {
pub(super) fn parse_sqrt(&mut self, latex_index: bool) -> EqNode {
if latex_index && self.current_type() == TokenType::LBracket {
self.pos += 1; let previous_limit = self.term_limit;
let close = self.tokens[self.pos..]
.iter()
.position(|token| token.ty == TokenType::RBracket)
.map_or(self.tokens.len(), |offset| self.pos + offset);
self.term_limit = self.term_limit.min(close);
let mut index_nodes = Vec::new();
while !self.at_end() && self.current_type() != TokenType::RBracket {
index_nodes.push(self.parse_element());
}
self.term_limit = previous_limit;
self.expect(TokenType::RBracket);
let body = self.parse_single_or_group();
return EqNode::Sqrt {
index: Some(Box::new(EqNode::Row(index_nodes).simplify())),
body: Box::new(body),
};
}
if self.current_type() == TokenType::LParen {
let close = self.paren_match[self.pos];
let has_of = self.tokens.get(close + 1).is_some_and(|token| {
token.ty == TokenType::Command && token.value.eq_ignore_ascii_case("of")
});
let group = self.parse_paren_group();
if has_of {
self.pos += 1; return EqNode::Sqrt {
index: Some(Box::new(group)),
body: Box::new(self.parse_single_or_group()),
};
}
return EqNode::Sqrt {
index: None,
body: Box::new(group),
};
}
if self.current_type() == TokenType::LBrace {
let saved_pos = self.pos;
let brace_end = self.find_matching_brace(self.pos + 1);
let after_brace = brace_end + 1;
let has_of = after_brace < self.tokens.len()
&& self.tokens[after_brace].ty == TokenType::Command
&& self.tokens[after_brace].value.eq_ignore_ascii_case("of");
if has_of {
let index = self.parse_group();
if self.current_type() == TokenType::Command
&& self.current_value().eq_ignore_ascii_case("of")
{
self.pos += 1;
}
let body = self.parse_single_or_group();
return EqNode::Sqrt {
index: Some(Box::new(index)),
body: Box::new(body),
};
}
self.pos = saved_pos;
}
if matches!(
self.current_type(),
TokenType::Number | TokenType::Command | TokenType::Text | TokenType::Quoted
) && self.tokens.get(self.pos + 1).is_some_and(|token| {
token.ty == TokenType::Command && token.value.eq_ignore_ascii_case("of")
}) {
let index = self.parse_single_or_group();
self.pos += 1; let body = self.parse_single_or_group();
return EqNode::Sqrt {
index: Some(Box::new(index)),
body: Box::new(body),
};
}
let body = self.parse_single_or_group();
EqNode::Sqrt {
index: None,
body: Box::new(body),
}
}
}