blob: 8ee1554b7396810213dc9e76d3a386c5160644ac [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///
David Tolnay95989db2019-01-01 15:05:57 -050024/// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -050025/// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam};
David Tolnay67fea042018-11-24 14:50:20 -080026/// use syn::parse::{Parse, ParseStream};
David Tolnay956449d2018-09-01 10:17:54 -070027///
28/// // A generic parameter, a single one of the comma-separated elements inside
29/// // angle brackets in:
30/// //
31/// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
32/// //
33/// // On invalid input, lookahead gives us a reasonable error message.
34/// //
35/// // error: expected one of: identifier, lifetime, `const`
36/// // |
37/// // 5 | fn f<!Sized>() {}
38/// // | ^
39/// enum GenericParam {
40/// Type(TypeParam),
41/// Lifetime(LifetimeDef),
42/// Const(ConstParam),
43/// }
44///
45/// impl Parse for GenericParam {
46/// fn parse(input: ParseStream) -> Result<Self> {
47/// let lookahead = input.lookahead1();
48/// if lookahead.peek(Ident) {
49/// input.parse().map(GenericParam::Type)
50/// } else if lookahead.peek(Lifetime) {
51/// input.parse().map(GenericParam::Lifetime)
52/// } else if lookahead.peek(Token![const]) {
53/// input.parse().map(GenericParam::Const)
54/// } else {
55/// Err(lookahead.error())
56/// }
57/// }
58/// }
David Tolnay956449d2018-09-01 10:17:54 -070059/// ```
David Tolnay18c754c2018-08-21 23:26:58 -040060pub struct Lookahead1<'a> {
61 scope: Span,
62 cursor: Cursor<'a>,
David Tolnay2d032802018-09-01 10:51:59 -070063 comparisons: RefCell<Vec<&'static str>>,
David Tolnay18c754c2018-08-21 23:26:58 -040064}
65
David Tolnay94f06632018-08-31 10:17:17 -070066pub fn new(scope: Span, cursor: Cursor) -> Lookahead1 {
67 Lookahead1 {
68 scope: scope,
69 cursor: cursor,
70 comparisons: RefCell::new(Vec::new()),
David Tolnay18c754c2018-08-21 23:26:58 -040071 }
David Tolnay94f06632018-08-31 10:17:17 -070072}
David Tolnay18c754c2018-08-21 23:26:58 -040073
David Tolnaycae851e2018-09-01 10:59:22 -070074fn peek_impl(
75 lookahead: &Lookahead1,
76 peek: fn(Cursor) -> bool,
77 display: fn() -> &'static str,
78) -> bool {
79 if peek(lookahead.cursor) {
80 return true;
81 }
82 lookahead.comparisons.borrow_mut().push(display());
83 false
84}
85
David Tolnay94f06632018-08-31 10:17:17 -070086impl<'a> Lookahead1<'a> {
David Tolnay6d829fc2018-09-01 14:20:32 -070087 /// Looks at the next token in the parse stream to determine whether it
88 /// matches the requested type of token.
David Tolnay7d229e82018-09-01 16:42:34 -070089 ///
90 /// # Syntax
91 ///
92 /// Note that this method does not use turbofish syntax. Pass the peek type
93 /// inside of parentheses.
94 ///
95 /// - `input.peek(Token![struct])`
96 /// - `input.peek(Token![==])`
97 /// - `input.peek(Ident)`
98 /// - `input.peek(Lifetime)`
99 /// - `input.peek(token::Brace)`
David Tolnay18c754c2018-08-21 23:26:58 -0400100 pub fn peek<T: Peek>(&self, token: T) -> bool {
101 let _ = token;
David Tolnaycae851e2018-09-01 10:59:22 -0700102 peek_impl(self, T::Token::peek, T::Token::display)
David Tolnay18c754c2018-08-21 23:26:58 -0400103 }
104
David Tolnay6d829fc2018-09-01 14:20:32 -0700105 /// Triggers an error at the current position of the parse stream.
106 ///
107 /// The error message will identify all of the expected token types that
108 /// have been peeked against this lookahead instance.
David Tolnay18c754c2018-08-21 23:26:58 -0400109 pub fn error(self) -> Error {
David Tolnayda1dc7c2018-08-24 11:57:28 -0400110 let comparisons = self.comparisons.borrow();
111 match comparisons.len() {
David Tolnayfb84fc02018-10-02 21:01:30 -0700112 0 => {
113 if self.cursor.eof() {
114 Error::new(self.scope, "unexpected end of input")
115 } else {
116 Error::new(self.cursor.span(), "unexpected token")
117 }
118 }
David Tolnayda1dc7c2018-08-24 11:57:28 -0400119 1 => {
120 let message = format!("expected {}", comparisons[0]);
121 error::new_at(self.scope, self.cursor, message)
122 }
David Tolnayeade99e2018-09-01 21:35:51 -0700123 2 => {
124 let message = format!("expected {} or {}", comparisons[0], comparisons[1]);
125 error::new_at(self.scope, self.cursor, message)
126 }
David Tolnayda1dc7c2018-08-24 11:57:28 -0400127 _ => {
David Tolnayc6e86c72018-08-24 12:28:40 -0400128 let join = comparisons.join(", ");
129 let message = format!("expected one of: {}", join);
David Tolnayda1dc7c2018-08-24 11:57:28 -0400130 error::new_at(self.scope, self.cursor, message)
131 }
132 }
David Tolnay18c754c2018-08-21 23:26:58 -0400133 }
134}
135
136/// Types that can be parsed by looking at just one token.
137///
David Tolnay8a44dbf2018-09-01 10:00:43 -0700138/// Use [`ParseStream::peek`] to peek one of these types in a parse stream
139/// without consuming it from the stream.
140///
David Tolnay18c754c2018-08-21 23:26:58 -0400141/// This trait is sealed and cannot be implemented for types outside of Syn.
David Tolnay8a44dbf2018-09-01 10:00:43 -0700142///
143/// [`ParseStream::peek`]: struct.ParseBuffer.html#method.peek
David Tolnay18c754c2018-08-21 23:26:58 -0400144pub trait Peek: private::Sealed {
145 // Not public API.
146 #[doc(hidden)]
147 type Token: Token;
148}
149
David Tolnayfcdfe312019-04-14 13:44:00 -0700150impl<F: Copy + FnOnce(TokenMarker) -> T, T: Token> Peek for F {
David Tolnay18c754c2018-08-21 23:26:58 -0400151 type Token = T;
152}
153
David Tolnay2b687b02018-08-24 13:36:36 -0400154pub enum TokenMarker {}
155
David Tolnay776f8e02018-08-24 22:32:10 -0400156impl<S> IntoSpans<S> for TokenMarker {
157 fn into_spans(self) -> S {
158 match self {}
159 }
160}
161
David Tolnay00f81fd2018-09-01 10:50:12 -0700162pub fn is_delimiter(cursor: Cursor, delimiter: Delimiter) -> bool {
163 cursor.group(delimiter).is_some()
David Tolnay2d84a082018-08-25 16:31:38 -0400164}
165
David Tolnay18c754c2018-08-21 23:26:58 -0400166mod private {
David Tolnay2b687b02018-08-24 13:36:36 -0400167 use super::{Token, TokenMarker};
David Tolnayfcdfe312019-04-14 13:44:00 -0700168 pub trait Sealed: Copy {}
169 impl<F: Copy + FnOnce(TokenMarker) -> T, T: Token> Sealed for F {}
David Tolnay18c754c2018-08-21 23:26:58 -0400170}