Skip to content

Commit c9db3e0

Browse files
committed
Auto merge of #87489 - bdalrhm:rustdoc-line-num, r=CraftSpider
`rustdoc`: compute correct line number for indented rust code blocks. This PR fixes a bug in `rustdoc` where it computes the wrong line number for indented rust code blocks (and subsequent blocks) it finds in markdown strings. To fix this issue, we decrement the line number if we find characters between the code block and the preceding line ending. I noticed this issue as I was trying to use `rustdoc` to extract examples from The Rust Reference and run them through the [Rust Model Checker](https://github.com/model-checking/rmc).
2 parents 434cb43 + e66dafc commit c9db3e0

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/librustdoc/html/markdown.rs

+6
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,12 @@ crate fn find_testable_code<T: doctest::Tester>(
692692
.join("\n");
693693

694694
nb_lines += doc[prev_offset..offset.start].lines().count();
695+
// If there are characters between the preceding line ending and
696+
// this code block, `str::lines` will return an additional line,
697+
// which we subtract here.
698+
if nb_lines != 0 && !&doc[prev_offset..offset.start].ends_with("\n") {
699+
nb_lines -= 1;
700+
}
695701
let line = tests.get_line() + nb_lines + 1;
696702
tests.add_test(text, block_info, line);
697703
prev_offset = offset.start;

src/librustdoc/html/markdown/tests.rs

+23-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{plain_text_summary, short_markdown_summary};
1+
use super::{find_testable_code, plain_text_summary, short_markdown_summary};
22
use super::{ErrorCodes, IdMap, Ignore, LangString, Markdown, MarkdownHtml};
33
use rustc_span::edition::{Edition, DEFAULT_EDITION};
44

@@ -300,3 +300,25 @@ fn test_markdown_html_escape() {
300300
t("Struct<'a, T>", "<p>Struct&lt;’a, T&gt;</p>\n");
301301
t("Struct<br>", "<p>Struct&lt;br&gt;</p>\n");
302302
}
303+
304+
#[test]
305+
fn test_find_testable_code_line() {
306+
fn t(input: &str, expect: &[usize]) {
307+
impl crate::doctest::Tester for Vec<usize> {
308+
fn add_test(&mut self, _test: String, _config: LangString, line: usize) {
309+
self.push(line);
310+
}
311+
}
312+
let mut lines = Vec::<usize>::new();
313+
find_testable_code(input, &mut lines, ErrorCodes::No, false, None);
314+
assert_eq!(lines, expect);
315+
}
316+
317+
t("", &[]);
318+
t("```rust\n```", &[1]);
319+
t(" ```rust\n```", &[1]);
320+
t("\n```rust\n```", &[2]);
321+
t("\n ```rust\n```", &[2]);
322+
t("```rust\n```\n```rust\n```", &[1, 3]);
323+
t("```rust\n```\n ```rust\n```", &[1, 3]);
324+
}

0 commit comments

Comments
 (0)