blob: 097a6b84ad62377307ff6d696d6197d50524c17c [file] [log] [blame]
David Tolnayad4b2472018-08-25 08:25:24 -04001use std;
David Tolnayb2dc98a2019-04-20 13:32:51 -07002use std::fmt::{self, Debug, Display};
David Tolnayad4b2472018-08-25 08:25:24 -04003use std::iter::FromIterator;
4
5use proc_macro2::{
6 Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree,
7};
Alex Crichton3ea5ca32018-11-16 02:43:46 -08008#[cfg(feature = "printing")]
9use quote::ToTokens;
David Tolnayad4b2472018-08-25 08:25:24 -040010
David Tolnaya72f2622018-11-24 13:39:45 -080011#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -040012use buffer::Cursor;
David Tolnayfe89fcc2018-09-08 17:56:31 -070013#[cfg(all(procmacro2_semver_exempt, feature = "parsing"))]
14use private;
David Tolnay32874802018-11-11 08:52:19 -080015use thread::ThreadBound;
David Tolnayad4b2472018-08-25 08:25:24 -040016
17/// The result of a Syn parser.
18pub type Result<T> = std::result::Result<T, Error>;
19
20/// Error returned when a Syn parser cannot parse the input tokens.
21///
22/// Refer to the [module documentation] for details about parsing in Syn.
23///
24/// [module documentation]: index.html
25///
26/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnayad4b2472018-08-25 08:25:24 -040027pub struct Error {
David Tolnay32874802018-11-11 08:52:19 -080028 // Span is implemented as an index into a thread-local interner to keep the
29 // size small. It is not safe to access from a different thread. We want
30 // errors to be Send and Sync to play nicely with the Failure crate, so pin
31 // the span we're given to its original thread and assume it is
32 // Span::call_site if accessed from any other thread.
Alex Crichton3ea5ca32018-11-16 02:43:46 -080033 start_span: ThreadBound<Span>,
34 end_span: ThreadBound<Span>,
David Tolnayad4b2472018-08-25 08:25:24 -040035 message: String,
36}
37
David Tolnay32874802018-11-11 08:52:19 -080038#[cfg(test)]
David Tolnay5f794802018-11-24 14:51:21 -080039struct _Test
40where
41 Error: Send + Sync;
David Tolnay32874802018-11-11 08:52:19 -080042
David Tolnayad4b2472018-08-25 08:25:24 -040043impl Error {
David Tolnay7c8efe92018-09-01 10:00:50 -070044 /// Usually the [`ParseStream::error`] method will be used instead, which
45 /// automatically uses the correct span from the current position of the
46 /// parse stream.
47 ///
48 /// Use `Error::new` when the error needs to be triggered on some span other
49 /// than where the parse stream is currently positioned.
50 ///
51 /// [`ParseStream::error`]: struct.ParseBuffer.html#method.error
52 ///
53 /// # Example
54 ///
David Tolnay95989db2019-01-01 15:05:57 -050055 /// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -050056 /// use syn::{Error, Ident, LitStr, Result, Token};
David Tolnay67fea042018-11-24 14:50:20 -080057 /// use syn::parse::ParseStream;
David Tolnay7c8efe92018-09-01 10:00:50 -070058 ///
59 /// // Parses input that looks like `name = "string"` where the key must be
60 /// // the identifier `name` and the value may be any string literal.
61 /// // Returns the string literal.
62 /// fn parse_name(input: ParseStream) -> Result<LitStr> {
63 /// let name_token: Ident = input.parse()?;
64 /// if name_token != "name" {
65 /// // Trigger an error not on the current position of the stream,
66 /// // but on the position of the unexpected identifier.
67 /// return Err(Error::new(name_token.span(), "expected `name`"));
68 /// }
69 /// input.parse::<Token![=]>()?;
70 /// let s: LitStr = input.parse()?;
71 /// Ok(s)
72 /// }
David Tolnay7c8efe92018-09-01 10:00:50 -070073 /// ```
David Tolnayad4b2472018-08-25 08:25:24 -040074 pub fn new<T: Display>(span: Span, message: T) -> Self {
75 Error {
Alex Crichton3ea5ca32018-11-16 02:43:46 -080076 start_span: ThreadBound::new(span),
77 end_span: ThreadBound::new(span),
78 message: message.to_string(),
79 }
80 }
81
David Tolnay3aa72f52018-11-16 04:21:54 -080082 /// Creates an error with the specified message spanning the given syntax
83 /// tree node.
Alex Crichton3ea5ca32018-11-16 02:43:46 -080084 ///
David Tolnay3aa72f52018-11-16 04:21:54 -080085 /// Unlike the `Error::new` constructor, this constructor takes an argument
86 /// `tokens` which is a syntax tree node. This allows the resulting `Error`
87 /// to attempt to span all tokens inside of `tokens`. While you would
88 /// typically be able to use the `Spanned` trait with the above `Error::new`
89 /// constructor, implementation limitations today mean that
90 /// `Error::new_spanned` may provide a higher-quality error message on
91 /// stable Rust.
Alex Crichton3ea5ca32018-11-16 02:43:46 -080092 ///
93 /// When in doubt it's recommended to stick to `Error::new` (or
94 /// `ParseStream::error`)!
95 #[cfg(feature = "printing")]
96 pub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self {
97 let mut iter = tokens.into_token_stream().into_iter();
David Tolnay708ef132018-11-16 04:10:53 -080098 let start = iter.next().map_or_else(Span::call_site, |t| t.span());
99 let end = iter.last().map_or(start, |t| t.span());
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800100 Error {
101 start_span: ThreadBound::new(start),
102 end_span: ThreadBound::new(end),
David Tolnayad4b2472018-08-25 08:25:24 -0400103 message: message.to_string(),
104 }
105 }
106
David Tolnaye7900732018-11-11 10:25:47 -0800107 /// The source location of the error.
108 ///
109 /// Spans are not thread-safe so this function returns `Span::call_site()`
110 /// if called from a different thread than the one on which the `Error` was
111 /// originally created.
David Tolnay7744d9d2018-08-25 22:15:52 -0400112 pub fn span(&self) -> Span {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800113 let start = match self.start_span.get() {
David Tolnay32874802018-11-11 08:52:19 -0800114 Some(span) => *span,
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800115 None => return Span::call_site(),
116 };
117
118 #[cfg(procmacro2_semver_exempt)]
119 {
120 let end = match self.end_span.get() {
121 Some(span) => *span,
122 None => return Span::call_site(),
123 };
David Tolnay2f12a6d2018-11-16 04:06:06 -0800124 start.join(end).unwrap_or(start)
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800125 }
126 #[cfg(not(procmacro2_semver_exempt))]
127 {
David Tolnay2f12a6d2018-11-16 04:06:06 -0800128 start
David Tolnay32874802018-11-11 08:52:19 -0800129 }
David Tolnay7744d9d2018-08-25 22:15:52 -0400130 }
131
David Tolnayad4b2472018-08-25 08:25:24 -0400132 /// Render the error as an invocation of [`compile_error!`].
133 ///
134 /// The [`parse_macro_input!`] macro provides a convenient way to invoke
135 /// this method correctly in a procedural macro.
136 ///
137 /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html
138 /// [`parse_macro_input!`]: ../macro.parse_macro_input.html
David Tolnay24e21f92018-09-06 02:08:07 -0700139 pub fn to_compile_error(&self) -> TokenStream {
David Tolnay5f794802018-11-24 14:51:21 -0800140 let start = self
141 .start_span
142 .get()
143 .cloned()
144 .unwrap_or_else(Span::call_site);
David Tolnaycaf11b42018-11-16 04:09:43 -0800145 let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site);
David Tolnay32874802018-11-11 08:52:19 -0800146
David Tolnayad4b2472018-08-25 08:25:24 -0400147 // compile_error!($message)
148 TokenStream::from_iter(vec![
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800149 TokenTree::Ident(Ident::new("compile_error", start)),
David Tolnayad4b2472018-08-25 08:25:24 -0400150 TokenTree::Punct({
151 let mut punct = Punct::new('!', Spacing::Alone);
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800152 punct.set_span(start);
David Tolnayad4b2472018-08-25 08:25:24 -0400153 punct
154 }),
155 TokenTree::Group({
156 let mut group = Group::new(Delimiter::Brace, {
157 TokenStream::from_iter(vec![TokenTree::Literal({
158 let mut string = Literal::string(&self.message);
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800159 string.set_span(end);
David Tolnayad4b2472018-08-25 08:25:24 -0400160 string
161 })])
162 });
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800163 group.set_span(end);
David Tolnayad4b2472018-08-25 08:25:24 -0400164 group
165 }),
166 ])
167 }
168}
169
David Tolnaya72f2622018-11-24 13:39:45 -0800170#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400171pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
172 if cursor.eof() {
173 Error::new(scope, format!("unexpected end of input, {}", message))
174 } else {
David Tolnayfe89fcc2018-09-08 17:56:31 -0700175 #[cfg(procmacro2_semver_exempt)]
176 let span = private::open_span_of_group(cursor);
177 #[cfg(not(procmacro2_semver_exempt))]
178 let span = cursor.span();
179 Error::new(span, message)
David Tolnayad4b2472018-08-25 08:25:24 -0400180 }
181}
182
David Tolnayb2dc98a2019-04-20 13:32:51 -0700183impl Debug for Error {
184 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
185 formatter.debug_tuple("Error").field(&self.message).finish()
186 }
187}
188
David Tolnayad4b2472018-08-25 08:25:24 -0400189impl Display for Error {
190 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
191 formatter.write_str(&self.message)
192 }
193}
194
David Tolnay32874802018-11-11 08:52:19 -0800195impl Clone for Error {
196 fn clone(&self) -> Self {
David Tolnay5f794802018-11-24 14:51:21 -0800197 let start = self
198 .start_span
199 .get()
200 .cloned()
201 .unwrap_or_else(Span::call_site);
David Tolnaycaf11b42018-11-16 04:09:43 -0800202 let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site);
David Tolnay32874802018-11-11 08:52:19 -0800203 Error {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800204 start_span: ThreadBound::new(start),
205 end_span: ThreadBound::new(end),
David Tolnay32874802018-11-11 08:52:19 -0800206 message: self.message.clone(),
207 }
208 }
209}
210
David Tolnayad4b2472018-08-25 08:25:24 -0400211impl std::error::Error for Error {
212 fn description(&self) -> &str {
213 "parse error"
214 }
215}
216
217impl From<LexError> for Error {
218 fn from(err: LexError) -> Self {
219 Error::new(Span::call_site(), format!("{:?}", err))
220 }
221}