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