2 use rustc_data_structures::sync::Lrc;
3 use rustc_errors::ErrorReported;
4 use rustc_feature::UnstableFeatures;
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};
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;
20 use std::collections::HashMap;
22 use std::io::{self, Write};
24 use std::path::PathBuf;
25 use std::process::{self, Command, Stdio};
28 use crate::clean::Attributes;
29 use crate::config::Options;
30 use crate::core::init_lints;
31 use crate::html::markdown::{self, ErrorCodes, Ignore, LangString};
32 use crate::passes::span_of_attrs;
34 #[derive(Clone, Default)]
35 pub struct TestOptions {
36 /// Whether to disable the default `extern crate my_crate;` when creating doctests.
37 pub no_crate_inject: bool,
38 /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
39 /// the default `#![allow(unused)]`.
40 pub display_warnings: bool,
41 /// Additional crate-level attributes to add to doctests.
42 pub attrs: Vec<String>,
45 pub fn run(options: Options) -> Result<(), ErrorReported> {
46 let input = config::Input::File(options.input.clone());
48 let invalid_codeblock_attributes_name = rustc_lint::builtin::INVALID_CODEBLOCK_ATTRIBUTES.name;
50 // In addition to those specific lints, we also need to allow those given through
51 // command line, otherwise they'll get ignored and we don't want that.
52 let allowed_lints = vec![invalid_codeblock_attributes_name.to_owned()];
54 let (lint_opts, lint_caps) = init_lints(allowed_lints, options.lint_opts.clone(), |lint| {
55 if lint.name == invalid_codeblock_attributes_name {
58 Some((lint.name_lower(), lint::Allow))
63 if options.proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
65 let sessopts = config::Options {
66 maybe_sysroot: options.maybe_sysroot.clone(),
67 search_paths: options.libs.clone(),
69 lint_opts: if !options.display_warnings { lint_opts } else { vec![] },
70 lint_cap: Some(options.lint_cap.clone().unwrap_or_else(|| lint::Forbid)),
71 cg: options.codegen_options.clone(),
72 externs: options.externs.clone(),
73 unstable_features: UnstableFeatures::from_environment(),
74 actually_rustdoc: true,
75 debugging_opts: config::DebuggingOptions { ..config::basic_debugging_options() },
76 edition: options.edition,
77 target_triple: options.target.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,
94 crate_name: options.crate_name.clone(),
97 override_queries: None,
98 make_codegen_backend: None,
99 registry: rustc_driver::diagnostics_registry(),
102 let mut test_args = options.test_args.clone();
103 let display_warnings = options.display_warnings;
105 let tests = interface::run_compiler(config, |compiler| {
106 compiler.enter(|queries| {
107 let lower_to_hir = queries.lower_to_hir()?;
109 let mut opts = scrape_test_config(lower_to_hir.peek().0);
110 opts.display_warnings |= options.display_warnings;
111 let enable_per_target_ignores = options.enable_per_target_ignores;
112 let mut collector = Collector::new(
113 queries.crate_name()?.peek().to_string(),
117 Some(compiler.session().parse_sess.clone_source_map()),
119 enable_per_target_ignores,
122 let mut global_ctxt = queries.global_ctxt()?.take();
124 global_ctxt.enter(|tcx| {
125 let krate = tcx.hir().krate();
127 let mut hir_collector = HirCollector {
128 sess: compiler.session(),
129 collector: &mut collector,
131 codes: ErrorCodes::from(
132 compiler.session().opts.unstable_features.is_nightly_build(),
136 hir_collector.visit_testable(
142 intravisit::walk_crate(this, krate);
146 compiler.session().abort_if_errors();
148 let ret: Result<_, ErrorReported> = Ok(collector.tests);
152 let tests = match tests {
154 Err(ErrorReported) => return Err(ErrorReported),
157 test_args.insert(0, "rustdoctest".to_string());
162 Some(testing::Options::new().display_output(display_warnings)),
168 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
169 fn scrape_test_config(krate: &::rustc_hir::Crate<'_>) -> TestOptions {
170 use rustc_ast_pretty::pprust;
173 TestOptions { no_crate_inject: false, display_warnings: false, attrs: Vec::new() };
175 let test_attrs: Vec<_> = krate
179 .filter(|a| a.has_name(sym::doc))
180 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
181 .filter(|a| a.has_name(sym::test))
183 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
186 if attr.has_name(sym::no_crate_inject) {
187 opts.no_crate_inject = true;
189 if attr.has_name(sym::attr) {
190 if let Some(l) = attr.meta_item_list() {
192 opts.attrs.push(pprust::meta_list_item_to_string(item));
201 /// Documentation test failure modes.
203 /// The test failed to compile.
205 /// The test is marked `compile_fail` but compiled successfully.
206 UnexpectedCompilePass,
207 /// The test failed to compile (as expected) but the compiler output did not contain all
208 /// expected error codes.
209 MissingErrorCodes(Vec<String>),
210 /// The test binary was unable to be executed.
211 ExecutionError(io::Error),
212 /// The test binary exited with a non-zero exit code.
214 /// This typically means an assertion in the test failed or another form of panic occurred.
215 ExecutionFailure(process::Output),
216 /// The test is marked `should_panic` but the test binary executed successfully.
221 Temp(tempfile::TempDir),
226 fn path(&self) -> &std::path::Path {
228 DirState::Temp(t) => t.path(),
229 DirState::Perm(p) => p.as_path(),
241 as_test_harness: bool,
242 runtool: Option<String>,
243 runtool_args: Vec<String>,
244 target: TargetTriple,
246 mut error_codes: Vec<String>,
251 ) -> Result<(), TestFailure> {
252 let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts, edition);
254 let output_file = outdir.path().join("rust_out");
256 let rustc_binary = options
259 .unwrap_or_else(|| rustc_interface::util::rustc_path().expect("found rustc"));
260 let mut compiler = Command::new(&rustc_binary);
261 compiler.arg("--crate-type").arg("bin");
262 for cfg in &options.cfgs {
263 compiler.arg("--cfg").arg(&cfg);
265 if let Some(sysroot) = options.maybe_sysroot {
266 compiler.arg("--sysroot").arg(sysroot);
268 compiler.arg("--edition").arg(&edition.to_string());
269 compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", path);
270 compiler.env("UNSTABLE_RUSTDOC_TEST_LINE", format!("{}", line as isize - line_offset as isize));
271 compiler.arg("-o").arg(&output_file);
273 compiler.arg("--test");
275 for lib_str in &options.lib_strs {
276 compiler.arg("-L").arg(&lib_str);
278 for extern_str in &options.extern_strs {
279 compiler.arg("--extern").arg(&extern_str);
281 compiler.arg("-Ccodegen-units=1");
282 for codegen_options_str in &options.codegen_options_strs {
283 compiler.arg("-C").arg(&codegen_options_str);
285 for debugging_option_str in &options.debugging_opts_strs {
286 compiler.arg("-Z").arg(&debugging_option_str);
288 if no_run && !compile_fail {
289 compiler.arg("--emit=metadata");
291 compiler.arg("--target").arg(match target {
292 TargetTriple::TargetTriple(s) => s,
293 TargetTriple::TargetPath(path) => {
294 path.to_str().expect("target path must be valid unicode").to_string()
299 compiler.stdin(Stdio::piped());
300 compiler.stderr(Stdio::piped());
302 let mut child = compiler.spawn().expect("Failed to spawn rustc process");
304 let stdin = child.stdin.as_mut().expect("Failed to open stdin");
305 stdin.write_all(test.as_bytes()).expect("could write out test sources");
307 let output = child.wait_with_output().expect("Failed to read stdout");
309 struct Bomb<'a>(&'a str);
310 impl Drop for Bomb<'_> {
312 eprint!("{}", self.0);
315 let out = str::from_utf8(&output.stderr).unwrap();
316 let _bomb = Bomb(&out);
317 match (output.status.success(), compile_fail) {
319 return Err(TestFailure::UnexpectedCompilePass);
323 if !error_codes.is_empty() {
324 error_codes.retain(|err| !out.contains(&format!("error[{}]: ", err)));
326 if !error_codes.is_empty() {
327 return Err(TestFailure::MissingErrorCodes(error_codes));
332 return Err(TestFailure::CompileError);
343 if let Some(tool) = runtool {
344 cmd = Command::new(tool);
345 cmd.args(runtool_args);
346 cmd.arg(output_file);
348 cmd = Command::new(output_file);
352 Err(e) => return Err(TestFailure::ExecutionError(e)),
354 if should_panic && out.status.success() {
355 return Err(TestFailure::UnexpectedRunPass);
356 } else if !should_panic && !out.status.success() {
357 return Err(TestFailure::ExecutionFailure(out));
365 /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
366 /// lines before the test code begins.
369 cratename: Option<&str>,
370 dont_insert_main: bool,
373 ) -> (String, usize) {
374 let (crate_attrs, everything_else, crates) = partition_source(s);
375 let everything_else = everything_else.trim();
376 let mut line_offset = 0;
377 let mut prog = String::new();
379 if opts.attrs.is_empty() && !opts.display_warnings {
380 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
381 // lints that are commonly triggered in doctests. The crate-level test attributes are
382 // commonly used to make tests fail in case they trigger warnings, so having this there in
383 // that case may cause some tests to pass when they shouldn't have.
384 prog.push_str("#![allow(unused)]\n");
388 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
389 for attr in &opts.attrs {
390 prog.push_str(&format!("#![{}]\n", attr));
394 // Now push any outer attributes from the example, assuming they
395 // are intended to be crate attributes.
396 prog.push_str(&crate_attrs);
397 prog.push_str(&crates);
399 // Uses librustc_ast to parse the doctest and find if there's a main fn and the extern
400 // crate already is included.
401 let result = rustc_driver::catch_fatal_errors(|| {
402 rustc_span::with_session_globals(edition, || {
403 use rustc_errors::emitter::EmitterWriter;
404 use rustc_errors::Handler;
405 use rustc_parse::maybe_new_parser_from_source_str;
406 use rustc_session::parse::ParseSess;
407 use rustc_span::source_map::FilePathMapping;
409 let filename = FileName::anon_source_code(s);
410 let source = crates + everything_else;
412 // Any errors in parsing should also appear when the doctest is compiled for real, so just
413 // send all the errors that librustc_ast emits directly into a `Sink` instead of stderr.
414 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
416 EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
417 // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
418 let handler = Handler::with_emitter(false, None, box emitter);
419 let sess = ParseSess::with_span_handler(handler, sm);
421 let mut found_main = false;
422 let mut found_extern_crate = cratename.is_none();
423 let mut found_macro = false;
425 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source) {
428 for mut err in errs {
432 return (found_main, found_extern_crate, found_macro);
437 match parser.parse_item() {
440 if let ast::ItemKind::Fn(..) = item.kind {
441 if item.ident.name == sym::main {
447 if !found_extern_crate {
448 if let ast::ItemKind::ExternCrate(original) = item.kind {
449 // This code will never be reached if `cratename` is none because
450 // `found_extern_crate` is initialized to `true` if it is none.
451 let cratename = cratename.unwrap();
454 Some(name) => found_extern_crate = name.as_str() == cratename,
455 None => found_extern_crate = item.ident.as_str() == cratename,
461 if let ast::ItemKind::MacCall(..) = item.kind {
466 if found_main && found_extern_crate {
478 (found_main, found_extern_crate, found_macro)
481 let (already_has_main, already_has_extern_crate, found_macro) = match result {
482 Ok(result) => result,
483 Err(ErrorReported) => {
484 // If the parser panicked due to a fatal error, pass the test code through unchanged.
485 // The error will be reported during compilation.
486 return (s.to_owned(), 0);
490 // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
491 // see it. In that case, run the old text-based scan to see if they at least have a main
492 // function written inside a macro invocation. See
493 // https://github.com/rust-lang/rust/issues/56898
494 let already_has_main = if found_macro && !already_has_main {
497 let comment = line.find("//");
498 if let Some(comment_begins) = comment { &line[0..comment_begins] } else { line }
500 .any(|code| code.contains("fn main"))
505 // Don't inject `extern crate std` because it's already injected by the
507 if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
508 if let Some(cratename) = cratename {
509 // Make sure its actually used if not included.
510 if s.contains(cratename) {
511 prog.push_str(&format!("extern crate {};\n", cratename));
517 // FIXME: This code cannot yet handle no_std test cases yet
518 if dont_insert_main || already_has_main || prog.contains("![no_std]") {
519 prog.push_str(everything_else);
521 let returns_result = everything_else.trim_end().ends_with("(())");
522 let (main_pre, main_post) = if returns_result {
524 "fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
525 "}\n_inner().unwrap() }",
528 ("fn main() {\n", "\n}")
530 prog.extend([main_pre, everything_else, main_post].iter().cloned());
534 debug!("final doctest:\n{}", prog);
539 // FIXME(aburka): use a real parser to deal with multiline attributes
540 fn partition_source(s: &str) -> (String, String, String) {
541 #[derive(Copy, Clone, PartialEq)]
542 enum PartitionState {
547 let mut state = PartitionState::Attrs;
548 let mut before = String::new();
549 let mut crates = String::new();
550 let mut after = String::new();
552 for line in s.lines() {
553 let trimline = line.trim();
555 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
556 // shunted into "everything else"
558 PartitionState::Attrs => {
559 state = if trimline.starts_with("#![")
560 || trimline.chars().all(|c| c.is_whitespace())
561 || (trimline.starts_with("//") && !trimline.starts_with("///"))
563 PartitionState::Attrs
564 } else if trimline.starts_with("extern crate")
565 || trimline.starts_with("#[macro_use] extern crate")
567 PartitionState::Crates
569 PartitionState::Other
572 PartitionState::Crates => {
573 state = if trimline.starts_with("extern crate")
574 || trimline.starts_with("#[macro_use] extern crate")
575 || trimline.chars().all(|c| c.is_whitespace())
576 || (trimline.starts_with("//") && !trimline.starts_with("///"))
578 PartitionState::Crates
580 PartitionState::Other
583 PartitionState::Other => {}
587 PartitionState::Attrs => {
588 before.push_str(line);
589 before.push_str("\n");
591 PartitionState::Crates => {
592 crates.push_str(line);
593 crates.push_str("\n");
595 PartitionState::Other => {
596 after.push_str(line);
597 after.push_str("\n");
602 debug!("before:\n{}", before);
603 debug!("crates:\n{}", crates);
604 debug!("after:\n{}", after);
606 (before, after, crates)
610 fn add_test(&mut self, test: String, config: LangString, line: usize);
611 fn get_line(&self) -> usize {
614 fn register_header(&mut self, _name: &str, _level: u32) {}
617 pub struct Collector {
618 pub tests: Vec<testing::TestDescAndFn>,
620 // The name of the test displayed to the user, separated by `::`.
622 // In tests from Rust source, this is the path to the item
623 // e.g., `["std", "vec", "Vec", "push"]`.
625 // In tests from a markdown file, this is the titles of all headers (h1~h6)
626 // of the sections that contain the code block, e.g., if the markdown file is
639 // the `names` vector of that test will be `["Title", "Subtitle"]`.
644 enable_per_target_ignores: bool,
648 source_map: Option<Lrc<SourceMap>>,
649 filename: Option<PathBuf>,
650 visited_tests: HashMap<(String, usize), usize>,
659 source_map: Option<Lrc<SourceMap>>,
660 filename: Option<PathBuf>,
661 enable_per_target_ignores: bool,
668 enable_per_target_ignores,
674 visited_tests: HashMap::new(),
678 fn generate_name(&self, line: usize, filename: &FileName) -> String {
679 let mut item_path = self.names.join("::");
680 if !item_path.is_empty() {
683 format!("{} - {}(line {})", filename, item_path, line)
686 pub fn set_position(&mut self, position: Span) {
687 self.position = position;
690 fn get_filename(&self) -> FileName {
691 if let Some(ref source_map) = self.source_map {
692 let filename = source_map.span_to_filename(self.position);
693 if let FileName::Real(ref filename) = filename {
694 if let Ok(cur_dir) = env::current_dir() {
695 if let Ok(path) = filename.local_path().strip_prefix(&cur_dir) {
696 return path.to_owned().into();
701 } else if let Some(ref filename) = self.filename {
702 filename.clone().into()
704 FileName::Custom("input".to_owned())
709 impl Tester for Collector {
710 fn add_test(&mut self, test: String, config: LangString, line: usize) {
711 let filename = self.get_filename();
712 let name = self.generate_name(line, &filename);
713 let cratename = self.cratename.to_string();
714 let opts = self.opts.clone();
715 let edition = config.edition.unwrap_or(self.options.edition);
716 let options = self.options.clone();
717 let runtool = self.options.runtool.clone();
718 let runtool_args = self.options.runtool_args.clone();
719 let target = self.options.target.clone();
720 let target_str = target.to_string();
722 // FIXME(#44940): if doctests ever support path remapping, then this filename
723 // needs to be the result of `SourceMap::span_to_unmapped_path`.
724 let path = match &filename {
725 FileName::Real(path) => path.local_path().to_path_buf(),
726 _ => PathBuf::from(r"doctest.rs"),
729 let outdir = if let Some(mut path) = options.persist_doctests.clone() {
730 // For example `module/file.rs` would become `module_file_rs`
731 let folder_name = filename
734 .map(|c| if c == '/' || c == '.' { '_' } else { c })
735 .collect::<String>();
738 "{name}_{line}_{number}",
741 // Increases the current test number, if this file already
742 // exists or it creates a new entry with a test number of 0.
744 .entry((folder_name.clone(), line))
745 .and_modify(|v| *v += 1)
751 std::fs::create_dir_all(&path)
752 .expect("Couldn't create directory for doctest executables");
757 TempFileBuilder::new()
758 .prefix("rustdoctest")
760 .expect("rustdoc needs a tempdir"),
764 debug!("creating test {}: {}", name, test);
765 self.tests.push(testing::TestDescAndFn {
766 desc: testing::TestDesc {
767 name: testing::DynTestName(name),
768 ignore: match config.ignore {
770 Ignore::None => false,
771 Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
773 // compiler failures are test failures
774 should_panic: testing::ShouldPanic::No,
775 allow_fail: config.allow_fail,
776 test_type: testing::TestType::DocTest,
778 testfn: testing::DynTestFn(box move || {
798 if let Err(err) = res {
800 TestFailure::CompileError => {
801 eprint!("Couldn't compile the test.");
803 TestFailure::UnexpectedCompilePass => {
804 eprint!("Test compiled successfully, but it's marked `compile_fail`.");
806 TestFailure::UnexpectedRunPass => {
807 eprint!("Test executable succeeded, but it's marked `should_panic`.");
809 TestFailure::MissingErrorCodes(codes) => {
810 eprint!("Some expected error codes were not found: {:?}", codes);
812 TestFailure::ExecutionError(err) => {
813 eprint!("Couldn't run the test: {}", err);
814 if err.kind() == io::ErrorKind::PermissionDenied {
815 eprint!(" - maybe your tempdir is mounted with noexec?");
818 TestFailure::ExecutionFailure(out) => {
819 let reason = if let Some(code) = out.status.code() {
820 format!("exit code {}", code)
822 String::from("terminated by signal")
825 eprintln!("Test executable failed ({}).", reason);
827 // FIXME(#12309): An unfortunate side-effect of capturing the test
828 // executable's output is that the relative ordering between the test's
829 // stdout and stderr is lost. However, this is better than the
830 // alternative: if the test executable inherited the parent's I/O
831 // handles the output wouldn't be captured at all, even on success.
833 // The ordering could be preserved if the test process' stderr was
834 // redirected to stdout, but that functionality does not exist in the
835 // standard library, so it may not be portable enough.
836 let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
837 let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
839 if !stdout.is_empty() || !stderr.is_empty() {
842 if !stdout.is_empty() {
843 eprintln!("stdout:\n{}", stdout);
846 if !stderr.is_empty() {
847 eprintln!("stderr:\n{}", stderr);
853 panic::resume_unwind(box ());
859 fn get_line(&self) -> usize {
860 if let Some(ref source_map) = self.source_map {
861 let line = self.position.lo().to_usize();
862 let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
863 if line > 0 { line - 1 } else { line }
869 fn register_header(&mut self, name: &str, level: u32) {
870 if self.use_headers {
871 // We use these headings as test names, so it's good if
872 // they're valid identifiers.
877 if (i == 0 && rustc_lexer::is_id_start(c))
878 || (i != 0 && rustc_lexer::is_id_continue(c))
885 .collect::<String>();
887 // Here we try to efficiently assemble the header titles into the
888 // test name in the form of `h1::h2::h3::h4::h5::h6`.
890 // Suppose that originally `self.names` contains `[h1, h2, h3]`...
891 let level = level as usize;
892 if level <= self.names.len() {
893 // ... Consider `level == 2`. All headers in the lower levels
894 // are irrelevant in this new level. So we should reset
895 // `self.names` to contain headers until <h2>, and replace that
896 // slot with the new name: `[h1, name]`.
897 self.names.truncate(level);
898 self.names[level - 1] = name;
900 // ... On the other hand, consider `level == 5`. This means we
901 // need to extend `self.names` to contain five headers. We fill
902 // in the missing level (<h4>) with `_`. Thus `self.names` will
903 // become `[h1, h2, h3, "_", name]`.
904 if level - 1 > self.names.len() {
905 self.names.resize(level - 1, "_".to_owned());
907 self.names.push(name);
913 struct HirCollector<'a, 'hir, 'tcx> {
915 collector: &'a mut Collector,
921 impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> {
922 fn visit_testable<F: FnOnce(&mut Self)>(
925 attrs: &[ast::Attribute],
930 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs, None);
931 if let Some(ref cfg) = attrs.cfg {
932 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
937 let has_name = !name.is_empty();
939 self.collector.names.push(name);
942 attrs.collapse_doc_comments();
943 attrs.unindent_doc_comments();
944 // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
945 // anything else, this will combine them for us.
946 if let Some(doc) = attrs.collapsed_doc_value() {
947 // Use the outermost invocation, so that doctest names come from where the docs were written.
950 .map(|span| span.ctxt().outer_expn().expansion_cause().unwrap_or(span))
951 .unwrap_or(DUMMY_SP);
952 self.collector.set_position(span);
953 markdown::find_testable_code(
957 self.collector.enable_per_target_ignores,
958 Some(&crate::html::markdown::ExtraInfo::new(
961 span_of_attrs(&attrs).unwrap_or(sp),
969 self.collector.names.pop();
974 impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> {
975 type Map = Map<'hir>;
977 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
978 intravisit::NestedVisitorMap::All(self.map)
981 fn visit_item(&mut self, item: &'hir hir::Item<'_>) {
982 let name = if let hir::ItemKind::Impl { ref self_ty, .. } = item.kind {
983 rustc_hir_pretty::id_to_string(&self.map, self_ty.hir_id)
985 item.ident.to_string()
988 self.visit_testable(name, &item.attrs, item.hir_id, item.span, |this| {
989 intravisit::walk_item(this, item);
993 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem<'_>) {
994 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
995 intravisit::walk_trait_item(this, item);
999 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem<'_>) {
1000 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1001 intravisit::walk_impl_item(this, item);
1005 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem<'_>) {
1006 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1007 intravisit::walk_foreign_item(this, item);
1013 v: &'hir hir::Variant<'_>,
1014 g: &'hir hir::Generics<'_>,
1015 item_id: hir::HirId,
1017 self.visit_testable(v.ident.to_string(), &v.attrs, v.id, v.span, |this| {
1018 intravisit::walk_variant(this, v, g, item_id);
1022 fn visit_struct_field(&mut self, f: &'hir hir::StructField<'_>) {
1023 self.visit_testable(f.ident.to_string(), &f.attrs, f.hir_id, f.span, |this| {
1024 intravisit::walk_struct_field(this, f);
1028 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef<'_>) {
1029 self.visit_testable(
1030 macro_def.ident.to_string(),