blob: 32adb4455c9c0ecdd87576efdee9d9ca3d0e0f20 [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 Tolnaye7900732018-11-11 10:25:47 -080087 /// The source location of the error.
88 ///
89 /// Spans are not thread-safe so this function returns `Span::call_site()`
90 /// if called from a different thread than the one on which the `Error` was
91 /// originally created.
David Tolnay7744d9d2018-08-25 22:15:52 -040092 pub fn span(&self) -> Span {
David Tolnay32874802018-11-11 08:52:19 -080093 match self.span.get() {
94 Some(span) => *span,
95 None => Span::call_site(),
96 }
David Tolnay7744d9d2018-08-25 22:15:52 -040097 }
98
David Tolnayad4b2472018-08-25 08:25:24 -040099 /// Render the error as an invocation of [`compile_error!`].
100 ///
101 /// The [`parse_macro_input!`] macro provides a convenient way to invoke
102 /// this method correctly in a procedural macro.
103 ///
104 /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html
105 /// [`parse_macro_input!`]: ../macro.parse_macro_input.html
David Tolnay24e21f92018-09-06 02:08:07 -0700106 pub fn to_compile_error(&self) -> TokenStream {
David Tolnay32874802018-11-11 08:52:19 -0800107 let span = self.span();
108
David Tolnayad4b2472018-08-25 08:25:24 -0400109 // compile_error!($message)
110 TokenStream::from_iter(vec![
David Tolnay32874802018-11-11 08:52:19 -0800111 TokenTree::Ident(Ident::new("compile_error", span)),
David Tolnayad4b2472018-08-25 08:25:24 -0400112 TokenTree::Punct({
113 let mut punct = Punct::new('!', Spacing::Alone);
David Tolnay32874802018-11-11 08:52:19 -0800114 punct.set_span(span);
David Tolnayad4b2472018-08-25 08:25:24 -0400115 punct
116 }),
117 TokenTree::Group({
118 let mut group = Group::new(Delimiter::Brace, {
119 TokenStream::from_iter(vec![TokenTree::Literal({
120 let mut string = Literal::string(&self.message);
David Tolnay32874802018-11-11 08:52:19 -0800121 string.set_span(span);
David Tolnayad4b2472018-08-25 08:25:24 -0400122 string
123 })])
124 });
David Tolnay32874802018-11-11 08:52:19 -0800125 group.set_span(span);
David Tolnayad4b2472018-08-25 08:25:24 -0400126 group
127 }),
128 ])
129 }
130}
131
David Tolnayad4b2472018-08-25 08:25:24 -0400132pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
133 if cursor.eof() {
134 Error::new(scope, format!("unexpected end of input, {}", message))
135 } else {
136 Error::new(cursor.span(), message)
137 }
138}
139
140impl Display for Error {
141 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
142 formatter.write_str(&self.message)
143 }
144}
145
David Tolnay32874802018-11-11 08:52:19 -0800146impl Clone for Error {
147 fn clone(&self) -> Self {
148 Error {
149 span: ThreadBound::new(self.span()),
150 message: self.message.clone(),
151 }
152 }
153}
154
David Tolnayad4b2472018-08-25 08:25:24 -0400155impl std::error::Error for Error {
156 fn description(&self) -> &str {
157 "parse error"
158 }
159}
160
161impl From<LexError> for Error {
162 fn from(err: LexError) -> Self {
163 Error::new(Span::call_site(), format!("{:?}", err))
164 }
165}