2 use rustc_data_structures::fx::FxHashMap;
3 use rustc_data_structures::sync::Lrc;
4 use rustc_errors::{ColorConfig, ErrorReported};
6 use rustc_hir::intravisit;
7 use rustc_hir::{HirId, CRATE_HIR_ID};
8 use rustc_interface::interface;
9 use rustc_middle::hir::map::Map;
10 use rustc_middle::ty::TyCtxt;
11 use rustc_session::config::{self, CrateType, ErrorOutputType};
12 use rustc_session::{lint, DiagnosticOutput, Session};
13 use rustc_span::edition::Edition;
14 use rustc_span::source_map::SourceMap;
15 use rustc_span::symbol::sym;
16 use rustc_span::{BytePos, FileName, Pos, Span, DUMMY_SP};
17 use rustc_target::spec::TargetTriple;
18 use tempfile::Builder as TempFileBuilder;
21 use std::io::{self, Write};
23 use std::path::PathBuf;
24 use std::process::{self, Command, Stdio};
27 use crate::clean::Attributes;
28 use crate::config::Options;
29 use crate::core::init_lints;
30 use crate::html::markdown::{self, ErrorCodes, Ignore, LangString};
31 use crate::passes::span_of_attrs;
33 #[derive(Clone, Default)]
34 crate struct TestOptions {
35 /// Whether to disable the default `extern crate my_crate;` when creating doctests.
36 crate no_crate_inject: bool,
37 /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
38 /// the default `#![allow(unused)]`.
39 crate display_warnings: bool,
40 /// Additional crate-level attributes to add to doctests.
41 crate attrs: Vec<String>,
44 crate fn run(options: Options) -> Result<(), ErrorReported> {
45 let input = config::Input::File(options.input.clone());
47 let invalid_codeblock_attributes_name = rustc_lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES.name;
49 // In addition to those specific lints, we also need to allow those given through
50 // command line, otherwise they'll get ignored and we don't want that.
51 let allowed_lints = vec![invalid_codeblock_attributes_name.to_owned()];
53 let (lint_opts, lint_caps) = init_lints(allowed_lints, options.lint_opts.clone(), |lint| {
54 if lint.name == invalid_codeblock_attributes_name {
57 Some((lint.name_lower(), lint::Allow))
62 if options.proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
64 let sessopts = config::Options {
65 maybe_sysroot: options.maybe_sysroot.clone(),
66 search_paths: options.libs.clone(),
68 lint_opts: if !options.display_warnings { lint_opts } else { vec![] },
69 lint_cap: Some(options.lint_cap.clone().unwrap_or_else(|| lint::Forbid)),
70 cg: options.codegen_options.clone(),
71 externs: options.externs.clone(),
72 unstable_features: options.render_options.unstable_features,
73 actually_rustdoc: true,
74 debugging_opts: config::DebuggingOptions { ..config::basic_debugging_options() },
75 edition: options.edition,
76 target_triple: options.target.clone(),
77 crate_name: options.crate_name.clone(),
78 ..config::Options::default()
81 let mut cfgs = options.cfgs.clone();
82 cfgs.push("doc".to_owned());
83 cfgs.push("doctest".to_owned());
84 let config = interface::Config {
86 crate_cfg: interface::parse_cfgspecs(cfgs),
92 diagnostic_output: DiagnosticOutput::Default,
96 override_queries: None,
97 make_codegen_backend: None,
98 registry: rustc_driver::diagnostics_registry(),
101 let mut test_args = options.test_args.clone();
102 let display_warnings = options.display_warnings;
104 let tests = interface::run_compiler(config, |compiler| {
105 compiler.enter(|queries| {
106 let lower_to_hir = queries.lower_to_hir()?;
108 let mut opts = scrape_test_config(lower_to_hir.peek().0);
109 opts.display_warnings |= options.display_warnings;
110 let enable_per_target_ignores = options.enable_per_target_ignores;
111 let mut collector = Collector::new(
112 queries.crate_name()?.peek().to_string(),
116 Some(compiler.session().parse_sess.clone_source_map()),
118 enable_per_target_ignores,
121 let mut global_ctxt = queries.global_ctxt()?.take();
123 global_ctxt.enter(|tcx| {
124 let krate = tcx.hir().krate();
126 let mut hir_collector = HirCollector {
127 sess: compiler.session(),
128 collector: &mut collector,
130 codes: ErrorCodes::from(
131 compiler.session().opts.unstable_features.is_nightly_build(),
135 hir_collector.visit_testable(
141 intravisit::walk_crate(this, krate);
145 compiler.session().abort_if_errors();
147 let ret: Result<_, ErrorReported> = Ok(collector.tests);
151 let tests = match tests {
153 Err(ErrorReported) => return Err(ErrorReported),
156 test_args.insert(0, "rustdoctest".to_string());
161 Some(testing::Options::new().display_output(display_warnings)),
167 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
168 fn scrape_test_config(krate: &::rustc_hir::Crate<'_>) -> TestOptions {
169 use rustc_ast_pretty::pprust;
172 TestOptions { no_crate_inject: false, display_warnings: false, attrs: Vec::new() };
174 let test_attrs: Vec<_> = krate
178 .filter(|a| a.has_name(sym::doc))
179 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
180 .filter(|a| a.has_name(sym::test))
182 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
185 if attr.has_name(sym::no_crate_inject) {
186 opts.no_crate_inject = true;
188 if attr.has_name(sym::attr) {
189 if let Some(l) = attr.meta_item_list() {
191 opts.attrs.push(pprust::meta_list_item_to_string(item));
200 /// Documentation test failure modes.
202 /// The test failed to compile.
204 /// The test is marked `compile_fail` but compiled successfully.
205 UnexpectedCompilePass,
206 /// The test failed to compile (as expected) but the compiler output did not contain all
207 /// expected error codes.
208 MissingErrorCodes(Vec<String>),
209 /// The test binary was unable to be executed.
210 ExecutionError(io::Error),
211 /// The test binary exited with a non-zero exit code.
213 /// This typically means an assertion in the test failed or another form of panic occurred.
214 ExecutionFailure(process::Output),
215 /// The test is marked `should_panic` but the test binary executed successfully.
220 Temp(tempfile::TempDir),
225 fn path(&self) -> &std::path::Path {
227 DirState::Temp(t) => t.path(),
228 DirState::Perm(p) => p.as_path(),
240 as_test_harness: bool,
241 runtool: Option<String>,
242 runtool_args: Vec<String>,
243 target: TargetTriple,
245 mut error_codes: Vec<String>,
251 ) -> Result<(), TestFailure> {
252 let (test, line_offset, supports_color) =
253 make_test(test, Some(cratename), as_test_harness, opts, edition, Some(test_id));
255 let output_file = outdir.path().join("rust_out");
257 let rustc_binary = options
260 .unwrap_or_else(|| rustc_interface::util::rustc_path().expect("found rustc"));
261 let mut compiler = Command::new(&rustc_binary);
262 compiler.arg("--crate-type").arg("bin");
263 for cfg in &options.cfgs {
264 compiler.arg("--cfg").arg(&cfg);
266 if let Some(sysroot) = options.maybe_sysroot {
267 compiler.arg("--sysroot").arg(sysroot);
269 compiler.arg("--edition").arg(&edition.to_string());
270 compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", path);
271 compiler.env("UNSTABLE_RUSTDOC_TEST_LINE", format!("{}", line as isize - line_offset as isize));
272 compiler.arg("-o").arg(&output_file);
274 compiler.arg("--test");
276 for lib_str in &options.lib_strs {
277 compiler.arg("-L").arg(&lib_str);
279 for extern_str in &options.extern_strs {
280 compiler.arg("--extern").arg(&extern_str);
282 compiler.arg("-Ccodegen-units=1");
283 for codegen_options_str in &options.codegen_options_strs {
284 compiler.arg("-C").arg(&codegen_options_str);
286 for debugging_option_str in &options.debugging_opts_strs {
287 compiler.arg("-Z").arg(&debugging_option_str);
289 if no_run && !compile_fail {
290 compiler.arg("--emit=metadata");
292 compiler.arg("--target").arg(match target {
293 TargetTriple::TargetTriple(s) => s,
294 TargetTriple::TargetPath(path) => {
295 path.to_str().expect("target path must be valid unicode").to_string()
298 if let ErrorOutputType::HumanReadable(kind) = options.error_format {
299 let (_, color_config) = kind.unzip();
301 ColorConfig::Never => {
302 compiler.arg("--color").arg("never");
304 ColorConfig::Always => {
305 compiler.arg("--color").arg("always");
307 ColorConfig::Auto => {
308 compiler.arg("--color").arg(if supports_color { "always" } else { "never" });
314 compiler.stdin(Stdio::piped());
315 compiler.stderr(Stdio::piped());
317 let mut child = compiler.spawn().expect("Failed to spawn rustc process");
319 let stdin = child.stdin.as_mut().expect("Failed to open stdin");
320 stdin.write_all(test.as_bytes()).expect("could write out test sources");
322 let output = child.wait_with_output().expect("Failed to read stdout");
324 struct Bomb<'a>(&'a str);
325 impl Drop for Bomb<'_> {
327 eprint!("{}", self.0);
330 let out = str::from_utf8(&output.stderr).unwrap();
331 let _bomb = Bomb(&out);
332 match (output.status.success(), compile_fail) {
334 return Err(TestFailure::UnexpectedCompilePass);
338 if !error_codes.is_empty() {
339 // We used to check if the output contained "error[{}]: " but since we added the
340 // colored output, we can't anymore because of the color escape characters before
342 error_codes.retain(|err| !out.contains(&format!("error[{}]", err)));
344 if !error_codes.is_empty() {
345 return Err(TestFailure::MissingErrorCodes(error_codes));
350 return Err(TestFailure::CompileError);
361 if let Some(tool) = runtool {
362 cmd = Command::new(tool);
363 cmd.args(runtool_args);
364 cmd.arg(output_file);
366 cmd = Command::new(output_file);
368 if let Some(run_directory) = options.test_run_directory {
369 cmd.current_dir(run_directory);
373 Err(e) => return Err(TestFailure::ExecutionError(e)),
375 if should_panic && out.status.success() {
376 return Err(TestFailure::UnexpectedRunPass);
377 } else if !should_panic && !out.status.success() {
378 return Err(TestFailure::ExecutionFailure(out));
386 /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
387 /// lines before the test code begins as well as if the output stream supports colors or not.
390 cratename: Option<&str>,
391 dont_insert_main: bool,
394 test_id: Option<&str>,
395 ) -> (String, usize, bool) {
396 let (crate_attrs, everything_else, crates) = partition_source(s);
397 let everything_else = everything_else.trim();
398 let mut line_offset = 0;
399 let mut prog = String::new();
400 let mut supports_color = false;
402 if opts.attrs.is_empty() && !opts.display_warnings {
403 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
404 // lints that are commonly triggered in doctests. The crate-level test attributes are
405 // commonly used to make tests fail in case they trigger warnings, so having this there in
406 // that case may cause some tests to pass when they shouldn't have.
407 prog.push_str("#![allow(unused)]\n");
411 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
412 for attr in &opts.attrs {
413 prog.push_str(&format!("#![{}]\n", attr));
417 // Now push any outer attributes from the example, assuming they
418 // are intended to be crate attributes.
419 prog.push_str(&crate_attrs);
420 prog.push_str(&crates);
422 // Uses librustc_ast to parse the doctest and find if there's a main fn and the extern
423 // crate already is included.
424 let result = rustc_driver::catch_fatal_errors(|| {
425 rustc_span::with_session_globals(edition, || {
426 use rustc_errors::emitter::{Emitter, EmitterWriter};
427 use rustc_errors::Handler;
428 use rustc_parse::maybe_new_parser_from_source_str;
429 use rustc_parse::parser::ForceCollect;
430 use rustc_session::parse::ParseSess;
431 use rustc_span::source_map::FilePathMapping;
433 let filename = FileName::anon_source_code(s);
434 let source = crates + everything_else;
436 // Any errors in parsing should also appear when the doctest is compiled for real, so just
437 // send all the errors that librustc_ast emits directly into a `Sink` instead of stderr.
438 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
440 EmitterWriter::stderr(ColorConfig::Auto, None, false, false, Some(80), false)
444 EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
446 // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
447 let handler = Handler::with_emitter(false, None, box emitter);
448 let sess = ParseSess::with_span_handler(handler, sm);
450 let mut found_main = false;
451 let mut found_extern_crate = cratename.is_none();
452 let mut found_macro = false;
454 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source) {
457 for mut err in errs {
461 return (found_main, found_extern_crate, found_macro);
466 match parser.parse_item(ForceCollect::No) {
469 if let ast::ItemKind::Fn(..) = item.kind {
470 if item.ident.name == sym::main {
476 if !found_extern_crate {
477 if let ast::ItemKind::ExternCrate(original) = item.kind {
478 // This code will never be reached if `cratename` is none because
479 // `found_extern_crate` is initialized to `true` if it is none.
480 let cratename = cratename.unwrap();
483 Some(name) => found_extern_crate = name.as_str() == cratename,
484 None => found_extern_crate = item.ident.as_str() == cratename,
490 if let ast::ItemKind::MacCall(..) = item.kind {
495 if found_main && found_extern_crate {
507 // Reset errors so that they won't be reported as compiler bugs when dropping the
508 // handler. Any errors in the tests will be reported when the test file is compiled,
509 // Note that we still need to cancel the errors above otherwise `DiagnosticBuilder`
510 // will panic on drop.
511 sess.span_diagnostic.reset_err_count();
513 (found_main, found_extern_crate, found_macro)
516 let (already_has_main, already_has_extern_crate, found_macro) = match result {
517 Ok(result) => result,
518 Err(ErrorReported) => {
519 // If the parser panicked due to a fatal error, pass the test code through unchanged.
520 // The error will be reported during compilation.
521 return (s.to_owned(), 0, false);
525 // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
526 // see it. In that case, run the old text-based scan to see if they at least have a main
527 // function written inside a macro invocation. See
528 // https://github.com/rust-lang/rust/issues/56898
529 let already_has_main = if found_macro && !already_has_main {
532 let comment = line.find("//");
533 if let Some(comment_begins) = comment { &line[0..comment_begins] } else { line }
535 .any(|code| code.contains("fn main"))
540 // Don't inject `extern crate std` because it's already injected by the
542 if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
543 if let Some(cratename) = cratename {
544 // Make sure its actually used if not included.
545 if s.contains(cratename) {
546 prog.push_str(&format!("extern crate {};\n", cratename));
552 // FIXME: This code cannot yet handle no_std test cases yet
553 if dont_insert_main || already_has_main || prog.contains("![no_std]") {
554 prog.push_str(everything_else);
556 let returns_result = everything_else.trim_end().ends_with("(())");
557 // Give each doctest main function a unique name.
558 // This is for example needed for the tooling around `-Z instrument-coverage`.
559 let inner_fn_name = if let Some(test_id) = test_id {
560 format!("_doctest_main_{}", test_id)
564 let inner_attr = if test_id.is_some() { "#[allow(non_snake_case)] " } else { "" };
565 let (main_pre, main_post) = if returns_result {
568 "fn main() {{ {}fn {}() -> Result<(), impl core::fmt::Debug> {{\n",
569 inner_attr, inner_fn_name
571 format!("\n}} {}().unwrap() }}", inner_fn_name),
573 } else if test_id.is_some() {
575 format!("fn main() {{ {}fn {}() {{\n", inner_attr, inner_fn_name),
576 format!("\n}} {}() }}", inner_fn_name),
579 ("fn main() {\n".into(), "\n}".into())
581 // Note on newlines: We insert a line/newline *before*, and *after*
582 // the doctest and adjust the `line_offset` accordingly.
583 // In the case of `-Z instrument-coverage`, this means that the generated
584 // inner `main` function spans from the doctest opening codeblock to the
585 // closing one. For example
586 // /// ``` <- start of the inner main
587 // /// <- code under doctest
588 // /// ``` <- end of the inner main
591 prog.extend([&main_pre, everything_else, &main_post].iter().cloned());
594 debug!("final doctest:\n{}", prog);
596 (prog, line_offset, supports_color)
599 // FIXME(aburka): use a real parser to deal with multiline attributes
600 fn partition_source(s: &str) -> (String, String, String) {
601 #[derive(Copy, Clone, PartialEq)]
602 enum PartitionState {
607 let mut state = PartitionState::Attrs;
608 let mut before = String::new();
609 let mut crates = String::new();
610 let mut after = String::new();
612 for line in s.lines() {
613 let trimline = line.trim();
615 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
616 // shunted into "everything else"
618 PartitionState::Attrs => {
619 state = if trimline.starts_with("#![")
620 || trimline.chars().all(|c| c.is_whitespace())
621 || (trimline.starts_with("//") && !trimline.starts_with("///"))
623 PartitionState::Attrs
624 } else if trimline.starts_with("extern crate")
625 || trimline.starts_with("#[macro_use] extern crate")
627 PartitionState::Crates
629 PartitionState::Other
632 PartitionState::Crates => {
633 state = if trimline.starts_with("extern crate")
634 || trimline.starts_with("#[macro_use] extern crate")
635 || trimline.chars().all(|c| c.is_whitespace())
636 || (trimline.starts_with("//") && !trimline.starts_with("///"))
638 PartitionState::Crates
640 PartitionState::Other
643 PartitionState::Other => {}
647 PartitionState::Attrs => {
648 before.push_str(line);
651 PartitionState::Crates => {
652 crates.push_str(line);
655 PartitionState::Other => {
656 after.push_str(line);
662 debug!("before:\n{}", before);
663 debug!("crates:\n{}", crates);
664 debug!("after:\n{}", after);
666 (before, after, crates)
670 fn add_test(&mut self, test: String, config: LangString, line: usize);
671 fn get_line(&self) -> usize {
674 fn register_header(&mut self, _name: &str, _level: u32) {}
677 crate struct Collector {
678 crate tests: Vec<testing::TestDescAndFn>,
680 // The name of the test displayed to the user, separated by `::`.
682 // In tests from Rust source, this is the path to the item
683 // e.g., `["std", "vec", "Vec", "push"]`.
685 // In tests from a markdown file, this is the titles of all headers (h1~h6)
686 // of the sections that contain the code block, e.g., if the markdown file is
699 // the `names` vector of that test will be `["Title", "Subtitle"]`.
704 enable_per_target_ignores: bool,
708 source_map: Option<Lrc<SourceMap>>,
709 filename: Option<PathBuf>,
710 visited_tests: FxHashMap<(String, usize), usize>,
719 source_map: Option<Lrc<SourceMap>>,
720 filename: Option<PathBuf>,
721 enable_per_target_ignores: bool,
728 enable_per_target_ignores,
734 visited_tests: FxHashMap::default(),
738 fn generate_name(&self, line: usize, filename: &FileName) -> String {
739 let mut item_path = self.names.join("::");
740 if !item_path.is_empty() {
743 format!("{} - {}(line {})", filename, item_path, line)
746 crate fn set_position(&mut self, position: Span) {
747 self.position = position;
750 fn get_filename(&self) -> FileName {
751 if let Some(ref source_map) = self.source_map {
752 let filename = source_map.span_to_filename(self.position);
753 if let FileName::Real(ref filename) = filename {
754 if let Ok(cur_dir) = env::current_dir() {
755 if let Ok(path) = filename.local_path().strip_prefix(&cur_dir) {
756 return path.to_owned().into();
761 } else if let Some(ref filename) = self.filename {
762 filename.clone().into()
764 FileName::Custom("input".to_owned())
769 impl Tester for Collector {
770 fn add_test(&mut self, test: String, config: LangString, line: usize) {
771 let filename = self.get_filename();
772 let name = self.generate_name(line, &filename);
773 let cratename = self.cratename.to_string();
774 let opts = self.opts.clone();
775 let edition = config.edition.unwrap_or(self.options.edition);
776 let options = self.options.clone();
777 let runtool = self.options.runtool.clone();
778 let runtool_args = self.options.runtool_args.clone();
779 let target = self.options.target.clone();
780 let target_str = target.to_string();
782 // FIXME(#44940): if doctests ever support path remapping, then this filename
783 // needs to be the result of `SourceMap::span_to_unmapped_path`.
784 let path = match &filename {
785 FileName::Real(path) => path.local_path().to_path_buf(),
786 _ => PathBuf::from(r"doctest.rs"),
789 // For example `module/file.rs` would become `module_file_rs`
793 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
794 .collect::<String>();
795 let test_id = format!(
796 "{file}_{line}_{number}",
800 // Increases the current test number, if this file already
801 // exists or it creates a new entry with a test number of 0.
802 self.visited_tests.entry((file.clone(), line)).and_modify(|v| *v += 1).or_insert(0)
805 let outdir = if let Some(mut path) = options.persist_doctests.clone() {
808 std::fs::create_dir_all(&path)
809 .expect("Couldn't create directory for doctest executables");
814 TempFileBuilder::new()
815 .prefix("rustdoctest")
817 .expect("rustdoc needs a tempdir"),
821 debug!("creating test {}: {}", name, test);
822 self.tests.push(testing::TestDescAndFn {
823 desc: testing::TestDesc {
824 name: testing::DynTestName(name),
825 ignore: match config.ignore {
827 Ignore::None => false,
828 Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
830 // compiler failures are test failures
831 should_panic: testing::ShouldPanic::No,
832 allow_fail: config.allow_fail,
833 test_type: testing::TestType::DocTest,
835 testfn: testing::DynTestFn(box move || {
856 if let Err(err) = res {
858 TestFailure::CompileError => {
859 eprint!("Couldn't compile the test.");
861 TestFailure::UnexpectedCompilePass => {
862 eprint!("Test compiled successfully, but it's marked `compile_fail`.");
864 TestFailure::UnexpectedRunPass => {
865 eprint!("Test executable succeeded, but it's marked `should_panic`.");
867 TestFailure::MissingErrorCodes(codes) => {
868 eprint!("Some expected error codes were not found: {:?}", codes);
870 TestFailure::ExecutionError(err) => {
871 eprint!("Couldn't run the test: {}", err);
872 if err.kind() == io::ErrorKind::PermissionDenied {
873 eprint!(" - maybe your tempdir is mounted with noexec?");
876 TestFailure::ExecutionFailure(out) => {
877 let reason = if let Some(code) = out.status.code() {
878 format!("exit code {}", code)
880 String::from("terminated by signal")
883 eprintln!("Test executable failed ({}).", reason);
885 // FIXME(#12309): An unfortunate side-effect of capturing the test
886 // executable's output is that the relative ordering between the test's
887 // stdout and stderr is lost. However, this is better than the
888 // alternative: if the test executable inherited the parent's I/O
889 // handles the output wouldn't be captured at all, even on success.
891 // The ordering could be preserved if the test process' stderr was
892 // redirected to stdout, but that functionality does not exist in the
893 // standard library, so it may not be portable enough.
894 let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
895 let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
897 if !stdout.is_empty() || !stderr.is_empty() {
900 if !stdout.is_empty() {
901 eprintln!("stdout:\n{}", stdout);
904 if !stderr.is_empty() {
905 eprintln!("stderr:\n{}", stderr);
911 panic::resume_unwind(box ());
917 fn get_line(&self) -> usize {
918 if let Some(ref source_map) = self.source_map {
919 let line = self.position.lo().to_usize();
920 let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
921 if line > 0 { line - 1 } else { line }
927 fn register_header(&mut self, name: &str, level: u32) {
928 if self.use_headers {
929 // We use these headings as test names, so it's good if
930 // they're valid identifiers.
935 if (i == 0 && rustc_lexer::is_id_start(c))
936 || (i != 0 && rustc_lexer::is_id_continue(c))
943 .collect::<String>();
945 // Here we try to efficiently assemble the header titles into the
946 // test name in the form of `h1::h2::h3::h4::h5::h6`.
948 // Suppose that originally `self.names` contains `[h1, h2, h3]`...
949 let level = level as usize;
950 if level <= self.names.len() {
951 // ... Consider `level == 2`. All headers in the lower levels
952 // are irrelevant in this new level. So we should reset
953 // `self.names` to contain headers until <h2>, and replace that
954 // slot with the new name: `[h1, name]`.
955 self.names.truncate(level);
956 self.names[level - 1] = name;
958 // ... On the other hand, consider `level == 5`. This means we
959 // need to extend `self.names` to contain five headers. We fill
960 // in the missing level (<h4>) with `_`. Thus `self.names` will
961 // become `[h1, h2, h3, "_", name]`.
962 if level - 1 > self.names.len() {
963 self.names.resize(level - 1, "_".to_owned());
965 self.names.push(name);
971 struct HirCollector<'a, 'hir, 'tcx> {
973 collector: &'a mut Collector,
979 impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> {
980 fn visit_testable<F: FnOnce(&mut Self)>(
983 attrs: &[ast::Attribute],
988 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs, None);
989 if let Some(ref cfg) = attrs.cfg {
990 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
995 let has_name = !name.is_empty();
997 self.collector.names.push(name);
1000 attrs.unindent_doc_comments();
1001 // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
1002 // anything else, this will combine them for us.
1003 if let Some(doc) = attrs.collapsed_doc_value() {
1004 // Use the outermost invocation, so that doctest names come from where the docs were written.
1007 .map(|span| span.ctxt().outer_expn().expansion_cause().unwrap_or(span))
1008 .unwrap_or(DUMMY_SP);
1009 self.collector.set_position(span);
1010 markdown::find_testable_code(
1014 self.collector.enable_per_target_ignores,
1015 Some(&crate::html::markdown::ExtraInfo::new(
1018 span_of_attrs(&attrs).unwrap_or(sp),
1026 self.collector.names.pop();
1031 impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> {
1032 type Map = Map<'hir>;
1034 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1035 intravisit::NestedVisitorMap::All(self.map)
1038 fn visit_item(&mut self, item: &'hir hir::Item<'_>) {
1039 let name = if let hir::ItemKind::Impl(impl_) = &item.kind {
1040 rustc_hir_pretty::id_to_string(&self.map, impl_.self_ty.hir_id)
1042 item.ident.to_string()
1045 self.visit_testable(name, &item.attrs, item.hir_id, item.span, |this| {
1046 intravisit::walk_item(this, item);
1050 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem<'_>) {
1051 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1052 intravisit::walk_trait_item(this, item);
1056 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem<'_>) {
1057 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1058 intravisit::walk_impl_item(this, item);
1062 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem<'_>) {
1063 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1064 intravisit::walk_foreign_item(this, item);
1070 v: &'hir hir::Variant<'_>,
1071 g: &'hir hir::Generics<'_>,
1072 item_id: hir::HirId,
1074 self.visit_testable(v.ident.to_string(), &v.attrs, v.id, v.span, |this| {
1075 intravisit::walk_variant(this, v, g, item_id);
1079 fn visit_struct_field(&mut self, f: &'hir hir::StructField<'_>) {
1080 self.visit_testable(f.ident.to_string(), &f.attrs, f.hir_id, f.span, |this| {
1081 intravisit::walk_struct_field(this, f);
1085 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef<'_>) {
1086 self.visit_testable(
1087 macro_def.ident.to_string(),