David Tolnay | 5553501 | 2018-01-05 16:39:23 -0800 | [diff] [blame] | 1 | // 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 Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 9 | use std; |
David Tolnay | c5ab8c6 | 2017-12-26 16:43:39 -0500 | [diff] [blame] | 10 | use std::fmt::{self, Display}; |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 11 | use std::iter::FromIterator; |
| 12 | |
| 13 | use proc_macro2::{ |
| 14 | Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree, |
| 15 | }; |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 16 | #[cfg(feature = "printing")] |
| 17 | use quote::ToTokens; |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 18 | |
| 19 | use buffer::Cursor; |
David Tolnay | 3287480 | 2018-11-11 08:52:19 -0800 | [diff] [blame] | 20 | use thread::ThreadBound; |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 21 | |
| 22 | /// The result of a Syn parser. |
| 23 | pub type Result<T> = std::result::Result<T, Error>; |
| 24 | |
| 25 | /// Error returned when a Syn parser cannot parse the input tokens. |
| 26 | /// |
| 27 | /// Refer to the [module documentation] for details about parsing in Syn. |
| 28 | /// |
| 29 | /// [module documentation]: index.html |
| 30 | /// |
| 31 | /// *This type is available if Syn is built with the `"parsing"` feature.* |
David Tolnay | 3287480 | 2018-11-11 08:52:19 -0800 | [diff] [blame] | 32 | #[derive(Debug)] |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 33 | pub struct Error { |
David Tolnay | 3287480 | 2018-11-11 08:52:19 -0800 | [diff] [blame] | 34 | // Span is implemented as an index into a thread-local interner to keep the |
| 35 | // size small. It is not safe to access from a different thread. We want |
| 36 | // errors to be Send and Sync to play nicely with the Failure crate, so pin |
| 37 | // the span we're given to its original thread and assume it is |
| 38 | // Span::call_site if accessed from any other thread. |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 39 | start_span: ThreadBound<Span>, |
| 40 | end_span: ThreadBound<Span>, |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 41 | message: String, |
| 42 | } |
| 43 | |
David Tolnay | 3287480 | 2018-11-11 08:52:19 -0800 | [diff] [blame] | 44 | #[cfg(test)] |
| 45 | struct _Test where Error: Send + Sync; |
| 46 | |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 47 | impl Error { |
David Tolnay | 7c8efe9 | 2018-09-01 10:00:50 -0700 | [diff] [blame] | 48 | /// Usually the [`ParseStream::error`] method will be used instead, which |
| 49 | /// automatically uses the correct span from the current position of the |
| 50 | /// parse stream. |
| 51 | /// |
| 52 | /// Use `Error::new` when the error needs to be triggered on some span other |
| 53 | /// than where the parse stream is currently positioned. |
| 54 | /// |
| 55 | /// [`ParseStream::error`]: struct.ParseBuffer.html#method.error |
| 56 | /// |
| 57 | /// # Example |
| 58 | /// |
| 59 | /// ``` |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 60 | /// #[macro_use] |
| 61 | /// extern crate syn; |
| 62 | /// |
| 63 | /// use syn::{Ident, LitStr}; |
David Tolnay | 7c8efe9 | 2018-09-01 10:00:50 -0700 | [diff] [blame] | 64 | /// use syn::parse::{Error, ParseStream, Result}; |
| 65 | /// |
| 66 | /// // Parses input that looks like `name = "string"` where the key must be |
| 67 | /// // the identifier `name` and the value may be any string literal. |
| 68 | /// // Returns the string literal. |
| 69 | /// fn parse_name(input: ParseStream) -> Result<LitStr> { |
| 70 | /// let name_token: Ident = input.parse()?; |
| 71 | /// if name_token != "name" { |
| 72 | /// // Trigger an error not on the current position of the stream, |
| 73 | /// // but on the position of the unexpected identifier. |
| 74 | /// return Err(Error::new(name_token.span(), "expected `name`")); |
| 75 | /// } |
| 76 | /// input.parse::<Token![=]>()?; |
| 77 | /// let s: LitStr = input.parse()?; |
| 78 | /// Ok(s) |
| 79 | /// } |
| 80 | /// # |
| 81 | /// # fn main() {} |
| 82 | /// ``` |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 83 | pub fn new<T: Display>(span: Span, message: T) -> Self { |
| 84 | Error { |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 85 | start_span: ThreadBound::new(span), |
| 86 | end_span: ThreadBound::new(span), |
| 87 | message: message.to_string(), |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /// Creates an error which spans the items provided with the specified |
| 92 | /// message. |
| 93 | /// |
| 94 | /// Unlike the `new` constructor this constructors takes a spanned item (the |
| 95 | /// first argument here). This allows the `Error` returned to attempt to |
| 96 | /// ensure it spans all the tokens inside of `tokens`. While you typically |
| 97 | /// can use the `Spanned` trait with the above `new` constructor |
| 98 | /// implementation limitations today mean that this constructor may provide |
| 99 | /// a higher-quality error message on stable Rust. |
| 100 | /// |
| 101 | /// When in doubt it's recommended to stick to `Error::new` (or |
| 102 | /// `ParseStream::error`)! |
| 103 | #[cfg(feature = "printing")] |
| 104 | pub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self { |
| 105 | let mut iter = tokens.into_token_stream().into_iter(); |
| 106 | let start = iter.next().map(|t| t.span()).unwrap_or(Span::call_site()); |
| 107 | let end = iter.last().map(|t| t.span()).unwrap_or(Span::call_site()); |
| 108 | Error { |
| 109 | start_span: ThreadBound::new(start), |
| 110 | end_span: ThreadBound::new(end), |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 111 | message: message.to_string(), |
| 112 | } |
| 113 | } |
| 114 | |
David Tolnay | e790073 | 2018-11-11 10:25:47 -0800 | [diff] [blame] | 115 | /// The source location of the error. |
| 116 | /// |
| 117 | /// Spans are not thread-safe so this function returns `Span::call_site()` |
| 118 | /// if called from a different thread than the one on which the `Error` was |
| 119 | /// originally created. |
David Tolnay | 7744d9d | 2018-08-25 22:15:52 -0400 | [diff] [blame] | 120 | pub fn span(&self) -> Span { |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 121 | let start = match self.start_span.get() { |
David Tolnay | 3287480 | 2018-11-11 08:52:19 -0800 | [diff] [blame] | 122 | Some(span) => *span, |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 123 | None => return Span::call_site(), |
| 124 | }; |
| 125 | |
| 126 | #[cfg(procmacro2_semver_exempt)] |
| 127 | { |
| 128 | let end = match self.end_span.get() { |
| 129 | Some(span) => *span, |
| 130 | None => return Span::call_site(), |
| 131 | }; |
| 132 | return start.join(end).unwrap_or(start) |
| 133 | |
| 134 | } |
| 135 | #[cfg(not(procmacro2_semver_exempt))] |
| 136 | { |
| 137 | return start; |
David Tolnay | 3287480 | 2018-11-11 08:52:19 -0800 | [diff] [blame] | 138 | } |
David Tolnay | 7744d9d | 2018-08-25 22:15:52 -0400 | [diff] [blame] | 139 | } |
| 140 | |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 141 | /// Render the error as an invocation of [`compile_error!`]. |
| 142 | /// |
| 143 | /// The [`parse_macro_input!`] macro provides a convenient way to invoke |
| 144 | /// this method correctly in a procedural macro. |
| 145 | /// |
| 146 | /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html |
| 147 | /// [`parse_macro_input!`]: ../macro.parse_macro_input.html |
David Tolnay | 24e21f9 | 2018-09-06 02:08:07 -0700 | [diff] [blame] | 148 | pub fn to_compile_error(&self) -> TokenStream { |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 149 | let start = self.start_span.get().cloned().unwrap_or(Span::call_site()); |
| 150 | let end = self.end_span.get().cloned().unwrap_or(Span::call_site()); |
David Tolnay | 3287480 | 2018-11-11 08:52:19 -0800 | [diff] [blame] | 151 | |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 152 | // compile_error!($message) |
| 153 | TokenStream::from_iter(vec![ |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 154 | TokenTree::Ident(Ident::new("compile_error", start)), |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 155 | TokenTree::Punct({ |
| 156 | let mut punct = Punct::new('!', Spacing::Alone); |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 157 | punct.set_span(start); |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 158 | punct |
| 159 | }), |
| 160 | TokenTree::Group({ |
| 161 | let mut group = Group::new(Delimiter::Brace, { |
| 162 | TokenStream::from_iter(vec![TokenTree::Literal({ |
| 163 | let mut string = Literal::string(&self.message); |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 164 | string.set_span(end); |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 165 | string |
| 166 | })]) |
| 167 | }); |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 168 | group.set_span(end); |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 169 | group |
| 170 | }), |
| 171 | ]) |
| 172 | } |
| 173 | } |
| 174 | |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 175 | pub 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 | |
| 183 | impl Display for Error { |
| 184 | fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 185 | formatter.write_str(&self.message) |
| 186 | } |
| 187 | } |
| 188 | |
David Tolnay | 3287480 | 2018-11-11 08:52:19 -0800 | [diff] [blame] | 189 | impl Clone for Error { |
| 190 | fn clone(&self) -> Self { |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 191 | let start = self.start_span.get().cloned().unwrap_or(Span::call_site()); |
| 192 | let end = self.end_span.get().cloned().unwrap_or(Span::call_site()); |
David Tolnay | 3287480 | 2018-11-11 08:52:19 -0800 | [diff] [blame] | 193 | Error { |
Alex Crichton | 3ea5ca3 | 2018-11-16 02:43:46 -0800 | [diff] [blame^] | 194 | start_span: ThreadBound::new(start), |
| 195 | end_span: ThreadBound::new(end), |
David Tolnay | 3287480 | 2018-11-11 08:52:19 -0800 | [diff] [blame] | 196 | message: self.message.clone(), |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
David Tolnay | ad4b247 | 2018-08-25 08:25:24 -0400 | [diff] [blame] | 201 | impl std::error::Error for Error { |
| 202 | fn description(&self) -> &str { |
| 203 | "parse error" |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | impl From<LexError> for Error { |
| 208 | fn from(err: LexError) -> Self { |
| 209 | Error::new(Span::call_site(), format!("{:?}", err)) |
| 210 | } |
| 211 | } |