1 use std;
2 use std::fmt::{self, Debug, Display};
3 use std::iter::FromIterator;
4
5 use proc_macro2::{
6 Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree,
7 };
8 #[cfg(feature = "printing")]
9 use quote::ToTokens;
10
11 #[cfg(feature = "parsing")]
12 use buffer::Cursor;
13 #[cfg(all(procmacro2_semver_exempt, feature = "parsing"))]
14 use private;
15 use thread::ThreadBound;
16
17 /// The result of a Syn parser.
18 pub 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.*
27 //
28 // TODO: change the parse module link to an intra rustdoc link, currently
29 // blocked on https://github.com/rust-lang/rust/issues/62830
30 pub struct Error {
31 // Span is implemented as an index into a thread-local interner to keep the
32 // size small. It is not safe to access from a different thread. We want
33 // errors to be Send and Sync to play nicely with the Failure crate, so pin
34 // the span we're given to its original thread and assume it is
35 // Span::call_site if accessed from any other thread.
36 start_span: ThreadBound<Span>,
37 end_span: ThreadBound<Span>,
38 message: String,
39 }
40
41 #[cfg(test)]
42 struct _Test
43 where
44 Error: Send + Sync;
45
46 impl Error {
47 /// Usually the [`ParseStream::error`] method will be used instead, which
48 /// automatically uses the correct span from the current position of the
49 /// parse stream.
50 ///
51 /// Use `Error::new` when the error needs to be triggered on some span other
52 /// than where the parse stream is currently positioned.
53 ///
54 /// [`ParseStream::error`]: crate::parse::ParseBuffer::error
55 ///
56 /// # Example
57 ///
58 /// ```edition2018
59 /// use syn::{Error, Ident, LitStr, Result, Token};
60 /// use syn::parse::ParseStream;
61 ///
62 /// // Parses input that looks like `name = "string"` where the key must be
63 /// // the identifier `name` and the value may be any string literal.
64 /// // Returns the string literal.
65 /// fn parse_name(input: ParseStream) -> Result<LitStr> {
66 /// let name_token: Ident = input.parse()?;
67 /// if name_token != "name" {
68 /// // Trigger an error not on the current position of the stream,
69 /// // but on the position of the unexpected identifier.
70 /// return Err(Error::new(name_token.span(), "expected `name`"));
71 /// }
72 /// input.parse::<Token![=]>()?;
73 /// let s: LitStr = input.parse()?;
74 /// Ok(s)
75 /// }
76 /// ```
new<T: Display>(span: Span, message: T) -> Self77 pub fn new<T: Display>(span: Span, message: T) -> Self {
78 Error {
79 start_span: ThreadBound::new(span),
80 end_span: ThreadBound::new(span),
81 message: message.to_string(),
82 }
83 }
84
85 /// Creates an error with the specified message spanning the given syntax
86 /// tree node.
87 ///
88 /// Unlike the `Error::new` constructor, this constructor takes an argument
89 /// `tokens` which is a syntax tree node. This allows the resulting `Error`
90 /// to attempt to span all tokens inside of `tokens`. While you would
91 /// typically be able to use the `Spanned` trait with the above `Error::new`
92 /// constructor, implementation limitations today mean that
93 /// `Error::new_spanned` may provide a higher-quality error message on
94 /// stable Rust.
95 ///
96 /// When in doubt it's recommended to stick to `Error::new` (or
97 /// `ParseStream::error`)!
98 #[cfg(feature = "printing")]
new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self99 pub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self {
100 let mut iter = tokens.into_token_stream().into_iter();
101 let start = iter.next().map_or_else(Span::call_site, |t| t.span());
102 let end = iter.last().map_or(start, |t| t.span());
103 Error {
104 start_span: ThreadBound::new(start),
105 end_span: ThreadBound::new(end),
106 message: message.to_string(),
107 }
108 }
109
110 /// The source location of the error.
111 ///
112 /// Spans are not thread-safe so this function returns `Span::call_site()`
113 /// if called from a different thread than the one on which the `Error` was
114 /// originally created.
span(&self) -> Span115 pub fn span(&self) -> Span {
116 let start = match self.start_span.get() {
117 Some(span) => *span,
118 None => return Span::call_site(),
119 };
120
121 #[cfg(procmacro2_semver_exempt)]
122 {
123 let end = match self.end_span.get() {
124 Some(span) => *span,
125 None => return Span::call_site(),
126 };
127 start.join(end).unwrap_or(start)
128 }
129 #[cfg(not(procmacro2_semver_exempt))]
130 {
131 start
132 }
133 }
134
135 /// Render the error as an invocation of [`compile_error!`].
136 ///
137 /// The [`parse_macro_input!`] macro provides a convenient way to invoke
138 /// this method correctly in a procedural macro.
139 ///
140 /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html
to_compile_error(&self) -> TokenStream141 pub fn to_compile_error(&self) -> TokenStream {
142 let start = self
143 .start_span
144 .get()
145 .cloned()
146 .unwrap_or_else(Span::call_site);
147 let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site);
148
149 // compile_error!($message)
150 TokenStream::from_iter(vec![
151 TokenTree::Ident(Ident::new("compile_error", start)),
152 TokenTree::Punct({
153 let mut punct = Punct::new('!', Spacing::Alone);
154 punct.set_span(start);
155 punct
156 }),
157 TokenTree::Group({
158 let mut group = Group::new(Delimiter::Brace, {
159 TokenStream::from_iter(vec![TokenTree::Literal({
160 let mut string = Literal::string(&self.message);
161 string.set_span(end);
162 string
163 })])
164 });
165 group.set_span(end);
166 group
167 }),
168 ])
169 }
170 }
171
172 #[cfg(feature = "parsing")]
new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error173 pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
174 if cursor.eof() {
175 Error::new(scope, format!("unexpected end of input, {}", message))
176 } else {
177 #[cfg(procmacro2_semver_exempt)]
178 let span = private::open_span_of_group(cursor);
179 #[cfg(not(procmacro2_semver_exempt))]
180 let span = cursor.span();
181 Error::new(span, message)
182 }
183 }
184
185 impl Debug for Error {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result186 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
187 formatter.debug_tuple("Error").field(&self.message).finish()
188 }
189 }
190
191 impl Display for Error {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result192 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
193 formatter.write_str(&self.message)
194 }
195 }
196
197 impl Clone for Error {
clone(&self) -> Self198 fn clone(&self) -> Self {
199 let start = self
200 .start_span
201 .get()
202 .cloned()
203 .unwrap_or_else(Span::call_site);
204 let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site);
205 Error {
206 start_span: ThreadBound::new(start),
207 end_span: ThreadBound::new(end),
208 message: self.message.clone(),
209 }
210 }
211 }
212
213 impl std::error::Error for Error {
description(&self) -> &str214 fn description(&self) -> &str {
215 "parse error"
216 }
217 }
218
219 impl From<LexError> for Error {
from(err: LexError) -> Self220 fn from(err: LexError) -> Self {
221 Error::new(Span::call_site(), format!("{:?}", err))
222 }
223 }
224