1 use rustc::hir::map::Map;
2 use rustc::session::{self, config, DiagnosticOutput};
3 use rustc::util::common::ErrorReported;
4 use rustc_data_structures::sync::Lrc;
5 use rustc_feature::UnstableFeatures;
7 use rustc_hir::intravisit;
8 use rustc_interface::interface;
9 use rustc_span::edition::Edition;
10 use rustc_span::source_map::SourceMap;
11 use rustc_span::symbol::sym;
12 use rustc_span::{BytePos, FileName, Pos, Span, DUMMY_SP};
13 use rustc_target::spec::TargetTriple;
15 use std::io::{self, Write};
17 use std::path::PathBuf;
18 use std::process::{self, Command, Stdio};
21 use syntax::with_globals;
22 use tempfile::Builder as TempFileBuilder;
24 use crate::clean::Attributes;
25 use crate::config::Options;
26 use crate::html::markdown::{self, ErrorCodes, Ignore, LangString};
28 #[derive(Clone, Default)]
29 pub struct TestOptions {
30 /// Whether to disable the default `extern crate my_crate;` when creating doctests.
31 pub no_crate_inject: bool,
32 /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
33 /// the default `#![allow(unused)]`.
34 pub display_warnings: bool,
35 /// Additional crate-level attributes to add to doctests.
36 pub attrs: Vec<String>,
39 pub fn run(options: Options) -> i32 {
40 let input = config::Input::File(options.input.clone());
42 let crate_types = if options.proc_macro_crate {
43 vec![config::CrateType::ProcMacro]
45 vec![config::CrateType::Rlib]
48 let sessopts = config::Options {
49 maybe_sysroot: options.maybe_sysroot.clone(),
50 search_paths: options.libs.clone(),
52 cg: options.codegen_options.clone(),
53 externs: options.externs.clone(),
54 unstable_features: UnstableFeatures::from_environment(),
55 lint_cap: Some(::rustc::lint::Level::Allow),
56 actually_rustdoc: true,
57 debugging_opts: config::DebuggingOptions { ..config::basic_debugging_options() },
58 edition: options.edition,
59 target_triple: options.target.clone(),
60 ..config::Options::default()
63 let mut cfgs = options.cfgs.clone();
64 cfgs.push("doc".to_owned());
65 cfgs.push("doctest".to_owned());
66 let config = interface::Config {
68 crate_cfg: interface::parse_cfgspecs(cfgs),
74 diagnostic_output: DiagnosticOutput::Default,
76 crate_name: options.crate_name.clone(),
77 lint_caps: Default::default(),
79 override_queries: None,
80 registry: rustc_driver::diagnostics_registry(),
83 let mut test_args = options.test_args.clone();
84 let display_warnings = options.display_warnings;
86 let tests = interface::run_compiler(config, |compiler| {
87 compiler.enter(|queries| {
88 let lower_to_hir = queries.lower_to_hir()?;
90 let mut opts = scrape_test_config(lower_to_hir.peek().0);
91 opts.display_warnings |= options.display_warnings;
92 let enable_per_target_ignores = options.enable_per_target_ignores;
93 let mut collector = Collector::new(
94 queries.crate_name()?.peek().to_string(),
98 Some(compiler.source_map().clone()),
100 enable_per_target_ignores,
103 let mut global_ctxt = queries.global_ctxt()?.take();
105 global_ctxt.enter(|tcx| {
106 let krate = tcx.hir().krate();
107 let mut hir_collector = HirCollector {
108 sess: compiler.session(),
109 collector: &mut collector,
111 codes: ErrorCodes::from(
112 compiler.session().opts.unstable_features.is_nightly_build(),
115 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
116 intravisit::walk_crate(this, krate);
119 compiler.session().abort_if_errors();
121 let ret: Result<_, ErrorReported> = Ok(collector.tests);
125 let tests = match tests {
127 Err(ErrorReported) => return 1,
130 test_args.insert(0, "rustdoctest".to_string());
135 Some(testing::Options::new().display_output(display_warnings)),
141 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
142 fn scrape_test_config(krate: &::rustc_hir::Crate) -> TestOptions {
143 use rustc_ast_pretty::pprust;
146 TestOptions { no_crate_inject: false, display_warnings: false, attrs: Vec::new() };
148 let test_attrs: Vec<_> = krate
151 .filter(|a| a.check_name(sym::doc))
152 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
153 .filter(|a| a.check_name(sym::test))
155 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
158 if attr.check_name(sym::no_crate_inject) {
159 opts.no_crate_inject = true;
161 if attr.check_name(sym::attr) {
162 if let Some(l) = attr.meta_item_list() {
164 opts.attrs.push(pprust::meta_list_item_to_string(item));
173 /// Documentation test failure modes.
175 /// The test failed to compile.
177 /// The test is marked `compile_fail` but compiled successfully.
178 UnexpectedCompilePass,
179 /// The test failed to compile (as expected) but the compiler output did not contain all
180 /// expected error codes.
181 MissingErrorCodes(Vec<String>),
182 /// The test binary was unable to be executed.
183 ExecutionError(io::Error),
184 /// The test binary exited with a non-zero exit code.
186 /// This typically means an assertion in the test failed or another form of panic occurred.
187 ExecutionFailure(process::Output),
188 /// The test is marked `should_panic` but the test binary executed successfully.
200 as_test_harness: bool,
201 runtool: Option<String>,
202 runtool_args: Vec<String>,
203 target: TargetTriple,
205 mut error_codes: Vec<String>,
208 ) -> Result<(), TestFailure> {
209 let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts, edition);
211 // FIXME(#44940): if doctests ever support path remapping, then this filename
212 // needs to be the result of `SourceMap::span_to_unmapped_path`.
213 let path = match filename {
214 FileName::Real(path) => path.clone(),
215 _ => PathBuf::from(r"doctest.rs"),
219 Temp(tempfile::TempDir),
224 fn path(&self) -> &std::path::Path {
226 DirState::Temp(t) => t.path(),
227 DirState::Perm(p) => p.as_path(),
232 let outdir = if let Some(mut path) = options.persist_doctests {
235 filename.to_string().rsplit('/').next().unwrap().replace(".", "_"),
238 std::fs::create_dir_all(&path).expect("Couldn't create directory for doctest executables");
243 TempFileBuilder::new()
244 .prefix("rustdoctest")
246 .expect("rustdoc needs a tempdir"),
249 let output_file = outdir.path().join("rust_out");
251 let rustc_binary = options
255 .unwrap_or_else(|| rustc_interface::util::rustc_path().expect("found rustc"));
256 let mut compiler = Command::new(&rustc_binary);
257 compiler.arg("--crate-type").arg("bin");
258 for cfg in &options.cfgs {
259 compiler.arg("--cfg").arg(&cfg);
261 if let Some(sysroot) = options.maybe_sysroot {
262 compiler.arg("--sysroot").arg(sysroot);
264 compiler.arg("--edition").arg(&edition.to_string());
265 compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", path);
266 compiler.env("UNSTABLE_RUSTDOC_TEST_LINE", format!("{}", line as isize - line_offset as isize));
267 compiler.arg("-o").arg(&output_file);
269 compiler.arg("--test");
271 for lib_str in &options.lib_strs {
272 compiler.arg("-L").arg(&lib_str);
274 for extern_str in &options.extern_strs {
275 compiler.arg("--extern").arg(&extern_str);
277 compiler.arg("-Ccodegen-units=1");
278 for codegen_options_str in &options.codegen_options_strs {
279 compiler.arg("-C").arg(&codegen_options_str);
281 for debugging_option_str in &options.debugging_options_strs {
282 compiler.arg("-Z").arg(&debugging_option_str);
284 if no_run && !compile_fail {
285 compiler.arg("--emit=metadata");
287 compiler.arg("--target").arg(target.to_string());
290 compiler.stdin(Stdio::piped());
291 compiler.stderr(Stdio::piped());
293 let mut child = compiler.spawn().expect("Failed to spawn rustc process");
295 let stdin = child.stdin.as_mut().expect("Failed to open stdin");
296 stdin.write_all(test.as_bytes()).expect("could write out test sources");
298 let output = child.wait_with_output().expect("Failed to read stdout");
300 struct Bomb<'a>(&'a str);
301 impl Drop for Bomb<'_> {
303 eprint!("{}", self.0);
306 let out = str::from_utf8(&output.stderr).unwrap();
307 let _bomb = Bomb(&out);
308 match (output.status.success(), compile_fail) {
310 return Err(TestFailure::UnexpectedCompilePass);
314 if !error_codes.is_empty() {
315 error_codes.retain(|err| !out.contains(&format!("error[{}]: ", err)));
317 if !error_codes.is_empty() {
318 return Err(TestFailure::MissingErrorCodes(error_codes));
323 return Err(TestFailure::CompileError);
334 if let Some(tool) = runtool {
335 cmd = Command::new(tool);
336 cmd.arg(output_file);
337 cmd.args(runtool_args);
339 cmd = Command::new(output_file);
343 Err(e) => return Err(TestFailure::ExecutionError(e)),
345 if should_panic && out.status.success() {
346 return Err(TestFailure::UnexpectedRunPass);
347 } else if !should_panic && !out.status.success() {
348 return Err(TestFailure::ExecutionFailure(out));
356 /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
357 /// lines before the test code begins.
360 cratename: Option<&str>,
361 dont_insert_main: bool,
364 ) -> (String, usize) {
365 let (crate_attrs, everything_else, crates) = partition_source(s);
366 let everything_else = everything_else.trim();
367 let mut line_offset = 0;
368 let mut prog = String::new();
370 if opts.attrs.is_empty() && !opts.display_warnings {
371 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
372 // lints that are commonly triggered in doctests. The crate-level test attributes are
373 // commonly used to make tests fail in case they trigger warnings, so having this there in
374 // that case may cause some tests to pass when they shouldn't have.
375 prog.push_str("#![allow(unused)]\n");
379 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
380 for attr in &opts.attrs {
381 prog.push_str(&format!("#![{}]\n", attr));
385 // Now push any outer attributes from the example, assuming they
386 // are intended to be crate attributes.
387 prog.push_str(&crate_attrs);
388 prog.push_str(&crates);
390 // Uses libsyntax to parse the doctest and find if there's a main fn and the extern
391 // crate already is included.
392 let result = rustc_driver::catch_fatal_errors(|| {
393 with_globals(edition, || {
394 use rustc_errors::emitter::EmitterWriter;
395 use rustc_errors::Handler;
396 use rustc_parse::maybe_new_parser_from_source_str;
397 use rustc_session::parse::ParseSess;
398 use rustc_span::source_map::FilePathMapping;
400 let filename = FileName::anon_source_code(s);
401 let source = crates + &everything_else;
403 // Any errors in parsing should also appear when the doctest is compiled for real, so just
404 // send all the errors that libsyntax emits directly into a `Sink` instead of stderr.
405 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
407 EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
408 // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
409 let handler = Handler::with_emitter(false, None, box emitter);
410 let sess = ParseSess::with_span_handler(handler, sm);
412 let mut found_main = false;
413 let mut found_extern_crate = cratename.is_none();
414 let mut found_macro = false;
416 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source) {
419 for mut err in errs {
423 return (found_main, found_extern_crate, found_macro);
428 match parser.parse_item() {
431 if let ast::ItemKind::Fn(..) = item.kind {
432 if item.ident.name == sym::main {
438 if !found_extern_crate {
439 if let ast::ItemKind::ExternCrate(original) = item.kind {
440 // This code will never be reached if `cratename` is none because
441 // `found_extern_crate` is initialized to `true` if it is none.
442 let cratename = cratename.unwrap();
445 Some(name) => found_extern_crate = name.as_str() == cratename,
446 None => found_extern_crate = item.ident.as_str() == cratename,
452 if let ast::ItemKind::Mac(..) = item.kind {
457 if found_main && found_extern_crate {
469 (found_main, found_extern_crate, found_macro)
472 let (already_has_main, already_has_extern_crate, found_macro) = match result {
473 Ok(result) => result,
474 Err(ErrorReported) => {
475 // If the parser panicked due to a fatal error, pass the test code through unchanged.
476 // The error will be reported during compilation.
477 return (s.to_owned(), 0);
481 // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
482 // see it. In that case, run the old text-based scan to see if they at least have a main
483 // function written inside a macro invocation. See
484 // https://github.com/rust-lang/rust/issues/56898
485 let already_has_main = if found_macro && !already_has_main {
488 let comment = line.find("//");
489 if let Some(comment_begins) = comment { &line[0..comment_begins] } else { line }
491 .any(|code| code.contains("fn main"))
496 // Don't inject `extern crate std` because it's already injected by the
498 if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
499 if let Some(cratename) = cratename {
500 // Make sure its actually used if not included.
501 if s.contains(cratename) {
502 prog.push_str(&format!("extern crate {};\n", cratename));
508 // FIXME: This code cannot yet handle no_std test cases yet
509 if dont_insert_main || already_has_main || prog.contains("![no_std]") {
510 prog.push_str(everything_else);
512 let returns_result = everything_else.trim_end().ends_with("(())");
513 let (main_pre, main_post) = if returns_result {
515 "fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
516 "}\n_inner().unwrap() }",
519 ("fn main() {\n", "\n}")
521 prog.extend([main_pre, everything_else, main_post].iter().cloned());
525 debug!("final doctest:\n{}", prog);
530 // FIXME(aburka): use a real parser to deal with multiline attributes
531 fn partition_source(s: &str) -> (String, String, String) {
532 #[derive(Copy, Clone, PartialEq)]
533 enum PartitionState {
538 let mut state = PartitionState::Attrs;
539 let mut before = String::new();
540 let mut crates = String::new();
541 let mut after = String::new();
543 for line in s.lines() {
544 let trimline = line.trim();
546 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
547 // shunted into "everything else"
549 PartitionState::Attrs => {
550 state = if trimline.starts_with("#![")
551 || trimline.chars().all(|c| c.is_whitespace())
552 || (trimline.starts_with("//") && !trimline.starts_with("///"))
554 PartitionState::Attrs
555 } else if trimline.starts_with("extern crate")
556 || trimline.starts_with("#[macro_use] extern crate")
558 PartitionState::Crates
560 PartitionState::Other
563 PartitionState::Crates => {
564 state = if trimline.starts_with("extern crate")
565 || trimline.starts_with("#[macro_use] extern crate")
566 || trimline.chars().all(|c| c.is_whitespace())
567 || (trimline.starts_with("//") && !trimline.starts_with("///"))
569 PartitionState::Crates
571 PartitionState::Other
574 PartitionState::Other => {}
578 PartitionState::Attrs => {
579 before.push_str(line);
580 before.push_str("\n");
582 PartitionState::Crates => {
583 crates.push_str(line);
584 crates.push_str("\n");
586 PartitionState::Other => {
587 after.push_str(line);
588 after.push_str("\n");
593 debug!("before:\n{}", before);
594 debug!("crates:\n{}", crates);
595 debug!("after:\n{}", after);
597 (before, after, crates)
601 fn add_test(&mut self, test: String, config: LangString, line: usize);
602 fn get_line(&self) -> usize {
605 fn register_header(&mut self, _name: &str, _level: u32) {}
608 pub struct Collector {
609 pub tests: Vec<testing::TestDescAndFn>,
611 // The name of the test displayed to the user, separated by `::`.
613 // In tests from Rust source, this is the path to the item
614 // e.g., `["std", "vec", "Vec", "push"]`.
616 // In tests from a markdown file, this is the titles of all headers (h1~h6)
617 // of the sections that contain the code block, e.g., if the markdown file is
630 // the `names` vector of that test will be `["Title", "Subtitle"]`.
635 enable_per_target_ignores: bool,
639 source_map: Option<Lrc<SourceMap>>,
640 filename: Option<PathBuf>,
649 source_map: Option<Lrc<SourceMap>>,
650 filename: Option<PathBuf>,
651 enable_per_target_ignores: bool,
658 enable_per_target_ignores,
667 fn generate_name(&self, line: usize, filename: &FileName) -> String {
668 format!("{} - {} (line {})", filename, self.names.join("::"), line)
671 pub fn set_position(&mut self, position: Span) {
672 self.position = position;
675 fn get_filename(&self) -> FileName {
676 if let Some(ref source_map) = self.source_map {
677 let filename = source_map.span_to_filename(self.position);
678 if let FileName::Real(ref filename) = filename {
679 if let Ok(cur_dir) = env::current_dir() {
680 if let Ok(path) = filename.strip_prefix(&cur_dir) {
681 return path.to_owned().into();
686 } else if let Some(ref filename) = self.filename {
687 filename.clone().into()
689 FileName::Custom("input".to_owned())
694 impl Tester for Collector {
695 fn add_test(&mut self, test: String, config: LangString, line: usize) {
696 let filename = self.get_filename();
697 let name = self.generate_name(line, &filename);
698 let cratename = self.cratename.to_string();
699 let opts = self.opts.clone();
700 let edition = config.edition.unwrap_or(self.options.edition.clone());
701 let options = self.options.clone();
702 let runtool = self.options.runtool.clone();
703 let runtool_args = self.options.runtool_args.clone();
704 let target = self.options.target.clone();
705 let target_str = target.to_string();
707 debug!("creating test {}: {}", name, test);
708 self.tests.push(testing::TestDescAndFn {
709 desc: testing::TestDesc {
710 name: testing::DynTestName(name),
711 ignore: match config.ignore {
713 Ignore::None => false,
714 Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
716 // compiler failures are test failures
717 should_panic: testing::ShouldPanic::No,
718 allow_fail: config.allow_fail,
719 test_type: testing::TestType::DocTest,
721 testfn: testing::DynTestFn(box move || {
740 if let Err(err) = res {
742 TestFailure::CompileError => {
743 eprint!("Couldn't compile the test.");
745 TestFailure::UnexpectedCompilePass => {
746 eprint!("Test compiled successfully, but it's marked `compile_fail`.");
748 TestFailure::UnexpectedRunPass => {
749 eprint!("Test executable succeeded, but it's marked `should_panic`.");
751 TestFailure::MissingErrorCodes(codes) => {
752 eprint!("Some expected error codes were not found: {:?}", codes);
754 TestFailure::ExecutionError(err) => {
755 eprint!("Couldn't run the test: {}", err);
756 if err.kind() == io::ErrorKind::PermissionDenied {
757 eprint!(" - maybe your tempdir is mounted with noexec?");
760 TestFailure::ExecutionFailure(out) => {
761 let reason = if let Some(code) = out.status.code() {
762 format!("exit code {}", code)
764 String::from("terminated by signal")
767 eprintln!("Test executable failed ({}).", reason);
769 // FIXME(#12309): An unfortunate side-effect of capturing the test
770 // executable's output is that the relative ordering between the test's
771 // stdout and stderr is lost. However, this is better than the
772 // alternative: if the test executable inherited the parent's I/O
773 // handles the output wouldn't be captured at all, even on success.
775 // The ordering could be preserved if the test process' stderr was
776 // redirected to stdout, but that functionality does not exist in the
777 // standard library, so it may not be portable enough.
778 let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
779 let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
781 if !stdout.is_empty() || !stderr.is_empty() {
784 if !stdout.is_empty() {
785 eprintln!("stdout:\n{}", stdout);
788 if !stderr.is_empty() {
789 eprintln!("stderr:\n{}", stderr);
795 panic::resume_unwind(box ());
801 fn get_line(&self) -> usize {
802 if let Some(ref source_map) = self.source_map {
803 let line = self.position.lo().to_usize();
804 let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
805 if line > 0 { line - 1 } else { line }
811 fn register_header(&mut self, name: &str, level: u32) {
812 if self.use_headers {
813 // We use these headings as test names, so it's good if
814 // they're valid identifiers.
819 if (i == 0 && rustc_lexer::is_id_start(c))
820 || (i != 0 && rustc_lexer::is_id_continue(c))
827 .collect::<String>();
829 // Here we try to efficiently assemble the header titles into the
830 // test name in the form of `h1::h2::h3::h4::h5::h6`.
832 // Suppose that originally `self.names` contains `[h1, h2, h3]`...
833 let level = level as usize;
834 if level <= self.names.len() {
835 // ... Consider `level == 2`. All headers in the lower levels
836 // are irrelevant in this new level. So we should reset
837 // `self.names` to contain headers until <h2>, and replace that
838 // slot with the new name: `[h1, name]`.
839 self.names.truncate(level);
840 self.names[level - 1] = name;
842 // ... On the other hand, consider `level == 5`. This means we
843 // need to extend `self.names` to contain five headers. We fill
844 // in the missing level (<h4>) with `_`. Thus `self.names` will
845 // become `[h1, h2, h3, "_", name]`.
846 if level - 1 > self.names.len() {
847 self.names.resize(level - 1, "_".to_owned());
849 self.names.push(name);
855 struct HirCollector<'a, 'hir> {
856 sess: &'a session::Session,
857 collector: &'a mut Collector,
862 impl<'a, 'hir> HirCollector<'a, 'hir> {
863 fn visit_testable<F: FnOnce(&mut Self)>(
866 attrs: &[ast::Attribute],
869 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
870 if let Some(ref cfg) = attrs.cfg {
871 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
876 let has_name = !name.is_empty();
878 self.collector.names.push(name);
881 attrs.collapse_doc_comments();
882 attrs.unindent_doc_comments();
883 // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
884 // anything else, this will combine them for us.
885 if let Some(doc) = attrs.collapsed_doc_value() {
886 self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
887 markdown::find_testable_code(
891 self.collector.enable_per_target_ignores,
898 self.collector.names.pop();
903 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
904 type Map = Map<'hir>;
906 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<'_, Self::Map> {
907 intravisit::NestedVisitorMap::All(&self.map)
910 fn visit_item(&mut self, item: &'hir hir::Item) {
911 let name = if let hir::ItemKind::Impl { ref self_ty, .. } = item.kind {
912 self.map.hir_to_pretty_string(self_ty.hir_id)
914 item.ident.to_string()
917 self.visit_testable(name, &item.attrs, |this| {
918 intravisit::walk_item(this, item);
922 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
923 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
924 intravisit::walk_trait_item(this, item);
928 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
929 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
930 intravisit::walk_impl_item(this, item);
934 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
935 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
936 intravisit::walk_foreign_item(this, item);
942 v: &'hir hir::Variant,
943 g: &'hir hir::Generics,
946 self.visit_testable(v.ident.to_string(), &v.attrs, |this| {
947 intravisit::walk_variant(this, v, g, item_id);
951 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
952 self.visit_testable(f.ident.to_string(), &f.attrs, |this| {
953 intravisit::walk_struct_field(this, f);
957 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
958 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());