blob: 16b92890b42476ade1ab138d4bf9f09001bcfbdb [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)]
45struct _Test where Error: Send + Sync;
46
David Tolnayad4b2472018-08-25 08:25:24 -040047impl Error {
David Tolnay7c8efe92018-09-01 10:00:50 -070048 /// 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 Tolnaya1c98072018-09-06 08:58:10 -070060 /// #[macro_use]
61 /// extern crate syn;
62 ///
63 /// use syn::{Ident, LitStr};
David Tolnay7c8efe92018-09-01 10:00:50 -070064 /// 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 Tolnayad4b2472018-08-25 08:25:24 -040083 pub fn new<T: Display>(span: Span, message: T) -> Self {
84 Error {
Alex Crichton3ea5ca32018-11-16 02:43:46 -080085 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 Tolnayad4b2472018-08-25 08:25:24 -0400111 message: message.to_string(),
112 }
113 }
114
David Tolnaye7900732018-11-11 10:25:47 -0800115 /// 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 Tolnay7744d9d2018-08-25 22:15:52 -0400120 pub fn span(&self) -> Span {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800121 let start = match self.start_span.get() {
David Tolnay32874802018-11-11 08:52:19 -0800122 Some(span) => *span,
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800123 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 Tolnay32874802018-11-11 08:52:19 -0800138 }
David Tolnay7744d9d2018-08-25 22:15:52 -0400139 }
140
David Tolnayad4b2472018-08-25 08:25:24 -0400141 /// 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 Tolnay24e21f92018-09-06 02:08:07 -0700148 pub fn to_compile_error(&self) -> TokenStream {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800149 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 Tolnay32874802018-11-11 08:52:19 -0800151
David Tolnayad4b2472018-08-25 08:25:24 -0400152 // compile_error!($message)
153 TokenStream::from_iter(vec![
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800154 TokenTree::Ident(Ident::new("compile_error", start)),
David Tolnayad4b2472018-08-25 08:25:24 -0400155 TokenTree::Punct({
156 let mut punct = Punct::new('!', Spacing::Alone);
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800157 punct.set_span(start);
David Tolnayad4b2472018-08-25 08:25:24 -0400158 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 Crichton3ea5ca32018-11-16 02:43:46 -0800164 string.set_span(end);
David Tolnayad4b2472018-08-25 08:25:24 -0400165 string
166 })])
167 });
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800168 group.set_span(end);
David Tolnayad4b2472018-08-25 08:25:24 -0400169 group
170 }),
171 ])
172 }
173}
174
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 {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800191 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 Tolnay32874802018-11-11 08:52:19 -0800193 Error {
Alex Crichton3ea5ca32018-11-16 02:43:46 -0800194 start_span: ThreadBound::new(start),
195 end_span: ThreadBound::new(end),
David Tolnay32874802018-11-11 08:52:19 -0800196 message: self.message.clone(),
197 }
198 }
199}
200
David Tolnayad4b2472018-08-25 08:25:24 -0400201impl std::error::Error for Error {
202 fn description(&self) -> &str {
203 "parse error"
204 }
205}
206
207impl From<LexError> for Error {
208 fn from(err: LexError) -> Self {
209 Error::new(Span::call_site(), format!("{:?}", err))
210 }
211}