Skip to content

Commit 117a28a

Browse files
committed
fix(mbe): desugar doc correctly for mbe
Fixes rust-lang#16110. The way rust desugars doc comments when expanding macros is rendering it as raw strings delimited with hashes. Rust-analyzer wasn't aware of this, so the desugared doc comments wouldn't match correctly when on the LHS of macro declarations. This PR fixes this by porting the code used by rustc: https://github.com/rust-lang/rust/blob/4cfdbd328b7171b2328d11b950b1af0978d6b1ef/compiler/rustc_ast/src/tokenstream.rs#L6837
1 parent f663521 commit 117a28a

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

crates/hir-def/src/macro_expansion_tests/mbe.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1218,8 +1218,10 @@ m! {
12181218
macro_rules! m {
12191219
($(#[$m:meta])+) => ( $(#[$m])+ fn bar() {} )
12201220
}
1221-
#[doc = " Single Line Doc 1"]
1222-
#[doc = "\n MultiLines Doc\n "] fn bar() {}
1221+
#[doc = r" Single Line Doc 1"]
1222+
#[doc = "
1223+
MultiLines Doc
1224+
"] fn bar() {}
12231225
"##]],
12241226
);
12251227
}
@@ -1260,8 +1262,10 @@ m! {
12601262
macro_rules! m {
12611263
($(#[$ m:meta])+) => ( $(#[$m])+ fn bar() {} )
12621264
}
1263-
#[doc = " 錦瑟無端五十弦,一弦一柱思華年。"]
1264-
#[doc = "\n 莊生曉夢迷蝴蝶,望帝春心託杜鵑。\n "] fn bar() {}
1265+
#[doc = r" 錦瑟無端五十弦,一弦一柱思華年。"]
1266+
#[doc = r"
1267+
莊生曉夢迷蝴蝶,望帝春心託杜鵑。
1268+
"] fn bar() {}
12651269
"##]],
12661270
);
12671271
}
@@ -1281,7 +1285,7 @@ m! {
12811285
macro_rules! m {
12821286
($(#[$m:meta])+) => ( $(#[$m])+ fn bar() {} )
12831287
}
1284-
#[doc = " \\ \" \'"] fn bar() {}
1288+
#[doc = r#" \ " '"#] fn bar() {}
12851289
"##]],
12861290
);
12871291
}

crates/mbe/src/syntax_bridge.rs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -406,9 +406,20 @@ fn doc_comment_text(comment: &ast::Comment) -> SmolStr {
406406
text = &text[0..text.len() - 2];
407407
}
408408

409-
// Quote the string
409+
let mut num_of_hashes = 0;
410+
let mut count = 0;
411+
for ch in text.chars() {
412+
count = match ch {
413+
'"' => 1,
414+
'#' if count > 0 => count + 1,
415+
_ => 0,
416+
};
417+
num_of_hashes = num_of_hashes.max(count);
418+
}
419+
420+
// Quote raw string with delimiters
410421
// Note that `tt::Literal` expect an escaped string
411-
let text = format!("\"{}\"", text.escape_debug());
422+
let text = format!("r{delim}\"{text}\"{delim}", delim = "#".repeat(num_of_hashes));
412423
text.into()
413424
}
414425

0 commit comments

Comments
 (0)