Skip to content

Commit

Permalink
Attempted to fix labelling, added labelling test
Browse files Browse the repository at this point in the history
  • Loading branch information
zesterer committed Feb 28, 2024
1 parent 3c8488e commit 6837537
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
20 changes: 19 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,7 @@ impl<'a, T, L> RichReason<'a, T, L> {
mut fmt_span: impl FnMut(&S, &mut fmt::Formatter<'_>) -> fmt::Result,
mut fmt_label: impl FnMut(&L, &mut fmt::Formatter<'_>) -> fmt::Result,
span: Option<&S>,
#[cfg(feature = "label")] context: &[(L, S)],
) -> fmt::Result {
match self {
RichReason::ExpectedFound { expected, found } => {
Expand Down Expand Up @@ -467,6 +468,13 @@ impl<'a, T, L> RichReason<'a, T, L> {
}
}
}
#[cfg(feature = "label")]
for (l, s) in context {
write!(f, " in ")?;
fmt_label(l, f)?;
write!(f, " at ")?;
fmt_span(s, f)?;
}
Ok(())
}
}
Expand Down Expand Up @@ -526,7 +534,15 @@ where
L: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner_fmt(f, T::fmt, |_: &(), _| Ok(()), L::fmt, None)
self.inner_fmt(
f,
T::fmt,
|_: &(), _| Ok(()),
L::fmt,
None,
#[cfg(feature = "label")]
&[],
)
}
}

Expand Down Expand Up @@ -557,6 +573,8 @@ impl<'a, T, S, L> Rich<'a, T, S, L> {
fmt_span,
fmt_label,
if with_spans { Some(&self.span) } else { None },
#[cfg(feature = "label")]
&self.context,
)
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/label.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ where
inp.errors.alt = old_alt;

if let Some(mut new_alt) = new_alt {
let before_next = before.offset.into() + 1;
let before_next = before.offset.into();
if new_alt.pos.into() == before_next {
new_alt.err.label_with(self.label.clone());
} else if self.is_context && new_alt.pos.into() > before_next {
Expand Down
26 changes: 26 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3518,4 +3518,30 @@ mod tests {
todo().map_with(|expr, e| (expr, e.span()))
}
}

#[cfg(feature = "label")]
#[test]
fn label() {
use crate::label::LabelError;

fn parser<'src>() -> impl Parser<'src, &'src str, (), extra::Err<Rich<'src, char>>> {
just("hello").labelled("greeting").as_context().ignored()
}

let mut err = <Rich<_> as crate::Error<&str>>::expected_found(
Some(Some('h'.into())),
Some('g'.into()),
(0..1).into(),
);
<Rich<_, _, _> as LabelError<&str, _>>::label_with(&mut err, "greeting");
assert_eq!(parser().parse("goodbye").into_errors(), vec![err]);

let mut err = <Rich<_> as crate::Error<&str>>::expected_found(
Some(Some('l'.into())),
Some('p'.into()),
(3..4).into(),
);
<Rich<_, _, _> as LabelError<&str, _>>::in_context(&mut err, "greeting", (0..3).into());
assert_eq!(parser().parse("help").into_errors(), vec![err]);
}
}

0 comments on commit 6837537

Please sign in to comment.