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