blob: c8fdbc8314f3fc2eb5696946aeecd74431d7c5cd [file] [log] [blame]
David Tolnay18c754c2018-08-21 23:26:58 -04001use std::cell::RefCell;
2
David Tolnay2d84a082018-08-25 16:31:38 -04003use proc_macro2::{Delimiter, Span};
David Tolnay18c754c2018-08-21 23:26:58 -04004
David Tolnayad4b2472018-08-25 08:25:24 -04005use buffer::Cursor;
6use error::{self, Error};
David Tolnay776f8e02018-08-24 22:32:10 -04007use span::IntoSpans;
David Tolnay776f8e02018-08-24 22:32:10 -04008use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -04009
10/// Support for checking the next token in a stream to decide how to parse.
11///
David Tolnay5c70ede2018-09-01 10:07:56 -070012/// An important advantage over [`ParseStream::peek`] is that here we
13/// automatically construct an appropriate error message based on the token
14/// alternatives that get peeked. If you are producing your own error message,
15/// go ahead and use `ParseStream::peek` instead.
16///
David Tolnay18c754c2018-08-21 23:26:58 -040017/// Use [`ParseStream::lookahead1`] to construct this object.
18///
David Tolnay5c70ede2018-09-01 10:07:56 -070019/// [`ParseStream::peek`]: struct.ParseBuffer.html#method.peek
David Tolnay18c754c2018-08-21 23:26:58 -040020/// [`ParseStream::lookahead1`]: struct.ParseBuffer.html#method.lookahead1
David Tolnay956449d2018-09-01 10:17:54 -070021///
22/// # Example
23///
24/// ```
David Tolnaya1c98072018-09-06 08:58:10 -070025/// #[macro_use]
26/// extern crate syn;
27///
David Tolnay67fea042018-11-24 14:50:20 -080028/// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, TypeParam};
29/// use syn::parse::{Parse, ParseStream};
David Tolnay956449d2018-09-01 10:17:54 -070030///
31/// // A generic parameter, a single one of the comma-separated elements inside
32/// // angle brackets in:
33/// //
34/// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
35/// //
36/// // On invalid input, lookahead gives us a reasonable error message.
37/// //
38/// // error: expected one of: identifier, lifetime, `const`
39/// // |
40/// // 5 | fn f<!Sized>() {}
41/// // | ^
42/// enum GenericParam {
43/// Type(TypeParam),
44/// Lifetime(LifetimeDef),
45/// Const(ConstParam),
46/// }
47///
48/// impl Parse for GenericParam {
49/// fn parse(input: ParseStream) -> Result<Self> {
50/// let lookahead = input.lookahead1();
51/// if lookahead.peek(Ident) {
52/// input.parse().map(GenericParam::Type)
53/// } else if lookahead.peek(Lifetime) {
54/// input.parse().map(GenericParam::Lifetime)
55/// } else if lookahead.peek(Token![const]) {
56/// input.parse().map(GenericParam::Const)
57/// } else {
58/// Err(lookahead.error())
59/// }
60/// }
61/// }
62/// #
63/// # fn main() {}
64/// ```
David Tolnay18c754c2018-08-21 23:26:58 -040065pub struct Lookahead1<'a> {
66 scope: Span,
67 cursor: Cursor<'a>,
David Tolnay2d032802018-09-01 10:51:59 -070068 comparisons: RefCell<Vec<&'static str>>,
David Tolnay18c754c2018-08-21 23:26:58 -040069}
70
David Tolnay94f06632018-08-31 10:17:17 -070071pub fn new(scope: Span, cursor: Cursor) -> Lookahead1 {
72 Lookahead1 {
73 scope: scope,
74 cursor: cursor,
75 comparisons: RefCell::new(Vec::new()),
David Tolnay18c754c2018-08-21 23:26:58 -040076 }
David Tolnay94f06632018-08-31 10:17:17 -070077}
David Tolnay18c754c2018-08-21 23:26:58 -040078
David Tolnaycae851e2018-09-01 10:59:22 -070079fn peek_impl(
80 lookahead: &Lookahead1,
81 peek: fn(Cursor) -> bool,
82 display: fn() -> &'static str,
83) -> bool {
84 if peek(lookahead.cursor) {
85 return true;
86 }
87 lookahead.comparisons.borrow_mut().push(display());
88 false
89}
90
David Tolnay94f06632018-08-31 10:17:17 -070091impl<'a> Lookahead1<'a> {
David Tolnay6d829fc2018-09-01 14:20:32 -070092 /// Looks at the next token in the parse stream to determine whether it
93 /// matches the requested type of token.
David Tolnay7d229e82018-09-01 16:42:34 -070094 ///
95 /// # Syntax
96 ///
97 /// Note that this method does not use turbofish syntax. Pass the peek type
98 /// inside of parentheses.
99 ///
100 /// - `input.peek(Token![struct])`
101 /// - `input.peek(Token![==])`
102 /// - `input.peek(Ident)`
103 /// - `input.peek(Lifetime)`
104 /// - `input.peek(token::Brace)`
David Tolnay18c754c2018-08-21 23:26:58 -0400105 pub fn peek<T: Peek>(&self, token: T) -> bool {
106 let _ = token;
David Tolnaycae851e2018-09-01 10:59:22 -0700107 peek_impl(self, T::Token::peek, T::Token::display)
David Tolnay18c754c2018-08-21 23:26:58 -0400108 }
109
David Tolnay6d829fc2018-09-01 14:20:32 -0700110 /// Triggers an error at the current position of the parse stream.
111 ///
112 /// The error message will identify all of the expected token types that
113 /// have been peeked against this lookahead instance.
David Tolnay18c754c2018-08-21 23:26:58 -0400114 pub fn error(self) -> Error {
David Tolnayda1dc7c2018-08-24 11:57:28 -0400115 let comparisons = self.comparisons.borrow();
116 match comparisons.len() {
David Tolnayfb84fc02018-10-02 21:01:30 -0700117 0 => {
118 if self.cursor.eof() {
119 Error::new(self.scope, "unexpected end of input")
120 } else {
121 Error::new(self.cursor.span(), "unexpected token")
122 }
123 }
David Tolnayda1dc7c2018-08-24 11:57:28 -0400124 1 => {
125 let message = format!("expected {}", comparisons[0]);
126 error::new_at(self.scope, self.cursor, message)
127 }
David Tolnayeade99e2018-09-01 21:35:51 -0700128 2 => {
129 let message = format!("expected {} or {}", comparisons[0], comparisons[1]);
130 error::new_at(self.scope, self.cursor, message)
131 }
David Tolnayda1dc7c2018-08-24 11:57:28 -0400132 _ => {
David Tolnayc6e86c72018-08-24 12:28:40 -0400133 let join = comparisons.join(", ");
134 let message = format!("expected one of: {}", join);
David Tolnayda1dc7c2018-08-24 11:57:28 -0400135 error::new_at(self.scope, self.cursor, message)
136 }
137 }
David Tolnay18c754c2018-08-21 23:26:58 -0400138 }
139}
140
141/// Types that can be parsed by looking at just one token.
142///
David Tolnay8a44dbf2018-09-01 10:00:43 -0700143/// Use [`ParseStream::peek`] to peek one of these types in a parse stream
144/// without consuming it from the stream.
145///
David Tolnay18c754c2018-08-21 23:26:58 -0400146/// This trait is sealed and cannot be implemented for types outside of Syn.
David Tolnay8a44dbf2018-09-01 10:00:43 -0700147///
148/// [`ParseStream::peek`]: struct.ParseBuffer.html#method.peek
David Tolnay18c754c2018-08-21 23:26:58 -0400149pub trait Peek: private::Sealed {
150 // Not public API.
151 #[doc(hidden)]
152 type Token: Token;
153}
154
David Tolnay2b687b02018-08-24 13:36:36 -0400155impl<F: FnOnce(TokenMarker) -> T, T: Token> Peek for F {
David Tolnay18c754c2018-08-21 23:26:58 -0400156 type Token = T;
157}
158
David Tolnay2b687b02018-08-24 13:36:36 -0400159pub enum TokenMarker {}
160
David Tolnay776f8e02018-08-24 22:32:10 -0400161impl<S> IntoSpans<S> for TokenMarker {
162 fn into_spans(self) -> S {
163 match self {}
164 }
165}
166
David Tolnay00f81fd2018-09-01 10:50:12 -0700167pub fn is_delimiter(cursor: Cursor, delimiter: Delimiter) -> bool {
168 cursor.group(delimiter).is_some()
David Tolnay2d84a082018-08-25 16:31:38 -0400169}
170
David Tolnay18c754c2018-08-21 23:26:58 -0400171mod private {
David Tolnay2b687b02018-08-24 13:36:36 -0400172 use super::{Token, TokenMarker};
David Tolnay18c754c2018-08-21 23:26:58 -0400173 pub trait Sealed {}
David Tolnay2b687b02018-08-24 13:36:36 -0400174 impl<F: FnOnce(TokenMarker) -> T, T: Token> Sealed for F {}
David Tolnay18c754c2018-08-21 23:26:58 -0400175}