Skip to content

Commit

Permalink
Auto merge of #16158 - saiintbrisson:fix/mbe/desugar-comment-to-raw-s…
Browse files Browse the repository at this point in the history
…tring, r=Veykril

fix(mbe): desugar doc correctly for mbe

Fixes #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/59096cdad0e527ce4d254b55aca58539f726d3d6/compiler/rustc_ast/src/tokenstream.rs#L662-L671
  • Loading branch information
bors committed Dec 19, 2023
2 parents f1d09c9 + 6f58e98 commit 484525f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
14 changes: 9 additions & 5 deletions crates/hir-def/src/macro_expansion_tests/mbe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1218,8 +1218,10 @@ m! {
macro_rules! m {
($(#[$m:meta])+) => ( $(#[$m])+ fn bar() {} )
}
#[doc = " Single Line Doc 1"]
#[doc = "\n MultiLines Doc\n "] fn bar() {}
#[doc = r" Single Line Doc 1"]
#[doc = r"
MultiLines Doc
"] fn bar() {}
"##]],
);
}
Expand Down Expand Up @@ -1260,8 +1262,10 @@ m! {
macro_rules! m {
($(#[$ m:meta])+) => ( $(#[$m])+ fn bar() {} )
}
#[doc = " 錦瑟無端五十弦,一弦一柱思華年。"]
#[doc = "\n 莊生曉夢迷蝴蝶,望帝春心託杜鵑。\n "] fn bar() {}
#[doc = r" 錦瑟無端五十弦,一弦一柱思華年。"]
#[doc = r"
莊生曉夢迷蝴蝶,望帝春心託杜鵑。
"] fn bar() {}
"##]],
);
}
Expand All @@ -1281,7 +1285,7 @@ m! {
macro_rules! m {
($(#[$m:meta])+) => ( $(#[$m])+ fn bar() {} )
}
#[doc = " \\ \" \'"] fn bar() {}
#[doc = r#" \ " '"#] fn bar() {}
"##]],
);
}
Expand Down
15 changes: 13 additions & 2 deletions crates/mbe/src/syntax_bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -406,9 +406,20 @@ fn doc_comment_text(comment: &ast::Comment) -> SmolStr {
text = &text[0..text.len() - 2];
}

// Quote the string
let mut num_of_hashes = 0;
let mut count = 0;
for ch in text.chars() {
count = match ch {
'"' => 1,
'#' if count > 0 => count + 1,
_ => 0,
};
num_of_hashes = num_of_hashes.max(count);
}

// Quote raw string with delimiters
// Note that `tt::Literal` expect an escaped string
let text = format!("\"{}\"", text.escape_debug());
let text = format!("r{delim}\"{text}\"{delim}", delim = "#".repeat(num_of_hashes));
text.into()
}

Expand Down

0 comments on commit 484525f

Please sign in to comment.