8560: Escape characters in doc comments in macros correctly r=jonas-schievink a=ChayimFriedman2

Previously they were escaped twice, both by `.escape_default()` and the debug view of strings (`{:?}`). This leads to things like newlines or tabs in documentation comments being `\\n`, but we unescape literals only once, ending up with `\n`.

This was hard to spot because CMark unescaped them (at least for `'` and `"`), but it did not do so in code blocks.

This also was the root cause of #7781. This issue was solved by using `.escape_debug()` instead of `.escape_default()`, but the real issue remained.
We can bring the `.escape_default()` back by now, however I didn't do it because it is probably slower than `.escape_debug()` (more work to do), and also in order to change the code the least.

Example (the keyword and primitive docs are `include!()`d at https://doc.rust-lang.org/src/std/lib.rs.html#570-578, and thus originate from macro):

Before:
![image](https://user-images.githubusercontent.com/24700207/115130096-40544300-9ff5-11eb-847b-969e7034e8a4.png)

After:
![image](https://user-images.githubusercontent.com/24700207/115130143-9cb76280-9ff5-11eb-9281-323746089440.png)


Co-authored-by: Chayim Refael Friedman <chayimfr@gmail.com>
This commit is contained in:
bors[bot] 2021-04-18 02:14:27 +00:00 committed by GitHub
commit 2ace128dd4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 3 deletions

View File

@ -213,7 +213,7 @@ fn doc_comment_text(comment: &ast::Comment) -> SmolStr {
// Quote the string
// Note that `tt::Literal` expect an escaped string
let text = format!("{:?}", text.escape_debug().to_string());
let text = format!("\"{}\"", text.escape_debug());
text.into()
}

View File

@ -936,7 +936,7 @@ fn test_meta_doc_comments() {
MultiLines Doc
*/
}"#,
"# [doc = \" Single Line Doc 1\"] # [doc = \"\\\\n MultiLines Doc\\\\n \"] fn bar () {}",
"# [doc = \" Single Line Doc 1\"] # [doc = \"\\n MultiLines Doc\\n \"] fn bar () {}",
);
}
@ -977,7 +977,27 @@ fn test_meta_doc_comments_non_latin() {
*/
}"#,
"# [doc = \" 錦瑟無端五十弦,一弦一柱思華年。\"] # [doc = \"\\\\n 莊生曉夢迷蝴蝶,望帝春心託杜鵑。\\\\n \"] fn bar () {}",
"# [doc = \" 錦瑟無端五十弦,一弦一柱思華年。\"] # [doc = \"\\n 莊生曉夢迷蝴蝶,望帝春心託杜鵑。\\n \"] fn bar () {}",
);
}
#[test]
fn test_meta_doc_comments_escaped_characters() {
parse_macro(
r#"
macro_rules! foo {
($(#[$ i:meta])+) => (
$(#[$ i])+
fn bar() {}
)
}
"#,
)
.assert_expand_items(
r#"foo! {
/// \ " '
}"#,
r#"# [doc = " \\ \" \'"] fn bar () {}"#,
);
}