Struct Error

pub struct Error { /* private fields */ }

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.

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

# const IGNORE: &str = stringify! {
#[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);

    /* ... */
    # TokenStream::new()
}

struct MyAttrArgs {
    # _k: [(); { stringify! {
    ...
    # }; 0 }]
}

impl Parse for MyAttrArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        # stringify! {
        ...
        # };
        # unimplemented!()
    }
}

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

# extern crate proc_macro;
#
# use proc_macro::TokenStream;
# use syn::{parse_macro_input, DeriveInput};
#
# const IGNORE: &str = stringify! {
#[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()
}
#
# mod expand {
#     use proc_macro2::TokenStream;
#     use syn::{DeriveInput, Result};
#
#     pub fn my_derive(input: DeriveInput) -> Result<TokenStream> {
#         unimplemented!()
#     }
# }

Implementations

impl Error

fn new(span: Span, message: impl Display) -> 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)
}
fn new_spanned(tokens: impl ToTokens, message: impl Display) -> Self

Creates an error with the specified message spanning the given syntax tree node.

Unlike the Error::new constructor, this constructor takes an argument tokens which is a syntax tree node. This allows the resulting Error to attempt to span all tokens inside of tokens. While you would typically be able to use the Spanned trait with the above Error::new constructor, implementation limitations today mean that Error::new_spanned may provide a higher-quality error message on stable Rust.

When in doubt it's recommended to stick to Error::new (or ParseStream::error)!

fn new_range<'a>(span: impl Into<Range<Cursor<'a>>>, message: impl Display) -> Self

Creates an error spanning the given cursor range.

Example

This parses a sequence of '+'-separated lifetimes and types like Vec<u8> + dyn Display + 'static, at least one of which must be a type.

use syn::{Lifetime, Token, Type};
use syn::parse::{Error, ParseStream, Result};

enum Thing {
    Lifetime(Lifetime),
    Type(Type),
}

fn parse_things(input: ParseStream) -> Result<Vec<Thing>> {
    let things_begin = input.cursor();
    let things_end;
    let mut things = Vec::new();
    let mut has_type = false;
    loop {
        if input.peek(Lifetime) {
            let lifetime: Lifetime = input.parse()?;
            things.push(Thing::Lifetime(lifetime));
        } else {
            let ty = input.call(Type::without_plus)?;
            things.push(Thing::Type(ty));
            has_type = true;
        }
        let plus_token: Option<Token![+]> = input.parse()?;
        if plus_token.is_none() {
            things_end = input.cursor();
            break;
        }
    }

    if has_type {
        Ok(things)
    } else {
        let msg = "things must not be all lifetimes, at least one type is required";
        Err(Error::new_range(things_begin..things_end, msg))
    }
}
error: things must not be all lifetimes, at least one type is required
 --> example.rs:4:23
  |
4 |     example!(THINGS = 'a + 'b, ...);
  |                       ^^^^^^^
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.

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.

fn into_compile_error(self) -> TokenStream

Render the error as an invocation of compile_error!.

Example

# extern crate proc_macro;
#
use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput, Error};

# const _: &str = stringify! {
#[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> {
        /* ... */
        # unimplemented!()
    }
}
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

impl Clone for Error

fn clone(&self) -> Self

impl Debug for Error

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

impl Display for Error

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

impl Error for Error

impl Extend<Error> for Error

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

impl From<LexError> for Error

fn from(err: LexError) -> Self

impl IntoIterator for Error

type Item = Error;
type IntoIter = IntoIter;
fn into_iter(self) -> Self::IntoIter

Auto Trait Implementations

impl Freeze for Error

impl RefUnwindSafe for Error

impl Send for Error

impl Sync for Error

impl Unpin for Error

impl UnsafeUnpin for Error

impl UnwindSafe for Error

Blanket Implementations

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

fn type_id(&self) -> TypeId

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

fn borrow(&self) -> &T

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

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

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

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

impl<T> From<T> for Error

fn from(t: T) -> T

Returns the argument unchanged.

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

type Owned = T;
fn to_owned(&self) -> T
fn clone_into(&self, target: &mut T)

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

fn to_string(&self) -> String

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

fn into(self) -> U

Calls U::from(self).

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

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

type Error = never;
fn try_from(value: U) -> Result<T, never>

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

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