Skip to main content

nom_supreme/
context.rs

1//! Enhanced context combinator for nom.
2//!
3//! This module introduces an updated, [`ContextError`], that allows for
4//! arbitrary types of data to be attached as context to errors, rather than
5//! requiring `&'static str`.
6
7use nom::error::{Error, ErrorKind, VerboseError, VerboseErrorKind};
8
9/// Updated version of [`nom::error::ContextError`]. Allows for arbitrary
10/// context types, rather than requiring `&'static str`
11pub trait ContextError<I, C>: Sized {
12    /// Create a new error from an input position, a context, and an existing
13    /// error. This is used by the [`.context`][crate::ParserExt::context]
14    /// combinator to add friendly information to errors when backtracking
15    /// through a parse tree.
16    fn add_context(location: I, ctx: C, other: Self) -> Self;
17}
18
19impl<I, C> ContextError<I, C> for () {
20    fn add_context(_location: I, _ctx: C, _other: Self) -> Self {}
21}
22
23impl<I, C> ContextError<I, C> for (I, ErrorKind) {
24    fn add_context(_location: I, _ctx: C, other: Self) -> Self {
25        other
26    }
27}
28
29impl<I, C> ContextError<I, C> for Error<I> {
30    fn add_context(_location: I, _ctx: C, other: Self) -> Self {
31        other
32    }
33}
34
35impl<I> ContextError<I, &'static str> for VerboseError<I> {
36    fn add_context(location: I, ctx: &'static str, mut other: Self) -> Self {
37        other
38            .errors
39            .push((location, VerboseErrorKind::Context(ctx)));
40
41        other
42    }
43}