blob: 793d2a8f3830d4a4aafeedb0358e2a0f807c7ec7 [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/// ```
25/// # extern crate syn;
26/// #
27/// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Token, TypeParam};
28/// use syn::parse::{Parse, ParseStream, Result};
29///
30/// // A generic parameter, a single one of the comma-separated elements inside
31/// // angle brackets in:
32/// //
33/// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
34/// //
35/// // On invalid input, lookahead gives us a reasonable error message.
36/// //
37/// // error: expected one of: identifier, lifetime, `const`
38/// // |
39/// // 5 | fn f<!Sized>() {}
40/// // | ^
41/// enum GenericParam {
42/// Type(TypeParam),
43/// Lifetime(LifetimeDef),
44/// Const(ConstParam),
45/// }
46///
47/// impl Parse for GenericParam {
48/// fn parse(input: ParseStream) -> Result<Self> {
49/// let lookahead = input.lookahead1();
50/// if lookahead.peek(Ident) {
51/// input.parse().map(GenericParam::Type)
52/// } else if lookahead.peek(Lifetime) {
53/// input.parse().map(GenericParam::Lifetime)
54/// } else if lookahead.peek(Token![const]) {
55/// input.parse().map(GenericParam::Const)
56/// } else {
57/// Err(lookahead.error())
58/// }
59/// }
60/// }
61/// #
62/// # fn main() {}
63/// ```
David Tolnay18c754c2018-08-21 23:26:58 -040064pub struct Lookahead1<'a> {
65 scope: Span,
66 cursor: Cursor<'a>,
David Tolnay2d032802018-09-01 10:51:59 -070067 comparisons: RefCell<Vec<&'static str>>,
David Tolnay18c754c2018-08-21 23:26:58 -040068}
69
David Tolnay94f06632018-08-31 10:17:17 -070070pub fn new(scope: Span, cursor: Cursor) -> Lookahead1 {
71 Lookahead1 {
72 scope: scope,
73 cursor: cursor,
74 comparisons: RefCell::new(Vec::new()),
David Tolnay18c754c2018-08-21 23:26:58 -040075 }
David Tolnay94f06632018-08-31 10:17:17 -070076}
David Tolnay18c754c2018-08-21 23:26:58 -040077
David Tolnaycae851e2018-09-01 10:59:22 -070078fn peek_impl(
79 lookahead: &Lookahead1,
80 peek: fn(Cursor) -> bool,
81 display: fn() -> &'static str,
82) -> bool {
83 if peek(lookahead.cursor) {
84 return true;
85 }
86 lookahead.comparisons.borrow_mut().push(display());
87 false
88}
89
David Tolnay94f06632018-08-31 10:17:17 -070090impl<'a> Lookahead1<'a> {
David Tolnay18c754c2018-08-21 23:26:58 -040091 pub fn peek<T: Peek>(&self, token: T) -> bool {
92 let _ = token;
David Tolnaycae851e2018-09-01 10:59:22 -070093 peek_impl(self, T::Token::peek, T::Token::display)
David Tolnay18c754c2018-08-21 23:26:58 -040094 }
95
96 pub fn error(self) -> Error {
David Tolnayda1dc7c2018-08-24 11:57:28 -040097 let comparisons = self.comparisons.borrow();
98 match comparisons.len() {
99 0 => if self.cursor.eof() {
100 Error::new(self.scope, "unexpected end of input")
101 } else {
102 Error::new(self.cursor.span(), "unexpected token")
103 },
104 1 => {
105 let message = format!("expected {}", comparisons[0]);
106 error::new_at(self.scope, self.cursor, message)
107 }
108 _ => {
David Tolnayc6e86c72018-08-24 12:28:40 -0400109 let join = comparisons.join(", ");
110 let message = format!("expected one of: {}", join);
David Tolnayda1dc7c2018-08-24 11:57:28 -0400111 error::new_at(self.scope, self.cursor, message)
112 }
113 }
David Tolnay18c754c2018-08-21 23:26:58 -0400114 }
115}
116
117/// Types that can be parsed by looking at just one token.
118///
David Tolnay8a44dbf2018-09-01 10:00:43 -0700119/// Use [`ParseStream::peek`] to peek one of these types in a parse stream
120/// without consuming it from the stream.
121///
David Tolnay18c754c2018-08-21 23:26:58 -0400122/// This trait is sealed and cannot be implemented for types outside of Syn.
David Tolnay8a44dbf2018-09-01 10:00:43 -0700123///
124/// [`ParseStream::peek`]: struct.ParseBuffer.html#method.peek
David Tolnay18c754c2018-08-21 23:26:58 -0400125pub trait Peek: private::Sealed {
126 // Not public API.
127 #[doc(hidden)]
128 type Token: Token;
129}
130
David Tolnay2b687b02018-08-24 13:36:36 -0400131impl<F: FnOnce(TokenMarker) -> T, T: Token> Peek for F {
David Tolnay18c754c2018-08-21 23:26:58 -0400132 type Token = T;
133}
134
David Tolnay2b687b02018-08-24 13:36:36 -0400135pub enum TokenMarker {}
136
David Tolnay776f8e02018-08-24 22:32:10 -0400137impl<S> IntoSpans<S> for TokenMarker {
138 fn into_spans(self) -> S {
139 match self {}
140 }
141}
142
David Tolnay00f81fd2018-09-01 10:50:12 -0700143pub fn is_delimiter(cursor: Cursor, delimiter: Delimiter) -> bool {
144 cursor.group(delimiter).is_some()
David Tolnay2d84a082018-08-25 16:31:38 -0400145}
146
David Tolnay18c754c2018-08-21 23:26:58 -0400147mod private {
David Tolnay2b687b02018-08-24 13:36:36 -0400148 use super::{Token, TokenMarker};
David Tolnay18c754c2018-08-21 23:26:58 -0400149 pub trait Sealed {}
David Tolnay2b687b02018-08-24 13:36:36 -0400150 impl<F: FnOnce(TokenMarker) -> T, T: Token> Sealed for F {}
David Tolnay18c754c2018-08-21 23:26:58 -0400151}