pub struct Error { /* private fields */ }
parsing
only.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_macro_input, AttributeArgs, ItemFn};
#[proc_macro_attribute]
pub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as AttributeArgs);
let input = parse_macro_input!(input as ItemFn);
/* ... */
}
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
impl Error
sourcepub fn new<T: Display>(span: Span, message: T) -> Self
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)
}
Examples found in repository?
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
fn check_unexpected(&self) -> Result<()> {
match inner_unexpected(self).1 {
Some(span) => Err(Error::new(span, "unexpected token")),
None => Ok(()),
}
}
}
#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
impl<T: Parse> Parse for Box<T> {
fn parse(input: ParseStream) -> Result<Self> {
input.parse().map(Box::new)
}
}
#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
impl<T: Parse + Token> Parse for Option<T> {
fn parse(input: ParseStream) -> Result<Self> {
if T::peek(input.cursor()) {
Ok(Some(input.parse()?))
} else {
Ok(None)
}
}
}
#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
impl Parse for TokenStream {
fn parse(input: ParseStream) -> Result<Self> {
input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
}
}
#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
impl Parse for TokenTree {
fn parse(input: ParseStream) -> Result<Self> {
input.step(|cursor| match cursor.token_tree() {
Some((tt, rest)) => Ok((tt, rest)),
None => Err(cursor.error("expected token tree")),
})
}
}
#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
impl Parse for Group {
fn parse(input: ParseStream) -> Result<Self> {
input.step(|cursor| {
for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
if let Some((inside, span, rest)) = cursor.group(*delim) {
let mut group = Group::new(*delim, inside.token_stream());
group.set_span(span);
return Ok((group, rest));
}
}
Err(cursor.error("expected group token"))
})
}
}
#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
impl Parse for Punct {
fn parse(input: ParseStream) -> Result<Self> {
input.step(|cursor| match cursor.punct() {
Some((punct, rest)) => Ok((punct, rest)),
None => Err(cursor.error("expected punctuation token")),
})
}
}
#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
impl Parse for Literal {
fn parse(input: ParseStream) -> Result<Self> {
input.step(|cursor| match cursor.literal() {
Some((literal, rest)) => Ok((literal, rest)),
None => Err(cursor.error("expected literal token")),
})
}
}
/// Parser that can parse Rust tokens into a particular syntax tree node.
///
/// Refer to the [module documentation] for details about parsing in Syn.
///
/// [module documentation]: self
///
/// *This trait is available only if Syn is built with the `"parsing"` feature.*
pub trait Parser: Sized {
type Output;
/// Parse a proc-macro2 token stream into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the stream, an error is returned.
fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
/// Parse tokens of source code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the stream, an error is returned.
///
/// *This method is available only if Syn is built with both the `"parsing"` and
/// `"proc-macro"` features.*
#[cfg(all(
not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))),
feature = "proc-macro"
))]
fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
self.parse2(proc_macro2::TokenStream::from(tokens))
}
/// Parse a string of Rust code into the chosen syntax tree node.
///
/// This function will check that the input is fully parsed. If there are
/// any unparsed tokens at the end of the string, an error is returned.
///
/// # Hygiene
///
/// Every span in the resulting syntax tree will be set to resolve at the
/// macro call site.
fn parse_str(self, s: &str) -> Result<Self::Output> {
self.parse2(proc_macro2::TokenStream::from_str(s)?)
}
// Not public API.
#[doc(hidden)]
#[cfg(any(feature = "full", feature = "derive"))]
fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
let _ = scope;
self.parse2(tokens)
}
// Not public API.
#[doc(hidden)]
#[cfg(any(feature = "full", feature = "derive"))]
fn __parse_stream(self, input: ParseStream) -> Result<Self::Output> {
input.parse().and_then(|tokens| self.parse2(tokens))
}
}
fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
let scope = Span::call_site();
let cursor = tokens.begin();
let unexpected = Rc::new(Cell::new(Unexpected::None));
new_parse_buffer(scope, cursor, unexpected)
}
impl<F, T> Parser for F
where
F: FnOnce(ParseStream) -> Result<T>,
{
type Output = T;
fn parse2(self, tokens: TokenStream) -> Result<T> {
let buf = TokenBuffer::new2(tokens);
let state = tokens_to_parse_buffer(&buf);
let node = self(&state)?;
state.check_unexpected()?;
if let Some(unexpected_span) = span_of_unexpected_ignoring_nones(state.cursor()) {
Err(Error::new(unexpected_span, "unexpected token"))
} else {
Ok(node)
}
}
#[cfg(any(feature = "full", feature = "derive"))]
fn __parse_scoped(self, scope: Span, tokens: TokenStream) -> Result<Self::Output> {
let buf = TokenBuffer::new2(tokens);
let cursor = buf.begin();
let unexpected = Rc::new(Cell::new(Unexpected::None));
let state = new_parse_buffer(scope, cursor, unexpected);
let node = self(&state)?;
state.check_unexpected()?;
if let Some(unexpected_span) = span_of_unexpected_ignoring_nones(state.cursor()) {
Err(Error::new(unexpected_span, "unexpected token"))
} else {
Ok(node)
}
}
More examples
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
pub fn base10_parse<N>(&self) -> Result<N>
where
N: FromStr,
N::Err: Display,
{
self.base10_digits()
.parse()
.map_err(|err| Error::new(self.span(), err))
}
pub fn suffix(&self) -> &str {
&self.repr.suffix
}
pub fn span(&self) -> Span {
self.repr.token.span()
}
pub fn set_span(&mut self, span: Span) {
self.repr.token.set_span(span);
}
pub fn token(&self) -> Literal {
self.repr.token.clone()
}
}
impl From<Literal> for LitInt {
fn from(token: Literal) -> Self {
let repr = token.to_string();
if let Some((digits, suffix)) = value::parse_lit_int(&repr) {
LitInt {
repr: Box::new(LitIntRepr {
token,
digits,
suffix,
}),
}
} else {
panic!("Not an integer literal: `{}`", repr);
}
}
}
impl Display for LitInt {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
self.repr.token.fmt(formatter)
}
}
impl LitFloat {
pub fn new(repr: &str, span: Span) -> Self {
let (digits, suffix) = match value::parse_lit_float(repr) {
Some(parse) => parse,
None => panic!("Not a float literal: `{}`", repr),
};
let mut token = match value::to_literal(repr, &digits, &suffix) {
Some(token) => token,
None => panic!("Unsupported float literal: `{}`", repr),
};
token.set_span(span);
LitFloat {
repr: Box::new(LitFloatRepr {
token,
digits,
suffix,
}),
}
}
pub fn base10_digits(&self) -> &str {
&self.repr.digits
}
pub fn base10_parse<N>(&self) -> Result<N>
where
N: FromStr,
N::Err: Display,
{
self.base10_digits()
.parse()
.map_err(|err| Error::new(self.span(), err))
}
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
if cursor.eof() {
Error::new(scope, format!("unexpected end of input, {}", message))
} else {
let span = crate::buffer::open_span_of_group(cursor);
Error::new(span, message)
}
}
#[cfg(all(feature = "parsing", any(feature = "full", feature = "derive")))]
pub fn new2<T: Display>(start: Span, end: Span, message: T) -> Error {
return new2(start, end, message.to_string());
fn new2(start: Span, end: Span, message: String) -> Error {
Error {
messages: vec![ErrorMessage {
start_span: ThreadBound::new(start),
end_span: ThreadBound::new(end),
message,
}],
}
}
}
impl Debug for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
if self.messages.len() == 1 {
formatter
.debug_tuple("Error")
.field(&self.messages[0])
.finish()
} else {
formatter
.debug_tuple("Error")
.field(&self.messages)
.finish()
}
}
}
impl Debug for ErrorMessage {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.message, formatter)
}
}
impl Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(&self.messages[0].message)
}
}
impl Clone for Error {
fn clone(&self) -> Self {
Error {
messages: self.messages.clone(),
}
}
}
impl Clone for ErrorMessage {
fn clone(&self) -> Self {
let start = self
.start_span
.get()
.cloned()
.unwrap_or_else(Span::call_site);
let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site);
ErrorMessage {
start_span: ThreadBound::new(start),
end_span: ThreadBound::new(end),
message: self.message.clone(),
}
}
}
impl std::error::Error for Error {}
impl From<LexError> for Error {
fn from(err: LexError) -> Self {
Error::new(err.span(), "lex error")
}
2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
fn parse(input: ParseStream) -> Result<Self> {
let lit: LitInt = input.parse()?;
if lit.suffix().is_empty() {
Ok(Index {
index: lit
.base10_digits()
.parse()
.map_err(|err| Error::new(lit.span(), err))?,
span: lit.span(),
})
} else {
Err(Error::new(lit.span(), "expected unsuffixed integer"))
}
}
}
fn multi_index(e: &mut Expr, dot_token: &mut Token![.], float: LitFloat) -> Result<bool> {
let mut float_repr = float.to_string();
let trailing_dot = float_repr.ends_with('.');
if trailing_dot {
float_repr.truncate(float_repr.len() - 1);
}
for part in float_repr.split('.') {
let index = crate::parse_str(part).map_err(|err| Error::new(float.span(), err))?;
#[cfg(not(syn_no_const_vec_new))]
let base = mem::replace(e, Expr::DUMMY);
#[cfg(syn_no_const_vec_new)]
let base = mem::replace(e, Expr::Verbatim(TokenStream::new()));
*e = Expr::Field(ExprField {
attrs: Vec::new(),
base: Box::new(base),
dot_token: Token![.](dot_token.span),
member: Member::Unnamed(index),
});
*dot_token = Token![.](float.span());
}
Ok(!trailing_dot)
}
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
fn punct_helper(input: ParseStream, token: &str, spans: &mut [Span; 3]) -> Result<()> {
input.step(|cursor| {
let mut cursor = *cursor;
assert!(token.len() <= spans.len());
for (i, ch) in token.chars().enumerate() {
match cursor.punct() {
Some((punct, rest)) => {
spans[i] = punct.span();
if punct.as_char() != ch {
break;
} else if i == token.len() - 1 {
return Ok(((), rest));
} else if punct.spacing() != Spacing::Joint {
break;
}
cursor = rest;
}
None => break,
}
}
Err(Error::new(spans[0], format!("expected `{}`", token)))
})
}
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
pub fn error(self) -> Error {
let comparisons = self.comparisons.borrow();
match comparisons.len() {
0 => {
if self.cursor.eof() {
Error::new(self.scope, "unexpected end of input")
} else {
Error::new(self.cursor.span(), "unexpected token")
}
}
1 => {
let message = format!("expected {}", comparisons[0]);
error::new_at(self.scope, self.cursor, message)
}
2 => {
let message = format!("expected {} or {}", comparisons[0], comparisons[1]);
error::new_at(self.scope, self.cursor, message)
}
_ => {
let join = comparisons.join(", ");
let message = format!("expected one of: {}", join);
error::new_at(self.scope, self.cursor, message)
}
}
}
sourcepub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self
pub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> 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
)!
Examples found in repository?
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
fn parse_impl(input: ParseStream, allow_verbatim_impl: bool) -> Result<Option<ItemImpl>> {
let mut attrs = input.call(Attribute::parse_outer)?;
let has_visibility = allow_verbatim_impl && input.parse::<Visibility>()?.is_some();
let defaultness: Option<Token![default]> = input.parse()?;
let unsafety: Option<Token![unsafe]> = input.parse()?;
let impl_token: Token![impl] = input.parse()?;
let has_generics = input.peek(Token![<])
&& (input.peek2(Token![>])
|| input.peek2(Token![#])
|| (input.peek2(Ident) || input.peek2(Lifetime))
&& (input.peek3(Token![:])
|| input.peek3(Token![,])
|| input.peek3(Token![>])
|| input.peek3(Token![=]))
|| input.peek2(Token![const]));
let mut generics: Generics = if has_generics {
input.parse()?
} else {
Generics::default()
};
let is_const_impl = allow_verbatim_impl
&& (input.peek(Token![const]) || input.peek(Token![?]) && input.peek2(Token![const]));
if is_const_impl {
input.parse::<Option<Token![?]>>()?;
input.parse::<Token![const]>()?;
}
let begin = input.fork();
let polarity = if input.peek(Token![!]) && !input.peek2(token::Brace) {
Some(input.parse::<Token![!]>()?)
} else {
None
};
#[cfg(not(feature = "printing"))]
let first_ty_span = input.span();
let mut first_ty: Type = input.parse()?;
let self_ty: Type;
let trait_;
let is_impl_for = input.peek(Token![for]);
if is_impl_for {
let for_token: Token![for] = input.parse()?;
let mut first_ty_ref = &first_ty;
while let Type::Group(ty) = first_ty_ref {
first_ty_ref = &ty.elem;
}
if let Type::Path(TypePath { qself: None, .. }) = first_ty_ref {
while let Type::Group(ty) = first_ty {
first_ty = *ty.elem;
}
if let Type::Path(TypePath { qself: None, path }) = first_ty {
trait_ = Some((polarity, path, for_token));
} else {
unreachable!();
}
} else if !allow_verbatim_impl {
#[cfg(feature = "printing")]
return Err(Error::new_spanned(first_ty_ref, "expected trait path"));
#[cfg(not(feature = "printing"))]
return Err(Error::new(first_ty_span, "expected trait path"));
} else {
trait_ = None;
}
self_ty = input.parse()?;
} else {
trait_ = None;
self_ty = if polarity.is_none() {
first_ty
} else {
Type::Verbatim(verbatim::between(begin, input))
};
}
generics.where_clause = input.parse()?;
let content;
let brace_token = braced!(content in input);
attr::parsing::parse_inner(&content, &mut attrs)?;
let mut items = Vec::new();
while !content.is_empty() {
items.push(content.parse()?);
}
if has_visibility || is_const_impl || is_impl_for && trait_.is_none() {
Ok(None)
} else {
Ok(Some(ItemImpl {
attrs,
defaultness,
unsafety,
impl_token,
generics,
trait_,
self_ty: Box::new(self_ty),
brace_token,
items,
}))
}
}
sourcepub fn span(&self) -> Span
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.
sourcepub fn to_compile_error(&self) -> TokenStream
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.
sourcepub fn into_compile_error(self) -> TokenStream
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> {
/* ... */
}
}
Trait Implementations§
source§impl Error for Error
impl Error for Error
1.30.0 · source§fn source(&self) -> Option<&(dyn Error + 'static)>
fn source(&self) -> Option<&(dyn Error + 'static)>
1.0.0 · source§fn description(&self) -> &str
fn description(&self) -> &str
source§impl Extend<Error> for Error
impl Extend<Error> for Error
source§fn extend<T: IntoIterator<Item = Error>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = Error>>(&mut self, iter: T)
source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)