blob: 3d8663a748ae1ea25ef55596e11458c941ab50f6 [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
19use buffer::Cursor;
David Tolnay32874802018-11-11 08:52:19 -080020use thread::ThreadBound;
David Tolnayad4b2472018-08-25 08:25:24 -040021
22/// The result of a Syn parser.
23pub 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 Tolnay32874802018-11-11 08:52:19 -080032#[derive(Debug)]
David Tolnayad4b2472018-08-25 08:25:24 -040033pub struct Error {
David Tolnay32874802018-11-11 08:52:19 -080034 // 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 Crichton3ea5ca32018-11-16 02:43:46 -080039 start_span: ThreadBound<Span>,
40 end_span: ThreadBound<Span>,
David Tolnayad4b2472018-08-25 08:25:24 -040041 message: String,
42}
43
David Tolnay32874802018-11-11 08:52:19 -080044#[cfg(test)]
David Tolnay5f794802018-11-24 14:51:21 -080045struct _Test
46where
47 Error: Send + Sync;
David Tolnay32874802018-11-11 08:52:19 -080048
David Tolnayad4b2472018-08-25 08:25:24 -040049impl Error {
David Tolnay7c8efe92018-09-01 10:00:50 -070050 /// Usually the [`ParseStream::error`] method will be used instead, which
51 /// automatically uses the correct span from the current position of the
52 /// parse stream.
53 ///
54 /// Use `Error::new` when the error needs to be triggered on some span other
55 /// than where the parse stream is currently positioned.
56 ///
57 /// [`ParseStream::error`]: struct.ParseBuffer.html#method.error
58 ///
59 /// # Example
60 ///
61 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -070062 /// #[macro_use]
63 /// extern crate syn;
64 ///
65 /// use syn::{Ident, LitStr};
David Tolnay7c8efe92018-09-01 10:00:50 -070066 /// use syn::parse::{Error, ParseStream, Result};
67 ///
68 /// // Parses input that looks like `name = "string"` where the key must be
69 /// // the identifier `name` and the value may be any string literal.
70 /// // Returns the string literal.
71 /// fn parse_name(input: ParseStream) -> Result<LitStr> {
72 /// let name_token: Ident = input.parse()?;
73 /// if name_token != "name" {
74 /// // Trigger an error not on the current position of the stream,
75 /// // but on the position of the unexpected identifier.
76 /// return Err(Error::new(name_token.span(), "expected `name`"));
77 /// }
78 /// input.parse::<Token![=]>()?;
79 /// let s: LitStr = input.parse()?;
80 /// Ok(s)
81 /// }
82 /// #
83 /// # fn main() {}
84 /// ```
David Tolnayad4b2472018-08-25 08:25:24 -040085 pub fn new<T: Display>(span: Span, message: T) -> Self {
86 Error {
Alex Crichton3ea5ca32018-11-16 02:43:46 -080087 start_span: ThreadBound::new(span),
88 end_span: ThreadBound::new(span),
89 message: message.to_string(),
90 }
91 }
92
David Tolnay3aa72f52018-11-16 04:21:54 -080093 /// Creates an error with the specified message spanning the given syntax
94 /// tree node.
Alex Crichton3ea5ca32018-11-16 02:43:46 -080095 ///
David Tolnay3aa72f52018-11-16 04:21:54 -080096 /// Unlike the `Error::new` constructor, this constructor takes an argument
97 /// `tokens` which is a syntax tree node. This allows the resulting `Error`
98 /// to attempt to span all tokens inside of `tokens`. While you would
99 /// typically be able to use the `Spanned` trait with the above `Error::new`
100 /// constructor, implementation limitations today mean that
101 /// `Error::new_spanned` may provide a higher-quality error message on
102 /// stable Rust.
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800103 ///
104 /// When in doubt it's recommended to stick to `Error::new` (or
105 /// `ParseStream::error`)!
106 #[cfg(feature = "printing")]
107 pub fn new_spanned<T: ToTokens, U: Display>(tokens: T, message: U) -> Self {
108 let mut iter = tokens.into_token_stream().into_iter();
David Tolnay708ef132018-11-16 04:10:53 -0800109 let start = iter.next().map_or_else(Span::call_site, |t| t.span());
110 let end = iter.last().map_or(start, |t| t.span());
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800111 Error {
112 start_span: ThreadBound::new(start),
113 end_span: ThreadBound::new(end),
David Tolnayad4b2472018-08-25 08:25:24 -0400114 message: message.to_string(),
115 }
116 }
117
David Tolnaye7900732018-11-11 10:25:47 -0800118 /// The source location of the error.
119 ///
120 /// Spans are not thread-safe so this function returns `Span::call_site()`
121 /// if called from a different thread than the one on which the `Error` was
122 /// originally created.
David Tolnay7744d9d2018-08-25 22:15:52 -0400123 pub fn span(&self) -> Span {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800124 let start = match self.start_span.get() {
David Tolnay32874802018-11-11 08:52:19 -0800125 Some(span) => *span,
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800126 None => return Span::call_site(),
127 };
128
129 #[cfg(procmacro2_semver_exempt)]
130 {
131 let end = match self.end_span.get() {
132 Some(span) => *span,
133 None => return Span::call_site(),
134 };
David Tolnay2f12a6d2018-11-16 04:06:06 -0800135 start.join(end).unwrap_or(start)
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800136 }
137 #[cfg(not(procmacro2_semver_exempt))]
138 {
David Tolnay2f12a6d2018-11-16 04:06:06 -0800139 start
David Tolnay32874802018-11-11 08:52:19 -0800140 }
David Tolnay7744d9d2018-08-25 22:15:52 -0400141 }
142
David Tolnayad4b2472018-08-25 08:25:24 -0400143 /// Render the error as an invocation of [`compile_error!`].
144 ///
145 /// The [`parse_macro_input!`] macro provides a convenient way to invoke
146 /// this method correctly in a procedural macro.
147 ///
148 /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html
149 /// [`parse_macro_input!`]: ../macro.parse_macro_input.html
David Tolnay24e21f92018-09-06 02:08:07 -0700150 pub fn to_compile_error(&self) -> TokenStream {
David Tolnay5f794802018-11-24 14:51:21 -0800151 let start = self
152 .start_span
153 .get()
154 .cloned()
155 .unwrap_or_else(Span::call_site);
David Tolnaycaf11b42018-11-16 04:09:43 -0800156 let end = self.end_span.get().cloned().unwrap_or_else(Span::call_site);
David Tolnay32874802018-11-11 08:52:19 -0800157
David Tolnayad4b2472018-08-25 08:25:24 -0400158 // compile_error!($message)
159 TokenStream::from_iter(vec![
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800160 TokenTree::Ident(Ident::new("compile_error", start)),
David Tolnayad4b2472018-08-25 08:25:24 -0400161 TokenTree::Punct({
162 let mut punct = Punct::new('!', Spacing::Alone);
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800163 punct.set_span(start);
David Tolnayad4b2472018-08-25 08:25:24 -0400164 punct
165 }),
166 TokenTree::Group({
167 let mut group = Group::new(Delimiter::Brace, {
168 TokenStream::from_iter(vec![TokenTree::Literal({
169 let mut string = Literal::string(&self.message);
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800170 string.set_span(end);
David Tolnayad4b2472018-08-25 08:25:24 -0400171 string
172 })])
173 });
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800174 group.set_span(end);
David Tolnayad4b2472018-08-25 08:25:24 -0400175 group
176 }),
177 ])
178 }
179}
180
David Tolnayad4b2472018-08-25 08:25:24 -0400181pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
182 if cursor.eof() {
183 Error::new(scope, format!("unexpected end of input, {}", message))
184 } else {
185 Error::new(cursor.span(), message)
186 }
187}
188
189impl 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}