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};
10 use smallvec::{smallvec, SmallVec};
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_data_structures::sync::Lrc;
17 /// An iterator over the token trees in a delimited token tree (`{ ... }`) or a sequence (`$(...)`).
19 Delimited { forest: Lrc<quoted::Delimited>, idx: usize, span: DelimSpan },
20 Sequence { forest: Lrc<quoted::SequenceRepetition>, idx: usize, sep: Option<Token> },
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() }
31 impl Iterator for Frame {
32 type Item = quoted::TokenTree;
34 fn next(&mut self) -> Option<quoted::TokenTree> {
36 Frame::Delimited { ref forest, ref mut idx, .. } => {
38 forest.tts.get(*idx - 1).cloned()
40 Frame::Sequence { ref forest, ref mut idx, .. } => {
42 forest.tts.get(*idx - 1).cloned()
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.
56 /// macro_rules! foo {
57 /// ($id:ident) => { println!("{}", stringify!($id)); }
63 /// `interp` would contain `$id => bar` and `src` would contain `println!("{}", stringify!($id));`.
65 /// `transcribe` would return a `TokenStream` containing `println!("{}", stringify!(bar));`.
67 /// Along the way, we do some additional error checking.
70 interp: &FxHashMap<Ident, Rc<NamedMatch>>,
71 src: Vec<quoted::TokenTree>,
73 // Nothing for us to transcribe...
75 return TokenStream::empty();
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)];
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();
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.
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.
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();
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.
107 // The else-case never produces a value for `tree` (it `continue`s or `return`s).
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();
114 if repeat_idx < repeat_len {
116 if let Some(sep) = sep {
117 result.push(TokenTree::Token(sep.clone()).into());
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 { .. } => {
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);
141 // Step back into the parent Delimited.
143 TokenTree::Delimited(span, forest.delim, TokenStream::new(result).into());
144 result = result_stack.pop().unwrap();
145 result.push(tree.into());
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.
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 => {
161 seq.span(), /* blame macro writer */
162 "attempted to repeat an expression containing no syntax variables \
163 matched as repeating at this depth",
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[..]);
175 LockstepIterSize::Constraint(len, _) => {
176 // We do this to avoid an extra clone above. We know that this is a
178 let (sp, seq) = if let quoted::TokenTree::Sequence(sp, seq) = seq {
184 // Is the repetition empty?
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");
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));
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
200 stack.push(Frame::Sequence {
202 sep: seq.separator.clone(),
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
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
219 if let NtTT(ref tt) = **nt {
220 result.push(tt.clone().into());
222 sp = sp.apply_mark(cx.current_expansion.mark);
223 let token = TokenTree::token(token::Interpolated(nt.clone()), sp);
224 result.push(token.into());
227 // We were unable to descend far enough. This is an error.
229 sp, /* blame the macro writer */
230 &format!("variable '{}' is still repeating at this depth", ident),
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).
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());
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()));
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());
264 // There should be no meta-var declarations in the invocation of a macro.
265 quoted::TokenTree::MetaVarDecl(..) => panic!("unexpected `TokenTree::MetaVarDecl"),
270 /// Lookup the meta-var named `ident` and return the matched token tree from the invocation using
271 /// the set of matches `interpolations`.
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(
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();
286 MatchedNonterminal(_) => break,
287 MatchedSeq(ref ads, _) => matched = Rc::new(ads[idx].clone()),
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).
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`).
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),
309 /// Two `Constraint`s on the same sequence had different lengths. This is an error.
310 Contradiction(String),
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 {
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) => {
328 "meta-variable `{}` repeats {} times, but `{}` repeats {} times",
329 l_id, l_len, r_id, r_len
331 LockstepIterSize::Contradiction(msg)
338 /// Given a `tree`, make sure that all sequences have the same length as the matches for the
339 /// appropriate meta-vars in `interpolations`.
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: "ed::TokenTree,
346 interpolations: &FxHashMap<Ident, Rc<NamedMatch>>,
347 repeats: &[(usize, usize)],
348 ) -> LockstepIterSize {
349 use quoted::TokenTree;
351 TokenTree::Delimited(_, ref delimed) => {
352 delimed.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| {
353 size.with(lockstep_iter_size(tt, interpolations, repeats))
356 TokenTree::Sequence(_, ref seq) => {
357 seq.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| {
358 size.with(lockstep_iter_size(tt, interpolations, repeats))
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),
367 _ => LockstepIterSize::Unconstrained,
370 TokenTree::Token(..) => LockstepIterSize::Unconstrained,