Skip to content

Commit

Permalink
Revert "better errors for unbalanced groups"
Browse files Browse the repository at this point in the history
This reverts commit 6724296.
  • Loading branch information
carloskiki committed Aug 6, 2024
1 parent 925242f commit 9e0db58
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 114 deletions.
88 changes: 0 additions & 88 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,94 +304,6 @@ impl Grouping {
pub(crate) fn is_math_env(&self) -> bool {
!matches!(self, Self::Normal | Self::LeftRight(_, _))
}

pub(crate) fn as_kind(&self) -> GroupingKind {
match self {
Self::Normal => GroupingKind::Normal,
Self::LeftRight(_, _) => GroupingKind::LeftRight,
Self::Array(_) => GroupingKind::Array,
Self::Matrix { .. } => GroupingKind::Matrix,
Self::Cases { .. } => GroupingKind::Cases,
Self::Equation { .. } => GroupingKind::Equation,
Self::Align { .. } => GroupingKind::Align,
Self::Aligned => GroupingKind::Aligned,
Self::SubArray { .. } => GroupingKind::SubArray,
Self::Alignat { .. } => GroupingKind::Alignat,
Self::Alignedat { .. } => GroupingKind::Alignedat,
Self::Gather { .. } => GroupingKind::Gather,
Self::Gathered => GroupingKind::Gathered,
Self::Multline => GroupingKind::Multline,
Self::Split => GroupingKind::Split,
}

}
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum GroupingKind {
Normal,
OptionalArgument,
BeginEnd,
LeftRight,
Array,
Matrix,
Cases,
Equation,
Align,
Aligned,
SubArray,
Alignat,
Alignedat,
Gather,
Gathered,
Multline,
Split,
}

impl GroupingKind {
pub(crate) fn opening_str(&self) -> &'static str {
match self {
Self::Normal => "{",
Self::OptionalArgument => "[",
Self::BeginEnd => "\\begin",
Self::LeftRight => "\\left",
Self::Array => "\\begin{array}",
Self::Matrix => "\\begin{matrix}",
Self::Cases => "\\begin{cases}",
Self::Equation => "\\begin{equation}",
Self::Align => "\\begin{align}",
Self::Aligned => "\\begin{aligned}",
Self::SubArray => "\\begin{subarray}",
Self::Alignat => "\\begin{alignat}",
Self::Alignedat => "\\begin{alignedat}",
Self::Gather => "\\begin{gather}",
Self::Gathered => "\\begin{gathered}",
Self::Multline => "\\begin{multline}",
Self::Split => "\\begin{split}",
}
}

pub(crate) fn closing_str(&self) -> &'static str {
match self {
Self::Normal => "}",
Self::OptionalArgument => "]",
Self::BeginEnd => "\\end",
Self::LeftRight => "\\right",
Self::Array => "\\end{array}",
Self::Matrix => "\\end{matrix}",
Self::Cases => "\\end{cases}",
Self::Equation => "\\end{equation}",
Self::Align => "\\end{align}",
Self::Aligned => "\\end{aligned}",
Self::SubArray => "\\end{subarray}",
Self::Alignat => "\\end{alignat}",
Self::Alignedat => "\\end{alignedat}",
Self::Gather => "\\end{gather}",
Self::Gathered => "\\end{gathered}",
Self::Multline => "\\end{multline}",
Self::Split => "\\end{split}",
}
}
}

/// Represents a column in a matrix or array environment.
Expand Down
13 changes: 4 additions & 9 deletions src/parser/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::{error::Error, fmt::Display};

use super::SpanStack;
use crate::event::{Grouping, GroupingKind};
use crate::event::Grouping;

/// Anything that could possibly go wrong while parsing.
///
Expand Down Expand Up @@ -146,7 +146,7 @@ pub(crate) type InnerResult<T> = std::result::Result<T, ErrorKind>;
#[derive(Debug)]
pub(crate) enum ErrorKind {
// TODO: this error is very misleading. Rework it.
UnbalancedGroup(Option<GroupingKind>),
UnbalancedGroup(Option<Grouping>),
Environment,
MathShift,
HashSign,
Expand Down Expand Up @@ -185,13 +185,7 @@ impl Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
// TODO: this error is very misleading. Rework it.
ErrorKind::UnbalancedGroup(group) => {
if let Some(group) = group {
write!(f, "unbalanced group of type {:?} found, expected it to end with \"{}\"", group, group.closing_str())
} else {
f.write_str("unexpected group closing found")
}
},
ErrorKind::UnbalancedGroup(_) => f.write_str("unbalanced group found"),
ErrorKind::Environment => f.write_str("unkown mathematical environment found"),
ErrorKind::MathShift => f.write_str(
"unexpected math `$` (math shift) character - this character cannot be used inside math mode"),
Expand Down Expand Up @@ -225,6 +219,7 @@ impl Display for ErrorKind {
}
ErrorKind::TooManyParams => f.write_str("macro definition contains too many parameters, the maximum is 9"),
ErrorKind::StandaloneHashSign => f.write_str("macro definition contains a standalone '#'"),
// TODO: should specify what the macro expects the prefix string to be.
ErrorKind::IncorrectMacroPrefix => f.write_str("macro use does not match its definition, expected it to begin with a prefix string as specified in the definition"),
ErrorKind::MacroAlreadyDefined => f.write_str("macro already defined"),
ErrorKind::MacroNotDefined => f.write_str("macro not defined"),
Expand Down
23 changes: 11 additions & 12 deletions src/parser/lex.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
attribute::{Dimension, DimensionUnit, Glue},
event::{DelimiterType, GroupingKind},
event::DelimiterType,
};

use super::{tables::token_to_delim, Argument, CharToken, ErrorKind, InnerResult, Token};
Expand All @@ -23,7 +23,7 @@ pub fn definition<'a>(input: &mut &'a str) -> InnerResult<(&'a str, &'a str, &'a
}

*input = rest;
let replacement_text = group_content(input, GroupingKind::Normal)?;
let replacement_text = group_content(input, "{", "}")?;

Ok((control_sequence, parameter_text, replacement_text))
}
Expand All @@ -32,7 +32,7 @@ pub fn definition<'a>(input: &mut &'a str) -> InnerResult<(&'a str, &'a str, &'a
pub fn argument<'a>(input: &mut &'a str) -> InnerResult<Argument<'a>> {
if let Some(rest) = input.trim_start().strip_prefix('{') {
*input = rest;
let content = group_content(input, GroupingKind::Normal)?;
let content = group_content(input, "{", "}")?;
Ok(Argument::Group(content))
} else {
Ok(Argument::Token(token(input)?))
Expand All @@ -42,7 +42,7 @@ pub fn argument<'a>(input: &mut &'a str) -> InnerResult<Argument<'a>> {
pub fn optional_argument<'a>(input: &mut &'a str) -> InnerResult<Option<&'a str>> {
if let Some(rest) = input.trim_start().strip_prefix('[') {
*input = rest;
let content = group_content(input, GroupingKind::OptionalArgument)?;
let content = group_content(input, "[", "]")?;
Ok(Some(content))
} else {
Ok(None)
Expand All @@ -52,7 +52,7 @@ pub fn optional_argument<'a>(input: &mut &'a str) -> InnerResult<Option<&'a str>
pub fn brace_argument<'a>(input: &mut &'a str) -> InnerResult<&'a str> {
if let Some(rest) = input.trim_start().strip_prefix('{') {
*input = rest;
group_content(input, GroupingKind::Normal)
group_content(input, "{", "}")
} else {
Err(ErrorKind::GroupArgument)
}
Expand All @@ -62,17 +62,15 @@ pub fn brace_argument<'a>(input: &mut &'a str) -> InnerResult<&'a str> {
///
/// The output is the content within the group without the surrounding `start` and `end`.
/// This content is guaranteed to be balanced.
pub fn group_content<'a>(input: &mut &'a str, grouping: GroupingKind) -> InnerResult<&'a str> {
let start = grouping.opening_str();
let end = grouping.closing_str();
pub fn group_content<'a>(input: &mut &'a str, start: &str, end: &str) -> InnerResult<&'a str> {
let mut escaped = false;
let mut index = 0;
let mut depth = 0u32;
let bytes = input.as_bytes();
while escaped || depth > 0 || !bytes[index..].starts_with(end.as_bytes()) {
if index + end.len() > input.len() {
*input = &input[input.len()..];
return Err(ErrorKind::UnbalancedGroup(Some(grouping)));
return Err(ErrorKind::UnbalancedGroup(None));
}
if !escaped && bytes[index..].starts_with(start.as_bytes()) {
depth += 1;
Expand Down Expand Up @@ -125,7 +123,7 @@ pub fn content_with_suffix<'a>(input: &mut &'a str, suffix: &str) -> InnerResult
index += rest_pos;
}
b'{' if !escaped => {
let conetent = group_content(&mut &input[index + 1..], GroupingKind::Normal)?;
let conetent = group_content(&mut &input[index + 1..], "{", "}")?;
index += conetent.len() + 1;
}
_ => escaped = false,
Expand Down Expand Up @@ -450,7 +448,8 @@ pub fn token<'a>(input: &mut &'a str) -> InnerResult<Token<'a>> {
#[cfg(test)]
mod tests {
use crate::{
attribute::DimensionUnit, event::GroupingKind, parser::{lex, Token}
attribute::DimensionUnit,
parser::{lex, Token},
};

#[test]
Expand Down Expand Up @@ -551,7 +550,7 @@ mod tests {
fn group_content() {
let mut input =
"this { { is a test } to see if { the content parsing { of this } } } works }";
let content = lex::group_content(&mut input, GroupingKind::Normal).unwrap();
let content = lex::group_content(&mut input, "{", "}").unwrap();
assert_eq!(
content,
"this { { is a test } to see if { the content parsing { of this } } } works "
Expand Down
13 changes: 8 additions & 5 deletions src/parser/primitives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ use core::panic;
use crate::{
attribute::{DimensionUnit, Font},
event::{
ArrayColumn as AC, ColorChange as CC, ColorTarget as CT, ColumnAlignment, Content as C, DelimiterSize, DelimiterType, Event as E, Grouping as G, GroupingKind, Line, RelationContent, ScriptPosition as SP, ScriptType as ST, StateChange as SC, Style as S, Visual as V
ArrayColumn as AC, ColorChange as CC, ColorTarget as CT, ColumnAlignment, Content as C,
DelimiterSize, DelimiterType, Event as E, Grouping as G, Line, RelationContent,
ScriptPosition as SP, ScriptType as ST, StateChange as SC, Style as S, Visual as V,
},
};

Expand Down Expand Up @@ -68,7 +70,7 @@ impl<'b, 'store> InnerParser<'b, 'store> {
},
'{' => {
let str = &mut self.content;
let group = lex::group_content(str, GroupingKind::Normal)?;
let group = lex::group_content(str, "{", "}")?;
self.buffer.extend([
I::Event(E::Begin(G::Normal)),
I::SubGroup { content: group, allowed_alignment_count: None },
Expand Down Expand Up @@ -530,7 +532,7 @@ impl<'b, 'store> InnerParser<'b, 'store> {
};

let curr_str = &mut self.content;
let group_content = lex::group_content(curr_str, GroupingKind::LeftRight)?;
let group_content = lex::group_content(curr_str, r"\left", r"\right")?;
let closing = if let Some(rest) = curr_str.strip_prefix('.') {
*curr_str = rest;
None
Expand Down Expand Up @@ -1436,7 +1438,7 @@ impl<'b, 'store> InnerParser<'b, 'store> {
}

"begingroup" => {
let group = lex::group_content(&mut self.content, GroupingKind::BeginEnd)?;
let group = lex::group_content(&mut self.content, "begingroup", "endgroup")?;
self.buffer.extend([
I::Event(E::Begin(G::Normal)),
I::SubGroup {
Expand Down Expand Up @@ -1648,7 +1650,8 @@ impl<'b, 'store> InnerParser<'b, 'store> {

let content = lex::group_content(
&mut self.content,
environment.as_kind()
&format!(r"\begin{{{argument}}}"),
&format!(r"\end{{{argument}}}"),
)?;
self.buffer.push(I::Event(E::Begin(environment)));
if let Some(style) = style {
Expand Down

0 comments on commit 9e0db58

Please sign in to comment.