Skip to main content

ParseError

Struct ParseError 

pub struct ParseError { /* private fields */ }
Expand description

A parse error carrying the original proc_macro2::Span of the offending token or expression start, plus an optional end span for range errors.

Used as the return type of all parser methods. Not Send + Sync because proc_macro2::Span wraps a compiler-internal handle that is only valid on the proc-macro thread. Convert to [CELError] via From when the error must cross thread boundaries or be stored for async reporting.

Implementations§

§

impl ParseError

pub fn new(message: impl Into<String>, span: Span) -> ParseError

Creates a new parse error with the given message and token span.

§Examples
use proc_macro2::Span;
use cel_parser::ParseError;

let e = ParseError::new("unexpected token", Span::call_site());
assert_eq!(e.message(), "unexpected token");

pub fn new_range( message: impl Into<String>, start: Span, end: Span, ) -> ParseError

Creates a parse error spanning a sub-expression from start to end.

Use this for op-lookup failures where the error implicates a full sub-expression rather than a single token. At runtime the two spans are merged into a contiguous underline; at compile time two separate compile_error!() diagnostics are emitted.

§Examples
use proc_macro2::Span;
use cel_parser::ParseError;

let start = Span::call_site();
let end = Span::call_site();
let e = ParseError::new_range("type mismatch", start, end);
assert_eq!(e.message(), "type mismatch");
assert!(e.end_span().is_some());

pub fn message(&self) -> &str

Returns the error message.

pub fn span(&self) -> Span

Returns the proc_macro2::Span of the offending token.

Use this span with quote_spanned! in proc-macro code to attach the compile_error! to the exact source location.

pub fn end_span(&self) -> Option<Span>

Returns the end span of this error, or None for single-point errors.

Some for errors created with new_range; None for errors created with new.

pub fn with_secondary(self, secondary: Vec<SpanLabel>) -> ParseError

Attaches secondary labelled spans, rendered as extra carets alongside the primary.

§Examples
use proc_macro2::Span;
use cel_parser::{ParseError, SourceSpan, SpanLabel};

let e = ParseError::new("bad", Span::call_site()).with_secondary(vec![SpanLabel {
    span: SourceSpan::new(1, 4, 1, 7),
    label: "also here".into(),
}]);
assert_eq!(e.message(), "bad");

pub fn secondary(&self) -> &[SpanLabel]

Returns the secondary labelled spans attached to this error.

§Examples
use cel_parser::{ParseError, SourceSpan, SpanLabel};
use proc_macro2::Span;

let e = ParseError::new("bad", Span::call_site()).with_secondary(vec![SpanLabel {
    span: SourceSpan::new(1, 0, 1, 3),
    label: "related".into(),
}]);
assert_eq!(e.secondary().len(), 1);

pub fn from_lex_error(source: &str, err: LexError) -> ParseError

Converts a lex failure (e.g. from proc_macro2::TokenStream::from_str) into a ParseError with a message describing the likely cause.

proc_macro2::LexError’s Display is the same generic string (“cannot parse string into token stream”) regardless of cause, but its span reliably points at the offending character. This inspects that character in source to report why lexing failed — unclosed/unexpected delimiter, unterminated string or character literal, unterminated block comment, or another invalid character — falling back to err’s own message only when the span doesn’t resolve to a character in source (e.g. it points past the end).

§Examples
use cel_parser::ParseError;
use proc_macro2::TokenStream;
use std::str::FromStr;

let source = "(1 + 2";
let lex_err = TokenStream::from_str(source).unwrap_err();
let err = ParseError::from_lex_error(source, lex_err);
assert_eq!(err.message(), "unclosed delimiter `(`: expected a matching `)`");

pub fn format_rustc_style( &self, source_code: &str, filename: &str, start_line: u32, renderer: &Renderer, ) -> String

Formats this error in rustc diagnostic style with source context.

Identical contract to [CELError::format_rustc_style] when no secondary spans are attached; prefer calling this directly on a ParseError rather than converting to CELError first when you have the source text at hand. When secondaries have been added via with_secondary, renders a multi-span diagnostic (the primary span plus one context caret per secondary) via [format_multi_span].

§Examples
use annotate_snippets::Renderer;
use cel_parser::CELParser;
use cel_parser::OpLookup;

let line = line!() + 1;
let source = "10 + 20 30";
let mut parser = CELParser::new(OpLookup::new());
if let Err(e) = parser.parse_str(source) {
    println!("{}", e.format_rustc_style(source, file!(), line, &Renderer::plain()));
}

Trait Implementations§

§

impl Clone for ParseError

§

fn clone(&self) -> ParseError

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for ParseError

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Display for ParseError

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Error for ParseError

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.