Struct Error

Source
pub struct Error { /* private fields */ }
Expand description

Error returned when a Syn parser cannot parse the input tokens.

§Error reporting in proc macros

The correct way to report errors back to the compiler from a procedural macro is by emitting an appropriately spanned invocation of compile_error! in the generated code. This produces a better diagnostic message than simply panicking the macro.

When parsing macro input, the parse_macro_input! macro handles the conversion to compile_error! automatically.

use proc_macro::TokenStream;
use syn::parse::{Parse, ParseStream, Result};
use syn::{parse_macro_input, ItemFn};

#[proc_macro_attribute]
pub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream {
    let args = parse_macro_input!(args as MyAttrArgs);
    let input = parse_macro_input!(input as ItemFn);

    /* ... */
}

struct MyAttrArgs {
    ...
}

impl Parse for MyAttrArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        ...
    }
}

For errors that arise later than the initial parsing stage, the .to_compile_error() or .into_compile_error() methods can be used to perform an explicit conversion to compile_error!.

#[proc_macro_derive(MyDerive)]
pub fn my_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    // fn(DeriveInput) -> syn::Result<proc_macro2::TokenStream>
    expand::my_derive(input)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

Implementations§

Source§

impl Error

Source

pub fn new<T: Display>(span: Span, message: T) -> Self

Usually the ParseStream::error method will be used instead, which automatically uses the correct span from the current position of the parse stream.

Use Error::new when the error needs to be triggered on some span other than where the parse stream is currently positioned.

§Example
use syn::{Error, Ident, LitStr, Result, Token};
use syn::parse::ParseStream;

// Parses input that looks like `name = "string"` where the key must be
// the identifier `name` and the value may be any string literal.
// Returns the string literal.
fn parse_name(input: ParseStream) -> Result<LitStr> {
    let name_token: Ident = input.parse()?;
    if name_token != "name" {
        // Trigger an error not on the current position of the stream,
        // but on the position of the unexpected identifier.
        return Err(Error::new(name_token.span(), "expected `name`"));
    }
    input.parse::<Token![=]>()?;
    let s: LitStr = input.parse()?;
    Ok(s)
}
Source

pub fn span(&self) -> Span

The source location of the error.

Spans are not thread-safe so this function returns Span::call_site() if called from a different thread than the one on which the Error was originally created.

Source

pub fn to_compile_error(&self) -> TokenStream

Render the error as an invocation of compile_error!.

The parse_macro_input! macro provides a convenient way to invoke this method correctly in a procedural macro.

Source

pub fn into_compile_error(self) -> TokenStream

Render the error as an invocation of compile_error!.

§Example
use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput, Error};

#[proc_macro_derive(MyTrait)]
pub fn derive_my_trait(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    my_trait::expand(input)
        .unwrap_or_else(Error::into_compile_error)
        .into()
}

mod my_trait {
    use proc_macro2::TokenStream;
    use syn::{DeriveInput, Result};

    pub(crate) fn expand(input: DeriveInput) -> Result<TokenStream> {
        /* ... */
    }
}
Source

pub fn combine(&mut self, another: Error)

Add another error message to self such that when to_compile_error() is called, both errors will be emitted together.

Trait Implementations§

Source§

impl Clone for Error

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Error

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Error for Error

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
Source§

impl Extend<Error> for Error

Source§

fn extend<T: IntoIterator<Item = Error>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl From<LexError> for Error

Source§

fn from(err: LexError) -> Self

Converts to this type from the input type.
Source§

impl<'a> IntoIterator for &'a Error

Source§

type Item = Error

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl IntoIterator for Error

Source§

type Item = Error

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl Freeze for Error

§

impl RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnwindSafe for Error

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> 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.