blob: 0f5afe18916fdf367ad9181632ccf8bff253974c [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 Tolnayb8a68e42019-04-22 14:01:56 -07007use sealed::lookahead::Sealed;
David Tolnay776f8e02018-08-24 22:32:10 -04008use span::IntoSpans;
David Tolnay776f8e02018-08-24 22:32:10 -04009use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -040010
11/// Support for checking the next token in a stream to decide how to parse.
12///
David Tolnay5c70ede2018-09-01 10:07:56 -070013/// An important advantage over [`ParseStream::peek`] is that here we
14/// automatically construct an appropriate error message based on the token
15/// alternatives that get peeked. If you are producing your own error message,
16/// go ahead and use `ParseStream::peek` instead.
17///
David Tolnay18c754c2018-08-21 23:26:58 -040018/// Use [`ParseStream::lookahead1`] to construct this object.
19///
David Tolnay5c70ede2018-09-01 10:07:56 -070020/// [`ParseStream::peek`]: struct.ParseBuffer.html#method.peek
David Tolnay18c754c2018-08-21 23:26:58 -040021/// [`ParseStream::lookahead1`]: struct.ParseBuffer.html#method.lookahead1
David Tolnay956449d2018-09-01 10:17:54 -070022///
23/// # Example
24///
David Tolnay95989db2019-01-01 15:05:57 -050025/// ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -050026/// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, Token, TypeParam};
David Tolnay67fea042018-11-24 14:50:20 -080027/// use syn::parse::{Parse, ParseStream};
David Tolnay956449d2018-09-01 10:17:54 -070028///
29/// // A generic parameter, a single one of the comma-separated elements inside
30/// // angle brackets in:
31/// //
32/// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
33/// //
34/// // On invalid input, lookahead gives us a reasonable error message.
35/// //
36/// // error: expected one of: identifier, lifetime, `const`
37/// // |
38/// // 5 | fn f<!Sized>() {}
39/// // | ^
40/// enum GenericParam {
41/// Type(TypeParam),
42/// Lifetime(LifetimeDef),
43/// Const(ConstParam),
44/// }
45///
46/// impl Parse for GenericParam {
47/// fn parse(input: ParseStream) -> Result<Self> {
48/// let lookahead = input.lookahead1();
49/// if lookahead.peek(Ident) {
50/// input.parse().map(GenericParam::Type)
51/// } else if lookahead.peek(Lifetime) {
52/// input.parse().map(GenericParam::Lifetime)
53/// } else if lookahead.peek(Token![const]) {
54/// input.parse().map(GenericParam::Const)
55/// } else {
56/// Err(lookahead.error())
57/// }
58/// }
59/// }
David Tolnay956449d2018-09-01 10:17:54 -070060/// ```
David Tolnay18c754c2018-08-21 23:26:58 -040061pub struct Lookahead1<'a> {
62 scope: Span,
63 cursor: Cursor<'a>,
David Tolnay2d032802018-09-01 10:51:59 -070064 comparisons: RefCell<Vec<&'static str>>,
David Tolnay18c754c2018-08-21 23:26:58 -040065}
66
David Tolnay94f06632018-08-31 10:17:17 -070067pub fn new(scope: Span, cursor: Cursor) -> Lookahead1 {
68 Lookahead1 {
69 scope: scope,
70 cursor: cursor,
71 comparisons: RefCell::new(Vec::new()),
David Tolnay18c754c2018-08-21 23:26:58 -040072 }
David Tolnay94f06632018-08-31 10:17:17 -070073}
David Tolnay18c754c2018-08-21 23:26:58 -040074
David Tolnaycae851e2018-09-01 10:59:22 -070075fn peek_impl(
76 lookahead: &Lookahead1,
77 peek: fn(Cursor) -> bool,
78 display: fn() -> &'static str,
79) -> bool {
80 if peek(lookahead.cursor) {
81 return true;
82 }
83 lookahead.comparisons.borrow_mut().push(display());
84 false
85}
86
David Tolnay94f06632018-08-31 10:17:17 -070087impl<'a> Lookahead1<'a> {
David Tolnay6d829fc2018-09-01 14:20:32 -070088 /// Looks at the next token in the parse stream to determine whether it
89 /// matches the requested type of token.
David Tolnay7d229e82018-09-01 16:42:34 -070090 ///
91 /// # Syntax
92 ///
93 /// Note that this method does not use turbofish syntax. Pass the peek type
94 /// inside of parentheses.
95 ///
96 /// - `input.peek(Token![struct])`
97 /// - `input.peek(Token![==])`
David Tolnayb8a68e42019-04-22 14:01:56 -070098 /// - `input.peek(Ident)`&emsp;*(does not accept keywords)*
99 /// - `input.peek(Ident::peek_any)`
David Tolnay7d229e82018-09-01 16:42:34 -0700100 /// - `input.peek(Lifetime)`
101 /// - `input.peek(token::Brace)`
David Tolnay18c754c2018-08-21 23:26:58 -0400102 pub fn peek<T: Peek>(&self, token: T) -> bool {
103 let _ = token;
David Tolnaycae851e2018-09-01 10:59:22 -0700104 peek_impl(self, T::Token::peek, T::Token::display)
David Tolnay18c754c2018-08-21 23:26:58 -0400105 }
106
David Tolnay6d829fc2018-09-01 14:20:32 -0700107 /// Triggers an error at the current position of the parse stream.
108 ///
109 /// The error message will identify all of the expected token types that
110 /// have been peeked against this lookahead instance.
David Tolnay18c754c2018-08-21 23:26:58 -0400111 pub fn error(self) -> Error {
David Tolnayda1dc7c2018-08-24 11:57:28 -0400112 let comparisons = self.comparisons.borrow();
113 match comparisons.len() {
David Tolnayfb84fc02018-10-02 21:01:30 -0700114 0 => {
115 if self.cursor.eof() {
116 Error::new(self.scope, "unexpected end of input")
117 } else {
118 Error::new(self.cursor.span(), "unexpected token")
119 }
120 }
David Tolnayda1dc7c2018-08-24 11:57:28 -0400121 1 => {
122 let message = format!("expected {}", comparisons[0]);
123 error::new_at(self.scope, self.cursor, message)
124 }
David Tolnayeade99e2018-09-01 21:35:51 -0700125 2 => {
126 let message = format!("expected {} or {}", comparisons[0], comparisons[1]);
127 error::new_at(self.scope, self.cursor, message)
128 }
David Tolnayda1dc7c2018-08-24 11:57:28 -0400129 _ => {
David Tolnayc6e86c72018-08-24 12:28:40 -0400130 let join = comparisons.join(", ");
131 let message = format!("expected one of: {}", join);
David Tolnayda1dc7c2018-08-24 11:57:28 -0400132 error::new_at(self.scope, self.cursor, message)
133 }
134 }
David Tolnay18c754c2018-08-21 23:26:58 -0400135 }
136}
137
138/// Types that can be parsed by looking at just one token.
139///
David Tolnay8a44dbf2018-09-01 10:00:43 -0700140/// Use [`ParseStream::peek`] to peek one of these types in a parse stream
141/// without consuming it from the stream.
142///
David Tolnay18c754c2018-08-21 23:26:58 -0400143/// This trait is sealed and cannot be implemented for types outside of Syn.
David Tolnay8a44dbf2018-09-01 10:00:43 -0700144///
145/// [`ParseStream::peek`]: struct.ParseBuffer.html#method.peek
David Tolnayb8a68e42019-04-22 14:01:56 -0700146pub trait Peek: Sealed {
David Tolnay18c754c2018-08-21 23:26:58 -0400147 // Not public API.
148 #[doc(hidden)]
149 type Token: Token;
150}
151
David Tolnayfcdfe312019-04-14 13:44:00 -0700152impl<F: Copy + FnOnce(TokenMarker) -> T, T: Token> Peek for F {
David Tolnay18c754c2018-08-21 23:26:58 -0400153 type Token = T;
154}
155
David Tolnay2b687b02018-08-24 13:36:36 -0400156pub enum TokenMarker {}
157
David Tolnay776f8e02018-08-24 22:32:10 -0400158impl<S> IntoSpans<S> for TokenMarker {
159 fn into_spans(self) -> S {
160 match self {}
161 }
162}
163
David Tolnay00f81fd2018-09-01 10:50:12 -0700164pub fn is_delimiter(cursor: Cursor, delimiter: Delimiter) -> bool {
165 cursor.group(delimiter).is_some()
David Tolnay2d84a082018-08-25 16:31:38 -0400166}
167
David Tolnayb8a68e42019-04-22 14:01:56 -0700168impl<F: Copy + FnOnce(TokenMarker) -> T, T: Token> Sealed for F {}