2 use rustc_ast::with_globals;
3 use rustc_data_structures::sync::Lrc;
4 use rustc_errors::ErrorReported;
5 use rustc_feature::UnstableFeatures;
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::ty::TyCtxt;
12 use rustc_session::{self, config, 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 std::collections::HashMap;
20 use std::io::{self, Write};
22 use std::path::PathBuf;
23 use std::process::{self, Command, Stdio};
25 use tempfile::Builder as TempFileBuilder;
27 use crate::clean::Attributes;
28 use crate::config::Options;
29 use crate::html::markdown::{self, ErrorCodes, Ignore, LangString};
30 use crate::passes::span_of_attrs;
32 #[derive(Clone, Default)]
33 pub struct TestOptions {
34 /// Whether to disable the default `extern crate my_crate;` when creating doctests.
35 pub no_crate_inject: bool,
36 /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
37 /// the default `#![allow(unused)]`.
38 pub display_warnings: bool,
39 /// Additional crate-level attributes to add to doctests.
40 pub attrs: Vec<String>,
43 pub fn run(options: Options) -> i32 {
44 let input = config::Input::File(options.input.clone());
46 let warnings_lint_name = lint::builtin::WARNINGS.name;
47 let invalid_codeblock_attribute_name = rustc_lint::builtin::INVALID_CODEBLOCK_ATTRIBUTE.name;
49 // In addition to those specific lints, we also need to whitelist those given through
50 // command line, otherwise they'll get ignored and we don't want that.
51 let mut whitelisted_lints =
52 vec![warnings_lint_name.to_owned(), invalid_codeblock_attribute_name.to_owned()];
54 whitelisted_lints.extend(options.lint_opts.iter().map(|(lint, _)| lint).cloned());
57 lint::builtin::HardwiredLints::get_lints()
59 .chain(rustc_lint::SoftLints::get_lints().into_iter())
62 let lint_opts = lints()
64 if lint.name == warnings_lint_name || lint.name == invalid_codeblock_attribute_name {
67 Some((lint.name_lower(), lint::Allow))
70 .chain(options.lint_opts.clone().into_iter())
73 let lint_caps = lints()
75 // We don't want to whitelist *all* lints so let's
77 if whitelisted_lints.iter().any(|l| lint.name == l) {
80 Some((lint::LintId::of(lint), lint::Allow))
85 let crate_types = if options.proc_macro_crate {
86 vec![config::CrateType::ProcMacro]
88 vec![config::CrateType::Rlib]
91 let sessopts = config::Options {
92 maybe_sysroot: options.maybe_sysroot.clone(),
93 search_paths: options.libs.clone(),
95 lint_opts: if !options.display_warnings { lint_opts } else { vec![] },
96 lint_cap: Some(options.lint_cap.clone().unwrap_or_else(|| lint::Forbid)),
97 cg: options.codegen_options.clone(),
98 externs: options.externs.clone(),
99 unstable_features: UnstableFeatures::from_environment(),
100 actually_rustdoc: true,
101 debugging_opts: config::DebuggingOptions { ..config::basic_debugging_options() },
102 edition: options.edition,
103 target_triple: options.target.clone(),
104 ..config::Options::default()
107 let mut cfgs = options.cfgs.clone();
108 cfgs.push("doc".to_owned());
109 cfgs.push("doctest".to_owned());
110 let config = interface::Config {
112 crate_cfg: interface::parse_cfgspecs(cfgs),
118 diagnostic_output: DiagnosticOutput::Default,
120 crate_name: options.crate_name.clone(),
122 register_lints: None,
123 override_queries: None,
124 registry: rustc_driver::diagnostics_registry(),
127 let mut test_args = options.test_args.clone();
128 let display_warnings = options.display_warnings;
130 let tests = interface::run_compiler(config, |compiler| {
131 compiler.enter(|queries| {
132 let lower_to_hir = queries.lower_to_hir()?;
134 let mut opts = scrape_test_config(lower_to_hir.peek().0);
135 opts.display_warnings |= options.display_warnings;
136 let enable_per_target_ignores = options.enable_per_target_ignores;
137 let mut collector = Collector::new(
138 queries.crate_name()?.peek().to_string(),
142 Some(compiler.source_map().clone()),
144 enable_per_target_ignores,
147 let mut global_ctxt = queries.global_ctxt()?.take();
149 global_ctxt.enter(|tcx| {
150 let krate = tcx.hir().krate();
152 let mut hir_collector = HirCollector {
153 sess: compiler.session(),
154 collector: &mut collector,
156 codes: ErrorCodes::from(
157 compiler.session().opts.unstable_features.is_nightly_build(),
161 hir_collector.visit_testable(
167 intravisit::walk_crate(this, krate);
171 compiler.session().abort_if_errors();
173 let ret: Result<_, ErrorReported> = Ok(collector.tests);
177 let tests = match tests {
179 Err(ErrorReported) => return 1,
182 test_args.insert(0, "rustdoctest".to_string());
187 Some(testing::Options::new().display_output(display_warnings)),
193 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
194 fn scrape_test_config(krate: &::rustc_hir::Crate) -> TestOptions {
195 use rustc_ast_pretty::pprust;
198 TestOptions { no_crate_inject: false, display_warnings: false, attrs: Vec::new() };
200 let test_attrs: Vec<_> = krate
204 .filter(|a| a.check_name(sym::doc))
205 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
206 .filter(|a| a.check_name(sym::test))
208 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
211 if attr.check_name(sym::no_crate_inject) {
212 opts.no_crate_inject = true;
214 if attr.check_name(sym::attr) {
215 if let Some(l) = attr.meta_item_list() {
217 opts.attrs.push(pprust::meta_list_item_to_string(item));
226 /// Documentation test failure modes.
228 /// The test failed to compile.
230 /// The test is marked `compile_fail` but compiled successfully.
231 UnexpectedCompilePass,
232 /// The test failed to compile (as expected) but the compiler output did not contain all
233 /// expected error codes.
234 MissingErrorCodes(Vec<String>),
235 /// The test binary was unable to be executed.
236 ExecutionError(io::Error),
237 /// The test binary exited with a non-zero exit code.
239 /// This typically means an assertion in the test failed or another form of panic occurred.
240 ExecutionFailure(process::Output),
241 /// The test is marked `should_panic` but the test binary executed successfully.
246 Temp(tempfile::TempDir),
251 fn path(&self) -> &std::path::Path {
253 DirState::Temp(t) => t.path(),
254 DirState::Perm(p) => p.as_path(),
266 as_test_harness: bool,
267 runtool: Option<String>,
268 runtool_args: Vec<String>,
269 target: TargetTriple,
271 mut error_codes: Vec<String>,
276 ) -> Result<(), TestFailure> {
277 let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts, edition);
279 let output_file = outdir.path().join("rust_out");
281 let rustc_binary = options
285 .unwrap_or_else(|| rustc_interface::util::rustc_path().expect("found rustc"));
286 let mut compiler = Command::new(&rustc_binary);
287 compiler.arg("--crate-type").arg("bin");
288 for cfg in &options.cfgs {
289 compiler.arg("--cfg").arg(&cfg);
291 if let Some(sysroot) = options.maybe_sysroot {
292 compiler.arg("--sysroot").arg(sysroot);
294 compiler.arg("--edition").arg(&edition.to_string());
295 compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", path);
296 compiler.env("UNSTABLE_RUSTDOC_TEST_LINE", format!("{}", line as isize - line_offset as isize));
297 compiler.arg("-o").arg(&output_file);
299 compiler.arg("--test");
301 for lib_str in &options.lib_strs {
302 compiler.arg("-L").arg(&lib_str);
304 for extern_str in &options.extern_strs {
305 compiler.arg("--extern").arg(&extern_str);
307 compiler.arg("-Ccodegen-units=1");
308 for codegen_options_str in &options.codegen_options_strs {
309 compiler.arg("-C").arg(&codegen_options_str);
311 for debugging_option_str in &options.debugging_options_strs {
312 compiler.arg("-Z").arg(&debugging_option_str);
314 if no_run && !compile_fail {
315 compiler.arg("--emit=metadata");
317 compiler.arg("--target").arg(match target {
318 TargetTriple::TargetTriple(s) => s,
319 TargetTriple::TargetPath(path) => {
320 path.to_str().expect("target path must be valid unicode").to_string()
325 compiler.stdin(Stdio::piped());
326 compiler.stderr(Stdio::piped());
328 let mut child = compiler.spawn().expect("Failed to spawn rustc process");
330 let stdin = child.stdin.as_mut().expect("Failed to open stdin");
331 stdin.write_all(test.as_bytes()).expect("could write out test sources");
333 let output = child.wait_with_output().expect("Failed to read stdout");
335 struct Bomb<'a>(&'a str);
336 impl Drop for Bomb<'_> {
338 eprint!("{}", self.0);
341 let out = str::from_utf8(&output.stderr).unwrap();
342 let _bomb = Bomb(&out);
343 match (output.status.success(), compile_fail) {
345 return Err(TestFailure::UnexpectedCompilePass);
349 if !error_codes.is_empty() {
350 error_codes.retain(|err| !out.contains(&format!("error[{}]: ", err)));
352 if !error_codes.is_empty() {
353 return Err(TestFailure::MissingErrorCodes(error_codes));
358 return Err(TestFailure::CompileError);
369 if let Some(tool) = runtool {
370 cmd = Command::new(tool);
371 cmd.args(runtool_args);
372 cmd.arg(output_file);
374 cmd = Command::new(output_file);
378 Err(e) => return Err(TestFailure::ExecutionError(e)),
380 if should_panic && out.status.success() {
381 return Err(TestFailure::UnexpectedRunPass);
382 } else if !should_panic && !out.status.success() {
383 return Err(TestFailure::ExecutionFailure(out));
391 /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
392 /// lines before the test code begins.
395 cratename: Option<&str>,
396 dont_insert_main: bool,
399 ) -> (String, usize) {
400 let (crate_attrs, everything_else, crates) = partition_source(s);
401 let everything_else = everything_else.trim();
402 let mut line_offset = 0;
403 let mut prog = String::new();
405 if opts.attrs.is_empty() && !opts.display_warnings {
406 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
407 // lints that are commonly triggered in doctests. The crate-level test attributes are
408 // commonly used to make tests fail in case they trigger warnings, so having this there in
409 // that case may cause some tests to pass when they shouldn't have.
410 prog.push_str("#![allow(unused)]\n");
414 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
415 for attr in &opts.attrs {
416 prog.push_str(&format!("#![{}]\n", attr));
420 // Now push any outer attributes from the example, assuming they
421 // are intended to be crate attributes.
422 prog.push_str(&crate_attrs);
423 prog.push_str(&crates);
425 // Uses librustc_ast to parse the doctest and find if there's a main fn and the extern
426 // crate already is included.
427 let result = rustc_driver::catch_fatal_errors(|| {
428 with_globals(edition, || {
429 use rustc_errors::emitter::EmitterWriter;
430 use rustc_errors::Handler;
431 use rustc_parse::maybe_new_parser_from_source_str;
432 use rustc_session::parse::ParseSess;
433 use rustc_span::source_map::FilePathMapping;
435 let filename = FileName::anon_source_code(s);
436 let source = crates + everything_else;
438 // Any errors in parsing should also appear when the doctest is compiled for real, so just
439 // send all the errors that librustc_ast emits directly into a `Sink` instead of stderr.
440 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
442 EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
443 // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
444 let handler = Handler::with_emitter(false, None, box emitter);
445 let sess = ParseSess::with_span_handler(handler, sm);
447 let mut found_main = false;
448 let mut found_extern_crate = cratename.is_none();
449 let mut found_macro = false;
451 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source) {
454 for mut err in errs {
458 return (found_main, found_extern_crate, found_macro);
463 match parser.parse_item() {
466 if let ast::ItemKind::Fn(..) = item.kind {
467 if item.ident.name == sym::main {
473 if !found_extern_crate {
474 if let ast::ItemKind::ExternCrate(original) = item.kind {
475 // This code will never be reached if `cratename` is none because
476 // `found_extern_crate` is initialized to `true` if it is none.
477 let cratename = cratename.unwrap();
480 Some(name) => found_extern_crate = name.as_str() == cratename,
481 None => found_extern_crate = item.ident.as_str() == cratename,
487 if let ast::ItemKind::MacCall(..) = item.kind {
492 if found_main && found_extern_crate {
504 (found_main, found_extern_crate, found_macro)
507 let (already_has_main, already_has_extern_crate, found_macro) = match result {
508 Ok(result) => result,
509 Err(ErrorReported) => {
510 // If the parser panicked due to a fatal error, pass the test code through unchanged.
511 // The error will be reported during compilation.
512 return (s.to_owned(), 0);
516 // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
517 // see it. In that case, run the old text-based scan to see if they at least have a main
518 // function written inside a macro invocation. See
519 // https://github.com/rust-lang/rust/issues/56898
520 let already_has_main = if found_macro && !already_has_main {
523 let comment = line.find("//");
524 if let Some(comment_begins) = comment { &line[0..comment_begins] } else { line }
526 .any(|code| code.contains("fn main"))
531 // Don't inject `extern crate std` because it's already injected by the
533 if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
534 if let Some(cratename) = cratename {
535 // Make sure its actually used if not included.
536 if s.contains(cratename) {
537 prog.push_str(&format!("extern crate {};\n", cratename));
543 // FIXME: This code cannot yet handle no_std test cases yet
544 if dont_insert_main || already_has_main || prog.contains("![no_std]") {
545 prog.push_str(everything_else);
547 let returns_result = everything_else.trim_end().ends_with("(())");
548 let (main_pre, main_post) = if returns_result {
550 "fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
551 "}\n_inner().unwrap() }",
554 ("fn main() {\n", "\n}")
556 prog.extend([main_pre, everything_else, main_post].iter().cloned());
560 debug!("final doctest:\n{}", prog);
565 // FIXME(aburka): use a real parser to deal with multiline attributes
566 fn partition_source(s: &str) -> (String, String, String) {
567 #[derive(Copy, Clone, PartialEq)]
568 enum PartitionState {
573 let mut state = PartitionState::Attrs;
574 let mut before = String::new();
575 let mut crates = String::new();
576 let mut after = String::new();
578 for line in s.lines() {
579 let trimline = line.trim();
581 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
582 // shunted into "everything else"
584 PartitionState::Attrs => {
585 state = if trimline.starts_with("#![")
586 || trimline.chars().all(|c| c.is_whitespace())
587 || (trimline.starts_with("//") && !trimline.starts_with("///"))
589 PartitionState::Attrs
590 } else if trimline.starts_with("extern crate")
591 || trimline.starts_with("#[macro_use] extern crate")
593 PartitionState::Crates
595 PartitionState::Other
598 PartitionState::Crates => {
599 state = if trimline.starts_with("extern crate")
600 || trimline.starts_with("#[macro_use] extern crate")
601 || trimline.chars().all(|c| c.is_whitespace())
602 || (trimline.starts_with("//") && !trimline.starts_with("///"))
604 PartitionState::Crates
606 PartitionState::Other
609 PartitionState::Other => {}
613 PartitionState::Attrs => {
614 before.push_str(line);
615 before.push_str("\n");
617 PartitionState::Crates => {
618 crates.push_str(line);
619 crates.push_str("\n");
621 PartitionState::Other => {
622 after.push_str(line);
623 after.push_str("\n");
628 debug!("before:\n{}", before);
629 debug!("crates:\n{}", crates);
630 debug!("after:\n{}", after);
632 (before, after, crates)
636 fn add_test(&mut self, test: String, config: LangString, line: usize);
637 fn get_line(&self) -> usize {
640 fn register_header(&mut self, _name: &str, _level: u32) {}
643 pub struct Collector {
644 pub tests: Vec<testing::TestDescAndFn>,
646 // The name of the test displayed to the user, separated by `::`.
648 // In tests from Rust source, this is the path to the item
649 // e.g., `["std", "vec", "Vec", "push"]`.
651 // In tests from a markdown file, this is the titles of all headers (h1~h6)
652 // of the sections that contain the code block, e.g., if the markdown file is
665 // the `names` vector of that test will be `["Title", "Subtitle"]`.
670 enable_per_target_ignores: bool,
674 source_map: Option<Lrc<SourceMap>>,
675 filename: Option<PathBuf>,
676 visited_tests: HashMap<(String, usize), usize>,
685 source_map: Option<Lrc<SourceMap>>,
686 filename: Option<PathBuf>,
687 enable_per_target_ignores: bool,
694 enable_per_target_ignores,
700 visited_tests: HashMap::new(),
704 fn generate_name(&self, line: usize, filename: &FileName) -> String {
705 format!("{} - {} (line {})", filename, self.names.join("::"), line)
708 pub fn set_position(&mut self, position: Span) {
709 self.position = position;
712 fn get_filename(&self) -> FileName {
713 if let Some(ref source_map) = self.source_map {
714 let filename = source_map.span_to_filename(self.position);
715 if let FileName::Real(ref filename) = filename {
716 if let Ok(cur_dir) = env::current_dir() {
717 if let Ok(path) = filename.strip_prefix(&cur_dir) {
718 return path.to_owned().into();
723 } else if let Some(ref filename) = self.filename {
724 filename.clone().into()
726 FileName::Custom("input".to_owned())
731 impl Tester for Collector {
732 fn add_test(&mut self, test: String, config: LangString, line: usize) {
733 let filename = self.get_filename();
734 let name = self.generate_name(line, &filename);
735 let cratename = self.cratename.to_string();
736 let opts = self.opts.clone();
737 let edition = config.edition.unwrap_or(self.options.edition);
738 let options = self.options.clone();
739 let runtool = self.options.runtool.clone();
740 let runtool_args = self.options.runtool_args.clone();
741 let target = self.options.target.clone();
742 let target_str = target.to_string();
744 // FIXME(#44940): if doctests ever support path remapping, then this filename
745 // needs to be the result of `SourceMap::span_to_unmapped_path`.
746 let path = match &filename {
747 FileName::Real(path) => path.clone(),
748 _ => PathBuf::from(r"doctest.rs"),
751 let outdir = if let Some(mut path) = options.persist_doctests.clone() {
752 // For example `module/file.rs` would become `module_file_rs`
753 let folder_name = filename
756 .map(|c| if c == '/' || c == '.' { '_' } else { c })
757 .collect::<String>();
760 "{name}_{line}_{number}",
763 // Increases the current test number, if this file already
764 // exists or it creates a new entry with a test number of 0.
766 .entry((folder_name.clone(), line))
767 .and_modify(|v| *v += 1)
773 std::fs::create_dir_all(&path)
774 .expect("Couldn't create directory for doctest executables");
779 TempFileBuilder::new()
780 .prefix("rustdoctest")
782 .expect("rustdoc needs a tempdir"),
786 debug!("creating test {}: {}", name, test);
787 self.tests.push(testing::TestDescAndFn {
788 desc: testing::TestDesc {
789 name: testing::DynTestName(name),
790 ignore: match config.ignore {
792 Ignore::None => false,
793 Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
795 // compiler failures are test failures
796 should_panic: testing::ShouldPanic::No,
797 allow_fail: config.allow_fail,
798 test_type: testing::TestType::DocTest,
800 testfn: testing::DynTestFn(box move || {
820 if let Err(err) = res {
822 TestFailure::CompileError => {
823 eprint!("Couldn't compile the test.");
825 TestFailure::UnexpectedCompilePass => {
826 eprint!("Test compiled successfully, but it's marked `compile_fail`.");
828 TestFailure::UnexpectedRunPass => {
829 eprint!("Test executable succeeded, but it's marked `should_panic`.");
831 TestFailure::MissingErrorCodes(codes) => {
832 eprint!("Some expected error codes were not found: {:?}", codes);
834 TestFailure::ExecutionError(err) => {
835 eprint!("Couldn't run the test: {}", err);
836 if err.kind() == io::ErrorKind::PermissionDenied {
837 eprint!(" - maybe your tempdir is mounted with noexec?");
840 TestFailure::ExecutionFailure(out) => {
841 let reason = if let Some(code) = out.status.code() {
842 format!("exit code {}", code)
844 String::from("terminated by signal")
847 eprintln!("Test executable failed ({}).", reason);
849 // FIXME(#12309): An unfortunate side-effect of capturing the test
850 // executable's output is that the relative ordering between the test's
851 // stdout and stderr is lost. However, this is better than the
852 // alternative: if the test executable inherited the parent's I/O
853 // handles the output wouldn't be captured at all, even on success.
855 // The ordering could be preserved if the test process' stderr was
856 // redirected to stdout, but that functionality does not exist in the
857 // standard library, so it may not be portable enough.
858 let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
859 let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
861 if !stdout.is_empty() || !stderr.is_empty() {
864 if !stdout.is_empty() {
865 eprintln!("stdout:\n{}", stdout);
868 if !stderr.is_empty() {
869 eprintln!("stderr:\n{}", stderr);
875 panic::resume_unwind(box ());
881 fn get_line(&self) -> usize {
882 if let Some(ref source_map) = self.source_map {
883 let line = self.position.lo().to_usize();
884 let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
885 if line > 0 { line - 1 } else { line }
891 fn register_header(&mut self, name: &str, level: u32) {
892 if self.use_headers {
893 // We use these headings as test names, so it's good if
894 // they're valid identifiers.
899 if (i == 0 && rustc_lexer::is_id_start(c))
900 || (i != 0 && rustc_lexer::is_id_continue(c))
907 .collect::<String>();
909 // Here we try to efficiently assemble the header titles into the
910 // test name in the form of `h1::h2::h3::h4::h5::h6`.
912 // Suppose that originally `self.names` contains `[h1, h2, h3]`...
913 let level = level as usize;
914 if level <= self.names.len() {
915 // ... Consider `level == 2`. All headers in the lower levels
916 // are irrelevant in this new level. So we should reset
917 // `self.names` to contain headers until <h2>, and replace that
918 // slot with the new name: `[h1, name]`.
919 self.names.truncate(level);
920 self.names[level - 1] = name;
922 // ... On the other hand, consider `level == 5`. This means we
923 // need to extend `self.names` to contain five headers. We fill
924 // in the missing level (<h4>) with `_`. Thus `self.names` will
925 // become `[h1, h2, h3, "_", name]`.
926 if level - 1 > self.names.len() {
927 self.names.resize(level - 1, "_".to_owned());
929 self.names.push(name);
935 struct HirCollector<'a, 'hir, 'tcx> {
937 collector: &'a mut Collector,
943 impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> {
944 fn visit_testable<F: FnOnce(&mut Self)>(
947 attrs: &[ast::Attribute],
952 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
953 if let Some(ref cfg) = attrs.cfg {
954 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
959 let has_name = !name.is_empty();
961 self.collector.names.push(name);
964 attrs.collapse_doc_comments();
965 attrs.unindent_doc_comments();
966 // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
967 // anything else, this will combine them for us.
968 if let Some(doc) = attrs.collapsed_doc_value() {
969 self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
970 markdown::find_testable_code(
974 self.collector.enable_per_target_ignores,
975 Some(&crate::html::markdown::ExtraInfo::new(
978 span_of_attrs(&attrs).unwrap_or(sp),
986 self.collector.names.pop();
991 impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> {
992 type Map = Map<'hir>;
994 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
995 intravisit::NestedVisitorMap::All(self.map)
998 fn visit_item(&mut self, item: &'hir hir::Item) {
999 let name = if let hir::ItemKind::Impl { ref self_ty, .. } = item.kind {
1000 rustc_hir_pretty::id_to_string(&self.map, self_ty.hir_id)
1002 item.ident.to_string()
1005 self.visit_testable(name, &item.attrs, item.hir_id, item.span, |this| {
1006 intravisit::walk_item(this, item);
1010 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
1011 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1012 intravisit::walk_trait_item(this, item);
1016 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
1017 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1018 intravisit::walk_impl_item(this, item);
1022 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
1023 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1024 intravisit::walk_foreign_item(this, item);
1030 v: &'hir hir::Variant,
1031 g: &'hir hir::Generics,
1032 item_id: hir::HirId,
1034 self.visit_testable(v.ident.to_string(), &v.attrs, v.id, v.span, |this| {
1035 intravisit::walk_variant(this, v, g, item_id);
1039 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
1040 self.visit_testable(f.ident.to_string(), &f.attrs, f.hir_id, f.span, |this| {
1041 intravisit::walk_struct_field(this, f);
1045 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
1046 self.visit_testable(
1047 macro_def.ident.to_string(),