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 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>,
250 ) -> Result<(), TestFailure> {
251 let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts, edition);
253 let output_file = outdir.path().join("rust_out");
255 let rustc_binary = options
258 .unwrap_or_else(|| rustc_interface::util::rustc_path().expect("found rustc"));
259 let mut compiler = Command::new(&rustc_binary);
260 compiler.arg("--crate-type").arg("bin");
261 for cfg in &options.cfgs {
262 compiler.arg("--cfg").arg(&cfg);
264 if let Some(sysroot) = options.maybe_sysroot {
265 compiler.arg("--sysroot").arg(sysroot);
267 compiler.arg("--edition").arg(&edition.to_string());
268 compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", path);
269 compiler.env("UNSTABLE_RUSTDOC_TEST_LINE", format!("{}", line as isize - line_offset as isize));
270 compiler.arg("-o").arg(&output_file);
272 compiler.arg("--test");
274 for lib_str in &options.lib_strs {
275 compiler.arg("-L").arg(&lib_str);
277 for extern_str in &options.extern_strs {
278 compiler.arg("--extern").arg(&extern_str);
280 compiler.arg("-Ccodegen-units=1");
281 for codegen_options_str in &options.codegen_options_strs {
282 compiler.arg("-C").arg(&codegen_options_str);
284 for debugging_option_str in &options.debugging_options_strs {
285 compiler.arg("-Z").arg(&debugging_option_str);
287 if no_run && !compile_fail {
288 compiler.arg("--emit=metadata");
290 compiler.arg("--target").arg(match target {
291 TargetTriple::TargetTriple(s) => s,
292 TargetTriple::TargetPath(path) => {
293 path.to_str().expect("target path must be valid unicode").to_string()
298 compiler.stdin(Stdio::piped());
299 compiler.stderr(Stdio::piped());
301 let mut child = compiler.spawn().expect("Failed to spawn rustc process");
303 let stdin = child.stdin.as_mut().expect("Failed to open stdin");
304 stdin.write_all(test.as_bytes()).expect("could write out test sources");
306 let output = child.wait_with_output().expect("Failed to read stdout");
308 struct Bomb<'a>(&'a str);
309 impl Drop for Bomb<'_> {
311 eprint!("{}", self.0);
314 let out = str::from_utf8(&output.stderr).unwrap();
315 let _bomb = Bomb(&out);
316 match (output.status.success(), compile_fail) {
318 return Err(TestFailure::UnexpectedCompilePass);
322 if !error_codes.is_empty() {
323 error_codes.retain(|err| !out.contains(&format!("error[{}]: ", err)));
325 if !error_codes.is_empty() {
326 return Err(TestFailure::MissingErrorCodes(error_codes));
331 return Err(TestFailure::CompileError);
342 if let Some(tool) = runtool {
343 cmd = Command::new(tool);
344 cmd.args(runtool_args);
345 cmd.arg(output_file);
347 cmd = Command::new(output_file);
351 Err(e) => return Err(TestFailure::ExecutionError(e)),
353 if should_panic && out.status.success() {
354 return Err(TestFailure::UnexpectedRunPass);
355 } else if !should_panic && !out.status.success() {
356 return Err(TestFailure::ExecutionFailure(out));
364 /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
365 /// lines before the test code begins.
368 cratename: Option<&str>,
369 dont_insert_main: bool,
372 ) -> (String, usize) {
373 let (crate_attrs, everything_else, crates) = partition_source(s);
374 let everything_else = everything_else.trim();
375 let mut line_offset = 0;
376 let mut prog = String::new();
378 if opts.attrs.is_empty() && !opts.display_warnings {
379 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
380 // lints that are commonly triggered in doctests. The crate-level test attributes are
381 // commonly used to make tests fail in case they trigger warnings, so having this there in
382 // that case may cause some tests to pass when they shouldn't have.
383 prog.push_str("#![allow(unused)]\n");
387 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
388 for attr in &opts.attrs {
389 prog.push_str(&format!("#![{}]\n", attr));
393 // Now push any outer attributes from the example, assuming they
394 // are intended to be crate attributes.
395 prog.push_str(&crate_attrs);
396 prog.push_str(&crates);
398 // Uses librustc_ast to parse the doctest and find if there's a main fn and the extern
399 // crate already is included.
400 let result = rustc_driver::catch_fatal_errors(|| {
401 rustc_span::with_session_globals(edition, || {
402 use rustc_errors::emitter::EmitterWriter;
403 use rustc_errors::Handler;
404 use rustc_parse::maybe_new_parser_from_source_str;
405 use rustc_session::parse::ParseSess;
406 use rustc_span::source_map::FilePathMapping;
408 let filename = FileName::anon_source_code(s);
409 let source = crates + everything_else;
411 // Any errors in parsing should also appear when the doctest is compiled for real, so just
412 // send all the errors that librustc_ast emits directly into a `Sink` instead of stderr.
413 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
415 EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
416 // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
417 let handler = Handler::with_emitter(false, None, box emitter);
418 let sess = ParseSess::with_span_handler(handler, sm);
420 let mut found_main = false;
421 let mut found_extern_crate = cratename.is_none();
422 let mut found_macro = false;
424 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source) {
427 for mut err in errs {
431 return (found_main, found_extern_crate, found_macro);
436 match parser.parse_item() {
439 if let ast::ItemKind::Fn(..) = item.kind {
440 if item.ident.name == sym::main {
446 if !found_extern_crate {
447 if let ast::ItemKind::ExternCrate(original) = item.kind {
448 // This code will never be reached if `cratename` is none because
449 // `found_extern_crate` is initialized to `true` if it is none.
450 let cratename = cratename.unwrap();
453 Some(name) => found_extern_crate = name.as_str() == cratename,
454 None => found_extern_crate = item.ident.as_str() == cratename,
460 if let ast::ItemKind::MacCall(..) = item.kind {
465 if found_main && found_extern_crate {
477 (found_main, found_extern_crate, found_macro)
480 let (already_has_main, already_has_extern_crate, found_macro) = match result {
481 Ok(result) => result,
482 Err(ErrorReported) => {
483 // If the parser panicked due to a fatal error, pass the test code through unchanged.
484 // The error will be reported during compilation.
485 return (s.to_owned(), 0);
489 // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
490 // see it. In that case, run the old text-based scan to see if they at least have a main
491 // function written inside a macro invocation. See
492 // https://github.com/rust-lang/rust/issues/56898
493 let already_has_main = if found_macro && !already_has_main {
496 let comment = line.find("//");
497 if let Some(comment_begins) = comment { &line[0..comment_begins] } else { line }
499 .any(|code| code.contains("fn main"))
504 // Don't inject `extern crate std` because it's already injected by the
506 if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
507 if let Some(cratename) = cratename {
508 // Make sure its actually used if not included.
509 if s.contains(cratename) {
510 prog.push_str(&format!("extern crate {};\n", cratename));
516 // FIXME: This code cannot yet handle no_std test cases yet
517 if dont_insert_main || already_has_main || prog.contains("![no_std]") {
518 prog.push_str(everything_else);
520 let returns_result = everything_else.trim_end().ends_with("(())");
521 let (main_pre, main_post) = if returns_result {
523 "fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
524 "}\n_inner().unwrap() }",
527 ("fn main() {\n", "\n}")
529 prog.extend([main_pre, everything_else, main_post].iter().cloned());
533 debug!("final doctest:\n{}", prog);
538 // FIXME(aburka): use a real parser to deal with multiline attributes
539 fn partition_source(s: &str) -> (String, String, String) {
540 #[derive(Copy, Clone, PartialEq)]
541 enum PartitionState {
546 let mut state = PartitionState::Attrs;
547 let mut before = String::new();
548 let mut crates = String::new();
549 let mut after = String::new();
551 for line in s.lines() {
552 let trimline = line.trim();
554 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
555 // shunted into "everything else"
557 PartitionState::Attrs => {
558 state = if trimline.starts_with("#![")
559 || trimline.chars().all(|c| c.is_whitespace())
560 || (trimline.starts_with("//") && !trimline.starts_with("///"))
562 PartitionState::Attrs
563 } else if trimline.starts_with("extern crate")
564 || trimline.starts_with("#[macro_use] extern crate")
566 PartitionState::Crates
568 PartitionState::Other
571 PartitionState::Crates => {
572 state = if trimline.starts_with("extern crate")
573 || trimline.starts_with("#[macro_use] extern crate")
574 || trimline.chars().all(|c| c.is_whitespace())
575 || (trimline.starts_with("//") && !trimline.starts_with("///"))
577 PartitionState::Crates
579 PartitionState::Other
582 PartitionState::Other => {}
586 PartitionState::Attrs => {
587 before.push_str(line);
588 before.push_str("\n");
590 PartitionState::Crates => {
591 crates.push_str(line);
592 crates.push_str("\n");
594 PartitionState::Other => {
595 after.push_str(line);
596 after.push_str("\n");
601 debug!("before:\n{}", before);
602 debug!("crates:\n{}", crates);
603 debug!("after:\n{}", after);
605 (before, after, crates)
609 fn add_test(&mut self, test: String, config: LangString, line: usize);
610 fn get_line(&self) -> usize {
613 fn register_header(&mut self, _name: &str, _level: u32) {}
616 pub struct Collector {
617 pub tests: Vec<testing::TestDescAndFn>,
619 // The name of the test displayed to the user, separated by `::`.
621 // In tests from Rust source, this is the path to the item
622 // e.g., `["std", "vec", "Vec", "push"]`.
624 // In tests from a markdown file, this is the titles of all headers (h1~h6)
625 // of the sections that contain the code block, e.g., if the markdown file is
638 // the `names` vector of that test will be `["Title", "Subtitle"]`.
643 enable_per_target_ignores: bool,
647 source_map: Option<Lrc<SourceMap>>,
648 filename: Option<PathBuf>,
649 visited_tests: HashMap<(String, usize), usize>,
658 source_map: Option<Lrc<SourceMap>>,
659 filename: Option<PathBuf>,
660 enable_per_target_ignores: bool,
667 enable_per_target_ignores,
673 visited_tests: HashMap::new(),
677 fn generate_name(&self, line: usize, filename: &FileName) -> String {
678 let mut item_path = self.names.join("::");
679 if !item_path.is_empty() {
682 format!("{} - {}(line {})", filename, item_path, line)
685 pub fn set_position(&mut self, position: Span) {
686 self.position = position;
689 fn get_filename(&self) -> FileName {
690 if let Some(ref source_map) = self.source_map {
691 let filename = source_map.span_to_filename(self.position);
692 if let FileName::Real(ref filename) = filename {
693 if let Ok(cur_dir) = env::current_dir() {
694 if let Ok(path) = filename.local_path().strip_prefix(&cur_dir) {
695 return path.to_owned().into();
700 } else if let Some(ref filename) = self.filename {
701 filename.clone().into()
703 FileName::Custom("input".to_owned())
708 impl Tester for Collector {
709 fn add_test(&mut self, test: String, config: LangString, line: usize) {
710 let filename = self.get_filename();
711 let name = self.generate_name(line, &filename);
712 let cratename = self.cratename.to_string();
713 let opts = self.opts.clone();
714 let edition = config.edition.unwrap_or(self.options.edition);
715 let options = self.options.clone();
716 let runtool = self.options.runtool.clone();
717 let runtool_args = self.options.runtool_args.clone();
718 let target = self.options.target.clone();
719 let target_str = target.to_string();
721 // FIXME(#44940): if doctests ever support path remapping, then this filename
722 // needs to be the result of `SourceMap::span_to_unmapped_path`.
723 let path = match &filename {
724 FileName::Real(path) => path.local_path().to_path_buf(),
725 _ => PathBuf::from(r"doctest.rs"),
728 let outdir = if let Some(mut path) = options.persist_doctests.clone() {
729 // For example `module/file.rs` would become `module_file_rs`
730 let folder_name = filename
733 .map(|c| if c == '/' || c == '.' { '_' } else { c })
734 .collect::<String>();
737 "{name}_{line}_{number}",
740 // Increases the current test number, if this file already
741 // exists or it creates a new entry with a test number of 0.
743 .entry((folder_name.clone(), line))
744 .and_modify(|v| *v += 1)
750 std::fs::create_dir_all(&path)
751 .expect("Couldn't create directory for doctest executables");
756 TempFileBuilder::new()
757 .prefix("rustdoctest")
759 .expect("rustdoc needs a tempdir"),
763 debug!("creating test {}: {}", name, test);
764 self.tests.push(testing::TestDescAndFn {
765 desc: testing::TestDesc {
766 name: testing::DynTestName(name),
767 ignore: match config.ignore {
769 Ignore::None => false,
770 Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
772 // compiler failures are test failures
773 should_panic: testing::ShouldPanic::No,
774 allow_fail: config.allow_fail,
775 test_type: testing::TestType::DocTest,
777 testfn: testing::DynTestFn(box move || {
797 if let Err(err) = res {
799 TestFailure::CompileError => {
800 eprint!("Couldn't compile the test.");
802 TestFailure::UnexpectedCompilePass => {
803 eprint!("Test compiled successfully, but it's marked `compile_fail`.");
805 TestFailure::UnexpectedRunPass => {
806 eprint!("Test executable succeeded, but it's marked `should_panic`.");
808 TestFailure::MissingErrorCodes(codes) => {
809 eprint!("Some expected error codes were not found: {:?}", codes);
811 TestFailure::ExecutionError(err) => {
812 eprint!("Couldn't run the test: {}", err);
813 if err.kind() == io::ErrorKind::PermissionDenied {
814 eprint!(" - maybe your tempdir is mounted with noexec?");
817 TestFailure::ExecutionFailure(out) => {
818 let reason = if let Some(code) = out.status.code() {
819 format!("exit code {}", code)
821 String::from("terminated by signal")
824 eprintln!("Test executable failed ({}).", reason);
826 // FIXME(#12309): An unfortunate side-effect of capturing the test
827 // executable's output is that the relative ordering between the test's
828 // stdout and stderr is lost. However, this is better than the
829 // alternative: if the test executable inherited the parent's I/O
830 // handles the output wouldn't be captured at all, even on success.
832 // The ordering could be preserved if the test process' stderr was
833 // redirected to stdout, but that functionality does not exist in the
834 // standard library, so it may not be portable enough.
835 let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
836 let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
838 if !stdout.is_empty() || !stderr.is_empty() {
841 if !stdout.is_empty() {
842 eprintln!("stdout:\n{}", stdout);
845 if !stderr.is_empty() {
846 eprintln!("stderr:\n{}", stderr);
852 panic::resume_unwind(box ());
858 fn get_line(&self) -> usize {
859 if let Some(ref source_map) = self.source_map {
860 let line = self.position.lo().to_usize();
861 let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
862 if line > 0 { line - 1 } else { line }
868 fn register_header(&mut self, name: &str, level: u32) {
869 if self.use_headers {
870 // We use these headings as test names, so it's good if
871 // they're valid identifiers.
876 if (i == 0 && rustc_lexer::is_id_start(c))
877 || (i != 0 && rustc_lexer::is_id_continue(c))
884 .collect::<String>();
886 // Here we try to efficiently assemble the header titles into the
887 // test name in the form of `h1::h2::h3::h4::h5::h6`.
889 // Suppose that originally `self.names` contains `[h1, h2, h3]`...
890 let level = level as usize;
891 if level <= self.names.len() {
892 // ... Consider `level == 2`. All headers in the lower levels
893 // are irrelevant in this new level. So we should reset
894 // `self.names` to contain headers until <h2>, and replace that
895 // slot with the new name: `[h1, name]`.
896 self.names.truncate(level);
897 self.names[level - 1] = name;
899 // ... On the other hand, consider `level == 5`. This means we
900 // need to extend `self.names` to contain five headers. We fill
901 // in the missing level (<h4>) with `_`. Thus `self.names` will
902 // become `[h1, h2, h3, "_", name]`.
903 if level - 1 > self.names.len() {
904 self.names.resize(level - 1, "_".to_owned());
906 self.names.push(name);
912 struct HirCollector<'a, 'hir, 'tcx> {
914 collector: &'a mut Collector,
920 impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> {
921 fn visit_testable<F: FnOnce(&mut Self)>(
924 attrs: &[ast::Attribute],
929 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
930 if let Some(ref cfg) = attrs.cfg {
931 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
936 let has_name = !name.is_empty();
938 self.collector.names.push(name);
941 attrs.collapse_doc_comments();
942 attrs.unindent_doc_comments();
943 // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
944 // anything else, this will combine them for us.
945 if let Some(doc) = attrs.collapsed_doc_value() {
946 // Use the outermost invocation, so that doctest names come from where the docs were written.
949 .map(|span| span.ctxt().outer_expn().expansion_cause().unwrap_or(span))
950 .unwrap_or(DUMMY_SP);
951 self.collector.set_position(span);
952 markdown::find_testable_code(
956 self.collector.enable_per_target_ignores,
957 Some(&crate::html::markdown::ExtraInfo::new(
960 span_of_attrs(&attrs).unwrap_or(sp),
968 self.collector.names.pop();
973 impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> {
974 type Map = Map<'hir>;
976 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
977 intravisit::NestedVisitorMap::All(self.map)
980 fn visit_item(&mut self, item: &'hir hir::Item<'_>) {
981 let name = if let hir::ItemKind::Impl { ref self_ty, .. } = item.kind {
982 rustc_hir_pretty::id_to_string(&self.map, self_ty.hir_id)
984 item.ident.to_string()
987 self.visit_testable(name, &item.attrs, item.hir_id, item.span, |this| {
988 intravisit::walk_item(this, item);
992 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem<'_>) {
993 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
994 intravisit::walk_trait_item(this, item);
998 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem<'_>) {
999 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1000 intravisit::walk_impl_item(this, item);
1004 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem<'_>) {
1005 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1006 intravisit::walk_foreign_item(this, item);
1012 v: &'hir hir::Variant<'_>,
1013 g: &'hir hir::Generics<'_>,
1014 item_id: hir::HirId,
1016 self.visit_testable(v.ident.to_string(), &v.attrs, v.id, v.span, |this| {
1017 intravisit::walk_variant(this, v, g, item_id);
1021 fn visit_struct_field(&mut self, f: &'hir hir::StructField<'_>) {
1022 self.visit_testable(f.ident.to_string(), &f.attrs, f.hir_id, f.span, |this| {
1023 intravisit::walk_struct_field(this, f);
1027 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef<'_>) {
1028 self.visit_testable(
1029 macro_def.ident.to_string(),