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