blob: 12be03eebc4ac9ad8c0cca4b2030a8618d7d906e [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};
16
17use buffer::Cursor;
David Tolnay32874802018-11-11 08:52:19 -080018use thread::ThreadBound;
David Tolnayad4b2472018-08-25 08:25:24 -040019
20/// The result of a Syn parser.
21pub type Result<T> = std::result::Result<T, Error>;
22
23/// Error returned when a Syn parser cannot parse the input tokens.
24///
25/// Refer to the [module documentation] for details about parsing in Syn.
26///
27/// [module documentation]: index.html
28///
29/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnay32874802018-11-11 08:52:19 -080030#[derive(Debug)]
David Tolnayad4b2472018-08-25 08:25:24 -040031pub struct Error {
David Tolnay32874802018-11-11 08:52:19 -080032 // Span is implemented as an index into a thread-local interner to keep the
33 // size small. It is not safe to access from a different thread. We want
34 // errors to be Send and Sync to play nicely with the Failure crate, so pin
35 // the span we're given to its original thread and assume it is
36 // Span::call_site if accessed from any other thread.
37 span: ThreadBound<Span>,
David Tolnayad4b2472018-08-25 08:25:24 -040038 message: String,
39}
40
David Tolnay32874802018-11-11 08:52:19 -080041#[cfg(test)]
42struct _Test where Error: Send + Sync;
43
David Tolnayad4b2472018-08-25 08:25:24 -040044impl Error {
David Tolnay7c8efe92018-09-01 10:00:50 -070045 /// Usually the [`ParseStream::error`] method will be used instead, which
46 /// automatically uses the correct span from the current position of the
47 /// parse stream.
48 ///
49 /// Use `Error::new` when the error needs to be triggered on some span other
50 /// than where the parse stream is currently positioned.
51 ///
52 /// [`ParseStream::error`]: struct.ParseBuffer.html#method.error
53 ///
54 /// # Example
55 ///
56 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -070057 /// #[macro_use]
58 /// extern crate syn;
59 ///
60 /// use syn::{Ident, LitStr};
David Tolnay7c8efe92018-09-01 10:00:50 -070061 /// use syn::parse::{Error, ParseStream, Result};
62 ///
63 /// // Parses input that looks like `name = "string"` where the key must be
64 /// // the identifier `name` and the value may be any string literal.
65 /// // Returns the string literal.
66 /// fn parse_name(input: ParseStream) -> Result<LitStr> {
67 /// let name_token: Ident = input.parse()?;
68 /// if name_token != "name" {
69 /// // Trigger an error not on the current position of the stream,
70 /// // but on the position of the unexpected identifier.
71 /// return Err(Error::new(name_token.span(), "expected `name`"));
72 /// }
73 /// input.parse::<Token![=]>()?;
74 /// let s: LitStr = input.parse()?;
75 /// Ok(s)
76 /// }
77 /// #
78 /// # fn main() {}
79 /// ```
David Tolnayad4b2472018-08-25 08:25:24 -040080 pub fn new<T: Display>(span: Span, message: T) -> Self {
81 Error {
David Tolnay32874802018-11-11 08:52:19 -080082 span: ThreadBound::new(span),
David Tolnayad4b2472018-08-25 08:25:24 -040083 message: message.to_string(),
84 }
85 }
86
David Tolnay7744d9d2018-08-25 22:15:52 -040087 pub fn span(&self) -> Span {
David Tolnay32874802018-11-11 08:52:19 -080088 match self.span.get() {
89 Some(span) => *span,
90 None => Span::call_site(),
91 }
David Tolnay7744d9d2018-08-25 22:15:52 -040092 }
93
David Tolnayad4b2472018-08-25 08:25:24 -040094 /// Render the error as an invocation of [`compile_error!`].
95 ///
96 /// The [`parse_macro_input!`] macro provides a convenient way to invoke
97 /// this method correctly in a procedural macro.
98 ///
99 /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html
100 /// [`parse_macro_input!`]: ../macro.parse_macro_input.html
David Tolnay24e21f92018-09-06 02:08:07 -0700101 pub fn to_compile_error(&self) -> TokenStream {
David Tolnay32874802018-11-11 08:52:19 -0800102 let span = self.span();
103
David Tolnayad4b2472018-08-25 08:25:24 -0400104 // compile_error!($message)
105 TokenStream::from_iter(vec![
David Tolnay32874802018-11-11 08:52:19 -0800106 TokenTree::Ident(Ident::new("compile_error", span)),
David Tolnayad4b2472018-08-25 08:25:24 -0400107 TokenTree::Punct({
108 let mut punct = Punct::new('!', Spacing::Alone);
David Tolnay32874802018-11-11 08:52:19 -0800109 punct.set_span(span);
David Tolnayad4b2472018-08-25 08:25:24 -0400110 punct
111 }),
112 TokenTree::Group({
113 let mut group = Group::new(Delimiter::Brace, {
114 TokenStream::from_iter(vec![TokenTree::Literal({
115 let mut string = Literal::string(&self.message);
David Tolnay32874802018-11-11 08:52:19 -0800116 string.set_span(span);
David Tolnayad4b2472018-08-25 08:25:24 -0400117 string
118 })])
119 });
David Tolnay32874802018-11-11 08:52:19 -0800120 group.set_span(span);
David Tolnayad4b2472018-08-25 08:25:24 -0400121 group
122 }),
123 ])
124 }
125}
126
David Tolnayad4b2472018-08-25 08:25:24 -0400127pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
128 if cursor.eof() {
129 Error::new(scope, format!("unexpected end of input, {}", message))
130 } else {
131 Error::new(cursor.span(), message)
132 }
133}
134
135impl Display for Error {
136 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
137 formatter.write_str(&self.message)
138 }
139}
140
David Tolnay32874802018-11-11 08:52:19 -0800141impl Clone for Error {
142 fn clone(&self) -> Self {
143 Error {
144 span: ThreadBound::new(self.span()),
145 message: self.message.clone(),
146 }
147 }
148}
149
David Tolnayad4b2472018-08-25 08:25:24 -0400150impl std::error::Error for Error {
151 fn description(&self) -> &str {
152 "parse error"
153 }
154}
155
156impl From<LexError> for Error {
157 fn from(err: LexError) -> Self {
158 Error::new(Span::call_site(), format!("{:?}", err))
159 }
160}