One sometimes needs to know the current index and/or the length of a repetition. There are clever but cludgy ways to achieve this, which make a macro even less readable.
It would be very useful and much easier for the macro engine to provide these values. I would suggest $.var
for the index (at which point of the repetition are we) and $#var
for the length (what number of elements are there.) These syntaxes are currently not possible, hence backwards compatible.
This should also work for nested repetitions, as shown in this example, which has an outer repeat of paren lists and an inner one of all but the 1st literal in each:
macro_rules! x {
($(($a:literal $($b:literal)+))+) => {
$($(println!("{} ({}/{}) -- {} ({}/{})", $a, $.a, $#a, $b, $.b, $#b);)+)+
// .. ## .. ## --- --- --- ---
}
}
x!((27 4 5 6)
(49 7 8 9 0));
27 (0/2) -- 4 (0/3)
27 (0/2) -- 5 (1/3)
27 (0/2) -- 6 (2/3)
49 (1/2) -- 7 (0/4)
49 (1/2) -- 8 (1/4)
49 (1/2) -- 9 (2/4)
49 (1/2) -- 0 (3/4)
See RFC 3086 and its tracking issue:
opened 07:50PM - 26 Mar 21 UTC
B-RFC-approved
T-lang
C-tracking-issue
F-macro-metavar-expr
S-tracking-design-concerns
This is a tracking issue for the RFC "3086" (rust-lang/rfcs#3086).
The feature … gate for the issue is `#![feature(macro_metavar_expr)]`.
### About tracking issues
Tracking issues are used to record the overall progress of implementation.
They are also used as hubs connecting to other relevant issues, e.g., bugs or open design questions.
A tracking issue is however *not* meant for large scale discussion, questions, or bug reports about a feature.
Instead, open a dedicated issue for the specific matter and add the relevant feature gate label.
### Steps
- [ ] Implement the RFC (cc @markbt -- has there been work done here already?)
- [ ] Adjust documentation ([see instructions on rustc-dev-guide][doc-guide])
- [ ] Stabilization PR ([see instructions on rustc-dev-guide][stabilization-guide])
[stabilization-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#stabilization-pr
[doc-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#documentation-prs
### Unresolved questions and bugs
- [ ] [Figure out problems around hygiene](https://github.com/rust-lang/rust/issues/83527#issuecomment-1073506711)
### Implementation history
<!--
Include a list of all the PRs that were involved in implementing the feature.
-->
5 Likes
More concretely, here's how your macro could look: playground
macro_rules! x {
($(($a:literal $($b:literal)+))+) => {
$($(println!("{} ({}/{}) -- {} ({}/{})",
$a, ${index(1)}, ${length(1)}, $b, ${index()}, ${length()});)+)+
}
}
Thanks for pointing it out! The tracking issue is beyond bewildering, especially as it seems to be changing over time.
This example you give here, however is clear and something I can grok.
system
Closed
April 17, 2024, 10:47pm
5
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.