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::config::{self, CrateType};
13 use rustc_session::{lint, DiagnosticOutput, Session};
14 use rustc_span::edition::Edition;
15 use rustc_span::source_map::SourceMap;
16 use rustc_span::symbol::sym;
17 use rustc_span::{BytePos, FileName, Pos, Span, DUMMY_SP};
18 use rustc_target::spec::TargetTriple;
19 use tempfile::Builder as TempFileBuilder;
21 use std::collections::HashMap;
23 use std::io::{self, Write};
25 use std::path::PathBuf;
26 use std::process::{self, Command, Stdio};
29 use crate::clean::Attributes;
30 use crate::config::Options;
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<(), String> {
46 let input = config::Input::File(options.input.clone());
48 let warnings_lint_name = lint::builtin::WARNINGS.name;
49 let invalid_codeblock_attribute_name = rustc_lint::builtin::INVALID_CODEBLOCK_ATTRIBUTE.name;
51 // In addition to those specific lints, we also need to whitelist those given through
52 // command line, otherwise they'll get ignored and we don't want that.
53 let mut whitelisted_lints =
54 vec![warnings_lint_name.to_owned(), invalid_codeblock_attribute_name.to_owned()];
56 whitelisted_lints.extend(options.lint_opts.iter().map(|(lint, _)| lint).cloned());
59 lint::builtin::HardwiredLints::get_lints()
61 .chain(rustc_lint::SoftLints::get_lints().into_iter())
64 let lint_opts = lints()
66 if lint.name == warnings_lint_name || lint.name == invalid_codeblock_attribute_name {
69 Some((lint.name_lower(), lint::Allow))
72 .chain(options.lint_opts.clone().into_iter())
75 let lint_caps = lints()
77 // We don't want to whitelist *all* lints so let's
79 if whitelisted_lints.iter().any(|l| lint.name == l) {
82 Some((lint::LintId::of(lint), lint::Allow))
88 if options.proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
90 let sessopts = config::Options {
91 maybe_sysroot: options.maybe_sysroot.clone(),
92 search_paths: options.libs.clone(),
94 lint_opts: if !options.display_warnings { lint_opts } else { vec![] },
95 lint_cap: Some(options.lint_cap.clone().unwrap_or_else(|| lint::Forbid)),
96 cg: options.codegen_options.clone(),
97 externs: options.externs.clone(),
98 unstable_features: UnstableFeatures::from_environment(),
99 actually_rustdoc: true,
100 debugging_opts: config::DebuggingOptions { ..config::basic_debugging_options() },
101 edition: options.edition,
102 target_triple: options.target.clone(),
103 ..config::Options::default()
106 let mut cfgs = options.cfgs.clone();
107 cfgs.push("doc".to_owned());
108 cfgs.push("doctest".to_owned());
109 let config = interface::Config {
111 crate_cfg: interface::parse_cfgspecs(cfgs),
117 diagnostic_output: DiagnosticOutput::Default,
119 crate_name: options.crate_name.clone(),
121 register_lints: None,
122 override_queries: None,
123 registry: rustc_driver::diagnostics_registry(),
126 let mut test_args = options.test_args.clone();
127 let display_warnings = options.display_warnings;
129 let tests = interface::run_compiler(config, |compiler| {
130 compiler.enter(|queries| {
131 let lower_to_hir = queries.lower_to_hir()?;
133 let mut opts = scrape_test_config(lower_to_hir.peek().0);
134 opts.display_warnings |= options.display_warnings;
135 let enable_per_target_ignores = options.enable_per_target_ignores;
136 let mut collector = Collector::new(
137 queries.crate_name()?.peek().to_string(),
141 Some(compiler.source_map().clone()),
143 enable_per_target_ignores,
146 let mut global_ctxt = queries.global_ctxt()?.take();
148 global_ctxt.enter(|tcx| {
149 let krate = tcx.hir().krate();
151 let mut hir_collector = HirCollector {
152 sess: compiler.session(),
153 collector: &mut collector,
155 codes: ErrorCodes::from(
156 compiler.session().opts.unstable_features.is_nightly_build(),
160 hir_collector.visit_testable(
166 intravisit::walk_crate(this, krate);
170 compiler.session().abort_if_errors();
172 let ret: Result<_, ErrorReported> = Ok(collector.tests);
176 let tests = match tests {
178 Err(ErrorReported) => return Err(String::new()),
181 test_args.insert(0, "rustdoctest".to_string());
186 Some(testing::Options::new().display_output(display_warnings)),
192 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
193 fn scrape_test_config(krate: &::rustc_hir::Crate) -> TestOptions {
194 use rustc_ast_pretty::pprust;
197 TestOptions { no_crate_inject: false, display_warnings: false, attrs: Vec::new() };
199 let test_attrs: Vec<_> = krate
203 .filter(|a| a.check_name(sym::doc))
204 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
205 .filter(|a| a.check_name(sym::test))
207 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
210 if attr.check_name(sym::no_crate_inject) {
211 opts.no_crate_inject = true;
213 if attr.check_name(sym::attr) {
214 if let Some(l) = attr.meta_item_list() {
216 opts.attrs.push(pprust::meta_list_item_to_string(item));
225 /// Documentation test failure modes.
227 /// The test failed to compile.
229 /// The test is marked `compile_fail` but compiled successfully.
230 UnexpectedCompilePass,
231 /// The test failed to compile (as expected) but the compiler output did not contain all
232 /// expected error codes.
233 MissingErrorCodes(Vec<String>),
234 /// The test binary was unable to be executed.
235 ExecutionError(io::Error),
236 /// The test binary exited with a non-zero exit code.
238 /// This typically means an assertion in the test failed or another form of panic occurred.
239 ExecutionFailure(process::Output),
240 /// The test is marked `should_panic` but the test binary executed successfully.
245 Temp(tempfile::TempDir),
250 fn path(&self) -> &std::path::Path {
252 DirState::Temp(t) => t.path(),
253 DirState::Perm(p) => p.as_path(),
265 as_test_harness: bool,
266 runtool: Option<String>,
267 runtool_args: Vec<String>,
268 target: TargetTriple,
270 mut error_codes: Vec<String>,
275 ) -> Result<(), TestFailure> {
276 let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts, edition);
278 let output_file = outdir.path().join("rust_out");
280 let rustc_binary = options
284 .unwrap_or_else(|| rustc_interface::util::rustc_path().expect("found rustc"));
285 let mut compiler = Command::new(&rustc_binary);
286 compiler.arg("--crate-type").arg("bin");
287 for cfg in &options.cfgs {
288 compiler.arg("--cfg").arg(&cfg);
290 if let Some(sysroot) = options.maybe_sysroot {
291 compiler.arg("--sysroot").arg(sysroot);
293 compiler.arg("--edition").arg(&edition.to_string());
294 compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", path);
295 compiler.env("UNSTABLE_RUSTDOC_TEST_LINE", format!("{}", line as isize - line_offset as isize));
296 compiler.arg("-o").arg(&output_file);
298 compiler.arg("--test");
300 for lib_str in &options.lib_strs {
301 compiler.arg("-L").arg(&lib_str);
303 for extern_str in &options.extern_strs {
304 compiler.arg("--extern").arg(&extern_str);
306 compiler.arg("-Ccodegen-units=1");
307 for codegen_options_str in &options.codegen_options_strs {
308 compiler.arg("-C").arg(&codegen_options_str);
310 for debugging_option_str in &options.debugging_options_strs {
311 compiler.arg("-Z").arg(&debugging_option_str);
313 if no_run && !compile_fail {
314 compiler.arg("--emit=metadata");
316 compiler.arg("--target").arg(match target {
317 TargetTriple::TargetTriple(s) => s,
318 TargetTriple::TargetPath(path) => {
319 path.to_str().expect("target path must be valid unicode").to_string()
324 compiler.stdin(Stdio::piped());
325 compiler.stderr(Stdio::piped());
327 let mut child = compiler.spawn().expect("Failed to spawn rustc process");
329 let stdin = child.stdin.as_mut().expect("Failed to open stdin");
330 stdin.write_all(test.as_bytes()).expect("could write out test sources");
332 let output = child.wait_with_output().expect("Failed to read stdout");
334 struct Bomb<'a>(&'a str);
335 impl Drop for Bomb<'_> {
337 eprint!("{}", self.0);
340 let out = str::from_utf8(&output.stderr).unwrap();
341 let _bomb = Bomb(&out);
342 match (output.status.success(), compile_fail) {
344 return Err(TestFailure::UnexpectedCompilePass);
348 if !error_codes.is_empty() {
349 error_codes.retain(|err| !out.contains(&format!("error[{}]: ", err)));
351 if !error_codes.is_empty() {
352 return Err(TestFailure::MissingErrorCodes(error_codes));
357 return Err(TestFailure::CompileError);
368 if let Some(tool) = runtool {
369 cmd = Command::new(tool);
370 cmd.args(runtool_args);
371 cmd.arg(output_file);
373 cmd = Command::new(output_file);
377 Err(e) => return Err(TestFailure::ExecutionError(e)),
379 if should_panic && out.status.success() {
380 return Err(TestFailure::UnexpectedRunPass);
381 } else if !should_panic && !out.status.success() {
382 return Err(TestFailure::ExecutionFailure(out));
390 /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
391 /// lines before the test code begins.
394 cratename: Option<&str>,
395 dont_insert_main: bool,
398 ) -> (String, usize) {
399 let (crate_attrs, everything_else, crates) = partition_source(s);
400 let everything_else = everything_else.trim();
401 let mut line_offset = 0;
402 let mut prog = String::new();
404 if opts.attrs.is_empty() && !opts.display_warnings {
405 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
406 // lints that are commonly triggered in doctests. The crate-level test attributes are
407 // commonly used to make tests fail in case they trigger warnings, so having this there in
408 // that case may cause some tests to pass when they shouldn't have.
409 prog.push_str("#![allow(unused)]\n");
413 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
414 for attr in &opts.attrs {
415 prog.push_str(&format!("#![{}]\n", attr));
419 // Now push any outer attributes from the example, assuming they
420 // are intended to be crate attributes.
421 prog.push_str(&crate_attrs);
422 prog.push_str(&crates);
424 // Uses librustc_ast to parse the doctest and find if there's a main fn and the extern
425 // crate already is included.
426 let result = rustc_driver::catch_fatal_errors(|| {
427 with_globals(edition, || {
428 use rustc_errors::emitter::EmitterWriter;
429 use rustc_errors::Handler;
430 use rustc_parse::maybe_new_parser_from_source_str;
431 use rustc_session::parse::ParseSess;
432 use rustc_span::source_map::FilePathMapping;
434 let filename = FileName::anon_source_code(s);
435 let source = crates + everything_else;
437 // Any errors in parsing should also appear when the doctest is compiled for real, so just
438 // send all the errors that librustc_ast emits directly into a `Sink` instead of stderr.
439 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
441 EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
442 // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
443 let handler = Handler::with_emitter(false, None, box emitter);
444 let sess = ParseSess::with_span_handler(handler, sm);
446 let mut found_main = false;
447 let mut found_extern_crate = cratename.is_none();
448 let mut found_macro = false;
450 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source) {
453 for mut err in errs {
457 return (found_main, found_extern_crate, found_macro);
462 match parser.parse_item() {
465 if let ast::ItemKind::Fn(..) = item.kind {
466 if item.ident.name == sym::main {
472 if !found_extern_crate {
473 if let ast::ItemKind::ExternCrate(original) = item.kind {
474 // This code will never be reached if `cratename` is none because
475 // `found_extern_crate` is initialized to `true` if it is none.
476 let cratename = cratename.unwrap();
479 Some(name) => found_extern_crate = name.as_str() == cratename,
480 None => found_extern_crate = item.ident.as_str() == cratename,
486 if let ast::ItemKind::MacCall(..) = item.kind {
491 if found_main && found_extern_crate {
503 (found_main, found_extern_crate, found_macro)
506 let (already_has_main, already_has_extern_crate, found_macro) = match result {
507 Ok(result) => result,
508 Err(ErrorReported) => {
509 // If the parser panicked due to a fatal error, pass the test code through unchanged.
510 // The error will be reported during compilation.
511 return (s.to_owned(), 0);
515 // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
516 // see it. In that case, run the old text-based scan to see if they at least have a main
517 // function written inside a macro invocation. See
518 // https://github.com/rust-lang/rust/issues/56898
519 let already_has_main = if found_macro && !already_has_main {
522 let comment = line.find("//");
523 if let Some(comment_begins) = comment { &line[0..comment_begins] } else { line }
525 .any(|code| code.contains("fn main"))
530 // Don't inject `extern crate std` because it's already injected by the
532 if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
533 if let Some(cratename) = cratename {
534 // Make sure its actually used if not included.
535 if s.contains(cratename) {
536 prog.push_str(&format!("extern crate {};\n", cratename));
542 // FIXME: This code cannot yet handle no_std test cases yet
543 if dont_insert_main || already_has_main || prog.contains("![no_std]") {
544 prog.push_str(everything_else);
546 let returns_result = everything_else.trim_end().ends_with("(())");
547 let (main_pre, main_post) = if returns_result {
549 "fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
550 "}\n_inner().unwrap() }",
553 ("fn main() {\n", "\n}")
555 prog.extend([main_pre, everything_else, main_post].iter().cloned());
559 debug!("final doctest:\n{}", prog);
564 // FIXME(aburka): use a real parser to deal with multiline attributes
565 fn partition_source(s: &str) -> (String, String, String) {
566 #[derive(Copy, Clone, PartialEq)]
567 enum PartitionState {
572 let mut state = PartitionState::Attrs;
573 let mut before = String::new();
574 let mut crates = String::new();
575 let mut after = String::new();
577 for line in s.lines() {
578 let trimline = line.trim();
580 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
581 // shunted into "everything else"
583 PartitionState::Attrs => {
584 state = if trimline.starts_with("#![")
585 || trimline.chars().all(|c| c.is_whitespace())
586 || (trimline.starts_with("//") && !trimline.starts_with("///"))
588 PartitionState::Attrs
589 } else if trimline.starts_with("extern crate")
590 || trimline.starts_with("#[macro_use] extern crate")
592 PartitionState::Crates
594 PartitionState::Other
597 PartitionState::Crates => {
598 state = if trimline.starts_with("extern crate")
599 || trimline.starts_with("#[macro_use] extern crate")
600 || trimline.chars().all(|c| c.is_whitespace())
601 || (trimline.starts_with("//") && !trimline.starts_with("///"))
603 PartitionState::Crates
605 PartitionState::Other
608 PartitionState::Other => {}
612 PartitionState::Attrs => {
613 before.push_str(line);
614 before.push_str("\n");
616 PartitionState::Crates => {
617 crates.push_str(line);
618 crates.push_str("\n");
620 PartitionState::Other => {
621 after.push_str(line);
622 after.push_str("\n");
627 debug!("before:\n{}", before);
628 debug!("crates:\n{}", crates);
629 debug!("after:\n{}", after);
631 (before, after, crates)
635 fn add_test(&mut self, test: String, config: LangString, line: usize);
636 fn get_line(&self) -> usize {
639 fn register_header(&mut self, _name: &str, _level: u32) {}
642 pub struct Collector {
643 pub tests: Vec<testing::TestDescAndFn>,
645 // The name of the test displayed to the user, separated by `::`.
647 // In tests from Rust source, this is the path to the item
648 // e.g., `["std", "vec", "Vec", "push"]`.
650 // In tests from a markdown file, this is the titles of all headers (h1~h6)
651 // of the sections that contain the code block, e.g., if the markdown file is
664 // the `names` vector of that test will be `["Title", "Subtitle"]`.
669 enable_per_target_ignores: bool,
673 source_map: Option<Lrc<SourceMap>>,
674 filename: Option<PathBuf>,
675 visited_tests: HashMap<(String, usize), usize>,
684 source_map: Option<Lrc<SourceMap>>,
685 filename: Option<PathBuf>,
686 enable_per_target_ignores: bool,
693 enable_per_target_ignores,
699 visited_tests: HashMap::new(),
703 fn generate_name(&self, line: usize, filename: &FileName) -> String {
704 format!("{} - {} (line {})", filename, self.names.join("::"), line)
707 pub fn set_position(&mut self, position: Span) {
708 self.position = position;
711 fn get_filename(&self) -> FileName {
712 if let Some(ref source_map) = self.source_map {
713 let filename = source_map.span_to_filename(self.position);
714 if let FileName::Real(ref filename) = filename {
715 if let Ok(cur_dir) = env::current_dir() {
716 if let Ok(path) = filename.strip_prefix(&cur_dir) {
717 return path.to_owned().into();
722 } else if let Some(ref filename) = self.filename {
723 filename.clone().into()
725 FileName::Custom("input".to_owned())
730 impl Tester for Collector {
731 fn add_test(&mut self, test: String, config: LangString, line: usize) {
732 let filename = self.get_filename();
733 let name = self.generate_name(line, &filename);
734 let cratename = self.cratename.to_string();
735 let opts = self.opts.clone();
736 let edition = config.edition.unwrap_or(self.options.edition);
737 let options = self.options.clone();
738 let runtool = self.options.runtool.clone();
739 let runtool_args = self.options.runtool_args.clone();
740 let target = self.options.target.clone();
741 let target_str = target.to_string();
743 // FIXME(#44940): if doctests ever support path remapping, then this filename
744 // needs to be the result of `SourceMap::span_to_unmapped_path`.
745 let path = match &filename {
746 FileName::Real(path) => path.clone(),
747 _ => PathBuf::from(r"doctest.rs"),
750 let outdir = if let Some(mut path) = options.persist_doctests.clone() {
751 // For example `module/file.rs` would become `module_file_rs`
752 let folder_name = filename
755 .map(|c| if c == '/' || c == '.' { '_' } else { c })
756 .collect::<String>();
759 "{name}_{line}_{number}",
762 // Increases the current test number, if this file already
763 // exists or it creates a new entry with a test number of 0.
765 .entry((folder_name.clone(), line))
766 .and_modify(|v| *v += 1)
772 std::fs::create_dir_all(&path)
773 .expect("Couldn't create directory for doctest executables");
778 TempFileBuilder::new()
779 .prefix("rustdoctest")
781 .expect("rustdoc needs a tempdir"),
785 debug!("creating test {}: {}", name, test);
786 self.tests.push(testing::TestDescAndFn {
787 desc: testing::TestDesc {
788 name: testing::DynTestName(name),
789 ignore: match config.ignore {
791 Ignore::None => false,
792 Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
794 // compiler failures are test failures
795 should_panic: testing::ShouldPanic::No,
796 allow_fail: config.allow_fail,
797 test_type: testing::TestType::DocTest,
799 testfn: testing::DynTestFn(box move || {
819 if let Err(err) = res {
821 TestFailure::CompileError => {
822 eprint!("Couldn't compile the test.");
824 TestFailure::UnexpectedCompilePass => {
825 eprint!("Test compiled successfully, but it's marked `compile_fail`.");
827 TestFailure::UnexpectedRunPass => {
828 eprint!("Test executable succeeded, but it's marked `should_panic`.");
830 TestFailure::MissingErrorCodes(codes) => {
831 eprint!("Some expected error codes were not found: {:?}", codes);
833 TestFailure::ExecutionError(err) => {
834 eprint!("Couldn't run the test: {}", err);
835 if err.kind() == io::ErrorKind::PermissionDenied {
836 eprint!(" - maybe your tempdir is mounted with noexec?");
839 TestFailure::ExecutionFailure(out) => {
840 let reason = if let Some(code) = out.status.code() {
841 format!("exit code {}", code)
843 String::from("terminated by signal")
846 eprintln!("Test executable failed ({}).", reason);
848 // FIXME(#12309): An unfortunate side-effect of capturing the test
849 // executable's output is that the relative ordering between the test's
850 // stdout and stderr is lost. However, this is better than the
851 // alternative: if the test executable inherited the parent's I/O
852 // handles the output wouldn't be captured at all, even on success.
854 // The ordering could be preserved if the test process' stderr was
855 // redirected to stdout, but that functionality does not exist in the
856 // standard library, so it may not be portable enough.
857 let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
858 let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
860 if !stdout.is_empty() || !stderr.is_empty() {
863 if !stdout.is_empty() {
864 eprintln!("stdout:\n{}", stdout);
867 if !stderr.is_empty() {
868 eprintln!("stderr:\n{}", stderr);
874 panic::resume_unwind(box ());
880 fn get_line(&self) -> usize {
881 if let Some(ref source_map) = self.source_map {
882 let line = self.position.lo().to_usize();
883 let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
884 if line > 0 { line - 1 } else { line }
890 fn register_header(&mut self, name: &str, level: u32) {
891 if self.use_headers {
892 // We use these headings as test names, so it's good if
893 // they're valid identifiers.
898 if (i == 0 && rustc_lexer::is_id_start(c))
899 || (i != 0 && rustc_lexer::is_id_continue(c))
906 .collect::<String>();
908 // Here we try to efficiently assemble the header titles into the
909 // test name in the form of `h1::h2::h3::h4::h5::h6`.
911 // Suppose that originally `self.names` contains `[h1, h2, h3]`...
912 let level = level as usize;
913 if level <= self.names.len() {
914 // ... Consider `level == 2`. All headers in the lower levels
915 // are irrelevant in this new level. So we should reset
916 // `self.names` to contain headers until <h2>, and replace that
917 // slot with the new name: `[h1, name]`.
918 self.names.truncate(level);
919 self.names[level - 1] = name;
921 // ... On the other hand, consider `level == 5`. This means we
922 // need to extend `self.names` to contain five headers. We fill
923 // in the missing level (<h4>) with `_`. Thus `self.names` will
924 // become `[h1, h2, h3, "_", name]`.
925 if level - 1 > self.names.len() {
926 self.names.resize(level - 1, "_".to_owned());
928 self.names.push(name);
934 struct HirCollector<'a, 'hir, 'tcx> {
936 collector: &'a mut Collector,
942 impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> {
943 fn visit_testable<F: FnOnce(&mut Self)>(
946 attrs: &[ast::Attribute],
951 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
952 if let Some(ref cfg) = attrs.cfg {
953 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
958 let has_name = !name.is_empty();
960 self.collector.names.push(name);
963 attrs.collapse_doc_comments();
964 attrs.unindent_doc_comments();
965 // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
966 // anything else, this will combine them for us.
967 if let Some(doc) = attrs.collapsed_doc_value() {
968 self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
969 markdown::find_testable_code(
973 self.collector.enable_per_target_ignores,
974 Some(&crate::html::markdown::ExtraInfo::new(
977 span_of_attrs(&attrs).unwrap_or(sp),
985 self.collector.names.pop();
990 impl<'a, 'hir, 'tcx> intravisit::Visitor<'hir> for HirCollector<'a, 'hir, 'tcx> {
991 type Map = Map<'hir>;
993 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
994 intravisit::NestedVisitorMap::All(self.map)
997 fn visit_item(&mut self, item: &'hir hir::Item) {
998 let name = if let hir::ItemKind::Impl { ref self_ty, .. } = item.kind {
999 rustc_hir_pretty::id_to_string(&self.map, self_ty.hir_id)
1001 item.ident.to_string()
1004 self.visit_testable(name, &item.attrs, item.hir_id, item.span, |this| {
1005 intravisit::walk_item(this, item);
1009 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
1010 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1011 intravisit::walk_trait_item(this, item);
1015 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
1016 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1017 intravisit::walk_impl_item(this, item);
1021 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
1022 self.visit_testable(item.ident.to_string(), &item.attrs, item.hir_id, item.span, |this| {
1023 intravisit::walk_foreign_item(this, item);
1029 v: &'hir hir::Variant,
1030 g: &'hir hir::Generics,
1031 item_id: hir::HirId,
1033 self.visit_testable(v.ident.to_string(), &v.attrs, v.id, v.span, |this| {
1034 intravisit::walk_variant(this, v, g, item_id);
1038 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
1039 self.visit_testable(f.ident.to_string(), &f.attrs, f.hir_id, f.span, |this| {
1040 intravisit::walk_struct_field(this, f);
1044 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
1045 self.visit_testable(
1046 macro_def.ident.to_string(),