blob: 16e568e8608ef8677c226c855258ec5bacd49d78 [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 Tolnay9b00f652018-09-01 10:31:02 -070048 /// # extern crate syn;
49 /// #
50 /// use syn::{Ident, LitStr, Token};
David Tolnay7c8efe92018-09-01 10:00:50 -070051 /// use syn::parse::{Error, ParseStream, Result};
52 ///
53 /// // Parses input that looks like `name = "string"` where the key must be
54 /// // the identifier `name` and the value may be any string literal.
55 /// // Returns the string literal.
56 /// fn parse_name(input: ParseStream) -> Result<LitStr> {
57 /// let name_token: Ident = input.parse()?;
58 /// if name_token != "name" {
59 /// // Trigger an error not on the current position of the stream,
60 /// // but on the position of the unexpected identifier.
61 /// return Err(Error::new(name_token.span(), "expected `name`"));
62 /// }
63 /// input.parse::<Token![=]>()?;
64 /// let s: LitStr = input.parse()?;
65 /// Ok(s)
66 /// }
67 /// #
68 /// # fn main() {}
69 /// ```
David Tolnayad4b2472018-08-25 08:25:24 -040070 pub fn new<T: Display>(span: Span, message: T) -> Self {
71 Error {
72 span: span,
73 message: message.to_string(),
74 }
75 }
76
David Tolnay7744d9d2018-08-25 22:15:52 -040077 pub fn span(&self) -> Span {
78 self.span
79 }
80
David Tolnayad4b2472018-08-25 08:25:24 -040081 /// Render the error as an invocation of [`compile_error!`].
82 ///
83 /// The [`parse_macro_input!`] macro provides a convenient way to invoke
84 /// this method correctly in a procedural macro.
85 ///
86 /// [`compile_error!`]: https://doc.rust-lang.org/std/macro.compile_error.html
87 /// [`parse_macro_input!`]: ../macro.parse_macro_input.html
88 pub fn into_compile_error(self) -> TokenStream {
89 // compile_error!($message)
90 TokenStream::from_iter(vec![
91 TokenTree::Ident(Ident::new("compile_error", self.span)),
92 TokenTree::Punct({
93 let mut punct = Punct::new('!', Spacing::Alone);
94 punct.set_span(self.span);
95 punct
96 }),
97 TokenTree::Group({
98 let mut group = Group::new(Delimiter::Brace, {
99 TokenStream::from_iter(vec![TokenTree::Literal({
100 let mut string = Literal::string(&self.message);
101 string.set_span(self.span);
102 string
103 })])
104 });
105 group.set_span(self.span);
106 group
107 }),
108 ])
109 }
110}
111
David Tolnayad4b2472018-08-25 08:25:24 -0400112pub fn new_at<T: Display>(scope: Span, cursor: Cursor, message: T) -> Error {
113 if cursor.eof() {
114 Error::new(scope, format!("unexpected end of input, {}", message))
115 } else {
116 Error::new(cursor.span(), message)
117 }
118}
119
120impl Display for Error {
121 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
122 formatter.write_str(&self.message)
123 }
124}
125
126impl std::error::Error for Error {
127 fn description(&self) -> &str {
128 "parse error"
129 }
130}
131
132impl From<LexError> for Error {
133 fn from(err: LexError) -> Self {
134 Error::new(Span::call_site(), format!("{:?}", err))
135 }
136}