blob: 712b9b7d8260f2db89bb02dca1bde900a3be63be [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;
18
19/// The result of a Syn parser.
20pub type Result<T> = std::result::Result<T, Error>;
21
22/// Error returned when a Syn parser cannot parse the input tokens.
23///
24/// Refer to the [module documentation] for details about parsing in Syn.
25///
26/// [module documentation]: index.html
27///
28/// *This type is available if Syn is built with the `"parsing"` feature.*
David Tolnay84526782018-09-06 02:06:07 -070029#[derive(Debug, Clone)]
David Tolnayad4b2472018-08-25 08:25:24 -040030pub struct Error {
31 span: Span,
32 message: String,
33}
34
35impl Error {
David Tolnay7c8efe92018-09-01 10:00:50 -070036 /// Usually the [`ParseStream::error`] method will be used instead, which
37 /// automatically uses the correct span from the current position of the
38 /// parse stream.
39 ///
40 /// Use `Error::new` when the error needs to be triggered on some span other
41 /// than where the parse stream is currently positioned.
42 ///
43 /// [`ParseStream::error`]: struct.ParseBuffer.html#method.error
44 ///
45 /// # Example
46 ///
47 /// ```
David Tolnaya1c98072018-09-06 08:58:10 -070048 /// #[macro_use]
49 /// extern crate syn;
50 ///
51 /// use syn::{Ident, LitStr};
David Tolnay7c8efe92018-09-01 10:00:50 -070052 /// use syn::parse::{Error, ParseStream, Result};
53 ///
54 /// // Parses input that looks like `name = "string"` where the key must be
55 /// // the identifier `name` and the value may be any string literal.
56 /// // Returns the string literal.
57 /// fn parse_name(input: ParseStream) -> Result<LitStr> {
58 /// let name_token: Ident = input.parse()?;
59 /// if name_token != "name" {
60 /// // Trigger an error not on the current position of the stream,
61 /// // but on the position of the unexpected identifier.
62 /// return Err(Error::new(name_token.span(), "expected `name`"));
63 /// }
64 /// input.parse::<Token![=]>()?;
65 /// let s: LitStr = input.parse()?;
66 /// Ok(s)
67 /// }
68 /// #
69 /// # fn main() {}
70 /// ```
David Tolnayad4b2472018-08-25 08:25:24 -040071 pub fn new<T: Display>(span: Span, message: T) -> Self {
72 Error {
73 span: span,
74 message: message.to_string(),
75 }
76 }
77
David Tolnay7744d9d2018-08-25 22:15:52 -040078 pub fn span(&self) -> Span {
79 self.span
80 }
81
David Tolnayad4b2472018-08-25 08:25:24 -040082 /// Render the error as an invocation of [`compile_error!`].
83 ///
84 /// The [`parse_macro_input!`] macro provides a convenient way to invoke
85 /// this method correctly in a procedural macro.
86 ///
87 /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html
88 /// [`parse_macro_input!`]: ../macro.parse_macro_input.html
David Tolnay24e21f92018-09-06 02:08:07 -070089 pub fn to_compile_error(&self) -> TokenStream {
David Tolnayad4b2472018-08-25 08:25:24 -040090 // compile_error!($message)
91 TokenStream::from_iter(vec![
92 TokenTree::Ident(Ident::new("compile_error", self.span)),
93 TokenTree::Punct({
94 let mut punct = Punct::new('!', Spacing::Alone);
95 punct.set_span(self.span);
96 punct
97 }),
98 TokenTree::Group({
99 let mut group = Group::new(Delimiter::Brace, {
100 TokenStream::from_iter(vec![TokenTree::Literal({
101 let mut string = Literal::string(&self.message);
102 string.set_span(self.span);
103 string
104 })])
105 });
106 group.set_span(self.span);
107 group
108 }),
109 ])
110 }
111}
112
David Tolnayad4b2472018-08-25 08:25:24 -0400113pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
114 if cursor.eof() {
115 Error::new(scope, format!("unexpected end of input, {}", message))
116 } else {
117 Error::new(cursor.span(), message)
118 }
119}
120
121impl Display for Error {
122 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
123 formatter.write_str(&self.message)
124 }
125}
126
127impl std::error::Error for Error {
128 fn description(&self) -> &str {
129 "parse error"
130 }
131}
132
133impl From<LexError> for Error {
134 fn from(err: LexError) -> Self {
135 Error::new(Span::call_site(), format!("{:?}", err))
136 }
137}