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