Skip to content

Commit 4dc24ae

Browse files
committed
Auto merge of #125798 - camelid:refactor-doctest, r=GuillaumeGomez
rustdoc: Refactor doctest collection and running code This code previously had a quite confusing structure, mixing the collection, processing, and running of doctests with multiple layers of indirection. There are also many cases where tons of parameters are passed to functions with little typing information (e.g., booleans or strings are often used). As a result, the source of bugs is obfuscated (e.g. #81070) and large changes (e.g. #123974) become unnecessarily complicated. This PR is a first step to try to simplify the code and make it easier to follow and less bug-prone. r? `@GuillaumeGomez`
2 parents e3c3ce6 + 6aab04e commit 4dc24ae

File tree

9 files changed

+1020
-890
lines changed

9 files changed

+1020
-890
lines changed

src/librustdoc/doctest.rs

+224-811
Large diffs are not rendered by default.

src/librustdoc/doctest/make.rs

+393
Large diffs are not rendered by default.

src/librustdoc/doctest/markdown.rs

+125
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
//! Doctest functionality used only for doctests in `.md` Markdown files.
2+
3+
use std::fs::read_to_string;
4+
5+
use rustc_span::FileName;
6+
use tempfile::tempdir;
7+
8+
use super::{
9+
generate_args_file, CreateRunnableDoctests, DoctestVisitor, GlobalTestOptions, ScrapedDoctest,
10+
};
11+
use crate::config::Options;
12+
use crate::html::markdown::{find_testable_code, ErrorCodes, LangString, MdRelLine};
13+
14+
struct MdCollector {
15+
tests: Vec<ScrapedDoctest>,
16+
cur_path: Vec<String>,
17+
filename: FileName,
18+
}
19+
20+
impl DoctestVisitor for MdCollector {
21+
fn visit_test(&mut self, test: String, config: LangString, rel_line: MdRelLine) {
22+
let filename = self.filename.clone();
23+
// First line of Markdown is line 1.
24+
let line = 1 + rel_line.offset();
25+
self.tests.push(ScrapedDoctest {
26+
filename,
27+
line,
28+
logical_path: self.cur_path.clone(),
29+
langstr: config,
30+
text: test,
31+
});
32+
}
33+
34+
fn visit_header(&mut self, name: &str, level: u32) {
35+
// We use these headings as test names, so it's good if
36+
// they're valid identifiers.
37+
let name = name
38+
.chars()
39+
.enumerate()
40+
.map(|(i, c)| {
41+
if (i == 0 && rustc_lexer::is_id_start(c))
42+
|| (i != 0 && rustc_lexer::is_id_continue(c))
43+
{
44+
c
45+
} else {
46+
'_'
47+
}
48+
})
49+
.collect::<String>();
50+
51+
// Here we try to efficiently assemble the header titles into the
52+
// test name in the form of `h1::h2::h3::h4::h5::h6`.
53+
//
54+
// Suppose that originally `self.cur_path` contains `[h1, h2, h3]`...
55+
let level = level as usize;
56+
if level <= self.cur_path.len() {
57+
// ... Consider `level == 2`. All headers in the lower levels
58+
// are irrelevant in this new level. So we should reset
59+
// `self.names` to contain headers until <h2>, and replace that
60+
// slot with the new name: `[h1, name]`.
61+
self.cur_path.truncate(level);
62+
self.cur_path[level - 1] = name;
63+
} else {
64+
// ... On the other hand, consider `level == 5`. This means we
65+
// need to extend `self.names` to contain five headers. We fill
66+
// in the missing level (<h4>) with `_`. Thus `self.names` will
67+
// become `[h1, h2, h3, "_", name]`.
68+
if level - 1 > self.cur_path.len() {
69+
self.cur_path.resize(level - 1, "_".to_owned());
70+
}
71+
self.cur_path.push(name);
72+
}
73+
}
74+
}
75+
76+
/// Runs any tests/code examples in the markdown file `options.input`.
77+
pub(crate) fn test(options: Options) -> Result<(), String> {
78+
use rustc_session::config::Input;
79+
let input_str = match &options.input {
80+
Input::File(path) => {
81+
read_to_string(&path).map_err(|err| format!("{}: {err}", path.display()))?
82+
}
83+
Input::Str { name: _, input } => input.clone(),
84+
};
85+
86+
// Obviously not a real crate name, but close enough for purposes of doctests.
87+
let crate_name = options.input.filestem().to_string();
88+
let temp_dir =
89+
tempdir().map_err(|error| format!("failed to create temporary directory: {error:?}"))?;
90+
let args_file = temp_dir.path().join("rustdoc-cfgs");
91+
generate_args_file(&args_file, &options)?;
92+
93+
let opts = GlobalTestOptions {
94+
crate_name,
95+
no_crate_inject: true,
96+
insert_indent_space: false,
97+
attrs: vec![],
98+
args_file,
99+
};
100+
101+
let mut md_collector = MdCollector {
102+
tests: vec![],
103+
cur_path: vec![],
104+
filename: options
105+
.input
106+
.opt_path()
107+
.map(ToOwned::to_owned)
108+
.map(FileName::from)
109+
.unwrap_or(FileName::Custom("input".to_owned())),
110+
};
111+
let codes = ErrorCodes::from(options.unstable_features.is_nightly_build());
112+
113+
find_testable_code(
114+
&input_str,
115+
&mut md_collector,
116+
codes,
117+
options.enable_per_target_ignores,
118+
None,
119+
);
120+
121+
let mut collector = CreateRunnableDoctests::new(options.clone(), opts);
122+
md_collector.tests.into_iter().for_each(|t| collector.add_test(t));
123+
crate::doctest::run_tests(options.test_args, options.nocapture, collector.tests);
124+
Ok(())
125+
}

src/librustdoc/doctest/rust.rs

+198
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
//! Doctest functionality used only for doctests in `.rs` source files.
2+
3+
use std::env;
4+
5+
use rustc_data_structures::{fx::FxHashSet, sync::Lrc};
6+
use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
7+
use rustc_hir::{self as hir, intravisit, CRATE_HIR_ID};
8+
use rustc_middle::hir::map::Map;
9+
use rustc_middle::hir::nested_filter;
10+
use rustc_middle::ty::TyCtxt;
11+
use rustc_resolve::rustdoc::span_of_fragments;
12+
use rustc_session::Session;
13+
use rustc_span::source_map::SourceMap;
14+
use rustc_span::{BytePos, FileName, Pos, Span, DUMMY_SP};
15+
16+
use super::{DoctestVisitor, ScrapedDoctest};
17+
use crate::clean::{types::AttributesExt, Attributes};
18+
use crate::html::markdown::{self, ErrorCodes, LangString, MdRelLine};
19+
20+
struct RustCollector {
21+
source_map: Lrc<SourceMap>,
22+
tests: Vec<ScrapedDoctest>,
23+
cur_path: Vec<String>,
24+
position: Span,
25+
}
26+
27+
impl RustCollector {
28+
fn get_filename(&self) -> FileName {
29+
let filename = self.source_map.span_to_filename(self.position);
30+
if let FileName::Real(ref filename) = filename
31+
&& let Ok(cur_dir) = env::current_dir()
32+
&& let Some(local_path) = filename.local_path()
33+
&& let Ok(path) = local_path.strip_prefix(&cur_dir)
34+
{
35+
return path.to_owned().into();
36+
}
37+
filename
38+
}
39+
40+
fn get_base_line(&self) -> usize {
41+
let sp_lo = self.position.lo().to_usize();
42+
let loc = self.source_map.lookup_char_pos(BytePos(sp_lo as u32));
43+
loc.line
44+
}
45+
}
46+
47+
impl DoctestVisitor for RustCollector {
48+
fn visit_test(&mut self, test: String, config: LangString, rel_line: MdRelLine) {
49+
let line = self.get_base_line() + rel_line.offset();
50+
self.tests.push(ScrapedDoctest {
51+
filename: self.get_filename(),
52+
line,
53+
logical_path: self.cur_path.clone(),
54+
langstr: config,
55+
text: test,
56+
});
57+
}
58+
59+
fn visit_header(&mut self, _name: &str, _level: u32) {}
60+
}
61+
62+
pub(super) struct HirCollector<'a, 'tcx> {
63+
sess: &'a Session,
64+
map: Map<'tcx>,
65+
codes: ErrorCodes,
66+
tcx: TyCtxt<'tcx>,
67+
enable_per_target_ignores: bool,
68+
collector: RustCollector,
69+
}
70+
71+
impl<'a, 'tcx> HirCollector<'a, 'tcx> {
72+
pub fn new(
73+
sess: &'a Session,
74+
map: Map<'tcx>,
75+
codes: ErrorCodes,
76+
enable_per_target_ignores: bool,
77+
tcx: TyCtxt<'tcx>,
78+
) -> Self {
79+
let collector = RustCollector {
80+
source_map: sess.psess.clone_source_map(),
81+
cur_path: vec![],
82+
position: DUMMY_SP,
83+
tests: vec![],
84+
};
85+
Self { sess, map, codes, enable_per_target_ignores, tcx, collector }
86+
}
87+
88+
pub fn collect_crate(mut self) -> Vec<ScrapedDoctest> {
89+
let tcx = self.tcx;
90+
self.visit_testable("".to_string(), CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID), |this| {
91+
tcx.hir().walk_toplevel_module(this)
92+
});
93+
self.collector.tests
94+
}
95+
}
96+
97+
impl<'a, 'tcx> HirCollector<'a, 'tcx> {
98+
fn visit_testable<F: FnOnce(&mut Self)>(
99+
&mut self,
100+
name: String,
101+
def_id: LocalDefId,
102+
sp: Span,
103+
nested: F,
104+
) {
105+
let ast_attrs = self.tcx.hir().attrs(self.tcx.local_def_id_to_hir_id(def_id));
106+
if let Some(ref cfg) = ast_attrs.cfg(self.tcx, &FxHashSet::default()) {
107+
if !cfg.matches(&self.sess.psess, Some(self.tcx.features())) {
108+
return;
109+
}
110+
}
111+
112+
let has_name = !name.is_empty();
113+
if has_name {
114+
self.collector.cur_path.push(name);
115+
}
116+
117+
// The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
118+
// anything else, this will combine them for us.
119+
let attrs = Attributes::from_ast(ast_attrs);
120+
if let Some(doc) = attrs.opt_doc_value() {
121+
// Use the outermost invocation, so that doctest names come from where the docs were written.
122+
let span = ast_attrs
123+
.iter()
124+
.find(|attr| attr.doc_str().is_some())
125+
.map(|attr| attr.span.ctxt().outer_expn().expansion_cause().unwrap_or(attr.span))
126+
.unwrap_or(DUMMY_SP);
127+
self.collector.position = span;
128+
markdown::find_testable_code(
129+
&doc,
130+
&mut self.collector,
131+
self.codes,
132+
self.enable_per_target_ignores,
133+
Some(&crate::html::markdown::ExtraInfo::new(
134+
self.tcx,
135+
def_id.to_def_id(),
136+
span_of_fragments(&attrs.doc_strings).unwrap_or(sp),
137+
)),
138+
);
139+
}
140+
141+
nested(self);
142+
143+
if has_name {
144+
self.collector.cur_path.pop();
145+
}
146+
}
147+
}
148+
149+
impl<'a, 'tcx> intravisit::Visitor<'tcx> for HirCollector<'a, 'tcx> {
150+
type NestedFilter = nested_filter::All;
151+
152+
fn nested_visit_map(&mut self) -> Self::Map {
153+
self.map
154+
}
155+
156+
fn visit_item(&mut self, item: &'tcx hir::Item<'_>) {
157+
let name = match &item.kind {
158+
hir::ItemKind::Impl(impl_) => {
159+
rustc_hir_pretty::id_to_string(&self.map, impl_.self_ty.hir_id)
160+
}
161+
_ => item.ident.to_string(),
162+
};
163+
164+
self.visit_testable(name, item.owner_id.def_id, item.span, |this| {
165+
intravisit::walk_item(this, item);
166+
});
167+
}
168+
169+
fn visit_trait_item(&mut self, item: &'tcx hir::TraitItem<'_>) {
170+
self.visit_testable(item.ident.to_string(), item.owner_id.def_id, item.span, |this| {
171+
intravisit::walk_trait_item(this, item);
172+
});
173+
}
174+
175+
fn visit_impl_item(&mut self, item: &'tcx hir::ImplItem<'_>) {
176+
self.visit_testable(item.ident.to_string(), item.owner_id.def_id, item.span, |this| {
177+
intravisit::walk_impl_item(this, item);
178+
});
179+
}
180+
181+
fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'_>) {
182+
self.visit_testable(item.ident.to_string(), item.owner_id.def_id, item.span, |this| {
183+
intravisit::walk_foreign_item(this, item);
184+
});
185+
}
186+
187+
fn visit_variant(&mut self, v: &'tcx hir::Variant<'_>) {
188+
self.visit_testable(v.ident.to_string(), v.def_id, v.span, |this| {
189+
intravisit::walk_variant(this, v);
190+
});
191+
}
192+
193+
fn visit_field_def(&mut self, f: &'tcx hir::FieldDef<'_>) {
194+
self.visit_testable(f.ident.to_string(), f.def_id, f.span, |this| {
195+
intravisit::walk_field_def(this, f);
196+
});
197+
}
198+
}

0 commit comments

Comments
 (0)