syn/error.rs
1#[cfg(feature = "parsing")]
2use crate::buffer::Cursor;
3use crate::ext::{PunctExt as _, TokenStreamExt as _};
4use crate::thread::ThreadBound;
5use proc_macro2::{
6 Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree,
7};
8#[cfg(feature = "printing")]
9use quote::ToTokens;
10use std::fmt::{self, Debug, Display};
11use std::slice;
12use std::vec;
13
14/// The result of a Syn parser.
15pub type Result<T> = std::result::Result<T, Error>;
16
17/// Error returned when a Syn parser cannot parse the input tokens.
18///
19/// # Error reporting in proc macros
20///
21/// The correct way to report errors back to the compiler from a procedural
22/// macro is by emitting an appropriately spanned invocation of
23/// [`compile_error!`] in the generated code. This produces a better diagnostic
24/// message than simply panicking the macro.
25///
26/// [`compile_error!`]: std::compile_error!
27///
28/// When parsing macro input, the [`parse_macro_input!`] macro handles the
29/// conversion to `compile_error!` automatically.
30///
31/// [`parse_macro_input!`]: crate::parse_macro_input!
32///
33/// ```
34/// # extern crate proc_macro;
35/// #
36/// use proc_macro::TokenStream;
37/// use syn::parse::{Parse, ParseStream, Result};
38/// use syn::{parse_macro_input, ItemFn};
39///
40/// # const IGNORE: &str = stringify! {
41/// #[proc_macro_attribute]
42/// # };
43/// pub fn my_attr(args: TokenStream, input: TokenStream) -> TokenStream {
44/// let args = parse_macro_input!(args as MyAttrArgs);
45/// let input = parse_macro_input!(input as ItemFn);
46///
47/// /* ... */
48/// # TokenStream::new()
49/// }
50///
51/// struct MyAttrArgs {
52/// # _k: [(); { stringify! {
53/// ...
54/// # }; 0 }]
55/// }
56///
57/// impl Parse for MyAttrArgs {
58/// fn parse(input: ParseStream) -> Result<Self> {
59/// # stringify! {
60/// ...
61/// # };
62/// # unimplemented!()
63/// }
64/// }
65/// ```
66///
67/// For errors that arise later than the initial parsing stage, the
68/// [`.to_compile_error()`] or [`.into_compile_error()`] methods can be used to
69/// perform an explicit conversion to `compile_error!`.
70///
71/// [`.to_compile_error()`]: Error::to_compile_error
72/// [`.into_compile_error()`]: Error::into_compile_error
73///
74/// ```
75/// # extern crate proc_macro;
76/// #
77/// # use proc_macro::TokenStream;
78/// # use syn::{parse_macro_input, DeriveInput};
79/// #
80/// # const IGNORE: &str = stringify! {
81/// #[proc_macro_derive(MyDerive)]
82/// # };
83/// pub fn my_derive(input: TokenStream) -> TokenStream {
84/// let input = parse_macro_input!(input as DeriveInput);
85///
86/// // fn(DeriveInput) -> syn::Result<proc_macro2::TokenStream>
87/// expand::my_derive(input)
88/// .unwrap_or_else(syn::Error::into_compile_error)
89/// .into()
90/// }
91/// #
92/// # mod expand {
93/// # use proc_macro2::TokenStream;
94/// # use syn::{DeriveInput, Result};
95/// #
96/// # pub fn my_derive(input: DeriveInput) -> Result<TokenStream> {
97/// # unimplemented!()
98/// # }
99/// # }
100/// ```
101pub struct Error {
102 messages: Vec<ErrorMessage>,
103}
104
105struct ErrorMessage {
106 // Span is implemented as an index into a thread-local interner to keep the
107 // size small. It is not safe to access from a different thread. We want
108 // errors to be Send and Sync to play nicely with ecosystem crates for error
109 // handling, so pin the span we're given to its original thread and assume
110 // it is Span::call_site if accessed from any other thread.
111 span: ThreadBound<SpanRange>,
112 message: String,
113}
114
115// Cannot use std::ops::Range<Span> because that does not implement Copy,
116// whereas ThreadBound<T> requires a Copy impl as a way to ensure no Drop impls
117// are involved.
118struct SpanRange {
119 start: Span,
120 end: Span,
121}
122
123#[cfg(test)]
124struct _Test
125where
126 Error: Send + Sync;
127
128impl Error {
129 /// Usually the [`ParseStream::error`] method will be used instead, which
130 /// automatically uses the correct span from the current position of the
131 /// parse stream.
132 ///
133 /// Use `Error::new` when the error needs to be triggered on some span other
134 /// than where the parse stream is currently positioned.
135 ///
136 /// [`ParseStream::error`]: crate::parse::ParseBuffer::error
137 ///
138 /// # Example
139 ///
140 /// ```
141 /// use syn::{Error, Ident, LitStr, Result, Token};
142 /// use syn::parse::ParseStream;
143 ///
144 /// // Parses input that looks like `name = "string"` where the key must be
145 /// // the identifier `name` and the value may be any string literal.
146 /// // Returns the string literal.
147 /// fn parse_name(input: ParseStream) -> Result<LitStr> {
148 /// let name_token: Ident = input.parse()?;
149 /// if name_token != "name" {
150 /// // Trigger an error not on the current position of the stream,
151 /// // but on the position of the unexpected identifier.
152 /// return Err(Error::new(name_token.span(), "expected `name`"));
153 /// }
154 /// input.parse::<Token![=]>()?;
155 /// let s: LitStr = input.parse()?;
156 /// Ok(s)
157 /// }
158 /// ```
159 pub fn new<T: Display>(span: Span, message: T) -> Self {
160 return new(span, message.to_string());
161
162 fn new(span: Span, message: String) -> Error {
163 Error {
164 messages: vec![ErrorMessage {
165 span: ThreadBound::new(SpanRange {
166 start: span,
167 end: span,
168 }),
169 message,
170 }],
171 }
172 }
173 }
174
175 /// Creates an error with the specified message spanning the given syntax
176 /// tree node.
177 ///
178 /// Unlike the `Error::new` constructor, this constructor takes an argument
179 /// `tokens` which is a syntax tree node. This allows the resulting `Error`
180 /// to attempt to span all tokens inside of `tokens`. While you would
181 /// typically be able to use the `Spanned` trait with the above `Error::new`
182 /// constructor, implementation limitations today mean that
183 /// `Error::new_spanned` may provide a higher-quality error message on
184 /// stable Rust.
185 ///
186 /// When in doubt it's recommended to stick to `Error::new` (or
187 /// `ParseStream::error`)!
188 #[cfg(feature = "printing")]
189 #[cfg_attr(docsrs, doc(cfg(feature = "printing")))]
190 pub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self {
191 return new_spanned(tokens.into_token_stream(), message.to_string());
192
193 fn new_spanned(tokens: TokenStream, message: String) -> Error {
194 let mut iter = tokens.into_iter();
195 let start = iter.next().map_or_else(Span::call_site, |t| t.span());
196 let end = iter.last().map_or(start, |t| t.span());
197 Error {
198 messages: vec![ErrorMessage {
199 span: ThreadBound::new(SpanRange { start, end }),
200 message,
201 }],
202 }
203 }
204 }
205
206 /// The source location of the error.
207 ///
208 /// Spans are not thread-safe so this function returns `Span::call_site()`
209 /// if called from a different thread than the one on which the `Error` was
210 /// originally created.
211 pub fn span(&self) -> Span {
212 let SpanRange { start, end } = match self.messages[0].span.get() {
213 Some(span) => *span,
214 None => return Span::call_site(),
215 };
216 start.join(end).unwrap_or(start)
217 }
218
219 /// Render the error as an invocation of [`compile_error!`].
220 ///
221 /// The [`parse_macro_input!`] macro provides a convenient way to invoke
222 /// this method correctly in a procedural macro.
223 ///
224 /// [`compile_error!`]: std::compile_error!
225 /// [`parse_macro_input!`]: crate::parse_macro_input!
226 pub fn to_compile_error(&self) -> TokenStream {
227 let mut tokens = TokenStream::new();
228 for msg in &self.messages {
229 ErrorMessage::to_compile_error(msg, &mut tokens);
230 }
231 tokens
232 }
233
234 /// Render the error as an invocation of [`compile_error!`].
235 ///
236 /// [`compile_error!`]: std::compile_error!
237 ///
238 /// # Example
239 ///
240 /// ```
241 /// # extern crate proc_macro;
242 /// #
243 /// use proc_macro::TokenStream;
244 /// use syn::{parse_macro_input, DeriveInput, Error};
245 ///
246 /// # const _: &str = stringify! {
247 /// #[proc_macro_derive(MyTrait)]
248 /// # };
249 /// pub fn derive_my_trait(input: TokenStream) -> TokenStream {
250 /// let input = parse_macro_input!(input as DeriveInput);
251 /// my_trait::expand(input)
252 /// .unwrap_or_else(Error::into_compile_error)
253 /// .into()
254 /// }
255 ///
256 /// mod my_trait {
257 /// use proc_macro2::TokenStream;
258 /// use syn::{DeriveInput, Result};
259 ///
260 /// pub(crate) fn expand(input: DeriveInput) -> Result<TokenStream> {
261 /// /* ... */
262 /// # unimplemented!()
263 /// }
264 /// }
265 /// ```
266 pub fn into_compile_error(self) -> TokenStream {
267 self.to_compile_error()
268 }
269
270 /// Add another error message to self such that when `to_compile_error()` is
271 /// called, both errors will be emitted together.
272 pub fn combine(&mut self, another: Error) {
273 self.messages.extend(another.messages);
274 }
275}
276
277impl ErrorMessage {
278 fn to_compile_error(&self, tokens: &mut TokenStream) {
279 let (start, end) = match self.span.get() {
280 Some(range) => (range.start, range.end),
281 None => (Span::call_site(), Span::call_site()),
282 };
283
284 // ::core::compile_error!($message)
285 tokens.append(TokenTree::Punct(Punct::new_spanned(
286 ':',
287 Spacing::Joint,
288 start,
289 )));
290 tokens.append(TokenTree::Punct(Punct::new_spanned(
291 ':',
292 Spacing::Alone,
293 start,
294 )));
295 tokens.append(TokenTree::Ident(Ident::new("core", start)));
296 tokens.append(TokenTree::Punct(Punct::new_spanned(
297 ':',
298 Spacing::Joint,
299 start,
300 )));
301 tokens.append(TokenTree::Punct(Punct::new_spanned(
302 ':',
303 Spacing::Alone,
304 start,
305 )));
306 tokens.append(TokenTree::Ident(Ident::new("compile_error", start)));
307 tokens.append(TokenTree::Punct(Punct::new_spanned(
308 '!',
309 Spacing::Alone,
310 start,
311 )));
312 tokens.append(TokenTree::Group({
313 let mut group = Group::new(
314 Delimiter::Brace,
315 TokenStream::from({
316 let mut string = Literal::string(&self.message);
317 string.set_span(end);
318 TokenTree::Literal(string)
319 }),
320 );
321 group.set_span(end);
322 group
323 }));
324 }
325}
326
327#[cfg(feature = "parsing")]
328pub(crate) fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
329 if cursor.eof() {
330 Error::new(scope, format!("unexpected end of input, {}", message))
331 } else {
332 let span = crate::buffer::open_span_of_group(cursor);
333 Error::new(span, message)
334 }
335}
336
337#[cfg(all(feature = "parsing", any(feature = "full", feature = "derive")))]
338pub(crate) fn new2<T: Display>(start: Span, end: Span, message: T) -> Error {
339 return new2(start, end, message.to_string());
340
341 fn new2(start: Span, end: Span, message: String) -> Error {
342 Error {
343 messages: vec![ErrorMessage {
344 span: ThreadBound::new(SpanRange { start, end }),
345 message,
346 }],
347 }
348 }
349}
350
351impl Debug for Error {
352 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
353 if self.messages.len() == 1 {
354 formatter
355 .debug_tuple("Error")
356 .field(&self.messages[0])
357 .finish()
358 } else {
359 formatter
360 .debug_tuple("Error")
361 .field(&self.messages)
362 .finish()
363 }
364 }
365}
366
367impl Debug for ErrorMessage {
368 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
369 Debug::fmt(&self.message, formatter)
370 }
371}
372
373impl Display for Error {
374 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
375 formatter.write_str(&self.messages[0].message)
376 }
377}
378
379impl Clone for Error {
380 fn clone(&self) -> Self {
381 Error {
382 messages: self.messages.clone(),
383 }
384 }
385}
386
387impl Clone for ErrorMessage {
388 fn clone(&self) -> Self {
389 ErrorMessage {
390 span: self.span,
391 message: self.message.clone(),
392 }
393 }
394}
395
396impl Clone for SpanRange {
397 fn clone(&self) -> Self {
398 *self
399 }
400}
401
402impl Copy for SpanRange {}
403
404impl std::error::Error for Error {}
405
406impl From<LexError> for Error {
407 fn from(err: LexError) -> Self {
408 Error::new(err.span(), err)
409 }
410}
411
412impl IntoIterator for Error {
413 type Item = Error;
414 type IntoIter = IntoIter;
415
416 fn into_iter(self) -> Self::IntoIter {
417 IntoIter {
418 messages: self.messages.into_iter(),
419 }
420 }
421}
422
423pub struct IntoIter {
424 messages: vec::IntoIter<ErrorMessage>,
425}
426
427impl Iterator for IntoIter {
428 type Item = Error;
429
430 fn next(&mut self) -> Option<Self::Item> {
431 Some(Error {
432 messages: vec![self.messages.next()?],
433 })
434 }
435}
436
437impl<'a> IntoIterator for &'a Error {
438 type Item = Error;
439 type IntoIter = Iter<'a>;
440
441 fn into_iter(self) -> Self::IntoIter {
442 Iter {
443 messages: self.messages.iter(),
444 }
445 }
446}
447
448pub struct Iter<'a> {
449 messages: slice::Iter<'a, ErrorMessage>,
450}
451
452impl<'a> Iterator for Iter<'a> {
453 type Item = Error;
454
455 fn next(&mut self) -> Option<Self::Item> {
456 Some(Error {
457 messages: vec![self.messages.next()?.clone()],
458 })
459 }
460}
461
462impl Extend<Error> for Error {
463 fn extend<T: IntoIterator<Item = Error>>(&mut self, iter: T) {
464 for err in iter {
465 self.combine(err);
466 }
467 }
468}