blob: 5e06e3f5ce5164fd336fd46cd82e2814ce59f7a6 [file] [log] [blame]
Alex Crichton954046c2017-05-30 21:49:42 -07001//! Discrete tokens that can be parsed out by synom.
2//!
3//! This module contains a number of useful tokens like `+=` and `/` along with
4//! keywords like `crate` and such. These structures are used to track the spans
5//! of these tokens and all implment the `ToTokens` and `Synom` traits when the
6//! corresponding feature is activated.
7
Alex Crichton7b9e02f2017-05-30 15:54:33 -07008use span::Span;
9
10macro_rules! tokens {
11 (
12 ops: {
13 $(($($op:tt)*),)*
14 }
15 delim: {
16 $(($($delim:tt)*),)*
17 }
18 syms: {
19 $(($($sym:tt)*),)*
20 }
21 ) => (
22 $(op! { $($op)* })*
23 $(delim! { $($delim)* })*
24 $(sym! { $($sym)* })*
25 )
26}
27
28macro_rules! op {
29 (pub struct $name:ident($($contents:tt)*) => $s:expr) => {
30 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
31 #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))]
32 #[derive(Default)]
33 pub struct $name(pub $($contents)*);
34
35 #[cfg(feature = "printing")]
36 impl ::quote::ToTokens for $name {
37 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
38 printing::op($s, &self.0, tokens);
39 }
40 }
41
42 #[cfg(feature = "parsing")]
43 impl ::Synom for $name {
Michael Layzell760fd662017-05-31 22:46:05 -040044 fn parse(tokens: $crate::Cursor) -> $crate::PResult<$name> {
Alex Crichton7b9e02f2017-05-30 15:54:33 -070045 parsing::op($s, tokens, $name)
46 }
47 }
48 }
49}
50
51macro_rules! sym {
52 (pub struct $name:ident => $s:expr) => {
53 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
54 #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))]
55 #[derive(Default)]
56 pub struct $name(pub Span);
57
58 #[cfg(feature = "printing")]
59 impl ::quote::ToTokens for $name {
60 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
61 printing::sym($s, &self.0, tokens);
62 }
63 }
64
65 #[cfg(feature = "parsing")]
66 impl ::Synom for $name {
Michael Layzell760fd662017-05-31 22:46:05 -040067 fn parse(tokens: $crate::Cursor) -> $crate::PResult<$name> {
Alex Crichton7b9e02f2017-05-30 15:54:33 -070068 parsing::sym($s, tokens, $name)
69 }
70 }
71 }
72}
73
74macro_rules! delim {
75 (pub struct $name:ident => $s:expr) => {
76 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
77 #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))]
78 #[derive(Default)]
79 pub struct $name(pub Span);
80
81 impl $name {
82 #[cfg(feature = "printing")]
83 pub fn surround<F>(&self,
84 tokens: &mut ::quote::Tokens,
85 f: F)
86 where F: FnOnce(&mut ::quote::Tokens)
87 {
88 printing::delim($s, &self.0, tokens, f);
89 }
90
91 #[cfg(feature = "parsing")]
Michael Layzell760fd662017-05-31 22:46:05 -040092 pub fn parse<F, R>(tokens: $crate::Cursor, f: F) -> $crate::PResult<(R, $name)>
93 where F: FnOnce($crate::Cursor) -> $crate::PResult<R>
Alex Crichton7b9e02f2017-05-30 15:54:33 -070094 {
95 parsing::delim($s, tokens, $name, f)
96 }
97 }
98 }
99}
100
101tokens! {
102 ops: {
103 (pub struct Add([Span; 1]) => "+"),
104 (pub struct AddEq([Span; 2]) => "+="),
105 (pub struct And([Span; 1]) => "&"),
106 (pub struct AndAnd([Span; 2]) => "&&"),
107 (pub struct AndEq([Span; 2]) => "&="),
108 (pub struct At([Span; 1]) => "@"),
109 (pub struct Bang([Span; 1]) => "!"),
110 (pub struct Caret([Span; 1]) => "^"),
111 (pub struct CaretEq([Span; 2]) => "^="),
112 (pub struct Colon([Span; 1]) => ":"),
113 (pub struct Colon2([Span; 2]) => "::"),
114 (pub struct Comma([Span; 1]) => ","),
115 (pub struct Div([Span; 1]) => "/"),
116 (pub struct DivEq([Span; 2]) => "/="),
117 (pub struct Dot([Span; 1]) => "."),
118 (pub struct Dot2([Span; 2]) => ".."),
119 (pub struct Dot3([Span; 3]) => "..."),
120 (pub struct Eq([Span; 1]) => "="),
121 (pub struct EqEq([Span; 2]) => "=="),
122 (pub struct Ge([Span; 2]) => ">="),
123 (pub struct Gt([Span; 1]) => ">"),
124 (pub struct Le([Span; 2]) => "<="),
125 (pub struct Lt([Span; 1]) => "<"),
126 (pub struct MulEq([Span; 2]) => "*="),
127 (pub struct Ne([Span; 2]) => "!="),
128 (pub struct Or([Span; 1]) => "|"),
129 (pub struct OrEq([Span; 2]) => "|="),
130 (pub struct OrOr([Span; 2]) => "||"),
131 (pub struct Pound([Span; 1]) => "#"),
132 (pub struct Question([Span; 1]) => "?"),
133 (pub struct RArrow([Span; 2]) => "->"),
134 (pub struct Rem([Span; 1]) => "%"),
135 (pub struct RemEq([Span; 2]) => "%="),
136 (pub struct Rocket([Span; 2]) => "=>"),
137 (pub struct Semi([Span; 1]) => ";"),
138 (pub struct Shl([Span; 2]) => "<<"),
139 (pub struct ShlEq([Span; 3]) => "<<="),
140 (pub struct Shr([Span; 2]) => ">>"),
141 (pub struct ShrEq([Span; 3]) => ">>="),
142 (pub struct Star([Span; 1]) => "*"),
143 (pub struct Sub([Span; 1]) => "-"),
144 (pub struct SubEq([Span; 2]) => "-="),
145 (pub struct Underscore([Span; 1]) => "_"),
146 }
147 delim: {
148 (pub struct Brace => "{"),
149 (pub struct Bracket => "["),
150 (pub struct Paren => "("),
151 }
152 syms: {
153 (pub struct As => "as"),
Alex Crichton954046c2017-05-30 21:49:42 -0700154 (pub struct Box_ => "box"),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700155 (pub struct Break => "break"),
Alex Crichton954046c2017-05-30 21:49:42 -0700156 (pub struct CapSelf => "Self"),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700157 (pub struct Catch => "catch"),
158 (pub struct Const => "const"),
159 (pub struct Continue => "continue"),
160 (pub struct Crate => "crate"),
Alex Crichton954046c2017-05-30 21:49:42 -0700161 (pub struct Default_ => "default"),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700162 (pub struct Do => "do"),
163 (pub struct Else => "else"),
164 (pub struct Enum => "enum"),
165 (pub struct Extern => "extern"),
Alex Crichton954046c2017-05-30 21:49:42 -0700166 (pub struct Fn_ => "fn"),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700167 (pub struct For => "for"),
168 (pub struct If => "if"),
169 (pub struct Impl => "impl"),
170 (pub struct In => "in"),
171 (pub struct Let => "let"),
172 (pub struct Loop => "loop"),
173 (pub struct Match => "match"),
174 (pub struct Mod => "mod"),
175 (pub struct Move => "move"),
176 (pub struct Mut => "mut"),
177 (pub struct Pub => "pub"),
178 (pub struct Ref => "ref"),
179 (pub struct Return => "return"),
180 (pub struct Self_ => "self"),
181 (pub struct Static => "static"),
182 (pub struct Struct => "struct"),
Alex Crichton954046c2017-05-30 21:49:42 -0700183 (pub struct Super => "super"),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700184 (pub struct Trait => "trait"),
185 (pub struct Type => "type"),
186 (pub struct Union => "union"),
187 (pub struct Unsafe => "unsafe"),
188 (pub struct Use => "use"),
189 (pub struct Where => "where"),
190 (pub struct While => "while"),
191 }
192}
193
194#[cfg(feature = "parsing")]
195mod parsing {
Alex Crichton954046c2017-05-30 21:49:42 -0700196 use proc_macro2::{TokenTree, TokenKind, Delimiter, OpKind};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700197
Michael Layzell760fd662017-05-31 22:46:05 -0400198 use {PResult, Cursor, parse_error};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700199 use span::Span;
200
201 pub trait FromSpans: Sized {
202 fn from_spans(spans: &[Span]) -> Self;
203 }
204
205 impl FromSpans for [Span; 1] {
206 fn from_spans(spans: &[Span]) -> Self {
207 [spans[0]]
208 }
209 }
210
211 impl FromSpans for [Span; 2] {
212 fn from_spans(spans: &[Span]) -> Self {
213 [spans[0], spans[1]]
214 }
215 }
216
217 impl FromSpans for [Span; 3] {
218 fn from_spans(spans: &[Span]) -> Self {
219 [spans[0], spans[1], spans[2]]
220 }
221 }
222
223 pub fn op<'a, T, R>(s: &str,
Michael Layzell760fd662017-05-31 22:46:05 -0400224 tokens: Cursor<'a>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700225 new: fn(T) -> R)
Michael Layzell760fd662017-05-31 22:46:05 -0400226 -> PResult<'a, R>
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700227 where T: FromSpans,
228 {
229 let mut spans = [Span::default(); 3];
Alex Crichton954046c2017-05-30 21:49:42 -0700230 assert!(s.len() <= spans.len());
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700231 let chars = s.chars();
232 let mut it = tokens.iter();
233
Alex Crichton954046c2017-05-30 21:49:42 -0700234 for (i, (ch, slot)) in chars.zip(&mut spans).enumerate() {
235 let tok = match it.next() {
236 Some(tok) => tok,
Michael Layzell760fd662017-05-31 22:46:05 -0400237 _ => return parse_error(),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700238 };
Alex Crichton954046c2017-05-30 21:49:42 -0700239 let kind = match tok.kind {
240 TokenKind::Op(c, kind) if c == ch => kind,
Michael Layzell760fd662017-05-31 22:46:05 -0400241 _ => return parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700242 };
243 if i != s.len() - 1 {
244 match kind {
245 OpKind::Joint => {}
Michael Layzell760fd662017-05-31 22:46:05 -0400246 OpKind::Alone => return parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700247 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700248 }
Alex Crichton954046c2017-05-30 21:49:42 -0700249 *slot = Span(tok.span);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700250 }
Michael Layzell760fd662017-05-31 22:46:05 -0400251 Ok((it.as_slice(), new(T::from_spans(&spans))))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700252 }
253
254 pub fn sym<'a, T>(sym: &str,
Michael Layzell760fd662017-05-31 22:46:05 -0400255 tokens: Cursor<'a>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700256 new: fn(Span) -> T)
Michael Layzell760fd662017-05-31 22:46:05 -0400257 -> PResult<'a, T>
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700258 {
259 let mut tokens = tokens.iter();
260 let (span, s) = match tokens.next() {
261 Some(&TokenTree { span, kind: TokenKind::Word(sym) }) => (span, sym),
Michael Layzell760fd662017-05-31 22:46:05 -0400262 _ => return parse_error(),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700263 };
264 if s.as_str() == sym {
Michael Layzell760fd662017-05-31 22:46:05 -0400265 Ok((tokens.as_slice(), new(Span(span))))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700266 } else {
Michael Layzell760fd662017-05-31 22:46:05 -0400267 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700268 }
269 }
270
271 pub fn delim<'a, F, R, T>(delim: &str,
Michael Layzell760fd662017-05-31 22:46:05 -0400272 tokens: Cursor<'a>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700273 new: fn(Span) -> T,
274 f: F)
Michael Layzell760fd662017-05-31 22:46:05 -0400275 -> PResult<'a, (R, T)>
276 where F: FnOnce(Cursor) -> PResult<R>
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700277 {
278 let delim = match delim {
279 "(" => Delimiter::Parenthesis,
280 "{" => Delimiter::Brace,
281 "[" => Delimiter::Bracket,
282 _ => panic!("unknown delimiter: {}", delim),
283 };
284 let mut tokens = tokens.iter();
285 let (span, d, others) = match tokens.next() {
286 Some(&TokenTree { span, kind: TokenKind::Sequence(d, ref rest) }) => {
287 (span, d, rest)
288 }
Michael Layzell760fd662017-05-31 22:46:05 -0400289 _ => return parse_error(),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700290 };
291 match (delim, d) {
292 (Delimiter::Parenthesis, Delimiter::Parenthesis) |
293 (Delimiter::Brace, Delimiter::Brace) |
294 (Delimiter::Bracket, Delimiter::Bracket) => {}
Michael Layzell760fd662017-05-31 22:46:05 -0400295 _ => return parse_error(),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700296 }
297
298 // TODO: Need a custom type to avoid this allocation every time we try
Michael Layzell760fd662017-05-31 22:46:05 -0400299 // this branch. (issue dtolnay/syn#148)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700300 let rest = others.clone().into_iter().collect::<Vec<_>>();
301 match f(&rest) {
Michael Layzell760fd662017-05-31 22:46:05 -0400302 Ok((remaining, ret)) => {
Alex Crichton954046c2017-05-30 21:49:42 -0700303 if remaining.is_empty() {
Michael Layzell760fd662017-05-31 22:46:05 -0400304 Ok((tokens.as_slice(), (ret, new(Span(span)))))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700305 } else {
Michael Layzell760fd662017-05-31 22:46:05 -0400306 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700307 }
308 }
Michael Layzell760fd662017-05-31 22:46:05 -0400309 Err(err) => Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700310 }
311 }
312}
313
314#[cfg(feature = "printing")]
315mod printing {
316 use proc_macro2::{TokenTree, TokenKind, OpKind};
317 use quote::Tokens;
318
319 use span::Span;
320
321 pub fn op(s: &str, spans: &[Span], tokens: &mut Tokens) {
322 assert_eq!(s.len(), spans.len());
323
324 let mut chars = s.chars();
325 let mut spans = spans.iter();
326 let ch = chars.next_back().unwrap();
327 let span = spans.next_back().unwrap();
328 for (ch, span) in chars.zip(spans) {
329 tokens.append(TokenTree {
330 span: span.0,
331 kind: TokenKind::Op(ch, OpKind::Joint),
332 });
333 }
334
335 tokens.append(TokenTree {
336 span: span.0,
337 kind: TokenKind::Op(ch, OpKind::Alone),
338 });
339 }
340
341 pub fn sym(s: &str, span: &Span, tokens: &mut Tokens) {
342 tokens.append(TokenTree {
343 span: span.0,
344 kind: TokenKind::Word(s.into()),
345 });
346 }
347
348 pub fn delim<F>(s: &str, span: &Span, tokens: &mut Tokens, f: F)
349 where F: FnOnce(&mut Tokens)
350 {
351 tokens.append_delimited(s, span.0, f)
352 }
353}