]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/transcribe.rs
Rollup merge of #61705 - petrhosek:llvm-cflags, r=alexcrichton
[rust.git] / src / libsyntax / ext / tt / transcribe.rs
1 use crate::ast::Ident;
2 use crate::ext::base::ExtCtxt;
3 use crate::ext::expand::Marker;
4 use crate::ext::tt::macro_parser::{MatchedNonterminal, MatchedSeq, NamedMatch};
5 use crate::ext::tt::quoted;
6 use crate::mut_visit::noop_visit_tt;
7 use crate::parse::token::{self, NtTT, Token};
8 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree, TreeAndJoint};
9
10 use smallvec::{smallvec, SmallVec};
11
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_data_structures::sync::Lrc;
14 use std::mem;
15 use std::rc::Rc;
16
17 /// An iterator over the token trees in a delimited token tree (`{ ... }`) or a sequence (`$(...)`).
18 enum Frame {
19     Delimited { forest: Lrc<quoted::Delimited>, idx: usize, span: DelimSpan },
20     Sequence { forest: Lrc<quoted::SequenceRepetition>, idx: usize, sep: Option<Token> },
21 }
22
23 impl Frame {
24     /// Construct a new frame around the delimited set of tokens.
25     fn new(tts: Vec<quoted::TokenTree>) -> Frame {
26         let forest = Lrc::new(quoted::Delimited { delim: token::NoDelim, tts: tts });
27         Frame::Delimited { forest: forest, idx: 0, span: DelimSpan::dummy() }
28     }
29 }
30
31 impl Iterator for Frame {
32     type Item = quoted::TokenTree;
33
34     fn next(&mut self) -> Option<quoted::TokenTree> {
35         match *self {
36             Frame::Delimited { ref forest, ref mut idx, .. } => {
37                 *idx += 1;
38                 forest.tts.get(*idx - 1).cloned()
39             }
40             Frame::Sequence { ref forest, ref mut idx, .. } => {
41                 *idx += 1;
42                 forest.tts.get(*idx - 1).cloned()
43             }
44         }
45     }
46 }
47
48 /// This can do Macro-By-Example transcription.
49 /// - `interp` is a map of meta-variables to the tokens (non-terminals) they matched in the
50 ///   invocation. We are assuming we already know there is a match.
51 /// - `src` is the RHS of the MBE, that is, the "example" we are filling in.
52 ///
53 /// For example,
54 ///
55 /// ```rust
56 /// macro_rules! foo {
57 ///     ($id:ident) => { println!("{}", stringify!($id)); }
58 /// }
59 ///
60 /// foo!(bar);
61 /// ```
62 ///
63 /// `interp` would contain `$id => bar` and `src` would contain `println!("{}", stringify!($id));`.
64 ///
65 /// `transcribe` would return a `TokenStream` containing `println!("{}", stringify!(bar));`.
66 ///
67 /// Along the way, we do some additional error checking.
68 pub fn transcribe(
69     cx: &ExtCtxt<'_>,
70     interp: &FxHashMap<Ident, Rc<NamedMatch>>,
71     src: Vec<quoted::TokenTree>,
72 ) -> TokenStream {
73     // Nothing for us to transcribe...
74     if src.is_empty() {
75         return TokenStream::empty();
76     }
77
78     // We descend into the RHS (`src`), expanding things as we go. This stack contains the things
79     // we have yet to expand/are still expanding. We start the stack off with the whole RHS.
80     let mut stack: SmallVec<[Frame; 1]> = smallvec![Frame::new(src)];
81
82     // As we descend in the RHS, we will need to be able to match nested sequences of matchers.
83     // `repeats` keeps track of where we are in matching at each level, with the last element being
84     // the most deeply nested sequence. This is used as a stack.
85     let mut repeats = Vec::new();
86
87     // `result` contains resulting token stream from the TokenTree we just finished processing. At
88     // the end, this will contain the full result of transcription, but at arbitrary points during
89     // `transcribe`, `result` will contain subsets of the final result.
90     //
91     // Specifically, as we descend into each TokenTree, we will push the existing results onto the
92     // `result_stack` and clear `results`. We will then produce the results of transcribing the
93     // TokenTree into `results`. Then, as we unwind back out of the `TokenTree`, we will pop the
94     // `result_stack` and append `results` too it to produce the new `results` up to that point.
95     //
96     // Thus, if we try to pop the `result_stack` and it is empty, we have reached the top-level
97     // again, and we are done transcribing.
98     let mut result: Vec<TreeAndJoint> = Vec::new();
99     let mut result_stack = Vec::new();
100
101     loop {
102         // Look at the last frame on the stack.
103         let tree = if let Some(tree) = stack.last_mut().unwrap().next() {
104             // If it still has a TokenTree we have not looked at yet, use that tree.
105             tree
106         }
107         // The else-case never produces a value for `tree` (it `continue`s or `return`s).
108         else {
109             // Otherwise, if we have just reached the end of a sequence and we can keep repeating,
110             // go back to the beginning of the sequence.
111             if let Frame::Sequence { idx, sep, .. } = stack.last_mut().unwrap() {
112                 let (repeat_idx, repeat_len) = repeats.last_mut().unwrap();
113                 *repeat_idx += 1;
114                 if repeat_idx < repeat_len {
115                     *idx = 0;
116                     if let Some(sep) = sep {
117                         result.push(TokenTree::Token(sep.clone()).into());
118                     }
119                     continue;
120                 }
121             }
122
123             // We are done with the top of the stack. Pop it. Depending on what it was, we do
124             // different things. Note that the outermost item must be the delimited, wrapped RHS
125             // that was passed in originally to `transcribe`.
126             match stack.pop().unwrap() {
127                 // Done with a sequence. Pop from repeats.
128                 Frame::Sequence { .. } => {
129                     repeats.pop();
130                 }
131
132                 // We are done processing a Delimited. If this is the top-level delimited, we are
133                 // done. Otherwise, we unwind the result_stack to append what we have produced to
134                 // any previous results.
135                 Frame::Delimited { forest, span, .. } => {
136                     if result_stack.is_empty() {
137                         // No results left to compute! We are back at the top-level.
138                         return TokenStream::new(result);
139                     }
140
141                     // Step back into the parent Delimited.
142                     let tree =
143                         TokenTree::Delimited(span, forest.delim, TokenStream::new(result).into());
144                     result = result_stack.pop().unwrap();
145                     result.push(tree.into());
146                 }
147             }
148             continue;
149         };
150
151         // At this point, we know we are in the middle of a TokenTree (the last one on `stack`).
152         // `tree` contains the next `TokenTree` to be processed.
153         match tree {
154             // We are descending into a sequence. We first make sure that the matchers in the RHS
155             // and the matches in `interp` have the same shape. Otherwise, either the caller or the
156             // macro writer has made a mistake.
157             seq @ quoted::TokenTree::Sequence(..) => {
158                 match lockstep_iter_size(&seq, interp, &repeats) {
159                     LockstepIterSize::Unconstrained => {
160                         cx.span_fatal(
161                             seq.span(), /* blame macro writer */
162                             "attempted to repeat an expression containing no syntax variables \
163                              matched as repeating at this depth",
164                         );
165                     }
166
167                     LockstepIterSize::Contradiction(ref msg) => {
168                         // FIXME: this really ought to be caught at macro definition time... It
169                         // happens when two meta-variables are used in the same repetition in a
170                         // sequence, but they come from different sequence matchers and repeat
171                         // different amounts.
172                         cx.span_fatal(seq.span(), &msg[..]);
173                     }
174
175                     LockstepIterSize::Constraint(len, _) => {
176                         // We do this to avoid an extra clone above. We know that this is a
177                         // sequence already.
178                         let (sp, seq) = if let quoted::TokenTree::Sequence(sp, seq) = seq {
179                             (sp, seq)
180                         } else {
181                             unreachable!()
182                         };
183
184                         // Is the repetition empty?
185                         if len == 0 {
186                             if seq.op == quoted::KleeneOp::OneOrMore {
187                                 // FIXME: this really ought to be caught at macro definition
188                                 // time... It happens when the Kleene operator in the matcher and
189                                 // the body for the same meta-variable do not match.
190                                 cx.span_fatal(sp.entire(), "this must repeat at least once");
191                             }
192                         } else {
193                             // 0 is the initial counter (we have done 0 repretitions so far). `len`
194                             // is the total number of reptitions we should generate.
195                             repeats.push((0, len));
196
197                             // The first time we encounter the sequence we push it to the stack. It
198                             // then gets reused (see the beginning of the loop) until we are done
199                             // repeating.
200                             stack.push(Frame::Sequence {
201                                 idx: 0,
202                                 sep: seq.separator.clone(),
203                                 forest: seq,
204                             });
205                         }
206                     }
207                 }
208             }
209
210             // Replace the meta-var with the matched token tree from the invocation.
211             quoted::TokenTree::MetaVar(mut sp, ident) => {
212                 // Find the matched nonterminal from the macro invocation, and use it to replace
213                 // the meta-var.
214                 if let Some(cur_matched) = lookup_cur_matched(ident, interp, &repeats) {
215                     if let MatchedNonterminal(ref nt) = *cur_matched {
216                         // FIXME #2887: why do we apply a mark when matching a token tree meta-var
217                         // (e.g. `$x:tt`), but not when we are matching any other type of token
218                         // tree?
219                         if let NtTT(ref tt) = **nt {
220                             result.push(tt.clone().into());
221                         } else {
222                             sp = sp.apply_mark(cx.current_expansion.mark);
223                             let token = TokenTree::token(token::Interpolated(nt.clone()), sp);
224                             result.push(token.into());
225                         }
226                     } else {
227                         // We were unable to descend far enough. This is an error.
228                         cx.span_fatal(
229                             sp, /* blame the macro writer */
230                             &format!("variable '{}' is still repeating at this depth", ident),
231                         );
232                     }
233                 } else {
234                     // If we aren't able to match the meta-var, we push it back into the result but
235                     // with modified syntax context. (I believe this supports nested macros).
236                     let ident =
237                         Ident::new(ident.name, ident.span.apply_mark(cx.current_expansion.mark));
238                     sp = sp.apply_mark(cx.current_expansion.mark);
239                     result.push(TokenTree::token(token::Dollar, sp).into());
240                     result.push(TokenTree::Token(Token::from_ast_ident(ident)).into());
241                 }
242             }
243
244             // If we are entering a new delimiter, we push its contents to the `stack` to be
245             // processed, and we push all of the currently produced results to the `result_stack`.
246             // We will produce all of the results of the inside of the `Delimited` and then we will
247             // jump back out of the Delimited, pop the result_stack and add the new results back to
248             // the previous results (from outside the Delimited).
249             quoted::TokenTree::Delimited(mut span, delimited) => {
250                 span = span.apply_mark(cx.current_expansion.mark);
251                 stack.push(Frame::Delimited { forest: delimited, idx: 0, span: span });
252                 result_stack.push(mem::replace(&mut result, Vec::new()));
253             }
254
255             // Nothing much to do here. Just push the token to the result, being careful to
256             // preserve syntax context.
257             quoted::TokenTree::Token(token) => {
258                 let mut marker = Marker(cx.current_expansion.mark);
259                 let mut tt = TokenTree::Token(token);
260                 noop_visit_tt(&mut tt, &mut marker);
261                 result.push(tt.into());
262             }
263
264             // There should be no meta-var declarations in the invocation of a macro.
265             quoted::TokenTree::MetaVarDecl(..) => panic!("unexpected `TokenTree::MetaVarDecl"),
266         }
267     }
268 }
269
270 /// Lookup the meta-var named `ident` and return the matched token tree from the invocation using
271 /// the set of matches `interpolations`.
272 ///
273 /// See the definition of `repeats` in the `transcribe` function. `repeats` is used to descend
274 /// into the right place in nested matchers. If we attempt to descend too far, the macro writer has
275 /// made a mistake, and we return `None`.
276 fn lookup_cur_matched(
277     ident: Ident,
278     interpolations: &FxHashMap<Ident, Rc<NamedMatch>>,
279     repeats: &[(usize, usize)],
280 ) -> Option<Rc<NamedMatch>> {
281     interpolations.get(&ident).map(|matched| {
282         let mut matched = matched.clone();
283         for &(idx, _) in repeats {
284             let m = matched.clone();
285             match *m {
286                 MatchedNonterminal(_) => break,
287                 MatchedSeq(ref ads, _) => matched = Rc::new(ads[idx].clone()),
288             }
289         }
290
291         matched
292     })
293 }
294
295 /// An accumulator over a TokenTree to be used with `fold`. During transcription, we need to make
296 /// sure that the size of each sequence and all of its nested sequences are the same as the sizes
297 /// of all the matched (nested) sequences in the macro invocation. If they don't match, somebody
298 /// has made a mistake (either the macro writer or caller).
299 #[derive(Clone)]
300 enum LockstepIterSize {
301     /// No constraints on length of matcher. This is true for any TokenTree variants except a
302     /// `MetaVar` with an actual `MatchedSeq` (as opposed to a `MatchedNonterminal`).
303     Unconstrained,
304
305     /// A `MetaVar` with an actual `MatchedSeq`. The length of the match and the name of the
306     /// meta-var are returned.
307     Constraint(usize, Ident),
308
309     /// Two `Constraint`s on the same sequence had different lengths. This is an error.
310     Contradiction(String),
311 }
312
313 impl LockstepIterSize {
314     /// Find incompatibilities in matcher/invocation sizes.
315     /// - `Unconstrained` is compatible with everything.
316     /// - `Contradiction` is incompatible with everything.
317     /// - `Constraint(len)` is only compatible with other constraints of the same length.
318     fn with(self, other: LockstepIterSize) -> LockstepIterSize {
319         match self {
320             LockstepIterSize::Unconstrained => other,
321             LockstepIterSize::Contradiction(_) => self,
322             LockstepIterSize::Constraint(l_len, ref l_id) => match other {
323                 LockstepIterSize::Unconstrained => self,
324                 LockstepIterSize::Contradiction(_) => other,
325                 LockstepIterSize::Constraint(r_len, _) if l_len == r_len => self,
326                 LockstepIterSize::Constraint(r_len, r_id) => {
327                     let msg = format!(
328                         "meta-variable `{}` repeats {} times, but `{}` repeats {} times",
329                         l_id, l_len, r_id, r_len
330                     );
331                     LockstepIterSize::Contradiction(msg)
332                 }
333             },
334         }
335     }
336 }
337
338 /// Given a `tree`, make sure that all sequences have the same length as the matches for the
339 /// appropriate meta-vars in `interpolations`.
340 ///
341 /// Note that if `repeats` does not match the exact correct depth of a meta-var,
342 /// `lookup_cur_matched` will return `None`, which is why this still works even in the presnece of
343 /// multiple nested matcher sequences.
344 fn lockstep_iter_size(
345     tree: &quoted::TokenTree,
346     interpolations: &FxHashMap<Ident, Rc<NamedMatch>>,
347     repeats: &[(usize, usize)],
348 ) -> LockstepIterSize {
349     use quoted::TokenTree;
350     match *tree {
351         TokenTree::Delimited(_, ref delimed) => {
352             delimed.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| {
353                 size.with(lockstep_iter_size(tt, interpolations, repeats))
354             })
355         }
356         TokenTree::Sequence(_, ref seq) => {
357             seq.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| {
358                 size.with(lockstep_iter_size(tt, interpolations, repeats))
359             })
360         }
361         TokenTree::MetaVar(_, name) | TokenTree::MetaVarDecl(_, name, _) => {
362             match lookup_cur_matched(name, interpolations, repeats) {
363                 Some(matched) => match *matched {
364                     MatchedNonterminal(_) => LockstepIterSize::Unconstrained,
365                     MatchedSeq(ref ads, _) => LockstepIterSize::Constraint(ads.len(), name),
366                 },
367                 _ => LockstepIterSize::Unconstrained,
368             }
369         }
370         TokenTree::Token(..) => LockstepIterSize::Unconstrained,
371     }
372 }