1 use rustc_data_structures::sync::Lrc;
2 use rustc_interface::interface;
4 use rustc::hir::intravisit;
5 use rustc::hir::def_id::LOCAL_CRATE;
6 use rustc::session::{self, config, DiagnosticOutput};
7 use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions};
8 use rustc::session::search_paths::SearchPath;
9 use rustc::util::common::ErrorReported;
11 use syntax::with_globals;
12 use syntax::source_map::SourceMap;
13 use syntax::edition::Edition;
14 use syntax::feature_gate::UnstableFeatures;
16 use std::io::prelude::*;
18 use std::panic::{self, AssertUnwindSafe};
19 use std::path::PathBuf;
20 use std::process::{self, Command};
22 use std::sync::{Arc, Mutex};
23 use syntax::symbol::sym;
24 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span, FileName};
25 use tempfile::Builder as TempFileBuilder;
28 use crate::clean::Attributes;
29 use crate::config::Options;
30 use crate::html::markdown::{self, ErrorCodes, LangString};
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 crate_types = if options.proc_macro_crate {
47 vec![config::CrateType::ProcMacro]
49 vec![config::CrateType::Dylib]
52 let sessopts = config::Options {
53 maybe_sysroot: options.maybe_sysroot.clone(),
54 search_paths: options.libs.clone(),
56 cg: options.codegen_options.clone(),
57 externs: options.externs.clone(),
58 unstable_features: UnstableFeatures::from_environment(),
59 lint_cap: Some(::rustc::lint::Level::Allow),
60 actually_rustdoc: true,
61 debugging_opts: config::DebuggingOptions {
62 ..config::basic_debugging_options()
64 edition: options.edition,
65 ..config::Options::default()
68 let config = interface::Config {
70 crate_cfg: config::parse_cfgspecs(options.cfgs.clone()),
76 diagnostic_output: DiagnosticOutput::Default,
78 crate_name: options.crate_name.clone(),
79 lint_caps: Default::default(),
82 let mut test_args = options.test_args.clone();
83 let display_warnings = options.display_warnings;
85 let tests = interface::run_compiler(config, |compiler| -> Result<_, ErrorReported> {
86 let lower_to_hir = compiler.lower_to_hir()?;
88 let mut opts = scrape_test_config(lower_to_hir.peek().0.borrow().krate());
89 opts.display_warnings |= options.display_warnings;
90 let mut collector = Collector::new(
91 compiler.crate_name()?.peek().to_string(),
94 options.codegen_options,
98 options.maybe_sysroot,
99 Some(compiler.source_map().clone()),
103 options.persist_doctests,
106 let mut global_ctxt = compiler.global_ctxt()?.take();
107 global_ctxt.enter(|tcx| {
108 let krate = tcx.hir().krate();
109 let mut hir_collector = HirCollector {
110 sess: compiler.session(),
111 collector: &mut collector,
113 codes: ErrorCodes::from(compiler.session().opts
114 .unstable_features.is_nightly_build()),
116 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
117 intravisit::walk_crate(this, krate);
122 }).expect("compiler aborted in rustdoc!");
124 test_args.insert(0, "rustdoctest".to_string());
129 testing::Options::new().display_output(display_warnings)
135 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
136 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
137 use syntax::print::pprust;
139 let mut opts = TestOptions {
140 no_crate_inject: false,
141 display_warnings: false,
145 let test_attrs: Vec<_> = krate.attrs.iter()
146 .filter(|a| a.check_name(sym::doc))
147 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
148 .filter(|a| a.check_name(sym::test))
150 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
153 if attr.check_name(sym::no_crate_inject) {
154 opts.no_crate_inject = true;
156 if attr.check_name(sym::attr) {
157 if let Some(l) = attr.meta_item_list() {
159 opts.attrs.push(pprust::meta_list_item_to_string(item));
168 /// Documentation test failure modes.
170 /// The test failed to compile.
172 /// The test is marked `compile_fail` but compiled successfully.
173 UnexpectedCompilePass,
174 /// The test failed to compile (as expected) but the compiler output did not contain all
175 /// expected error codes.
176 MissingErrorCodes(Vec<String>),
177 /// The test binary was unable to be executed.
178 ExecutionError(io::Error),
179 /// The test binary exited with a non-zero exit code.
181 /// This typically means an assertion in the test failed or another form of panic occurred.
182 ExecutionFailure(process::Output),
183 /// The test is marked `should_panic` but the test binary executed successfully.
193 libs: Vec<SearchPath>,
198 as_test_harness: bool,
200 mut error_codes: Vec<String>,
202 maybe_sysroot: Option<PathBuf>,
203 linker: Option<PathBuf>,
205 persist_doctests: Option<PathBuf>,
206 ) -> Result<(), TestFailure> {
207 let (test, line_offset) = match panic::catch_unwind(|| {
208 make_test(test, Some(cratename), as_test_harness, opts, edition)
210 Ok((test, line_offset)) => (test, line_offset),
211 Err(cause) if cause.is::<errors::FatalErrorMarker>() => {
212 // If the parser used by `make_test` panicked due to a fatal error, pass the test code
213 // through unchanged. The error will be reported during compilation.
216 Err(cause) => panic::resume_unwind(cause),
219 // FIXME(#44940): if doctests ever support path remapping, then this filename
220 // needs to be the result of `SourceMap::span_to_unmapped_path`.
221 let path = match filename {
222 FileName::Real(path) => path.clone(),
223 _ => PathBuf::from(r"doctest.rs"),
226 let input = config::Input::Str {
227 name: FileName::DocTest(path, line as isize - line_offset as isize),
230 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
232 let sessopts = config::Options {
235 crate_types: vec![config::CrateType::Executable],
236 output_types: outputs,
238 cg: config::CodegenOptions {
242 test: as_test_harness,
243 unstable_features: UnstableFeatures::from_environment(),
244 debugging_opts: config::DebuggingOptions {
245 ..config::basic_debugging_options()
248 ..config::Options::default()
251 // Shuffle around a few input and output handles here. We're going to pass
252 // an explicit handle into rustc to collect output messages, but we also
253 // want to catch the error message that rustc prints when it fails.
255 // We take our thread-local stderr (likely set by the test runner) and replace
256 // it with a sink that is also passed to rustc itself. When this function
257 // returns the output of the sink is copied onto the output of our own thread.
259 // The basic idea is to not use a default Handler for rustc, and then also
260 // not print things by default to the actual stderr.
261 struct Sink(Arc<Mutex<Vec<u8>>>);
262 impl Write for Sink {
263 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
264 Write::write(&mut *self.0.lock().unwrap(), data)
266 fn flush(&mut self) -> io::Result<()> { Ok(()) }
268 struct Bomb(Arc<Mutex<Vec<u8>>>, Option<Box<dyn Write+Send>>);
271 let mut old = self.1.take().unwrap();
272 let _ = old.write_all(&self.0.lock().unwrap());
273 io::set_panic(Some(old));
276 let data = Arc::new(Mutex::new(Vec::new()));
278 let old = io::set_panic(Some(box Sink(data.clone())));
279 let _bomb = Bomb(data.clone(), Some(old.unwrap_or(box io::stdout())));
282 Temp(tempfile::TempDir),
287 fn path(&self) -> &std::path::Path {
289 DirState::Temp(t) => t.path(),
290 DirState::Perm(p) => p.as_path(),
295 let outdir = if let Some(mut path) = persist_doctests {
296 path.push(format!("{}_{}",
305 std::fs::create_dir_all(&path)
306 .expect("Couldn't create directory for doctest executables");
310 DirState::Temp(TempFileBuilder::new()
311 .prefix("rustdoctest")
313 .expect("rustdoc needs a tempdir"))
315 let output_file = outdir.path().join("rust_out");
317 let config = interface::Config {
319 crate_cfg: config::parse_cfgspecs(cfgs),
322 output_file: Some(output_file.clone()),
325 diagnostic_output: DiagnosticOutput::Raw(box Sink(data.clone())),
326 stderr: Some(data.clone()),
328 lint_caps: Default::default(),
331 let compile_result = panic::catch_unwind(AssertUnwindSafe(|| {
332 interface::run_compiler(config, |compiler| {
334 compiler.global_ctxt().and_then(|global_ctxt| global_ctxt.take().enter(|tcx| {
335 tcx.analysis(LOCAL_CRATE)
338 compiler.compile().ok();
340 compiler.session().compile_status()
342 })).map_err(|_| ()).and_then(|s| s.map_err(|_| ()));
344 match (compile_result, compile_fail) {
346 return Err(TestFailure::UnexpectedCompilePass);
348 (Ok(()), false) => {}
350 if !error_codes.is_empty() {
351 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
352 error_codes.retain(|err| !out.contains(err));
354 if !error_codes.is_empty() {
355 return Err(TestFailure::MissingErrorCodes(error_codes));
360 return Err(TestFailure::CompileError);
369 let mut cmd = Command::new(output_file);
372 Err(e) => return Err(TestFailure::ExecutionError(e)),
374 if should_panic && out.status.success() {
375 return Err(TestFailure::UnexpectedRunPass);
376 } else if !should_panic && !out.status.success() {
377 return Err(TestFailure::ExecutionFailure(out));
385 /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
386 /// lines before the test code begins.
390 /// This function uses the compiler's parser internally. The parser will panic if it encounters a
391 /// fatal error while parsing the test.
392 pub fn make_test(s: &str,
393 cratename: Option<&str>,
394 dont_insert_main: bool,
398 let (crate_attrs, everything_else, crates) = partition_source(s);
399 let everything_else = everything_else.trim();
400 let mut line_offset = 0;
401 let mut prog = String::new();
403 if opts.attrs.is_empty() && !opts.display_warnings {
404 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
405 // lints that are commonly triggered in doctests. The crate-level test attributes are
406 // commonly used to make tests fail in case they trigger warnings, so having this there in
407 // that case may cause some tests to pass when they shouldn't have.
408 prog.push_str("#![allow(unused)]\n");
412 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
413 for attr in &opts.attrs {
414 prog.push_str(&format!("#![{}]\n", attr));
418 // Now push any outer attributes from the example, assuming they
419 // are intended to be crate attributes.
420 prog.push_str(&crate_attrs);
421 prog.push_str(&crates);
423 // Uses libsyntax to parse the doctest and find if there's a main fn and the extern
424 // crate already is included.
425 let (already_has_main, already_has_extern_crate, found_macro) = with_globals(edition, || {
426 use crate::syntax::{parse::{self, ParseSess}, source_map::FilePathMapping};
427 use errors::emitter::EmitterWriter;
430 let filename = FileName::anon_source_code(s);
431 let source = crates + &everything_else;
433 // Any errors in parsing should also appear when the doctest is compiled for real, so just
434 // send all the errors that libsyntax emits directly into a `Sink` instead of stderr.
435 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
436 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false);
437 // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
438 let handler = Handler::with_emitter(false, None, box emitter);
439 let sess = ParseSess::with_span_handler(handler, cm);
441 let mut found_main = false;
442 let mut found_extern_crate = cratename.is_none();
443 let mut found_macro = false;
445 let mut parser = match parse::maybe_new_parser_from_source_str(&sess, filename, source) {
448 for mut err in errs {
452 return (found_main, found_extern_crate, found_macro);
457 match parser.parse_item() {
460 if let ast::ItemKind::Fn(..) = item.node {
461 if item.ident.as_str() == "main" {
467 if !found_extern_crate {
468 if let ast::ItemKind::ExternCrate(original) = item.node {
469 // This code will never be reached if `cratename` is none because
470 // `found_extern_crate` is initialized to `true` if it is none.
471 let cratename = cratename.unwrap();
474 Some(name) => found_extern_crate = name.as_str() == cratename,
475 None => found_extern_crate = item.ident.as_str() == cratename,
481 if let ast::ItemKind::Mac(..) = item.node {
486 if found_main && found_extern_crate {
498 (found_main, found_extern_crate, found_macro)
501 // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
502 // see it. In that case, run the old text-based scan to see if they at least have a main
503 // function written inside a macro invocation. See
504 // https://github.com/rust-lang/rust/issues/56898
505 let already_has_main = if found_macro && !already_has_main {
508 let comment = line.find("//");
509 if let Some(comment_begins) = comment {
510 &line[0..comment_begins]
515 .any(|code| code.contains("fn main"))
520 // Don't inject `extern crate std` because it's already injected by the
522 if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
523 if let Some(cratename) = cratename {
524 // Make sure its actually used if not included.
525 if s.contains(cratename) {
526 prog.push_str(&format!("extern crate {};\n", cratename));
532 // FIXME: This code cannot yet handle no_std test cases yet
533 if dont_insert_main || already_has_main || prog.contains("![no_std]") {
534 prog.push_str(everything_else);
536 let returns_result = everything_else.trim_end().ends_with("(())");
537 let (main_pre, main_post) = if returns_result {
538 ("fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
539 "}\n_inner().unwrap() }")
541 ("fn main() {\n", "\n}")
543 prog.extend([main_pre, everything_else, main_post].iter().cloned());
547 debug!("final doctest:\n{}", prog);
552 // FIXME(aburka): use a real parser to deal with multiline attributes
553 fn partition_source(s: &str) -> (String, String, String) {
554 #[derive(Copy, Clone, PartialEq)]
555 enum PartitionState {
560 let mut state = PartitionState::Attrs;
561 let mut before = String::new();
562 let mut crates = String::new();
563 let mut after = String::new();
565 for line in s.lines() {
566 let trimline = line.trim();
568 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
569 // shunted into "everything else"
571 PartitionState::Attrs => {
572 state = if trimline.starts_with("#![") ||
573 trimline.chars().all(|c| c.is_whitespace()) ||
574 (trimline.starts_with("//") && !trimline.starts_with("///"))
576 PartitionState::Attrs
577 } else if trimline.starts_with("extern crate") ||
578 trimline.starts_with("#[macro_use] extern crate")
580 PartitionState::Crates
582 PartitionState::Other
585 PartitionState::Crates => {
586 state = if trimline.starts_with("extern crate") ||
587 trimline.starts_with("#[macro_use] extern crate") ||
588 trimline.chars().all(|c| c.is_whitespace()) ||
589 (trimline.starts_with("//") && !trimline.starts_with("///"))
591 PartitionState::Crates
593 PartitionState::Other
596 PartitionState::Other => {}
600 PartitionState::Attrs => {
601 before.push_str(line);
602 before.push_str("\n");
604 PartitionState::Crates => {
605 crates.push_str(line);
606 crates.push_str("\n");
608 PartitionState::Other => {
609 after.push_str(line);
610 after.push_str("\n");
615 debug!("before:\n{}", before);
616 debug!("crates:\n{}", crates);
617 debug!("after:\n{}", after);
619 (before, after, crates)
623 fn add_test(&mut self, test: String, config: LangString, line: usize);
624 fn get_line(&self) -> usize {
627 fn register_header(&mut self, _name: &str, _level: u32) {}
630 pub struct Collector {
631 pub tests: Vec<testing::TestDescAndFn>,
633 // The name of the test displayed to the user, separated by `::`.
635 // In tests from Rust source, this is the path to the item
636 // e.g., `["std", "vec", "Vec", "push"]`.
638 // In tests from a markdown file, this is the titles of all headers (h1~h6)
639 // of the sections that contain the code block, e.g., if the markdown file is
652 // the `names` vector of that test will be `["Title", "Subtitle"]`.
656 libs: Vec<SearchPath>,
662 maybe_sysroot: Option<PathBuf>,
664 source_map: Option<Lrc<SourceMap>>,
665 filename: Option<PathBuf>,
666 linker: Option<PathBuf>,
668 persist_doctests: Option<PathBuf>,
672 pub fn new(cratename: String, cfgs: Vec<String>, libs: Vec<SearchPath>, cg: CodegenOptions,
673 externs: Externs, use_headers: bool, opts: TestOptions,
674 maybe_sysroot: Option<PathBuf>, source_map: Option<Lrc<SourceMap>>,
675 filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition,
676 persist_doctests: Option<PathBuf>) -> Collector {
697 fn generate_name(&self, line: usize, filename: &FileName) -> String {
698 format!("{} - {} (line {})", filename, self.names.join("::"), line)
701 pub fn set_position(&mut self, position: Span) {
702 self.position = position;
705 fn get_filename(&self) -> FileName {
706 if let Some(ref source_map) = self.source_map {
707 let filename = source_map.span_to_filename(self.position);
708 if let FileName::Real(ref filename) = filename {
709 if let Ok(cur_dir) = env::current_dir() {
710 if let Ok(path) = filename.strip_prefix(&cur_dir) {
711 return path.to_owned().into();
716 } else if let Some(ref filename) = self.filename {
717 filename.clone().into()
719 FileName::Custom("input".to_owned())
724 impl Tester for Collector {
725 fn add_test(&mut self, test: String, config: LangString, line: usize) {
726 let filename = self.get_filename();
727 let name = self.generate_name(line, &filename);
728 let cfgs = self.cfgs.clone();
729 let libs = self.libs.clone();
730 let cg = self.cg.clone();
731 let externs = self.externs.clone();
732 let cratename = self.cratename.to_string();
733 let opts = self.opts.clone();
734 let maybe_sysroot = self.maybe_sysroot.clone();
735 let linker = self.linker.clone();
736 let edition = config.edition.unwrap_or(self.edition);
737 let persist_doctests = self.persist_doctests.clone();
739 debug!("creating test {}: {}", name, test);
740 self.tests.push(testing::TestDescAndFn {
741 desc: testing::TestDesc {
742 name: testing::DynTestName(name),
743 ignore: config.ignore,
744 // compiler failures are test failures
745 should_panic: testing::ShouldPanic::No,
746 allow_fail: config.allow_fail,
748 testfn: testing::DynTestFn(box move || {
770 if let Err(err) = res {
772 TestFailure::CompileError => {
773 eprint!("Couldn't compile the test.");
775 TestFailure::UnexpectedCompilePass => {
776 eprint!("Test compiled successfully, but it's marked `compile_fail`.");
778 TestFailure::UnexpectedRunPass => {
779 eprint!("Test executable succeeded, but it's marked `should_panic`.");
781 TestFailure::MissingErrorCodes(codes) => {
782 eprint!("Some expected error codes were not found: {:?}", codes);
784 TestFailure::ExecutionError(err) => {
785 eprint!("Couldn't run the test: {}", err);
786 if err.kind() == io::ErrorKind::PermissionDenied {
787 eprint!(" - maybe your tempdir is mounted with noexec?");
790 TestFailure::ExecutionFailure(out) => {
791 let reason = if let Some(code) = out.status.code() {
792 format!("exit code {}", code)
794 String::from("terminated by signal")
797 eprintln!("Test executable failed ({}).", reason);
799 // FIXME(#12309): An unfortunate side-effect of capturing the test
800 // executable's output is that the relative ordering between the test's
801 // stdout and stderr is lost. However, this is better than the
802 // alternative: if the test executable inherited the parent's I/O
803 // handles the output wouldn't be captured at all, even on success.
805 // The ordering could be preserved if the test process' stderr was
806 // redirected to stdout, but that functionality does not exist in the
807 // standard library, so it may not be portable enough.
808 let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
809 let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
811 if !stdout.is_empty() || !stderr.is_empty() {
814 if !stdout.is_empty() {
815 eprintln!("stdout:\n{}", stdout);
818 if !stderr.is_empty() {
819 eprintln!("stderr:\n{}", stderr);
825 panic::resume_unwind(box ());
831 fn get_line(&self) -> usize {
832 if let Some(ref source_map) = self.source_map {
833 let line = self.position.lo().to_usize();
834 let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
835 if line > 0 { line - 1 } else { line }
841 fn register_header(&mut self, name: &str, level: u32) {
842 if self.use_headers {
843 // We use these headings as test names, so it's good if
844 // they're valid identifiers.
845 let name = name.chars().enumerate().map(|(i, c)| {
846 if (i == 0 && c.is_xid_start()) ||
847 (i != 0 && c.is_xid_continue()) {
852 }).collect::<String>();
854 // Here we try to efficiently assemble the header titles into the
855 // test name in the form of `h1::h2::h3::h4::h5::h6`.
857 // Suppose that originally `self.names` contains `[h1, h2, h3]`...
858 let level = level as usize;
859 if level <= self.names.len() {
860 // ... Consider `level == 2`. All headers in the lower levels
861 // are irrelevant in this new level. So we should reset
862 // `self.names` to contain headers until <h2>, and replace that
863 // slot with the new name: `[h1, name]`.
864 self.names.truncate(level);
865 self.names[level - 1] = name;
867 // ... On the other hand, consider `level == 5`. This means we
868 // need to extend `self.names` to contain five headers. We fill
869 // in the missing level (<h4>) with `_`. Thus `self.names` will
870 // become `[h1, h2, h3, "_", name]`.
871 if level - 1 > self.names.len() {
872 self.names.resize(level - 1, "_".to_owned());
874 self.names.push(name);
880 struct HirCollector<'a, 'hir> {
881 sess: &'a session::Session,
882 collector: &'a mut Collector,
883 map: &'a hir::map::Map<'hir>,
887 impl<'a, 'hir> HirCollector<'a, 'hir> {
888 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
890 attrs: &[ast::Attribute],
892 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
893 if let Some(ref cfg) = attrs.cfg {
894 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
899 let has_name = !name.is_empty();
901 self.collector.names.push(name);
904 attrs.collapse_doc_comments();
905 attrs.unindent_doc_comments();
906 // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
907 // anything else, this will combine them for us.
908 if let Some(doc) = attrs.collapsed_doc_value() {
909 self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
910 markdown::find_testable_code(&doc, self.collector, self.codes);
916 self.collector.names.pop();
921 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
922 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
923 intravisit::NestedVisitorMap::All(&self.map)
926 fn visit_item(&mut self, item: &'hir hir::Item) {
927 let name = if let hir::ItemKind::Impl(.., ref ty, _) = item.node {
928 self.map.hir_to_pretty_string(ty.hir_id)
930 item.ident.to_string()
933 self.visit_testable(name, &item.attrs, |this| {
934 intravisit::walk_item(this, item);
938 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
939 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
940 intravisit::walk_trait_item(this, item);
944 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
945 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
946 intravisit::walk_impl_item(this, item);
950 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
951 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
952 intravisit::walk_foreign_item(this, item);
956 fn visit_variant(&mut self,
957 v: &'hir hir::Variant,
958 g: &'hir hir::Generics,
959 item_id: hir::HirId) {
960 self.visit_testable(v.ident.to_string(), &v.attrs, |this| {
961 intravisit::walk_variant(this, v, g, item_id);
965 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
966 self.visit_testable(f.ident.to_string(), &f.attrs, |this| {
967 intravisit::walk_struct_field(this, f);
971 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
972 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());