blob: 13095ccf2c8a168c8e46018204fae0544d7660db [file] [log] [blame]
David Tolnayad4b2472018-08-25 08:25:24 -04001use std;
David Tolnayc5ab8c62017-12-26 16:43:39 -05002use std::fmt::{self, 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 Tolnay32874802018-11-11 08:52:19 -080013use thread::ThreadBound;
David Tolnayad4b2472018-08-25 08:25:24 -040014
15/// The result of a Syn parser.
16pub type Result<T> = std::result::Result<T, Error>;
17
18/// Error returned when a Syn parser cannot parse the input tokens.
19///
20/// Refer to the [module documentation] for details about parsing in Syn.
21///
22/// [module documentation]: index.html
23///
24/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnay32874802018-11-11 08:52:19 -080025#[derive(Debug)]
David Tolnayad4b2472018-08-25 08:25:24 -040026pub struct Error {
David Tolnay32874802018-11-11 08:52:19 -080027 // Span is implemented as an index into a thread-local interner to keep the
28 // size small. It is not safe to access from a different thread. We want
29 // errors to be Send and Sync to play nicely with the Failure crate, so pin
30 // the span we're given to its original thread and assume it is
31 // Span::call_site if accessed from any other thread.
Alex Crichton3ea5ca32018-11-16 02:43:46 -080032 start_span: ThreadBound<Span>,
33 end_span: ThreadBound<Span>,
David Tolnayad4b2472018-08-25 08:25:24 -040034 message: String,
35}
36
David Tolnay32874802018-11-11 08:52:19 -080037#[cfg(test)]
David Tolnay5f794802018-11-24 14:51:21 -080038struct _Test
39where
40 Error: Send + Sync;
David Tolnay32874802018-11-11 08:52:19 -080041
David Tolnayad4b2472018-08-25 08:25:24 -040042impl Error {
David Tolnay7c8efe92018-09-01 10:00:50 -070043 /// Usually the [`ParseStream::error`] method will be used instead, which
44 /// automatically uses the correct span from the current position of the
45 /// parse stream.
46 ///
47 /// Use `Error::new` when the error needs to be triggered on some span other
48 /// than where the parse stream is currently positioned.
49 ///
50 /// [`ParseStream::error`]: struct.ParseBuffer.html#method.error
51 ///
52 /// # Example
53 ///
54 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -070055 /// #[macro_use]
56 /// extern crate syn;
57 ///
David Tolnay67fea042018-11-24 14:50:20 -080058 /// use syn::{Error, Ident, LitStr, Result};
59 /// use syn::parse::ParseStream;
David Tolnay7c8efe92018-09-01 10:00:50 -070060 ///
61 /// // Parses input that looks like `name = "string"` where the key must be
62 /// // the identifier `name` and the value may be any string literal.
63 /// // Returns the string literal.
64 /// fn parse_name(input: ParseStream) -> Result<LitStr> {
65 /// let name_token: Ident = input.parse()?;
66 /// if name_token != "name" {
67 /// // Trigger an error not on the current position of the stream,
68 /// // but on the position of the unexpected identifier.
69 /// return Err(Error::new(name_token.span(), "expected `name`"));
70 /// }
71 /// input.parse::<Token![=]>()?;
72 /// let s: LitStr = input.parse()?;
73 /// Ok(s)
74 /// }
75 /// #
76 /// # fn main() {}
77 /// ```
David Tolnayad4b2472018-08-25 08:25:24 -040078 pub fn new<T: Display>(span: Span, message: T) -> Self {
79 Error {
Alex Crichton3ea5ca32018-11-16 02:43:46 -080080 start_span: ThreadBound::new(span),
81 end_span: ThreadBound::new(span),
82 message: message.to_string(),
83 }
84 }
85
David Tolnay3aa72f52018-11-16 04:21:54 -080086 /// Creates an error with the specified message spanning the given syntax
87 /// tree node.
Alex Crichton3ea5ca32018-11-16 02:43:46 -080088 ///
David Tolnay3aa72f52018-11-16 04:21:54 -080089 /// Unlike the `Error::new` constructor, this constructor takes an argument
90 /// `tokens` which is a syntax tree node. This allows the resulting `Error`
91 /// to attempt to span all tokens inside of `tokens`. While you would
92 /// typically be able to use the `Spanned` trait with the above `Error::new`
93 /// constructor, implementation limitations today mean that
94 /// `Error::new_spanned` may provide a higher-quality error message on
95 /// stable Rust.
Alex Crichton3ea5ca32018-11-16 02:43:46 -080096 ///
97 /// When in doubt it's recommended to stick to `Error::new` (or
98 /// `ParseStream::error`)!
99 #[cfg(feature = "printing")]
100 pub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self {
101 let mut iter = tokens.into_token_stream().into_iter();
David Tolnay708ef132018-11-16 04:10:53 -0800102 let start = iter.next().map_or_else(Span::call_site, |t| t.span());
103 let end = iter.last().map_or(start, |t| t.span());
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800104 Error {
105 start_span: ThreadBound::new(start),
106 end_span: ThreadBound::new(end),
David Tolnayad4b2472018-08-25 08:25:24 -0400107 message: message.to_string(),
108 }
109 }
110
David Tolnaye7900732018-11-11 10:25:47 -0800111 /// The source location of the error.
112 ///
113 /// Spans are not thread-safe so this function returns `Span::call_site()`
114 /// if called from a different thread than the one on which the `Error` was
115 /// originally created.
David Tolnay7744d9d2018-08-25 22:15:52 -0400116 pub fn span(&self) -> Span {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800117 let start = match self.start_span.get() {
David Tolnay32874802018-11-11 08:52:19 -0800118 Some(span) => *span,
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800119 None => return Span::call_site(),
120 };
121
122 #[cfg(procmacro2_semver_exempt)]
123 {
124 let end = match self.end_span.get() {
125 Some(span) => *span,
126 None => return Span::call_site(),
127 };
David Tolnay2f12a6d2018-11-16 04:06:06 -0800128 start.join(end).unwrap_or(start)
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800129 }
130 #[cfg(not(procmacro2_semver_exempt))]
131 {
David Tolnay2f12a6d2018-11-16 04:06:06 -0800132 start
David Tolnay32874802018-11-11 08:52:19 -0800133 }
David Tolnay7744d9d2018-08-25 22:15:52 -0400134 }
135
David Tolnayad4b2472018-08-25 08:25:24 -0400136 /// Render the error as an invocation of [`compile_error!`].
137 ///
138 /// The [`parse_macro_input!`] macro provides a convenient way to invoke
139 /// this method correctly in a procedural macro.
140 ///
141 /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html
142 /// [`parse_macro_input!`]: ../macro.parse_macro_input.html
David Tolnay24e21f92018-09-06 02:08:07 -0700143 pub fn to_compile_error(&self) -> TokenStream {
David Tolnay5f794802018-11-24 14:51:21 -0800144 let start = self
145 .start_span
146 .get()
147 .cloned()
148 .unwrap_or_else(Span::call_site);
David Tolnaycaf11b42018-11-16 04:09:43 -0800149 let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site);
David Tolnay32874802018-11-11 08:52:19 -0800150
David Tolnayad4b2472018-08-25 08:25:24 -0400151 // compile_error!($message)
152 TokenStream::from_iter(vec![
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800153 TokenTree::Ident(Ident::new("compile_error", start)),
David Tolnayad4b2472018-08-25 08:25:24 -0400154 TokenTree::Punct({
155 let mut punct = Punct::new('!', Spacing::Alone);
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800156 punct.set_span(start);
David Tolnayad4b2472018-08-25 08:25:24 -0400157 punct
158 }),
159 TokenTree::Group({
160 let mut group = Group::new(Delimiter::Brace, {
161 TokenStream::from_iter(vec![TokenTree::Literal({
162 let mut string = Literal::string(&self.message);
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800163 string.set_span(end);
David Tolnayad4b2472018-08-25 08:25:24 -0400164 string
165 })])
166 });
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800167 group.set_span(end);
David Tolnayad4b2472018-08-25 08:25:24 -0400168 group
169 }),
170 ])
171 }
172}
173
David Tolnaya72f2622018-11-24 13:39:45 -0800174#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400175pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
176 if cursor.eof() {
177 Error::new(scope, format!("unexpected end of input, {}", message))
178 } else {
179 Error::new(cursor.span(), message)
180 }
181}
182
183impl Display for Error {
184 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
185 formatter.write_str(&self.message)
186 }
187}
188
David Tolnay32874802018-11-11 08:52:19 -0800189impl Clone for Error {
190 fn clone(&self) -> Self {
David Tolnay5f794802018-11-24 14:51:21 -0800191 let start = self
192 .start_span
193 .get()
194 .cloned()
195 .unwrap_or_else(Span::call_site);
David Tolnaycaf11b42018-11-16 04:09:43 -0800196 let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site);
David Tolnay32874802018-11-11 08:52:19 -0800197 Error {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800198 start_span: ThreadBound::new(start),
199 end_span: ThreadBound::new(end),
David Tolnay32874802018-11-11 08:52:19 -0800200 message: self.message.clone(),
201 }
202 }
203}
204
David Tolnayad4b2472018-08-25 08:25:24 -0400205impl std::error::Error for Error {
206 fn description(&self) -> &str {
207 "parse error"
208 }
209}
210
211impl From<LexError> for Error {
212 fn from(err: LexError) -> Self {
213 Error::new(Span::call_site(), format!("{:?}", err))
214 }
215}