1use std::fmt::Write;
2
3use rustc_data_structures::fx::FxIndexSet;
4use rustc_span::edition::Edition;
5
6use crate::doctest::{
7 DocTestBuilder, GlobalTestOptions, IndividualTestOptions, RunnableDocTest, RustdocOptions,
8 ScrapedDocTest, TestFailure, UnusedExterns, run_test,
9};
10use crate::html::markdown::{Ignore, LangString};
11
12pub(crate) struct DocTestRunner {
14 crate_attrs: FxIndexSet<String>,
15 ids: String,
16 output: String,
17 supports_color: bool,
18 nb_tests: usize,
19}
20
21impl DocTestRunner {
22 pub(crate) fn new() -> Self {
23 Self {
24 crate_attrs: FxIndexSet::default(),
25 ids: String::new(),
26 output: String::new(),
27 supports_color: true,
28 nb_tests: 0,
29 }
30 }
31
32 pub(crate) fn add_test(
33 &mut self,
34 doctest: &DocTestBuilder,
35 scraped_test: &ScrapedDocTest,
36 target_str: &str,
37 ) {
38 let ignore = match scraped_test.langstr.ignore {
39 Ignore::All => true,
40 Ignore::None => false,
41 Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
42 };
43 if !ignore {
44 for line in doctest.crate_attrs.split('\n') {
45 self.crate_attrs.insert(line.to_string());
46 }
47 }
48 if !self.ids.is_empty() {
49 self.ids.push(',');
50 }
51 self.ids.push_str(&format!(
52 "{}::TEST",
53 generate_mergeable_doctest(
54 doctest,
55 scraped_test,
56 ignore,
57 self.nb_tests,
58 &mut self.output
59 ),
60 ));
61 self.supports_color &= doctest.supports_color;
62 self.nb_tests += 1;
63 }
64
65 pub(crate) fn run_merged_tests(
66 &mut self,
67 test_options: IndividualTestOptions,
68 edition: Edition,
69 opts: &GlobalTestOptions,
70 test_args: &[String],
71 rustdoc_options: &RustdocOptions,
72 ) -> Result<bool, ()> {
73 let mut code = "\
74#![allow(unused_extern_crates)]
75#![allow(internal_features)]
76#![feature(test)]
77#![feature(rustc_attrs)]
78"
79 .to_string();
80
81 for crate_attr in &self.crate_attrs {
82 code.push_str(crate_attr);
83 code.push('\n');
84 }
85
86 if opts.attrs.is_empty() {
87 code.push_str("#![allow(unused)]\n");
92 }
93
94 for attr in &opts.attrs {
96 code.push_str(&format!("#![{attr}]\n"));
97 }
98
99 code.push_str("extern crate test;\n");
100
101 let test_args = test_args.iter().fold(String::new(), |mut x, arg| {
102 write!(x, "{arg:?}.to_string(),").unwrap();
103 x
104 });
105 write!(
106 code,
107 "\
108{output}
109
110mod __doctest_mod {{
111 use std::sync::OnceLock;
112 use std::path::PathBuf;
113
114 pub static BINARY_PATH: OnceLock<PathBuf> = OnceLock::new();
115 pub const RUN_OPTION: &str = \"RUSTDOC_DOCTEST_RUN_NB_TEST\";
116
117 #[allow(unused)]
118 pub fn doctest_path() -> Option<&'static PathBuf> {{
119 self::BINARY_PATH.get()
120 }}
121
122 #[allow(unused)]
123 pub fn doctest_runner(bin: &std::path::Path, test_nb: usize) -> Result<(), String> {{
124 let out = std::process::Command::new(bin)
125 .env(self::RUN_OPTION, test_nb.to_string())
126 .args(std::env::args().skip(1).collect::<Vec<_>>())
127 .output()
128 .expect(\"failed to run command\");
129 if !out.status.success() {{
130 Err(String::from_utf8_lossy(&out.stderr).to_string())
131 }} else {{
132 Ok(())
133 }}
134 }}
135}}
136
137#[rustc_main]
138fn main() -> std::process::ExitCode {{
139const TESTS: [test::TestDescAndFn; {nb_tests}] = [{ids}];
140let test_marker = std::ffi::OsStr::new(__doctest_mod::RUN_OPTION);
141let test_args = &[{test_args}];
142const ENV_BIN: &'static str = \"RUSTDOC_DOCTEST_BIN_PATH\";
143
144if let Ok(binary) = std::env::var(ENV_BIN) {{
145 let _ = crate::__doctest_mod::BINARY_PATH.set(binary.into());
146 unsafe {{ std::env::remove_var(ENV_BIN); }}
147 return std::process::Termination::report(test::test_main(test_args, Vec::from(TESTS), None));
148}} else if let Ok(nb_test) = std::env::var(__doctest_mod::RUN_OPTION) {{
149 if let Ok(nb_test) = nb_test.parse::<usize>() {{
150 if let Some(test) = TESTS.get(nb_test) {{
151 if let test::StaticTestFn(f) = test.testfn {{
152 return std::process::Termination::report(f());
153 }}
154 }}
155 }}
156 panic!(\"Unexpected value for `{{}}`\", __doctest_mod::RUN_OPTION);
157}}
158
159eprintln!(\"WARNING: No rustdoc doctest environment variable provided so doctests will be run in \
160the same process\");
161std::process::Termination::report(test::test_main(test_args, Vec::from(TESTS), None))
162}}",
163 nb_tests = self.nb_tests,
164 output = self.output,
165 ids = self.ids,
166 )
167 .expect("failed to generate test code");
168 let runnable_test = RunnableDocTest {
169 full_test_code: code,
170 full_test_line_offset: 0,
171 test_opts: test_options,
172 global_opts: opts.clone(),
173 langstr: LangString::default(),
174 line: 0,
175 edition,
176 no_run: false,
177 is_multiple_tests: true,
178 };
179 let ret =
180 run_test(runnable_test, rustdoc_options, self.supports_color, |_: UnusedExterns| {});
181 if let Err(TestFailure::CompileError) = ret { Err(()) } else { Ok(ret.is_ok()) }
182 }
183}
184
185fn generate_mergeable_doctest(
187 doctest: &DocTestBuilder,
188 scraped_test: &ScrapedDocTest,
189 ignore: bool,
190 id: usize,
191 output: &mut String,
192) -> String {
193 let test_id = format!("__doctest_{id}");
194
195 if ignore {
196 writeln!(output, "mod {test_id} {{\n").unwrap();
198 } else {
199 writeln!(output, "mod {test_id} {{\n{}{}", doctest.crates, doctest.maybe_crate_attrs)
200 .unwrap();
201 if doctest.has_main_fn {
202 output.push_str(&doctest.everything_else);
203 } else {
204 let returns_result = if doctest.everything_else.trim_end().ends_with("(())") {
205 "-> Result<(), impl core::fmt::Debug>"
206 } else {
207 ""
208 };
209 write!(
210 output,
211 "\
212fn main() {returns_result} {{
213{}
214}}",
215 doctest.everything_else
216 )
217 .unwrap();
218 }
219 }
220 let not_running = ignore || scraped_test.langstr.no_run;
221 writeln!(
222 output,
223 "
224pub const TEST: test::TestDescAndFn = test::TestDescAndFn::new_doctest(
225{test_name:?}, {ignore}, {file:?}, {line}, {no_run}, {should_panic},
226test::StaticTestFn(
227 || {{{runner}}},
228));
229}}",
230 test_name = scraped_test.name,
231 file = scraped_test.path(),
232 line = scraped_test.line,
233 no_run = scraped_test.langstr.no_run,
234 should_panic = !scraped_test.langstr.no_run && scraped_test.langstr.should_panic,
235 runner = if not_running {
238 "test::assert_test_result(Ok::<(), String>(()))".to_string()
239 } else {
240 format!(
241 "
242if let Some(bin_path) = crate::__doctest_mod::doctest_path() {{
243 test::assert_test_result(crate::__doctest_mod::doctest_runner(bin_path, {id}))
244}} else {{
245 test::assert_test_result(self::main())
246}}
247",
248 )
249 },
250 )
251 .unwrap();
252 test_id
253}