]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/doctest.rs
Rollup merge of #105071 - nnethercote:nnethercote-mailmap, r=compiler-errors
[rust.git] / src / librustdoc / doctest.rs
1 use rustc_ast as ast;
2 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
3 use rustc_data_structures::sync::Lrc;
4 use rustc_errors::{ColorConfig, ErrorGuaranteed, FatalError};
5 use rustc_hir as hir;
6 use rustc_hir::def_id::LOCAL_CRATE;
7 use rustc_hir::intravisit;
8 use rustc_hir::{HirId, CRATE_HIR_ID};
9 use rustc_interface::interface;
10 use rustc_middle::hir::map::Map;
11 use rustc_middle::hir::nested_filter;
12 use rustc_middle::ty::TyCtxt;
13 use rustc_parse::maybe_new_parser_from_source_str;
14 use rustc_parse::parser::attr::InnerAttrPolicy;
15 use rustc_session::config::{self, CrateType, ErrorOutputType};
16 use rustc_session::parse::ParseSess;
17 use rustc_session::{lint, Session};
18 use rustc_span::edition::Edition;
19 use rustc_span::source_map::SourceMap;
20 use rustc_span::symbol::sym;
21 use rustc_span::{BytePos, FileName, Pos, Span, DUMMY_SP};
22 use rustc_target::spec::{Target, TargetTriple};
23 use tempfile::Builder as TempFileBuilder;
24
25 use std::env;
26 use std::io::{self, Write};
27 use std::panic;
28 use std::path::PathBuf;
29 use std::process::{self, Command, Stdio};
30 use std::str;
31 use std::sync::atomic::{AtomicUsize, Ordering};
32 use std::sync::{Arc, Mutex};
33
34 use crate::clean::{types::AttributesExt, Attributes};
35 use crate::config::Options as RustdocOptions;
36 use crate::html::markdown::{self, ErrorCodes, Ignore, LangString};
37 use crate::lint::init_lints;
38 use crate::passes::span_of_attrs;
39
40 /// Options that apply to all doctests in a crate or Markdown file (for `rustdoc foo.md`).
41 #[derive(Clone, Default)]
42 pub(crate) struct GlobalTestOptions {
43     /// Whether to disable the default `extern crate my_crate;` when creating doctests.
44     pub(crate) no_crate_inject: bool,
45     /// Additional crate-level attributes to add to doctests.
46     pub(crate) attrs: Vec<String>,
47 }
48
49 pub(crate) fn run(options: RustdocOptions) -> Result<(), ErrorGuaranteed> {
50     let input = config::Input::File(options.input.clone());
51
52     let invalid_codeblock_attributes_name = crate::lint::INVALID_CODEBLOCK_ATTRIBUTES.name;
53
54     // See core::create_config for what's going on here.
55     let allowed_lints = vec![
56         invalid_codeblock_attributes_name.to_owned(),
57         lint::builtin::UNKNOWN_LINTS.name.to_owned(),
58         lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_owned(),
59     ];
60
61     let (lint_opts, lint_caps) = init_lints(allowed_lints, options.lint_opts.clone(), |lint| {
62         if lint.name == invalid_codeblock_attributes_name {
63             None
64         } else {
65             Some((lint.name_lower(), lint::Allow))
66         }
67     });
68
69     debug!(?lint_opts);
70
71     let crate_types =
72         if options.proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
73
74     let sessopts = config::Options {
75         maybe_sysroot: options.maybe_sysroot.clone(),
76         search_paths: options.libs.clone(),
77         crate_types,
78         lint_opts,
79         lint_cap: Some(options.lint_cap.unwrap_or(lint::Forbid)),
80         cg: options.codegen_options.clone(),
81         externs: options.externs.clone(),
82         unstable_features: options.unstable_features,
83         actually_rustdoc: true,
84         edition: options.edition,
85         target_triple: options.target.clone(),
86         crate_name: options.crate_name.clone(),
87         ..config::Options::default()
88     };
89
90     let mut cfgs = options.cfgs.clone();
91     cfgs.push("doc".to_owned());
92     cfgs.push("doctest".to_owned());
93     let config = interface::Config {
94         opts: sessopts,
95         crate_cfg: interface::parse_cfgspecs(cfgs),
96         crate_check_cfg: interface::parse_check_cfg(options.check_cfgs.clone()),
97         input,
98         input_path: None,
99         output_file: None,
100         output_dir: None,
101         file_loader: None,
102         lint_caps,
103         parse_sess_created: None,
104         register_lints: Some(Box::new(crate::lint::register_lints)),
105         override_queries: None,
106         make_codegen_backend: None,
107         registry: rustc_driver::diagnostics_registry(),
108     };
109
110     let test_args = options.test_args.clone();
111     let nocapture = options.nocapture;
112     let externs = options.externs.clone();
113     let json_unused_externs = options.json_unused_externs;
114
115     let (tests, unused_extern_reports, compiling_test_count) =
116         interface::run_compiler(config, |compiler| {
117             compiler.enter(|queries| {
118                 let mut global_ctxt = queries.global_ctxt()?.take();
119
120                 let collector = global_ctxt.enter(|tcx| {
121                     let crate_attrs = tcx.hir().attrs(CRATE_HIR_ID);
122
123                     let opts = scrape_test_config(crate_attrs);
124                     let enable_per_target_ignores = options.enable_per_target_ignores;
125                     let mut collector = Collector::new(
126                         tcx.crate_name(LOCAL_CRATE).to_string(),
127                         options,
128                         false,
129                         opts,
130                         Some(compiler.session().parse_sess.clone_source_map()),
131                         None,
132                         enable_per_target_ignores,
133                     );
134
135                     let mut hir_collector = HirCollector {
136                         sess: compiler.session(),
137                         collector: &mut collector,
138                         map: tcx.hir(),
139                         codes: ErrorCodes::from(
140                             compiler.session().opts.unstable_features.is_nightly_build(),
141                         ),
142                         tcx,
143                     };
144                     hir_collector.visit_testable(
145                         "".to_string(),
146                         CRATE_HIR_ID,
147                         tcx.hir().span(CRATE_HIR_ID),
148                         |this| tcx.hir().walk_toplevel_module(this),
149                     );
150
151                     collector
152                 });
153                 if compiler.session().diagnostic().has_errors_or_lint_errors().is_some() {
154                     FatalError.raise();
155                 }
156
157                 let unused_extern_reports = collector.unused_extern_reports.clone();
158                 let compiling_test_count = collector.compiling_test_count.load(Ordering::SeqCst);
159                 let ret: Result<_, ErrorGuaranteed> =
160                     Ok((collector.tests, unused_extern_reports, compiling_test_count));
161                 ret
162             })
163         })?;
164
165     run_tests(test_args, nocapture, tests);
166
167     // Collect and warn about unused externs, but only if we've gotten
168     // reports for each doctest
169     if json_unused_externs.is_enabled() {
170         let unused_extern_reports: Vec<_> =
171             std::mem::take(&mut unused_extern_reports.lock().unwrap());
172         if unused_extern_reports.len() == compiling_test_count {
173             let extern_names = externs.iter().map(|(name, _)| name).collect::<FxHashSet<&String>>();
174             let mut unused_extern_names = unused_extern_reports
175                 .iter()
176                 .map(|uexts| uexts.unused_extern_names.iter().collect::<FxHashSet<&String>>())
177                 .fold(extern_names, |uextsa, uextsb| {
178                     uextsa.intersection(&uextsb).copied().collect::<FxHashSet<&String>>()
179                 })
180                 .iter()
181                 .map(|v| (*v).clone())
182                 .collect::<Vec<String>>();
183             unused_extern_names.sort();
184             // Take the most severe lint level
185             let lint_level = unused_extern_reports
186                 .iter()
187                 .map(|uexts| uexts.lint_level.as_str())
188                 .max_by_key(|v| match *v {
189                     "warn" => 1,
190                     "deny" => 2,
191                     "forbid" => 3,
192                     // The allow lint level is not expected,
193                     // as if allow is specified, no message
194                     // is to be emitted.
195                     v => unreachable!("Invalid lint level '{}'", v),
196                 })
197                 .unwrap_or("warn")
198                 .to_string();
199             let uext = UnusedExterns { lint_level, unused_extern_names };
200             let unused_extern_json = serde_json::to_string(&uext).unwrap();
201             eprintln!("{unused_extern_json}");
202         }
203     }
204
205     Ok(())
206 }
207
208 pub(crate) fn run_tests(
209     mut test_args: Vec<String>,
210     nocapture: bool,
211     mut tests: Vec<test::TestDescAndFn>,
212 ) {
213     test_args.insert(0, "rustdoctest".to_string());
214     if nocapture {
215         test_args.push("--nocapture".to_string());
216     }
217     tests.sort_by(|a, b| a.desc.name.as_slice().cmp(&b.desc.name.as_slice()));
218     test::test_main(&test_args, tests, None);
219 }
220
221 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
222 fn scrape_test_config(attrs: &[ast::Attribute]) -> GlobalTestOptions {
223     use rustc_ast_pretty::pprust;
224
225     let mut opts = GlobalTestOptions { no_crate_inject: false, attrs: Vec::new() };
226
227     let test_attrs: Vec<_> = attrs
228         .iter()
229         .filter(|a| a.has_name(sym::doc))
230         .flat_map(|a| a.meta_item_list().unwrap_or_default())
231         .filter(|a| a.has_name(sym::test))
232         .collect();
233     let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
234
235     for attr in attrs {
236         if attr.has_name(sym::no_crate_inject) {
237             opts.no_crate_inject = true;
238         }
239         if attr.has_name(sym::attr) {
240             if let Some(l) = attr.meta_item_list() {
241                 for item in l {
242                     opts.attrs.push(pprust::meta_list_item_to_string(item));
243                 }
244             }
245         }
246     }
247
248     opts
249 }
250
251 /// Documentation test failure modes.
252 enum TestFailure {
253     /// The test failed to compile.
254     CompileError,
255     /// The test is marked `compile_fail` but compiled successfully.
256     UnexpectedCompilePass,
257     /// The test failed to compile (as expected) but the compiler output did not contain all
258     /// expected error codes.
259     MissingErrorCodes(Vec<String>),
260     /// The test binary was unable to be executed.
261     ExecutionError(io::Error),
262     /// The test binary exited with a non-zero exit code.
263     ///
264     /// This typically means an assertion in the test failed or another form of panic occurred.
265     ExecutionFailure(process::Output),
266     /// The test is marked `should_panic` but the test binary executed successfully.
267     UnexpectedRunPass,
268 }
269
270 enum DirState {
271     Temp(tempfile::TempDir),
272     Perm(PathBuf),
273 }
274
275 impl DirState {
276     fn path(&self) -> &std::path::Path {
277         match self {
278             DirState::Temp(t) => t.path(),
279             DirState::Perm(p) => p.as_path(),
280         }
281     }
282 }
283
284 // NOTE: Keep this in sync with the equivalent structs in rustc
285 // and cargo.
286 // We could unify this struct the one in rustc but they have different
287 // ownership semantics, so doing so would create wasteful allocations.
288 #[derive(serde::Serialize, serde::Deserialize)]
289 struct UnusedExterns {
290     /// Lint level of the unused_crate_dependencies lint
291     lint_level: String,
292     /// List of unused externs by their names.
293     unused_extern_names: Vec<String>,
294 }
295
296 fn add_exe_suffix(input: String, target: &TargetTriple) -> String {
297     let exe_suffix = match target {
298         TargetTriple::TargetTriple(_) => Target::expect_builtin(target).options.exe_suffix,
299         TargetTriple::TargetJson { contents, .. } => {
300             Target::from_json(contents.parse().unwrap()).unwrap().0.options.exe_suffix
301         }
302     };
303     input + &exe_suffix
304 }
305
306 fn run_test(
307     test: &str,
308     crate_name: &str,
309     line: usize,
310     rustdoc_options: RustdocOptions,
311     mut lang_string: LangString,
312     no_run: bool,
313     runtool: Option<String>,
314     runtool_args: Vec<String>,
315     target: TargetTriple,
316     opts: &GlobalTestOptions,
317     edition: Edition,
318     outdir: DirState,
319     path: PathBuf,
320     test_id: &str,
321     report_unused_externs: impl Fn(UnusedExterns),
322 ) -> Result<(), TestFailure> {
323     let (test, line_offset, supports_color) =
324         make_test(test, Some(crate_name), lang_string.test_harness, opts, edition, Some(test_id));
325
326     // Make sure we emit well-formed executable names for our target.
327     let rust_out = add_exe_suffix("rust_out".to_owned(), &target);
328     let output_file = outdir.path().join(rust_out);
329
330     let rustc_binary = rustdoc_options
331         .test_builder
332         .as_deref()
333         .unwrap_or_else(|| rustc_interface::util::rustc_path().expect("found rustc"));
334     let mut compiler = Command::new(&rustc_binary);
335     compiler.arg("--crate-type").arg("bin");
336     for cfg in &rustdoc_options.cfgs {
337         compiler.arg("--cfg").arg(&cfg);
338     }
339     if !rustdoc_options.check_cfgs.is_empty() {
340         compiler.arg("-Z").arg("unstable-options");
341         for check_cfg in &rustdoc_options.check_cfgs {
342             compiler.arg("--check-cfg").arg(&check_cfg);
343         }
344     }
345     if let Some(sysroot) = rustdoc_options.maybe_sysroot {
346         compiler.arg("--sysroot").arg(sysroot);
347     }
348     compiler.arg("--edition").arg(&edition.to_string());
349     compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", path);
350     compiler.env("UNSTABLE_RUSTDOC_TEST_LINE", format!("{}", line as isize - line_offset as isize));
351     compiler.arg("-o").arg(&output_file);
352     if lang_string.test_harness {
353         compiler.arg("--test");
354     }
355     if rustdoc_options.json_unused_externs.is_enabled() && !lang_string.compile_fail {
356         compiler.arg("--error-format=json");
357         compiler.arg("--json").arg("unused-externs");
358         compiler.arg("-Z").arg("unstable-options");
359         compiler.arg("-W").arg("unused_crate_dependencies");
360     }
361     for lib_str in &rustdoc_options.lib_strs {
362         compiler.arg("-L").arg(&lib_str);
363     }
364     for extern_str in &rustdoc_options.extern_strs {
365         compiler.arg("--extern").arg(&extern_str);
366     }
367     compiler.arg("-Ccodegen-units=1");
368     for codegen_options_str in &rustdoc_options.codegen_options_strs {
369         compiler.arg("-C").arg(&codegen_options_str);
370     }
371     for unstable_option_str in &rustdoc_options.unstable_opts_strs {
372         compiler.arg("-Z").arg(&unstable_option_str);
373     }
374     if no_run && !lang_string.compile_fail && rustdoc_options.persist_doctests.is_none() {
375         compiler.arg("--emit=metadata");
376     }
377     compiler.arg("--target").arg(match target {
378         TargetTriple::TargetTriple(s) => s,
379         TargetTriple::TargetJson { path_for_rustdoc, .. } => {
380             path_for_rustdoc.to_str().expect("target path must be valid unicode").to_string()
381         }
382     });
383     if let ErrorOutputType::HumanReadable(kind) = rustdoc_options.error_format {
384         let (short, color_config) = kind.unzip();
385
386         if short {
387             compiler.arg("--error-format").arg("short");
388         }
389
390         match color_config {
391             ColorConfig::Never => {
392                 compiler.arg("--color").arg("never");
393             }
394             ColorConfig::Always => {
395                 compiler.arg("--color").arg("always");
396             }
397             ColorConfig::Auto => {
398                 compiler.arg("--color").arg(if supports_color { "always" } else { "never" });
399             }
400         }
401     }
402
403     compiler.arg("-");
404     compiler.stdin(Stdio::piped());
405     compiler.stderr(Stdio::piped());
406
407     let mut child = compiler.spawn().expect("Failed to spawn rustc process");
408     {
409         let stdin = child.stdin.as_mut().expect("Failed to open stdin");
410         stdin.write_all(test.as_bytes()).expect("could write out test sources");
411     }
412     let output = child.wait_with_output().expect("Failed to read stdout");
413
414     struct Bomb<'a>(&'a str);
415     impl Drop for Bomb<'_> {
416         fn drop(&mut self) {
417             eprint!("{}", self.0);
418         }
419     }
420     let mut out = str::from_utf8(&output.stderr)
421         .unwrap()
422         .lines()
423         .filter(|l| {
424             if let Ok(uext) = serde_json::from_str::<UnusedExterns>(l) {
425                 report_unused_externs(uext);
426                 false
427             } else {
428                 true
429             }
430         })
431         .intersperse_with(|| "\n")
432         .collect::<String>();
433
434     // Add a \n to the end to properly terminate the last line,
435     // but only if there was output to be printed
436     if !out.is_empty() {
437         out.push('\n');
438     }
439
440     let _bomb = Bomb(&out);
441     match (output.status.success(), lang_string.compile_fail) {
442         (true, true) => {
443             return Err(TestFailure::UnexpectedCompilePass);
444         }
445         (true, false) => {}
446         (false, true) => {
447             if !lang_string.error_codes.is_empty() {
448                 // We used to check if the output contained "error[{}]: " but since we added the
449                 // colored output, we can't anymore because of the color escape characters before
450                 // the ":".
451                 lang_string.error_codes.retain(|err| !out.contains(&format!("error[{err}]")));
452
453                 if !lang_string.error_codes.is_empty() {
454                     return Err(TestFailure::MissingErrorCodes(lang_string.error_codes));
455                 }
456             }
457         }
458         (false, false) => {
459             return Err(TestFailure::CompileError);
460         }
461     }
462
463     if no_run {
464         return Ok(());
465     }
466
467     // Run the code!
468     let mut cmd;
469
470     if let Some(tool) = runtool {
471         cmd = Command::new(tool);
472         cmd.args(runtool_args);
473         cmd.arg(output_file);
474     } else {
475         cmd = Command::new(output_file);
476     }
477     if let Some(run_directory) = rustdoc_options.test_run_directory {
478         cmd.current_dir(run_directory);
479     }
480
481     let result = if rustdoc_options.nocapture {
482         cmd.status().map(|status| process::Output {
483             status,
484             stdout: Vec::new(),
485             stderr: Vec::new(),
486         })
487     } else {
488         cmd.output()
489     };
490     match result {
491         Err(e) => return Err(TestFailure::ExecutionError(e)),
492         Ok(out) => {
493             if lang_string.should_panic && out.status.success() {
494                 return Err(TestFailure::UnexpectedRunPass);
495             } else if !lang_string.should_panic && !out.status.success() {
496                 return Err(TestFailure::ExecutionFailure(out));
497             }
498         }
499     }
500
501     Ok(())
502 }
503
504 /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
505 /// lines before the test code begins as well as if the output stream supports colors or not.
506 pub(crate) fn make_test(
507     s: &str,
508     crate_name: Option<&str>,
509     dont_insert_main: bool,
510     opts: &GlobalTestOptions,
511     edition: Edition,
512     test_id: Option<&str>,
513 ) -> (String, usize, bool) {
514     let (crate_attrs, everything_else, crates) = partition_source(s, edition);
515     let everything_else = everything_else.trim();
516     let mut line_offset = 0;
517     let mut prog = String::new();
518     let mut supports_color = false;
519
520     if opts.attrs.is_empty() {
521         // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
522         // lints that are commonly triggered in doctests. The crate-level test attributes are
523         // commonly used to make tests fail in case they trigger warnings, so having this there in
524         // that case may cause some tests to pass when they shouldn't have.
525         prog.push_str("#![allow(unused)]\n");
526         line_offset += 1;
527     }
528
529     // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
530     for attr in &opts.attrs {
531         prog.push_str(&format!("#![{attr}]\n"));
532         line_offset += 1;
533     }
534
535     // Now push any outer attributes from the example, assuming they
536     // are intended to be crate attributes.
537     prog.push_str(&crate_attrs);
538     prog.push_str(&crates);
539
540     // Uses librustc_ast to parse the doctest and find if there's a main fn and the extern
541     // crate already is included.
542     let result = rustc_driver::catch_fatal_errors(|| {
543         rustc_span::create_session_if_not_set_then(edition, |_| {
544             use rustc_errors::emitter::{Emitter, EmitterWriter};
545             use rustc_errors::Handler;
546             use rustc_parse::parser::ForceCollect;
547             use rustc_span::source_map::FilePathMapping;
548
549             let filename = FileName::anon_source_code(s);
550             let source = crates + everything_else;
551
552             // Any errors in parsing should also appear when the doctest is compiled for real, so just
553             // send all the errors that librustc_ast emits directly into a `Sink` instead of stderr.
554             let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
555             let fallback_bundle =
556                 rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
557             supports_color = EmitterWriter::stderr(
558                 ColorConfig::Auto,
559                 None,
560                 None,
561                 fallback_bundle.clone(),
562                 false,
563                 false,
564                 Some(80),
565                 false,
566                 false,
567             )
568             .supports_color();
569
570             let emitter = EmitterWriter::new(
571                 Box::new(io::sink()),
572                 None,
573                 None,
574                 fallback_bundle,
575                 false,
576                 false,
577                 false,
578                 None,
579                 false,
580                 false,
581             );
582
583             // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
584             let handler = Handler::with_emitter(false, None, Box::new(emitter));
585             let sess = ParseSess::with_span_handler(handler, sm);
586
587             let mut found_main = false;
588             let mut found_extern_crate = crate_name.is_none();
589             let mut found_macro = false;
590
591             let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source) {
592                 Ok(p) => p,
593                 Err(errs) => {
594                     drop(errs);
595                     return (found_main, found_extern_crate, found_macro);
596                 }
597             };
598
599             loop {
600                 match parser.parse_item(ForceCollect::No) {
601                     Ok(Some(item)) => {
602                         if !found_main {
603                             if let ast::ItemKind::Fn(..) = item.kind {
604                                 if item.ident.name == sym::main {
605                                     found_main = true;
606                                 }
607                             }
608                         }
609
610                         if !found_extern_crate {
611                             if let ast::ItemKind::ExternCrate(original) = item.kind {
612                                 // This code will never be reached if `crate_name` is none because
613                                 // `found_extern_crate` is initialized to `true` if it is none.
614                                 let crate_name = crate_name.unwrap();
615
616                                 match original {
617                                     Some(name) => found_extern_crate = name.as_str() == crate_name,
618                                     None => found_extern_crate = item.ident.as_str() == crate_name,
619                                 }
620                             }
621                         }
622
623                         if !found_macro {
624                             if let ast::ItemKind::MacCall(..) = item.kind {
625                                 found_macro = true;
626                             }
627                         }
628
629                         if found_main && found_extern_crate {
630                             break;
631                         }
632                     }
633                     Ok(None) => break,
634                     Err(e) => {
635                         e.cancel();
636                         break;
637                     }
638                 }
639
640                 // The supplied slice is only used for diagnostics,
641                 // which are swallowed here anyway.
642                 parser.maybe_consume_incorrect_semicolon(&[]);
643             }
644
645             // Reset errors so that they won't be reported as compiler bugs when dropping the
646             // handler. Any errors in the tests will be reported when the test file is compiled,
647             // Note that we still need to cancel the errors above otherwise `DiagnosticBuilder`
648             // will panic on drop.
649             sess.span_diagnostic.reset_err_count();
650
651             (found_main, found_extern_crate, found_macro)
652         })
653     });
654     let Ok((already_has_main, already_has_extern_crate, found_macro)) = result
655     else {
656         // If the parser panicked due to a fatal error, pass the test code through unchanged.
657         // The error will be reported during compilation.
658         return (s.to_owned(), 0, false);
659     };
660
661     // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
662     // see it. In that case, run the old text-based scan to see if they at least have a main
663     // function written inside a macro invocation. See
664     // https://github.com/rust-lang/rust/issues/56898
665     let already_has_main = if found_macro && !already_has_main {
666         s.lines()
667             .map(|line| {
668                 let comment = line.find("//");
669                 if let Some(comment_begins) = comment { &line[0..comment_begins] } else { line }
670             })
671             .any(|code| code.contains("fn main"))
672     } else {
673         already_has_main
674     };
675
676     // Don't inject `extern crate std` because it's already injected by the
677     // compiler.
678     if !already_has_extern_crate && !opts.no_crate_inject && crate_name != Some("std") {
679         if let Some(crate_name) = crate_name {
680             // Don't inject `extern crate` if the crate is never used.
681             // NOTE: this is terribly inaccurate because it doesn't actually
682             // parse the source, but only has false positives, not false
683             // negatives.
684             if s.contains(crate_name) {
685                 prog.push_str(&format!("extern crate r#{crate_name};\n"));
686                 line_offset += 1;
687             }
688         }
689     }
690
691     // FIXME: This code cannot yet handle no_std test cases yet
692     if dont_insert_main || already_has_main || prog.contains("![no_std]") {
693         prog.push_str(everything_else);
694     } else {
695         let returns_result = everything_else.trim_end().ends_with("(())");
696         // Give each doctest main function a unique name.
697         // This is for example needed for the tooling around `-C instrument-coverage`.
698         let inner_fn_name = if let Some(test_id) = test_id {
699             format!("_doctest_main_{test_id}")
700         } else {
701             "_inner".into()
702         };
703         let inner_attr = if test_id.is_some() { "#[allow(non_snake_case)] " } else { "" };
704         let (main_pre, main_post) = if returns_result {
705             (
706                 format!(
707                     "fn main() {{ {inner_attr}fn {inner_fn_name}() -> Result<(), impl core::fmt::Debug> {{\n",
708                 ),
709                 format!("\n}} {inner_fn_name}().unwrap() }}"),
710             )
711         } else if test_id.is_some() {
712             (
713                 format!("fn main() {{ {inner_attr}fn {inner_fn_name}() {{\n",),
714                 format!("\n}} {inner_fn_name}() }}"),
715             )
716         } else {
717             ("fn main() {\n".into(), "\n}".into())
718         };
719         // Note on newlines: We insert a line/newline *before*, and *after*
720         // the doctest and adjust the `line_offset` accordingly.
721         // In the case of `-C instrument-coverage`, this means that the generated
722         // inner `main` function spans from the doctest opening codeblock to the
723         // closing one. For example
724         // /// ``` <- start of the inner main
725         // /// <- code under doctest
726         // /// ``` <- end of the inner main
727         line_offset += 1;
728
729         prog.extend([&main_pre, everything_else, &main_post].iter().cloned());
730     }
731
732     debug!("final doctest:\n{prog}");
733
734     (prog, line_offset, supports_color)
735 }
736
737 fn check_if_attr_is_complete(source: &str, edition: Edition) -> bool {
738     if source.is_empty() {
739         // Empty content so nothing to check in here...
740         return true;
741     }
742     rustc_driver::catch_fatal_errors(|| {
743         rustc_span::create_session_if_not_set_then(edition, |_| {
744             use rustc_errors::emitter::EmitterWriter;
745             use rustc_errors::Handler;
746             use rustc_span::source_map::FilePathMapping;
747
748             let filename = FileName::anon_source_code(source);
749             // Any errors in parsing should also appear when the doctest is compiled for real, so just
750             // send all the errors that librustc_ast emits directly into a `Sink` instead of stderr.
751             let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
752             let fallback_bundle =
753                 rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
754
755             let emitter = EmitterWriter::new(
756                 Box::new(io::sink()),
757                 None,
758                 None,
759                 fallback_bundle,
760                 false,
761                 false,
762                 false,
763                 None,
764                 false,
765                 false,
766             );
767
768             let handler = Handler::with_emitter(false, None, Box::new(emitter));
769             let sess = ParseSess::with_span_handler(handler, sm);
770             let mut parser =
771                 match maybe_new_parser_from_source_str(&sess, filename, source.to_owned()) {
772                     Ok(p) => p,
773                     Err(_) => {
774                         debug!("Cannot build a parser to check mod attr so skipping...");
775                         return true;
776                     }
777                 };
778             // If a parsing error happened, it's very likely that the attribute is incomplete.
779             if let Err(e) = parser.parse_attribute(InnerAttrPolicy::Permitted) {
780                 e.cancel();
781                 return false;
782             }
783             // We now check if there is an unclosed delimiter for the attribute. To do so, we look at
784             // the `unclosed_delims` and see if the opening square bracket was closed.
785             parser
786                 .unclosed_delims()
787                 .get(0)
788                 .map(|unclosed| {
789                     unclosed.unclosed_span.map(|s| s.lo()).unwrap_or(BytePos(0)) != BytePos(2)
790                 })
791                 .unwrap_or(true)
792         })
793     })
794     .unwrap_or(false)
795 }
796
797 fn partition_source(s: &str, edition: Edition) -> (String, String, String) {
798     #[derive(Copy, Clone, PartialEq)]
799     enum PartitionState {
800         Attrs,
801         Crates,
802         Other,
803     }
804     let mut state = PartitionState::Attrs;
805     let mut before = String::new();
806     let mut crates = String::new();
807     let mut after = String::new();
808
809     let mut mod_attr_pending = String::new();
810
811     for line in s.lines() {
812         let trimline = line.trim();
813
814         // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
815         // shunted into "everything else"
816         match state {
817             PartitionState::Attrs => {
818                 state = if trimline.starts_with("#![") {
819                     if !check_if_attr_is_complete(line, edition) {
820                         mod_attr_pending = line.to_owned();
821                     } else {
822                         mod_attr_pending.clear();
823                     }
824                     PartitionState::Attrs
825                 } else if trimline.chars().all(|c| c.is_whitespace())
826                     || (trimline.starts_with("//") && !trimline.starts_with("///"))
827                 {
828                     PartitionState::Attrs
829                 } else if trimline.starts_with("extern crate")
830                     || trimline.starts_with("#[macro_use] extern crate")
831                 {
832                     PartitionState::Crates
833                 } else {
834                     // First we check if the previous attribute was "complete"...
835                     if !mod_attr_pending.is_empty() {
836                         // If not, then we append the new line into the pending attribute to check
837                         // if this time it's complete...
838                         mod_attr_pending.push_str(line);
839                         if !trimline.is_empty()
840                             && check_if_attr_is_complete(&mod_attr_pending, edition)
841                         {
842                             // If it's complete, then we can clear the pending content.
843                             mod_attr_pending.clear();
844                         }
845                         // In any case, this is considered as `PartitionState::Attrs` so it's
846                         // prepended before rustdoc's inserts.
847                         PartitionState::Attrs
848                     } else {
849                         PartitionState::Other
850                     }
851                 };
852             }
853             PartitionState::Crates => {
854                 state = if trimline.starts_with("extern crate")
855                     || trimline.starts_with("#[macro_use] extern crate")
856                     || trimline.chars().all(|c| c.is_whitespace())
857                     || (trimline.starts_with("//") && !trimline.starts_with("///"))
858                 {
859                     PartitionState::Crates
860                 } else {
861                     PartitionState::Other
862                 };
863             }
864             PartitionState::Other => {}
865         }
866
867         match state {
868             PartitionState::Attrs => {
869                 before.push_str(line);
870                 before.push('\n');
871             }
872             PartitionState::Crates => {
873                 crates.push_str(line);
874                 crates.push('\n');
875             }
876             PartitionState::Other => {
877                 after.push_str(line);
878                 after.push('\n');
879             }
880         }
881     }
882
883     debug!("before:\n{before}");
884     debug!("crates:\n{crates}");
885     debug!("after:\n{after}");
886
887     (before, after, crates)
888 }
889
890 pub(crate) trait Tester {
891     fn add_test(&mut self, test: String, config: LangString, line: usize);
892     fn get_line(&self) -> usize {
893         0
894     }
895     fn register_header(&mut self, _name: &str, _level: u32) {}
896 }
897
898 pub(crate) struct Collector {
899     pub(crate) tests: Vec<test::TestDescAndFn>,
900
901     // The name of the test displayed to the user, separated by `::`.
902     //
903     // In tests from Rust source, this is the path to the item
904     // e.g., `["std", "vec", "Vec", "push"]`.
905     //
906     // In tests from a markdown file, this is the titles of all headers (h1~h6)
907     // of the sections that contain the code block, e.g., if the markdown file is
908     // written as:
909     //
910     // ``````markdown
911     // # Title
912     //
913     // ## Subtitle
914     //
915     // ```rust
916     // assert!(true);
917     // ```
918     // ``````
919     //
920     // the `names` vector of that test will be `["Title", "Subtitle"]`.
921     names: Vec<String>,
922
923     rustdoc_options: RustdocOptions,
924     use_headers: bool,
925     enable_per_target_ignores: bool,
926     crate_name: String,
927     opts: GlobalTestOptions,
928     position: Span,
929     source_map: Option<Lrc<SourceMap>>,
930     filename: Option<PathBuf>,
931     visited_tests: FxHashMap<(String, usize), usize>,
932     unused_extern_reports: Arc<Mutex<Vec<UnusedExterns>>>,
933     compiling_test_count: AtomicUsize,
934 }
935
936 impl Collector {
937     pub(crate) fn new(
938         crate_name: String,
939         rustdoc_options: RustdocOptions,
940         use_headers: bool,
941         opts: GlobalTestOptions,
942         source_map: Option<Lrc<SourceMap>>,
943         filename: Option<PathBuf>,
944         enable_per_target_ignores: bool,
945     ) -> Collector {
946         Collector {
947             tests: Vec::new(),
948             names: Vec::new(),
949             rustdoc_options,
950             use_headers,
951             enable_per_target_ignores,
952             crate_name,
953             opts,
954             position: DUMMY_SP,
955             source_map,
956             filename,
957             visited_tests: FxHashMap::default(),
958             unused_extern_reports: Default::default(),
959             compiling_test_count: AtomicUsize::new(0),
960         }
961     }
962
963     fn generate_name(&self, line: usize, filename: &FileName) -> String {
964         let mut item_path = self.names.join("::");
965         item_path.retain(|c| c != ' ');
966         if !item_path.is_empty() {
967             item_path.push(' ');
968         }
969         format!("{} - {}(line {})", filename.prefer_local(), item_path, line)
970     }
971
972     pub(crate) fn set_position(&mut self, position: Span) {
973         self.position = position;
974     }
975
976     fn get_filename(&self) -> FileName {
977         if let Some(ref source_map) = self.source_map {
978             let filename = source_map.span_to_filename(self.position);
979             if let FileName::Real(ref filename) = filename {
980                 if let Ok(cur_dir) = env::current_dir() {
981                     if let Some(local_path) = filename.local_path() {
982                         if let Ok(path) = local_path.strip_prefix(&cur_dir) {
983                             return path.to_owned().into();
984                         }
985                     }
986                 }
987             }
988             filename
989         } else if let Some(ref filename) = self.filename {
990             filename.clone().into()
991         } else {
992             FileName::Custom("input".to_owned())
993         }
994     }
995 }
996
997 impl Tester for Collector {
998     fn add_test(&mut self, test: String, config: LangString, line: usize) {
999         let filename = self.get_filename();
1000         let name = self.generate_name(line, &filename);
1001         let crate_name = self.crate_name.clone();
1002         let opts = self.opts.clone();
1003         let edition = config.edition.unwrap_or(self.rustdoc_options.edition);
1004         let rustdoc_options = self.rustdoc_options.clone();
1005         let runtool = self.rustdoc_options.runtool.clone();
1006         let runtool_args = self.rustdoc_options.runtool_args.clone();
1007         let target = self.rustdoc_options.target.clone();
1008         let target_str = target.to_string();
1009         let unused_externs = self.unused_extern_reports.clone();
1010         let no_run = config.no_run || rustdoc_options.no_run;
1011         if !config.compile_fail {
1012             self.compiling_test_count.fetch_add(1, Ordering::SeqCst);
1013         }
1014
1015         let path = match &filename {
1016             FileName::Real(path) => {
1017                 if let Some(local_path) = path.local_path() {
1018                     local_path.to_path_buf()
1019                 } else {
1020                     // Somehow we got the filename from the metadata of another crate, should never happen
1021                     unreachable!("doctest from a different crate");
1022                 }
1023             }
1024             _ => PathBuf::from(r"doctest.rs"),
1025         };
1026
1027         // For example `module/file.rs` would become `module_file_rs`
1028         let file = filename
1029             .prefer_local()
1030             .to_string_lossy()
1031             .chars()
1032             .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
1033             .collect::<String>();
1034         let test_id = format!(
1035             "{file}_{line}_{number}",
1036             file = file,
1037             line = line,
1038             number = {
1039                 // Increases the current test number, if this file already
1040                 // exists or it creates a new entry with a test number of 0.
1041                 self.visited_tests.entry((file.clone(), line)).and_modify(|v| *v += 1).or_insert(0)
1042             },
1043         );
1044         let outdir = if let Some(mut path) = rustdoc_options.persist_doctests.clone() {
1045             path.push(&test_id);
1046
1047             if let Err(err) = std::fs::create_dir_all(&path) {
1048                 eprintln!("Couldn't create directory for doctest executables: {}", err);
1049                 panic::resume_unwind(Box::new(()));
1050             }
1051
1052             DirState::Perm(path)
1053         } else {
1054             DirState::Temp(
1055                 TempFileBuilder::new()
1056                     .prefix("rustdoctest")
1057                     .tempdir()
1058                     .expect("rustdoc needs a tempdir"),
1059             )
1060         };
1061
1062         debug!("creating test {name}: {test}");
1063         self.tests.push(test::TestDescAndFn {
1064             desc: test::TestDesc {
1065                 name: test::DynTestName(name),
1066                 ignore: match config.ignore {
1067                     Ignore::All => true,
1068                     Ignore::None => false,
1069                     Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
1070                 },
1071                 ignore_message: None,
1072                 // compiler failures are test failures
1073                 should_panic: test::ShouldPanic::No,
1074                 compile_fail: config.compile_fail,
1075                 no_run,
1076                 test_type: test::TestType::DocTest,
1077             },
1078             testfn: test::DynTestFn(Box::new(move || {
1079                 let report_unused_externs = |uext| {
1080                     unused_externs.lock().unwrap().push(uext);
1081                 };
1082                 let res = run_test(
1083                     &test,
1084                     &crate_name,
1085                     line,
1086                     rustdoc_options,
1087                     config,
1088                     no_run,
1089                     runtool,
1090                     runtool_args,
1091                     target,
1092                     &opts,
1093                     edition,
1094                     outdir,
1095                     path,
1096                     &test_id,
1097                     report_unused_externs,
1098                 );
1099
1100                 if let Err(err) = res {
1101                     match err {
1102                         TestFailure::CompileError => {
1103                             eprint!("Couldn't compile the test.");
1104                         }
1105                         TestFailure::UnexpectedCompilePass => {
1106                             eprint!("Test compiled successfully, but it's marked `compile_fail`.");
1107                         }
1108                         TestFailure::UnexpectedRunPass => {
1109                             eprint!("Test executable succeeded, but it's marked `should_panic`.");
1110                         }
1111                         TestFailure::MissingErrorCodes(codes) => {
1112                             eprint!("Some expected error codes were not found: {:?}", codes);
1113                         }
1114                         TestFailure::ExecutionError(err) => {
1115                             eprint!("Couldn't run the test: {err}");
1116                             if err.kind() == io::ErrorKind::PermissionDenied {
1117                                 eprint!(" - maybe your tempdir is mounted with noexec?");
1118                             }
1119                         }
1120                         TestFailure::ExecutionFailure(out) => {
1121                             eprintln!("Test executable failed ({reason}).", reason = out.status);
1122
1123                             // FIXME(#12309): An unfortunate side-effect of capturing the test
1124                             // executable's output is that the relative ordering between the test's
1125                             // stdout and stderr is lost. However, this is better than the
1126                             // alternative: if the test executable inherited the parent's I/O
1127                             // handles the output wouldn't be captured at all, even on success.
1128                             //
1129                             // The ordering could be preserved if the test process' stderr was
1130                             // redirected to stdout, but that functionality does not exist in the
1131                             // standard library, so it may not be portable enough.
1132                             let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
1133                             let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
1134
1135                             if !stdout.is_empty() || !stderr.is_empty() {
1136                                 eprintln!();
1137
1138                                 if !stdout.is_empty() {
1139                                     eprintln!("stdout:\n{stdout}");
1140                                 }
1141
1142                                 if !stderr.is_empty() {
1143                                     eprintln!("stderr:\n{stderr}");
1144                                 }
1145                             }
1146                         }
1147                     }
1148
1149                     panic::resume_unwind(Box::new(()));
1150                 }
1151                 Ok(())
1152             })),
1153         });
1154     }
1155
1156     fn get_line(&self) -> usize {
1157         if let Some(ref source_map) = self.source_map {
1158             let line = self.position.lo().to_usize();
1159             let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
1160             if line > 0 { line - 1 } else { line }
1161         } else {
1162             0
1163         }
1164     }
1165
1166     fn register_header(&mut self, name: &str, level: u32) {
1167         if self.use_headers {
1168             // We use these headings as test names, so it's good if
1169             // they're valid identifiers.
1170             let name = name
1171                 .chars()
1172                 .enumerate()
1173                 .map(|(i, c)| {
1174                     if (i == 0 && rustc_lexer::is_id_start(c))
1175                         || (i != 0 && rustc_lexer::is_id_continue(c))
1176                     {
1177                         c
1178                     } else {
1179                         '_'
1180                     }
1181                 })
1182                 .collect::<String>();
1183
1184             // Here we try to efficiently assemble the header titles into the
1185             // test name in the form of `h1::h2::h3::h4::h5::h6`.
1186             //
1187             // Suppose that originally `self.names` contains `[h1, h2, h3]`...
1188             let level = level as usize;
1189             if level <= self.names.len() {
1190                 // ... Consider `level == 2`. All headers in the lower levels
1191                 // are irrelevant in this new level. So we should reset
1192                 // `self.names` to contain headers until <h2>, and replace that
1193                 // slot with the new name: `[h1, name]`.
1194                 self.names.truncate(level);
1195                 self.names[level - 1] = name;
1196             } else {
1197                 // ... On the other hand, consider `level == 5`. This means we
1198                 // need to extend `self.names` to contain five headers. We fill
1199                 // in the missing level (<h4>) with `_`. Thus `self.names` will
1200                 // become `[h1, h2, h3, "_", name]`.
1201                 if level - 1 > self.names.len() {
1202                     self.names.resize(level - 1, "_".to_owned());
1203                 }
1204                 self.names.push(name);
1205             }
1206         }
1207     }
1208 }
1209
1210 struct HirCollector<'a, 'hir, 'tcx> {
1211     sess: &'a Session,
1212     collector: &'a mut Collector,
1213     map: Map<'hir>,
1214     codes: ErrorCodes,
1215     tcx: TyCtxt<'tcx>,
1216 }
1217
1218 impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> {
1219     fn visit_testable<F: FnOnce(&mut Self)>(
1220         &mut self,
1221         name: String,
1222         hir_id: HirId,
1223         sp: Span,
1224         nested: F,
1225     ) {
1226         let ast_attrs = self.tcx.hir().attrs(hir_id);
1227         if let Some(ref cfg) = ast_attrs.cfg(self.tcx, &FxHashSet::default()) {
1228             if !cfg.matches(&self.sess.parse_sess, Some(self.sess.features_untracked())) {
1229                 return;
1230             }
1231         }
1232
1233         let has_name = !name.is_empty();
1234         if has_name {
1235             self.collector.names.push(name);
1236         }
1237
1238         // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
1239         // anything else, this will combine them for us.
1240         let attrs = Attributes::from_ast(ast_attrs);
1241         if let Some(doc) = attrs.collapsed_doc_value() {
1242             // Use the outermost invocation, so that doctest names come from where the docs were written.
1243             let span = ast_attrs
1244                 .span()
1245                 .map(|span| span.ctxt().outer_expn().expansion_cause().unwrap_or(span))
1246                 .unwrap_or(DUMMY_SP);
1247             self.collector.set_position(span);
1248             markdown::find_testable_code(
1249                 &doc,
1250                 self.collector,
1251                 self.codes,
1252                 self.collector.enable_per_target_ignores,
1253                 Some(&crate::html::markdown::ExtraInfo::new(
1254                     self.tcx,
1255                     hir_id,
1256                     span_of_attrs(&attrs).unwrap_or(sp),
1257                 )),
1258             );
1259         }
1260
1261         nested(self);
1262
1263         if has_name {
1264             self.collector.names.pop();
1265         }
1266     }
1267 }
1268
1269 impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> {
1270     type NestedFilter = nested_filter::All;
1271
1272     fn nested_visit_map(&mut self) -> Self::Map {
1273         self.map
1274     }
1275
1276     fn visit_item(&mut self, item: &'hir hir::Item<'_>) {
1277         let name = match &item.kind {
1278             hir::ItemKind::Impl(impl_) => {
1279                 rustc_hir_pretty::id_to_string(&self.map, impl_.self_ty.hir_id)
1280             }
1281             _ => item.ident.to_string(),
1282         };
1283
1284         self.visit_testable(name, item.hir_id(), item.span, |this| {
1285             intravisit::walk_item(this, item);
1286         });
1287     }
1288
1289     fn visit_trait_item(&mut self, item: &'hir hir::TraitItem<'_>) {
1290         self.visit_testable(item.ident.to_string(), item.hir_id(), item.span, |this| {
1291             intravisit::walk_trait_item(this, item);
1292         });
1293     }
1294
1295     fn visit_impl_item(&mut self, item: &'hir hir::ImplItem<'_>) {
1296         self.visit_testable(item.ident.to_string(), item.hir_id(), item.span, |this| {
1297             intravisit::walk_impl_item(this, item);
1298         });
1299     }
1300
1301     fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem<'_>) {
1302         self.visit_testable(item.ident.to_string(), item.hir_id(), item.span, |this| {
1303             intravisit::walk_foreign_item(this, item);
1304         });
1305     }
1306
1307     fn visit_variant(&mut self, v: &'hir hir::Variant<'_>) {
1308         self.visit_testable(v.ident.to_string(), v.hir_id, v.span, |this| {
1309             intravisit::walk_variant(this, v);
1310         });
1311     }
1312
1313     fn visit_field_def(&mut self, f: &'hir hir::FieldDef<'_>) {
1314         self.visit_testable(f.ident.to_string(), f.hir_id, f.span, |this| {
1315             intravisit::walk_field_def(this, f);
1316         });
1317     }
1318 }
1319
1320 #[cfg(test)]
1321 mod tests;