]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/mbe/transcribe.rs
Fix off by one error and add ui test.
[rust.git] / compiler / rustc_expand / src / mbe / transcribe.rs
1 use crate::base::ExtCtxt;
2 use crate::mbe::macro_parser::{MatchedNonterminal, MatchedSeq, MatchedTokenTree, NamedMatch};
3 use crate::mbe::{self, MetaVarExpr};
4 use rustc_ast::mut_visit::{self, MutVisitor};
5 use rustc_ast::token::{self, Delimiter, Token, TokenKind};
6 use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree, TreeAndSpacing};
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_errors::{pluralize, PResult};
9 use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed};
10 use rustc_span::hygiene::{LocalExpnId, Transparency};
11 use rustc_span::symbol::{sym, Ident, MacroRulesNormalizedIdent};
12 use rustc_span::Span;
13
14 use smallvec::{smallvec, SmallVec};
15 use std::mem;
16
17 // A Marker adds the given mark to the syntax context.
18 struct Marker(LocalExpnId, Transparency);
19
20 impl MutVisitor for Marker {
21     const VISIT_TOKENS: bool = true;
22
23     fn visit_span(&mut self, span: &mut Span) {
24         *span = span.apply_mark(self.0.to_expn_id(), self.1)
25     }
26 }
27
28 /// An iterator over the token trees in a delimited token tree (`{ ... }`) or a sequence (`$(...)`).
29 enum Frame<'a> {
30     Delimited { tts: &'a [mbe::TokenTree], idx: usize, delim: Delimiter, span: DelimSpan },
31     Sequence { tts: &'a [mbe::TokenTree], idx: usize, sep: Option<Token> },
32 }
33
34 impl<'a> Frame<'a> {
35     /// Construct a new frame around the delimited set of tokens.
36     fn new(src: &'a mbe::Delimited, span: DelimSpan) -> Frame<'a> {
37         Frame::Delimited { tts: &src.tts, idx: 0, delim: src.delim, span }
38     }
39 }
40
41 impl<'a> Iterator for Frame<'a> {
42     type Item = &'a mbe::TokenTree;
43
44     fn next(&mut self) -> Option<&'a mbe::TokenTree> {
45         match self {
46             Frame::Delimited { tts, ref mut idx, .. }
47             | Frame::Sequence { tts, ref mut idx, .. } => {
48                 let res = tts.get(*idx);
49                 *idx += 1;
50                 res
51             }
52         }
53     }
54 }
55
56 /// This can do Macro-By-Example transcription.
57 /// - `interp` is a map of meta-variables to the tokens (non-terminals) they matched in the
58 ///   invocation. We are assuming we already know there is a match.
59 /// - `src` is the RHS of the MBE, that is, the "example" we are filling in.
60 ///
61 /// For example,
62 ///
63 /// ```rust
64 /// macro_rules! foo {
65 ///     ($id:ident) => { println!("{}", stringify!($id)); }
66 /// }
67 ///
68 /// foo!(bar);
69 /// ```
70 ///
71 /// `interp` would contain `$id => bar` and `src` would contain `println!("{}", stringify!($id));`.
72 ///
73 /// `transcribe` would return a `TokenStream` containing `println!("{}", stringify!(bar));`.
74 ///
75 /// Along the way, we do some additional error checking.
76 pub(super) fn transcribe<'a>(
77     cx: &ExtCtxt<'a>,
78     interp: &FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
79     src: &mbe::Delimited,
80     src_span: DelimSpan,
81     transparency: Transparency,
82 ) -> PResult<'a, TokenStream> {
83     // Nothing for us to transcribe...
84     if src.tts.is_empty() {
85         return Ok(TokenStream::default());
86     }
87
88     // We descend into the RHS (`src`), expanding things as we go. This stack contains the things
89     // we have yet to expand/are still expanding. We start the stack off with the whole RHS.
90     let mut stack: SmallVec<[Frame<'_>; 1]> = smallvec![Frame::new(&src, src_span)];
91
92     // As we descend in the RHS, we will need to be able to match nested sequences of matchers.
93     // `repeats` keeps track of where we are in matching at each level, with the last element being
94     // the most deeply nested sequence. This is used as a stack.
95     let mut repeats = Vec::new();
96
97     // `result` contains resulting token stream from the TokenTree we just finished processing. At
98     // the end, this will contain the full result of transcription, but at arbitrary points during
99     // `transcribe`, `result` will contain subsets of the final result.
100     //
101     // Specifically, as we descend into each TokenTree, we will push the existing results onto the
102     // `result_stack` and clear `results`. We will then produce the results of transcribing the
103     // TokenTree into `results`. Then, as we unwind back out of the `TokenTree`, we will pop the
104     // `result_stack` and append `results` too it to produce the new `results` up to that point.
105     //
106     // Thus, if we try to pop the `result_stack` and it is empty, we have reached the top-level
107     // again, and we are done transcribing.
108     let mut result: Vec<TreeAndSpacing> = Vec::new();
109     let mut result_stack = Vec::new();
110     let mut marker = Marker(cx.current_expansion.id, transparency);
111
112     loop {
113         // Look at the last frame on the stack.
114         // If it still has a TokenTree we have not looked at yet, use that tree.
115         let Some(tree) = stack.last_mut().unwrap().next() else {
116             // This else-case never produces a value for `tree` (it `continue`s or `return`s).
117
118             // Otherwise, if we have just reached the end of a sequence and we can keep repeating,
119             // go back to the beginning of the sequence.
120             if let Frame::Sequence { idx, sep, .. } = stack.last_mut().unwrap() {
121                 let (repeat_idx, repeat_len) = repeats.last_mut().unwrap();
122                 *repeat_idx += 1;
123                 if repeat_idx < repeat_len {
124                     *idx = 0;
125                     if let Some(sep) = sep {
126                         result.push(TokenTree::Token(sep.clone()).into());
127                     }
128                     continue;
129                 }
130             }
131
132             // We are done with the top of the stack. Pop it. Depending on what it was, we do
133             // different things. Note that the outermost item must be the delimited, wrapped RHS
134             // that was passed in originally to `transcribe`.
135             match stack.pop().unwrap() {
136                 // Done with a sequence. Pop from repeats.
137                 Frame::Sequence { .. } => {
138                     repeats.pop();
139                 }
140
141                 // We are done processing a Delimited. If this is the top-level delimited, we are
142                 // done. Otherwise, we unwind the result_stack to append what we have produced to
143                 // any previous results.
144                 Frame::Delimited { delim, span, .. } => {
145                     if result_stack.is_empty() {
146                         // No results left to compute! We are back at the top-level.
147                         return Ok(TokenStream::new(result));
148                     }
149
150                     // Step back into the parent Delimited.
151                     let tree = TokenTree::Delimited(span, delim, TokenStream::new(result));
152                     result = result_stack.pop().unwrap();
153                     result.push(tree.into());
154                 }
155             }
156             continue;
157         };
158
159         // At this point, we know we are in the middle of a TokenTree (the last one on `stack`).
160         // `tree` contains the next `TokenTree` to be processed.
161         match tree {
162             // We are descending into a sequence. We first make sure that the matchers in the RHS
163             // and the matches in `interp` have the same shape. Otherwise, either the caller or the
164             // macro writer has made a mistake.
165             seq @ mbe::TokenTree::Sequence(_, delimited) => {
166                 match lockstep_iter_size(&seq, interp, &repeats) {
167                     LockstepIterSize::Unconstrained => {
168                         return Err(cx.struct_span_err(
169                             seq.span(), /* blame macro writer */
170                             "attempted to repeat an expression containing no syntax variables \
171                              matched as repeating at this depth",
172                         ));
173                     }
174
175                     LockstepIterSize::Contradiction(msg) => {
176                         // FIXME: this really ought to be caught at macro definition time... It
177                         // happens when two meta-variables are used in the same repetition in a
178                         // sequence, but they come from different sequence matchers and repeat
179                         // different amounts.
180                         return Err(cx.struct_span_err(seq.span(), &msg));
181                     }
182
183                     LockstepIterSize::Constraint(len, _) => {
184                         // We do this to avoid an extra clone above. We know that this is a
185                         // sequence already.
186                         let mbe::TokenTree::Sequence(sp, seq) = seq else {
187                             unreachable!()
188                         };
189
190                         // Is the repetition empty?
191                         if len == 0 {
192                             if seq.kleene.op == mbe::KleeneOp::OneOrMore {
193                                 // FIXME: this really ought to be caught at macro definition
194                                 // time... It happens when the Kleene operator in the matcher and
195                                 // the body for the same meta-variable do not match.
196                                 return Err(cx.struct_span_err(
197                                     sp.entire(),
198                                     "this must repeat at least once",
199                                 ));
200                             }
201                         } else {
202                             // 0 is the initial counter (we have done 0 repetitions so far). `len`
203                             // is the total number of repetitions we should generate.
204                             repeats.push((0, len));
205
206                             // The first time we encounter the sequence we push it to the stack. It
207                             // then gets reused (see the beginning of the loop) until we are done
208                             // repeating.
209                             stack.push(Frame::Sequence {
210                                 idx: 0,
211                                 sep: seq.separator.clone(),
212                                 tts: &delimited.tts,
213                             });
214                         }
215                     }
216                 }
217             }
218
219             // Replace the meta-var with the matched token tree from the invocation.
220             mbe::TokenTree::MetaVar(mut sp, mut original_ident) => {
221                 // Find the matched nonterminal from the macro invocation, and use it to replace
222                 // the meta-var.
223                 let ident = MacroRulesNormalizedIdent::new(original_ident);
224                 if let Some(cur_matched) = lookup_cur_matched(ident, interp, &repeats) {
225                     match cur_matched {
226                         MatchedTokenTree(ref tt) => {
227                             // `tt`s are emitted into the output stream directly as "raw tokens",
228                             // without wrapping them into groups.
229                             let token = tt.clone();
230                             result.push(token.into());
231                         }
232                         MatchedNonterminal(ref nt) => {
233                             // Other variables are emitted into the output stream as groups with
234                             // `Delimiter::Invisible` to maintain parsing priorities.
235                             // `Interpolated` is currently used for such groups in rustc parser.
236                             marker.visit_span(&mut sp);
237                             let token = TokenTree::token(token::Interpolated(nt.clone()), sp);
238                             result.push(token.into());
239                         }
240                         MatchedSeq(..) => {
241                             // We were unable to descend far enough. This is an error.
242                             return Err(cx.struct_span_err(
243                                 sp, /* blame the macro writer */
244                                 &format!("variable '{}' is still repeating at this depth", ident),
245                             ));
246                         }
247                     }
248                 } else {
249                     // If we aren't able to match the meta-var, we push it back into the result but
250                     // with modified syntax context. (I believe this supports nested macros).
251                     marker.visit_span(&mut sp);
252                     marker.visit_ident(&mut original_ident);
253                     result.push(TokenTree::token(token::Dollar, sp).into());
254                     result.push(TokenTree::Token(Token::from_ast_ident(original_ident)).into());
255                 }
256             }
257
258             // Replace meta-variable expressions with the result of their expansion.
259             mbe::TokenTree::MetaVarExpr(sp, expr) => {
260                 transcribe_metavar_expr(cx, expr, interp, &mut marker, &repeats, &mut result, &sp)?;
261             }
262
263             // If we are entering a new delimiter, we push its contents to the `stack` to be
264             // processed, and we push all of the currently produced results to the `result_stack`.
265             // We will produce all of the results of the inside of the `Delimited` and then we will
266             // jump back out of the Delimited, pop the result_stack and add the new results back to
267             // the previous results (from outside the Delimited).
268             mbe::TokenTree::Delimited(mut span, delimited) => {
269                 mut_visit::visit_delim_span(&mut span, &mut marker);
270                 stack.push(Frame::Delimited {
271                     tts: &delimited.tts,
272                     delim: delimited.delim,
273                     idx: 0,
274                     span,
275                 });
276                 result_stack.push(mem::take(&mut result));
277             }
278
279             // Nothing much to do here. Just push the token to the result, being careful to
280             // preserve syntax context.
281             mbe::TokenTree::Token(token) => {
282                 let mut token = token.clone();
283                 mut_visit::visit_token(&mut token, &mut marker);
284                 let tt = TokenTree::Token(token);
285                 result.push(tt.into());
286             }
287
288             // There should be no meta-var declarations in the invocation of a macro.
289             mbe::TokenTree::MetaVarDecl(..) => panic!("unexpected `TokenTree::MetaVarDecl"),
290         }
291     }
292 }
293
294 /// Lookup the meta-var named `ident` and return the matched token tree from the invocation using
295 /// the set of matches `interpolations`.
296 ///
297 /// See the definition of `repeats` in the `transcribe` function. `repeats` is used to descend
298 /// into the right place in nested matchers. If we attempt to descend too far, the macro writer has
299 /// made a mistake, and we return `None`.
300 fn lookup_cur_matched<'a>(
301     ident: MacroRulesNormalizedIdent,
302     interpolations: &'a FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
303     repeats: &[(usize, usize)],
304 ) -> Option<&'a NamedMatch> {
305     interpolations.get(&ident).map(|matched| {
306         let mut matched = matched;
307         for &(idx, _) in repeats {
308             match matched {
309                 MatchedTokenTree(_) | MatchedNonterminal(_) => break,
310                 MatchedSeq(ref ads) => matched = ads.get(idx).unwrap(),
311             }
312         }
313
314         matched
315     })
316 }
317
318 /// An accumulator over a TokenTree to be used with `fold`. During transcription, we need to make
319 /// sure that the size of each sequence and all of its nested sequences are the same as the sizes
320 /// of all the matched (nested) sequences in the macro invocation. If they don't match, somebody
321 /// has made a mistake (either the macro writer or caller).
322 #[derive(Clone)]
323 enum LockstepIterSize {
324     /// No constraints on length of matcher. This is true for any TokenTree variants except a
325     /// `MetaVar` with an actual `MatchedSeq` (as opposed to a `MatchedNonterminal`).
326     Unconstrained,
327
328     /// A `MetaVar` with an actual `MatchedSeq`. The length of the match and the name of the
329     /// meta-var are returned.
330     Constraint(usize, MacroRulesNormalizedIdent),
331
332     /// Two `Constraint`s on the same sequence had different lengths. This is an error.
333     Contradiction(String),
334 }
335
336 impl LockstepIterSize {
337     /// Find incompatibilities in matcher/invocation sizes.
338     /// - `Unconstrained` is compatible with everything.
339     /// - `Contradiction` is incompatible with everything.
340     /// - `Constraint(len)` is only compatible with other constraints of the same length.
341     fn with(self, other: LockstepIterSize) -> LockstepIterSize {
342         match self {
343             LockstepIterSize::Unconstrained => other,
344             LockstepIterSize::Contradiction(_) => self,
345             LockstepIterSize::Constraint(l_len, ref l_id) => match other {
346                 LockstepIterSize::Unconstrained => self,
347                 LockstepIterSize::Contradiction(_) => other,
348                 LockstepIterSize::Constraint(r_len, _) if l_len == r_len => self,
349                 LockstepIterSize::Constraint(r_len, r_id) => {
350                     let msg = format!(
351                         "meta-variable `{}` repeats {} time{}, but `{}` repeats {} time{}",
352                         l_id,
353                         l_len,
354                         pluralize!(l_len),
355                         r_id,
356                         r_len,
357                         pluralize!(r_len),
358                     );
359                     LockstepIterSize::Contradiction(msg)
360                 }
361             },
362         }
363     }
364 }
365
366 /// Given a `tree`, make sure that all sequences have the same length as the matches for the
367 /// appropriate meta-vars in `interpolations`.
368 ///
369 /// Note that if `repeats` does not match the exact correct depth of a meta-var,
370 /// `lookup_cur_matched` will return `None`, which is why this still works even in the presence of
371 /// multiple nested matcher sequences.
372 ///
373 /// Example: `$($($x $y)+*);+` -- we need to make sure that `x` and `y` repeat the same amount as
374 /// each other at the given depth when the macro was invoked. If they don't it might mean they were
375 /// declared at unequal depths or there was a compile bug. For example, if we have 3 repetitions of
376 /// the outer sequence and 4 repetitions of the inner sequence for `x`, we should have the same for
377 /// `y`; otherwise, we can't transcribe them both at the given depth.
378 fn lockstep_iter_size(
379     tree: &mbe::TokenTree,
380     interpolations: &FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
381     repeats: &[(usize, usize)],
382 ) -> LockstepIterSize {
383     use mbe::TokenTree;
384     match *tree {
385         TokenTree::Delimited(_, ref delimited) => {
386             delimited.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| {
387                 size.with(lockstep_iter_size(tt, interpolations, repeats))
388             })
389         }
390         TokenTree::Sequence(_, ref seq) => {
391             seq.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| {
392                 size.with(lockstep_iter_size(tt, interpolations, repeats))
393             })
394         }
395         TokenTree::MetaVar(_, name) | TokenTree::MetaVarDecl(_, name, _) => {
396             let name = MacroRulesNormalizedIdent::new(name);
397             match lookup_cur_matched(name, interpolations, repeats) {
398                 Some(matched) => match matched {
399                     MatchedTokenTree(_) | MatchedNonterminal(_) => LockstepIterSize::Unconstrained,
400                     MatchedSeq(ref ads) => LockstepIterSize::Constraint(ads.len(), name),
401                 },
402                 _ => LockstepIterSize::Unconstrained,
403             }
404         }
405         TokenTree::MetaVarExpr(_, ref expr) => {
406             let default_rslt = LockstepIterSize::Unconstrained;
407             let Some(ident) = expr.ident() else { return default_rslt; };
408             let name = MacroRulesNormalizedIdent::new(ident);
409             match lookup_cur_matched(name, interpolations, repeats) {
410                 Some(MatchedSeq(ref ads)) => {
411                     default_rslt.with(LockstepIterSize::Constraint(ads.len(), name))
412                 }
413                 _ => default_rslt,
414             }
415         }
416         TokenTree::Token(..) => LockstepIterSize::Unconstrained,
417     }
418 }
419
420 /// Used solely by the `count` meta-variable expression, counts the outer-most repetitions at a
421 /// given optional nested depth.
422 ///
423 /// For example, a macro parameter of `$( { $( $foo:ident ),* } )*` called with `{ a, b } { c }`:
424 ///
425 /// * `[ $( ${count(foo)} ),* ]` will return [2, 1] with a, b = 2 and c = 1
426 /// * `[ $( ${count(foo, 0)} ),* ]` will be the same as `[ $( ${count(foo)} ),* ]`
427 /// * `[ $( ${count(foo, 1)} ),* ]` will return an error because `${count(foo, 1)}` is
428 ///   declared inside a single repetition and the index `1` implies two nested repetitions.
429 fn count_repetitions<'a>(
430     cx: &ExtCtxt<'a>,
431     depth_opt: Option<usize>,
432     mut matched: &NamedMatch,
433     repeats: &[(usize, usize)],
434     sp: &DelimSpan,
435 ) -> PResult<'a, usize> {
436     // Recursively count the number of matches in `matched` at given depth
437     // (or at the top-level of `matched` if no depth is given).
438     fn count<'a>(
439         cx: &ExtCtxt<'a>,
440         declared_lhs_depth: usize,
441         depth_opt: Option<usize>,
442         matched: &NamedMatch,
443         sp: &DelimSpan,
444     ) -> PResult<'a, usize> {
445         match matched {
446             MatchedTokenTree(_) | MatchedNonterminal(_) => {
447                 if declared_lhs_depth == 0 {
448                     return Err(cx.struct_span_err(
449                         sp.entire(),
450                         "`count` can not be placed inside the inner-most repetition",
451                     ));
452                 }
453                 match depth_opt {
454                     None => Ok(1),
455                     Some(_) => Err(out_of_bounds_err(cx, declared_lhs_depth, sp.entire(), "count")),
456                 }
457             }
458             MatchedSeq(ref named_matches) => {
459                 let new_declared_lhs_depth = declared_lhs_depth + 1;
460                 match depth_opt {
461                     None => named_matches
462                         .iter()
463                         .map(|elem| count(cx, new_declared_lhs_depth, None, elem, sp))
464                         .sum(),
465                     Some(0) => Ok(named_matches.len()),
466                     Some(depth) => named_matches
467                         .iter()
468                         .map(|elem| count(cx, new_declared_lhs_depth, Some(depth - 1), elem, sp))
469                         .sum(),
470                 }
471             }
472         }
473     }
474     // `repeats` records all of the nested levels at which we are currently
475     // matching meta-variables. The meta-var-expr `count($x)` only counts
476     // matches that occur in this "subtree" of the `NamedMatch` where we
477     // are currently transcribing, so we need to descend to that subtree
478     // before we start counting. `matched` contains the various levels of the
479     // tree as we descend, and its final value is the subtree we are currently at.
480     for &(idx, _) in repeats {
481         if let MatchedSeq(ref ads) = matched {
482             matched = &ads[idx];
483         }
484     }
485     count(cx, 0, depth_opt, matched, sp)
486 }
487
488 /// Returns a `NamedMatch` item declared on the LHS given an arbitrary [Ident]
489 fn matched_from_ident<'ctx, 'interp, 'rslt>(
490     cx: &ExtCtxt<'ctx>,
491     ident: Ident,
492     interp: &'interp FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
493 ) -> PResult<'ctx, &'rslt NamedMatch>
494 where
495     'interp: 'rslt,
496 {
497     let span = ident.span;
498     let key = MacroRulesNormalizedIdent::new(ident);
499     interp.get(&key).ok_or_else(|| {
500         cx.struct_span_err(
501             span,
502             &format!("variable `{}` is not recognized in meta-variable expression", key),
503         )
504     })
505 }
506
507 /// Used by meta-variable expressions when an user input is out of the actual declared bounds. For
508 /// example, index(999999) in an repetition of only three elements.
509 fn out_of_bounds_err<'a>(
510     cx: &ExtCtxt<'a>,
511     max: usize,
512     span: Span,
513     ty: &str,
514 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
515     cx.struct_span_err(span, &format!("{ty} depth must be less than {max}"))
516 }
517
518 fn transcribe_metavar_expr<'a>(
519     cx: &ExtCtxt<'a>,
520     expr: &MetaVarExpr,
521     interp: &FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
522     marker: &mut Marker,
523     repeats: &[(usize, usize)],
524     result: &mut Vec<TreeAndSpacing>,
525     sp: &DelimSpan,
526 ) -> PResult<'a, ()> {
527     let mut visited_span = || {
528         let mut span = sp.entire();
529         marker.visit_span(&mut span);
530         span
531     };
532     match *expr {
533         MetaVarExpr::Count(original_ident, depth_opt) => {
534             let matched = matched_from_ident(cx, original_ident, interp)?;
535             let count = count_repetitions(cx, depth_opt, matched, &repeats, sp)?;
536             let tt = TokenTree::token(
537                 TokenKind::lit(token::Integer, sym::integer(count), None),
538                 visited_span(),
539             );
540             result.push(tt.into());
541         }
542         MetaVarExpr::Ignore(original_ident) => {
543             // Used to ensure that `original_ident` is present in the LHS
544             let _ = matched_from_ident(cx, original_ident, interp)?;
545         }
546         MetaVarExpr::Index(depth) => match repeats.iter().nth_back(depth) {
547             Some((index, _)) => {
548                 result.push(
549                     TokenTree::token(
550                         TokenKind::lit(token::Integer, sym::integer(*index), None),
551                         visited_span(),
552                     )
553                     .into(),
554                 );
555             }
556             None => return Err(out_of_bounds_err(cx, repeats.len(), sp.entire(), "index")),
557         },
558         MetaVarExpr::Length(depth) => match repeats.iter().nth_back(depth) {
559             Some((_, length)) => {
560                 result.push(
561                     TokenTree::token(
562                         TokenKind::lit(token::Integer, sym::integer(*length), None),
563                         visited_span(),
564                     )
565                     .into(),
566                 );
567             }
568             None => return Err(out_of_bounds_err(cx, repeats.len(), sp.entire(), "length")),
569         },
570     }
571     Ok(())
572 }