Skip to content

Commit 9c60af0

Browse files
Rollup merge of #160570 - mejrs:concat_str, r=petrochenkov
macro_metavar_expr_concat: support concatenating into string literals Usually if you want to concatenate string literals in macros you expand into some combination of concat! and stringify! invocations. However this does not work in nested MetaItems, since those are never expanded (unlike `#[path = EXPR]` attributes like `#[doc = include_str!("README.md")]`. This PR adds support for that using `${concat_str(...)}`, similar to `${concat(...)}`. It is unstable under the same `macro_metavar_expr_concat` feature. See the tests in this PR for examples. My motivation for adding this is that I've seen (and had myself) some cases where this would have been really useful. Thus I'd like to add this experimentally.
2 parents 1b7b9ea + 6c0f3aa commit 9c60af0

11 files changed

Lines changed: 228 additions & 32 deletions

File tree

‎compiler/rustc_expand/src/mbe/metavar_expr.rs‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,11 @@ pub(crate) const UNSUPPORTED_CONCAT_ELEM_ERR: &str = "expected identifier or str
1515
/// A meta-variable expression, for expansions based on properties of meta-variables.
1616
#[derive(Debug, PartialEq, Encodable, Decodable)]
1717
pub(crate) enum MetaVarExpr {
18-
/// Unification of two or more identifiers.
19-
Concat(Box<[MetaVarExprConcatElem]>),
18+
/// Unification of two or more identifiers/literals/metavariables into an identifier.
19+
ConcatIdent(Box<[MetaVarExprConcatElem]>),
20+
21+
/// Unification of two or more identifiers/literals/metavariables into a string literal.
22+
ConcatStr(Box<[MetaVarExprConcatElem]>),
2023

2124
/// The number of repetitions of an identifier.
2225
Count(Ident, usize),
@@ -73,7 +76,12 @@ impl MetaVarExpr {
7376

7477
let mut iter = args.iter();
7578
let rslt = match ident.name {
76-
sym::concat => parse_concat(&mut iter, psess, outer_span, ident.span)?,
79+
sym::concat => {
80+
MetaVarExpr::ConcatIdent(parse_concat(&mut iter, psess, outer_span, ident.span)?)
81+
}
82+
sym::concat_str => {
83+
MetaVarExpr::ConcatStr(parse_concat(&mut iter, psess, outer_span, ident.span)?)
84+
}
7785
sym::count => parse_count(&mut iter, psess, ident.span)?,
7886
sym::ignore => {
7987
eat_dollar(&mut iter, psess, ident.span)?;
@@ -95,7 +103,7 @@ impl MetaVarExpr {
95103

96104
pub(crate) fn for_each_metavar<A>(&self, mut aux: A, mut cb: impl FnMut(A, &Ident) -> A) -> A {
97105
match self {
98-
MetaVarExpr::Concat(elems) => {
106+
MetaVarExpr::ConcatIdent(elems) | MetaVarExpr::ConcatStr(elems) => {
99107
for elem in elems {
100108
if let MetaVarExprConcatElem::Var(ident) = elem {
101109
aux = cb(aux, ident)
@@ -175,7 +183,7 @@ fn parse_concat<'psess>(
175183
psess: &'psess ParseSess,
176184
outer_span: Span,
177185
expr_ident_span: Span,
178-
) -> PResult<'psess, MetaVarExpr> {
186+
) -> PResult<'psess, Box<[MetaVarExprConcatElem]>> {
179187
let mut result = Vec::new();
180188
loop {
181189
let is_var = try_eat_dollar(iter);
@@ -210,7 +218,7 @@ fn parse_concat<'psess>(
210218
.dcx()
211219
.struct_span_err(expr_ident_span, "`concat` must have at least two elements"));
212220
}
213-
Ok(MetaVarExpr::Concat(result.into()))
221+
Ok(result.into())
214222
}
215223

216224
/// Parse a meta-variable `count` expression: `count(ident[, depth])`

‎compiler/rustc_expand/src/mbe/quoted.rs‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_feature::Features;
77
use rustc_session::Session;
88
use rustc_session::diagnostics::feature_err;
99
use rustc_span::edition::Edition;
10-
use rustc_span::{Ident, Span, kw, sym};
10+
use rustc_span::{Ident, Span, Symbol, kw, sym};
1111

1212
use crate::diagnostics;
1313
use crate::mbe::macro_parser::count_metavar_decls;
@@ -204,9 +204,14 @@ fn maybe_emit_macro_metavar_expr_feature(features: &Features, sess: &Session, sp
204204
}
205205
}
206206

207-
fn maybe_emit_macro_metavar_expr_concat_feature(features: &Features, sess: &Session, span: Span) {
207+
fn maybe_emit_macro_metavar_expr_concat_feature(
208+
features: &Features,
209+
sess: &Session,
210+
span: Span,
211+
what: Symbol,
212+
) {
208213
if !features.macro_metavar_expr_concat() {
209-
let msg = "the `concat` meta-variable expression is unstable";
214+
let msg = format!("the `{what}` meta-variable expression is unstable");
210215
feature_err(sess, sym::macro_metavar_expr_concat, span, msg).emit();
211216
}
212217
}
@@ -278,11 +283,19 @@ fn parse_tree<'a>(
278283
return TokenTree::token(token::Dollar, dollar_span);
279284
}
280285
Ok(elem) => {
281-
if let MetaVarExpr::Concat(_) = elem {
286+
if matches!(elem, MetaVarExpr::ConcatIdent(_)) {
287+
maybe_emit_macro_metavar_expr_concat_feature(
288+
features,
289+
sess,
290+
delim_span.entire(),
291+
sym::concat,
292+
);
293+
} else if matches!(elem, MetaVarExpr::ConcatStr(_)) {
282294
maybe_emit_macro_metavar_expr_concat_feature(
283295
features,
284296
sess,
285297
delim_span.entire(),
298+
sym::concat_str,
286299
);
287300
} else {
288301
maybe_emit_macro_metavar_expr_feature(

‎compiler/rustc_expand/src/mbe/transcribe.rs‎

Lines changed: 45 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,8 @@ fn transcribe_metavar_expr<'tx>(
597597
) -> PResult<'tx, ()> {
598598
let dcx = tscx.psess.dcx();
599599
let tt = match *expr {
600-
MetaVarExpr::Concat(ref elements) => metavar_expr_concat(tscx, dspan, elements)?,
600+
MetaVarExpr::ConcatIdent(ref elements) => metavar_expr_concat_ident(tscx, dspan, elements)?,
601+
MetaVarExpr::ConcatStr(ref elements) => metavar_expr_concat_str(tscx, dspan, elements)?,
601602
MetaVarExpr::Count(original_ident, depth) => {
602603
let matched = matched_from_ident(dcx, original_ident, tscx.interp)?;
603604
let count = count_repetitions(dcx, depth, matched, &tscx.repeats, &dspan)?;
@@ -635,11 +636,52 @@ fn transcribe_metavar_expr<'tx>(
635636
}
636637

637638
/// Handle the `${concat(...)}` metavariable expression.
638-
fn metavar_expr_concat<'tx>(
639+
fn metavar_expr_concat_ident<'tx>(
640+
tscx: &mut TranscrCtx<'tx, '_>,
641+
dspan: DelimSpan,
642+
elements: &[MetaVarExprConcatElem],
643+
) -> PResult<'tx, TokenTree> {
644+
let (symbol, concatenated_span) = metavar_expr_concat(tscx, dspan, elements)?;
645+
if !rustc_lexer::is_ident(symbol.as_str()) {
646+
return Err(tscx.psess.dcx().create_err(ConcatInvalidIdent {
647+
span: concatenated_span,
648+
reason: InvalidIdentReason::new(symbol),
649+
}));
650+
}
651+
tscx.psess.symbol_gallery.insert(symbol, concatenated_span);
652+
653+
// The current implementation marks the span as coming from the macro regardless of
654+
// contexts of the concatenated identifiers but this behavior may change in the
655+
// future.
656+
Ok(TokenTree::Token(
657+
Token::from_ast_ident(Ident::new(symbol, concatenated_span)),
658+
Spacing::Alone,
659+
))
660+
}
661+
662+
/// Handle the `${concat_str(...)}` metavariable expression.
663+
fn metavar_expr_concat_str<'tx>(
639664
tscx: &mut TranscrCtx<'tx, '_>,
640665
dspan: DelimSpan,
641666
elements: &[MetaVarExprConcatElem],
642667
) -> PResult<'tx, TokenTree> {
668+
let (symbol, concatenated_span) = metavar_expr_concat(tscx, dspan, elements)?;
669+
670+
// The current implementation marks the span as coming from the macro regardless of
671+
// contexts of the concatenated identifiers but this behavior may change in the
672+
// future.
673+
Ok(TokenTree::Token(
674+
Token::new(TokenKind::lit(LitKind::Str, symbol, None), concatenated_span),
675+
Spacing::Alone,
676+
))
677+
}
678+
679+
/// Shared logic for concat/concat_str metavariable expressions
680+
fn metavar_expr_concat<'tx>(
681+
tscx: &mut TranscrCtx<'tx, '_>,
682+
dspan: DelimSpan,
683+
elements: &[MetaVarExprConcatElem],
684+
) -> PResult<'tx, (Symbol, Span)> {
643685
let dcx = tscx.psess.dcx();
644686
let mut concatenated = String::new();
645687
for element in elements {
@@ -668,21 +710,7 @@ fn metavar_expr_concat<'tx>(
668710
}
669711
let symbol = nfc_normalize(&concatenated);
670712
let concatenated_span = tscx.visited_dspan(dspan);
671-
if !rustc_lexer::is_ident(symbol.as_str()) {
672-
return Err(dcx.create_err(ConcatInvalidIdent {
673-
span: concatenated_span,
674-
reason: InvalidIdentReason::new(symbol),
675-
}));
676-
}
677-
tscx.psess.symbol_gallery.insert(symbol, concatenated_span);
678-
679-
// The current implementation marks the span as coming from the macro regardless of
680-
// contexts of the concatenated identifiers but this behavior may change in the
681-
// future.
682-
Ok(TokenTree::Token(
683-
Token::from_ast_ident(Ident::new(symbol, concatenated_span)),
684-
Spacing::Alone,
685-
))
713+
Ok((symbol, concatenated_span))
686714
}
687715

688716
/// Store the metavariable span for this original span into a side table.

‎compiler/rustc_span/src/symbol.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,7 @@ symbols! {
680680
complex,
681681
concat,
682682
concat_bytes,
683+
concat_str,
683684
conservative_impl_trait,
684685
console,
685686
const_allocate,

‎tests/ui/feature-gates/feature-gate-macro-metavar-expr-concat.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
macro_rules! join {
22
($lhs:ident, $rhs:ident) => {
3-
let ${concat($lhs, $rhs)}: () = ();
3+
let ${concat($lhs, $rhs)}: &'static str = ${concat_str($lhs, $rhs)};
44
//~^ ERROR the `concat` meta-variable expression is unstable
5+
//~| ERROR the `concat_str` meta-variable expression is unstable
56
};
67
}
78

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
11
error[E0658]: the `concat` meta-variable expression is unstable
22
--> $DIR/feature-gate-macro-metavar-expr-concat.rs:3:14
33
|
4-
LL | let ${concat($lhs, $rhs)}: () = ();
4+
LL | let ${concat($lhs, $rhs)}: &'static str = ${concat_str($lhs, $rhs)};
55
| ^^^^^^^^^^^^^^^^^^^^
66
|
77
= note: see issue #124225 <https://github.com/rust-lang/rust/issues/124225> for more information
88
= help: add `#![feature(macro_metavar_expr_concat)]` to the crate attributes to enable
99
= note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
1010

11-
error: aborting due to 1 previous error
11+
error[E0658]: the `concat_str` meta-variable expression is unstable
12+
--> $DIR/feature-gate-macro-metavar-expr-concat.rs:3:52
13+
|
14+
LL | let ${concat($lhs, $rhs)}: &'static str = ${concat_str($lhs, $rhs)};
15+
| ^^^^^^^^^^^^^^^^^^^^^^^^
16+
|
17+
= note: see issue #124225 <https://github.com/rust-lang/rust/issues/124225> for more information
18+
= help: add `#![feature(macro_metavar_expr_concat)]` to the crate attributes to enable
19+
= note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
20+
21+
error: aborting due to 2 previous errors
1222

1323
For more information about this error, try `rustc --explain E0658`.

‎tests/ui/macros/metavar-expressions/concat-allowed-operations.rs‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
macro_rules! create_things {
77
($lhs:ident) => {
8-
struct ${concat($lhs, _separated_idents_in_a_struct)} {
8+
struct ${concat($lhs, _separated_idents_in_a_struct)} {
99
foo: i32,
1010
${concat($lhs, _separated_idents_in_a_field)}: i32,
1111
}
@@ -20,80 +20,127 @@ macro_rules! create_things {
2020

2121
macro_rules! many_idents {
2222
($a:ident, $c:ident) => {
23+
#[allow(dead_code, reason = ${concat_str($a, B, $c, D)})]
2324
const ${concat($a, B, $c, D)}: i32 = 1;
2425
};
2526
}
2627

2728
macro_rules! valid_tts {
2829
($_0:tt, $_1:tt) => {
30+
#[allow(dead_code, reason = ${concat_str($_0, $_1)})]
2931
const ${concat($_0, $_1)}: i32 = 1;
3032
}
3133
}
3234

3335
macro_rules! without_dollar_sign_is_an_ident {
3436
($ident:ident) => {
37+
#[allow(dead_code, reason = ${concat_str(VAR, ident)})]
3538
const ${concat(VAR, ident)}: i32 = 1;
39+
#[allow(dead_code, reason = ${concat_str(VAR, $ident)})]
3640
const ${concat(VAR, $ident)}: i32 = 2;
3741
};
3842
}
3943

4044
macro_rules! combinations {
4145
($ident:ident, $literal:literal, $tt_ident:tt, $tt_literal:tt) => {{
4246
// tt ident
47+
#[allow(dead_code, reason = ${concat_str($tt_ident, b)})]
4348
let ${concat($tt_ident, b)} = ();
49+
#[allow(dead_code, reason = ${concat_str($tt_ident, _b)})]
4450
let ${concat($tt_ident, _b)} = ();
51+
#[allow(dead_code, reason = ${concat_str($tt_ident, "b")})]
4552
let ${concat($tt_ident, "b")} = ();
53+
#[allow(dead_code, reason = ${concat_str($tt_ident, $tt_ident)})]
4654
let ${concat($tt_ident, $tt_ident)} = ();
55+
#[allow(dead_code, reason = ${concat_str($tt_ident, $tt_literal)})]
4756
let ${concat($tt_ident, $tt_literal)} = ();
57+
#[allow(dead_code, reason = ${concat_str($tt_ident, $ident)})]
58+
let ${concat($tt_ident, $ident)} = ();
59+
#[allow(dead_code, reason = ${concat_str($tt_ident, $ident)})]
4860
let ${concat($tt_ident, $ident)} = ();
49-
let ${concat($tt_ident, $literal)} = ();
5061
// tt literal
62+
#[allow(dead_code, reason = ${concat_str($tt_literal, b)})]
5163
let ${concat($tt_literal, b)} = ();
64+
#[allow(dead_code, reason = ${concat_str($tt_literal, _b)})]
5265
let ${concat($tt_literal, _b)} = ();
66+
#[allow(dead_code, reason = ${concat_str($tt_literal, "b")})]
5367
let ${concat($tt_literal, "b")} = ();
68+
#[allow(dead_code, reason = ${concat_str($tt_literal, $tt_ident)})]
5469
let ${concat($tt_literal, $tt_ident)} = ();
70+
#[allow(dead_code, reason = ${concat_str($tt_literal, $tt_literal)})]
5571
let ${concat($tt_literal, $tt_literal)} = ();
72+
#[allow(dead_code, reason = ${concat_str($tt_literal, $ident)})]
5673
let ${concat($tt_literal, $ident)} = ();
74+
#[allow(dead_code, reason = ${concat_str($tt_literal, $literal)})]
5775
let ${concat($tt_literal, $literal)} = ();
5876

5977
// ident (adhoc)
78+
#[allow(dead_code, reason = ${concat_str(_b, b)})]
6079
let ${concat(_b, b)} = ();
80+
#[allow(dead_code, reason = ${concat_str(_b, _b)})]
6181
let ${concat(_b, _b)} = ();
82+
#[allow(dead_code, reason = ${concat_str(_b, "b")})]
6283
let ${concat(_b, "b")} = ();
84+
#[allow(dead_code, reason = ${concat_str(_b, $tt_ident)})]
6385
let ${concat(_b, $tt_ident)} = ();
86+
#[allow(dead_code, reason = ${concat_str(_b, $tt_literal)})]
6487
let ${concat(_b, $tt_literal)} = ();
88+
#[allow(dead_code, reason = ${concat_str(_b, $ident)})]
6589
let ${concat(_b, $ident)} = ();
90+
#[allow(dead_code, reason = ${concat_str(_b, $literal)})]
6691
let ${concat(_b, $literal)} = ();
6792
// ident (param)
93+
#[allow(dead_code, reason = ${concat_str($ident, b)})]
6894
let ${concat($ident, b)} = ();
95+
#[allow(dead_code, reason = ${concat_str($ident, _b)})]
6996
let ${concat($ident, _b)} = ();
97+
#[allow(dead_code, reason = ${concat_str($ident, "b")})]
7098
let ${concat($ident, "b")} = ();
99+
#[allow(dead_code, reason = ${concat_str($ident, $tt_ident)})]
71100
let ${concat($ident, $tt_ident)} = ();
101+
#[allow(dead_code, reason = ${concat_str($ident, $tt_literal)})]
72102
let ${concat($ident, $tt_literal)} = ();
103+
#[allow(dead_code, reason = ${concat_str($ident, $ident)})]
73104
let ${concat($ident, $ident)} = ();
105+
#[allow(dead_code, reason = ${concat_str($ident, $literal)})]
74106
let ${concat($ident, $literal)} = ();
75107

76108
// literal (adhoc)
109+
#[allow(dead_code, reason = ${concat_str("a", b)})]
77110
let ${concat("a", b)} = ();
111+
#[allow(dead_code, reason = ${concat_str("a", _b)})]
78112
let ${concat("a", _b)} = ();
113+
#[allow(dead_code, reason = ${concat_str("a", "b")})]
79114
let ${concat("a", "b")} = ();
115+
#[allow(dead_code, reason = ${concat_str("a", $tt_ident)})]
80116
let ${concat("a", $tt_ident)} = ();
117+
#[allow(dead_code, reason = ${concat_str("a", $tt_literal)})]
81118
let ${concat("a", $tt_literal)} = ();
119+
#[allow(dead_code, reason = ${concat_str("a", $ident)})]
82120
let ${concat("a", $ident)} = ();
121+
#[allow(dead_code, reason = ${concat_str("a", $literal)})]
83122
let ${concat("a", $literal)} = ();
84123
// literal (param)
124+
#[allow(dead_code, reason = ${concat_str($literal, b)})]
85125
let ${concat($literal, b)} = ();
126+
#[allow(dead_code, reason = ${concat_str($literal, _b)})]
86127
let ${concat($literal, _b)} = ();
128+
#[allow(dead_code, reason = ${concat_str($literal, "b")})]
87129
let ${concat($literal, "b")} = ();
130+
#[allow(dead_code, reason = ${concat_str($literal, $tt_ident)})]
88131
let ${concat($literal, $tt_ident)} = ();
132+
#[allow(dead_code, reason = ${concat_str($literal, $tt_literal)})]
89133
let ${concat($literal, $tt_literal)} = ();
134+
#[allow(dead_code, reason = ${concat_str($literal, $ident)})]
90135
let ${concat($literal, $ident)} = ();
136+
#[allow(dead_code, reason = ${concat_str($literal, $literal)})]
91137
let ${concat($literal, $literal)} = ();
92138
}};
93139
}
94140

95141
macro_rules! int_struct {
96142
($n: literal) => {
143+
#[allow(dead_code, reason = ${concat_str(E, $n)})]
97144
struct ${concat(E, $n)};
98145
}
99146
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
//@ run-pass
2+
3+
#![feature(macro_metavar_expr_concat)]
4+
5+
macro_rules! escape_literal {
6+
($literal:literal, $concatted:literal) => {
7+
let lit = ${concat_str("_", "\"foo", $literal)};
8+
assert_eq!(lit, concat!("_", "\"foo", $literal));
9+
assert_eq!(lit, $concatted);
10+
11+
}
12+
}
13+
14+
fn main(){
15+
escape_literal!("\u{00BD}", "_\"foo\u{00BD}");
16+
escape_literal!("\x41", "_\"foo\x41");
17+
escape_literal!("🤷", "_\"foo🤷");
18+
escape_literal!("\u{1F980}", "_\"foo🦀");
19+
escape_literal!("aaa \"bbb\" ccc", "_\"fooaaa \"bbb\" ccc");
20+
}

0 commit comments

Comments
 (0)