blob: ca56c269080aac23a9c599d4e86a9f91da5adaac [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnayad4b2472018-08-25 08:25:24 -04009use std;
David Tolnayc5ab8c62017-12-26 16:43:39 -050010use std::fmt::{self, Display};
David Tolnayad4b2472018-08-25 08:25:24 -040011use std::iter::FromIterator;
12
13use proc_macro2::{
14 Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree,
15};
Alex Crichton3ea5ca32018-11-16 02:43:46 -080016#[cfg(feature = "printing")]
17use quote::ToTokens;
David Tolnayad4b2472018-08-25 08:25:24 -040018
David Tolnaya72f2622018-11-24 13:39:45 -080019#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -040020use buffer::Cursor;
David Tolnay32874802018-11-11 08:52:19 -080021use thread::ThreadBound;
David Tolnayad4b2472018-08-25 08:25:24 -040022
23/// The result of a Syn parser.
24pub type Result<T> = std::result::Result<T, Error>;
25
26/// Error returned when a Syn parser cannot parse the input tokens.
27///
28/// Refer to the [module documentation] for details about parsing in Syn.
29///
30/// [module documentation]: index.html
31///
32/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnay32874802018-11-11 08:52:19 -080033#[derive(Debug)]
David Tolnayad4b2472018-08-25 08:25:24 -040034pub struct Error {
David Tolnay32874802018-11-11 08:52:19 -080035 // Span is implemented as an index into a thread-local interner to keep the
36 // size small. It is not safe to access from a different thread. We want
37 // errors to be Send and Sync to play nicely with the Failure crate, so pin
38 // the span we're given to its original thread and assume it is
39 // Span::call_site if accessed from any other thread.
Alex Crichton3ea5ca32018-11-16 02:43:46 -080040 start_span: ThreadBound<Span>,
41 end_span: ThreadBound<Span>,
David Tolnayad4b2472018-08-25 08:25:24 -040042 message: String,
43}
44
David Tolnay32874802018-11-11 08:52:19 -080045#[cfg(test)]
46struct _Test where Error: Send + Sync;
47
David Tolnayad4b2472018-08-25 08:25:24 -040048impl Error {
David Tolnay7c8efe92018-09-01 10:00:50 -070049 /// Usually the [`ParseStream::error`] method will be used instead, which
50 /// automatically uses the correct span from the current position of the
51 /// parse stream.
52 ///
53 /// Use `Error::new` when the error needs to be triggered on some span other
54 /// than where the parse stream is currently positioned.
55 ///
56 /// [`ParseStream::error`]: struct.ParseBuffer.html#method.error
57 ///
58 /// # Example
59 ///
60 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -070061 /// #[macro_use]
62 /// extern crate syn;
63 ///
David Tolnay67fea042018-11-24 14:50:20 -080064 /// use syn::{Error, Ident, LitStr, Result};
65 /// use syn::parse::ParseStream;
David Tolnay7c8efe92018-09-01 10:00:50 -070066 ///
67 /// // Parses input that looks like `name = "string"` where the key must be
68 /// // the identifier `name` and the value may be any string literal.
69 /// // Returns the string literal.
70 /// fn parse_name(input: ParseStream) -> Result<LitStr> {
71 /// let name_token: Ident = input.parse()?;
72 /// if name_token != "name" {
73 /// // Trigger an error not on the current position of the stream,
74 /// // but on the position of the unexpected identifier.
75 /// return Err(Error::new(name_token.span(), "expected `name`"));
76 /// }
77 /// input.parse::<Token![=]>()?;
78 /// let s: LitStr = input.parse()?;
79 /// Ok(s)
80 /// }
81 /// #
82 /// # fn main() {}
83 /// ```
David Tolnayad4b2472018-08-25 08:25:24 -040084 pub fn new<T: Display>(span: Span, message: T) -> Self {
85 Error {
Alex Crichton3ea5ca32018-11-16 02:43:46 -080086 start_span: ThreadBound::new(span),
87 end_span: ThreadBound::new(span),
88 message: message.to_string(),
89 }
90 }
91
David Tolnay3aa72f52018-11-16 04:21:54 -080092 /// Creates an error with the specified message spanning the given syntax
93 /// tree node.
Alex Crichton3ea5ca32018-11-16 02:43:46 -080094 ///
David Tolnay3aa72f52018-11-16 04:21:54 -080095 /// Unlike the `Error::new` constructor, this constructor takes an argument
96 /// `tokens` which is a syntax tree node. This allows the resulting `Error`
97 /// to attempt to span all tokens inside of `tokens`. While you would
98 /// typically be able to use the `Spanned` trait with the above `Error::new`
99 /// constructor, implementation limitations today mean that
100 /// `Error::new_spanned` may provide a higher-quality error message on
101 /// stable Rust.
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800102 ///
103 /// When in doubt it's recommended to stick to `Error::new` (or
104 /// `ParseStream::error`)!
105 #[cfg(feature = "printing")]
106 pub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self {
107 let mut iter = tokens.into_token_stream().into_iter();
David Tolnay708ef132018-11-16 04:10:53 -0800108 let start = iter.next().map_or_else(Span::call_site, |t| t.span());
109 let end = iter.last().map_or(start, |t| t.span());
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800110 Error {
111 start_span: ThreadBound::new(start),
112 end_span: ThreadBound::new(end),
David Tolnayad4b2472018-08-25 08:25:24 -0400113 message: message.to_string(),
114 }
115 }
116
David Tolnaye7900732018-11-11 10:25:47 -0800117 /// The source location of the error.
118 ///
119 /// Spans are not thread-safe so this function returns `Span::call_site()`
120 /// if called from a different thread than the one on which the `Error` was
121 /// originally created.
David Tolnay7744d9d2018-08-25 22:15:52 -0400122 pub fn span(&self) -> Span {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800123 let start = match self.start_span.get() {
David Tolnay32874802018-11-11 08:52:19 -0800124 Some(span) => *span,
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800125 None => return Span::call_site(),
126 };
127
128 #[cfg(procmacro2_semver_exempt)]
129 {
130 let end = match self.end_span.get() {
131 Some(span) => *span,
132 None => return Span::call_site(),
133 };
David Tolnay2f12a6d2018-11-16 04:06:06 -0800134 start.join(end).unwrap_or(start)
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800135 }
136 #[cfg(not(procmacro2_semver_exempt))]
137 {
David Tolnay2f12a6d2018-11-16 04:06:06 -0800138 start
David Tolnay32874802018-11-11 08:52:19 -0800139 }
David Tolnay7744d9d2018-08-25 22:15:52 -0400140 }
141
David Tolnayad4b2472018-08-25 08:25:24 -0400142 /// Render the error as an invocation of [`compile_error!`].
143 ///
144 /// The [`parse_macro_input!`] macro provides a convenient way to invoke
145 /// this method correctly in a procedural macro.
146 ///
147 /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html
148 /// [`parse_macro_input!`]: ../macro.parse_macro_input.html
David Tolnay24e21f92018-09-06 02:08:07 -0700149 pub fn to_compile_error(&self) -> TokenStream {
David Tolnaycaf11b42018-11-16 04:09:43 -0800150 let start = self.start_span.get().cloned().unwrap_or_else(Span::call_site);
151 let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site);
David Tolnay32874802018-11-11 08:52:19 -0800152
David Tolnayad4b2472018-08-25 08:25:24 -0400153 // compile_error!($message)
154 TokenStream::from_iter(vec![
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800155 TokenTree::Ident(Ident::new("compile_error", start)),
David Tolnayad4b2472018-08-25 08:25:24 -0400156 TokenTree::Punct({
157 let mut punct = Punct::new('!', Spacing::Alone);
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800158 punct.set_span(start);
David Tolnayad4b2472018-08-25 08:25:24 -0400159 punct
160 }),
161 TokenTree::Group({
162 let mut group = Group::new(Delimiter::Brace, {
163 TokenStream::from_iter(vec![TokenTree::Literal({
164 let mut string = Literal::string(&self.message);
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800165 string.set_span(end);
David Tolnayad4b2472018-08-25 08:25:24 -0400166 string
167 })])
168 });
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800169 group.set_span(end);
David Tolnayad4b2472018-08-25 08:25:24 -0400170 group
171 }),
172 ])
173 }
174}
175
David Tolnaya72f2622018-11-24 13:39:45 -0800176#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400177pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
178 if cursor.eof() {
179 Error::new(scope, format!("unexpected end of input, {}", message))
180 } else {
181 Error::new(cursor.span(), message)
182 }
183}
184
185impl Display for Error {
186 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
187 formatter.write_str(&self.message)
188 }
189}
190
David Tolnay32874802018-11-11 08:52:19 -0800191impl Clone for Error {
192 fn clone(&self) -> Self {
David Tolnaycaf11b42018-11-16 04:09:43 -0800193 let start = self.start_span.get().cloned().unwrap_or_else(Span::call_site);
194 let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site);
David Tolnay32874802018-11-11 08:52:19 -0800195 Error {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800196 start_span: ThreadBound::new(start),
197 end_span: ThreadBound::new(end),
David Tolnay32874802018-11-11 08:52:19 -0800198 message: self.message.clone(),
199 }
200 }
201}
202
David Tolnayad4b2472018-08-25 08:25:24 -0400203impl std::error::Error for Error {
204 fn description(&self) -> &str {
205 "parse error"
206 }
207}
208
209impl From<LexError> for Error {
210 fn from(err: LexError) -> Self {
211 Error::new(Span::call_site(), format!("{:?}", err))
212 }
213}