]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
rustdoc: pretty-print Unevaluated expressions in types.
[rust.git] / src / librustdoc / test.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::collections::HashMap;
12 use std::env;
13 use std::ffi::OsString;
14 use std::io::prelude::*;
15 use std::io;
16 use std::path::{Path, PathBuf};
17 use std::panic::{self, AssertUnwindSafe};
18 use std::process::Command;
19 use std::rc::Rc;
20 use std::str;
21 use std::sync::{Arc, Mutex};
22
23 use testing;
24 use rustc_lint;
25 use rustc::dep_graph::DepGraph;
26 use rustc::hir;
27 use rustc::hir::intravisit;
28 use rustc::session::{self, CompileIncomplete, config};
29 use rustc::session::config::{OutputType, OutputTypes, Externs};
30 use rustc::session::search_paths::{SearchPaths, PathKind};
31 use rustc_back::dynamic_lib::DynamicLibrary;
32 use rustc_back::tempdir::TempDir;
33 use rustc_driver::{self, driver, Compilation};
34 use rustc_driver::driver::phase_2_configure_and_expand;
35 use rustc_driver::pretty::ReplaceBodyWithLoop;
36 use rustc_metadata::cstore::CStore;
37 use rustc_resolve::MakeGlobMap;
38 use rustc_trans;
39 use rustc_trans::back::link;
40 use syntax::ast;
41 use syntax::codemap::CodeMap;
42 use syntax::feature_gate::UnstableFeatures;
43 use syntax::fold::Folder;
44 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span};
45 use errors;
46 use errors::emitter::ColorConfig;
47
48 use clean::Attributes;
49 use html::markdown::{self, RenderType};
50
51 #[derive(Clone, Default)]
52 pub struct TestOptions {
53     pub no_crate_inject: bool,
54     pub attrs: Vec<String>,
55 }
56
57 pub fn run(input: &str,
58            cfgs: Vec<String>,
59            libs: SearchPaths,
60            externs: Externs,
61            mut test_args: Vec<String>,
62            crate_name: Option<String>,
63            maybe_sysroot: Option<PathBuf>,
64            render_type: RenderType,
65            display_warnings: bool)
66            -> isize {
67     let input_path = PathBuf::from(input);
68     let input = config::Input::File(input_path.clone());
69
70     let sessopts = config::Options {
71         maybe_sysroot: maybe_sysroot.clone().or_else(
72             || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
73         search_paths: libs.clone(),
74         crate_types: vec![config::CrateTypeDylib],
75         externs: externs.clone(),
76         unstable_features: UnstableFeatures::from_environment(),
77         lint_cap: Some(::rustc::lint::Level::Allow),
78         actually_rustdoc: true,
79         ..config::basic_options().clone()
80     };
81
82     let codemap = Rc::new(CodeMap::new(sessopts.file_path_mapping()));
83     let handler =
84         errors::Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
85
86     let dep_graph = DepGraph::new(false);
87     let _ignore = dep_graph.in_ignore();
88     let cstore = Rc::new(CStore::new(box rustc_trans::LlvmMetadataLoader));
89     let mut sess = session::build_session_(
90         sessopts, &dep_graph, Some(input_path.clone()), handler, codemap.clone()
91     );
92     rustc_trans::init(&sess);
93     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
94     sess.parse_sess.config =
95         config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
96
97     let krate = panictry!(driver::phase_1_parse_input(&driver::CompileController::basic(),
98                                                       &sess,
99                                                       &input));
100     let krate = ReplaceBodyWithLoop::new().fold_crate(krate);
101     let driver::ExpansionResult { defs, mut hir_forest, .. } = {
102         phase_2_configure_and_expand(
103             &sess, &cstore, krate, None, "rustdoc-test", None, MakeGlobMap::No, |_| Ok(())
104         ).expect("phase_2_configure_and_expand aborted in rustdoc!")
105     };
106
107     let crate_name = crate_name.unwrap_or_else(|| {
108         link::find_crate_name(None, &hir_forest.krate().attrs, &input)
109     });
110     let opts = scrape_test_config(hir_forest.krate());
111     let mut collector = Collector::new(crate_name,
112                                        cfgs,
113                                        libs,
114                                        externs,
115                                        false,
116                                        opts,
117                                        maybe_sysroot,
118                                        Some(codemap),
119                                        None,
120                                        render_type);
121
122     {
123         let dep_graph = DepGraph::new(false);
124         let _ignore = dep_graph.in_ignore();
125         let map = hir::map::map_crate(&mut hir_forest, defs);
126         let krate = map.krate();
127         let mut hir_collector = HirCollector {
128             sess: &sess,
129             collector: &mut collector,
130             map: &map
131         };
132         hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
133             intravisit::walk_crate(this, krate);
134         });
135     }
136
137     test_args.insert(0, "rustdoctest".to_string());
138
139     testing::test_main(&test_args,
140                        collector.tests.into_iter().collect(),
141                        testing::Options::new().display_output(display_warnings));
142     0
143 }
144
145 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
146 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
147     use syntax::print::pprust;
148
149     let mut opts = TestOptions {
150         no_crate_inject: false,
151         attrs: Vec::new(),
152     };
153
154     let test_attrs: Vec<_> = krate.attrs.iter()
155         .filter(|a| a.check_name("doc"))
156         .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
157         .filter(|a| a.check_name("test"))
158         .collect();
159     let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
160
161     for attr in attrs {
162         if attr.check_name("no_crate_inject") {
163             opts.no_crate_inject = true;
164         }
165         if attr.check_name("attr") {
166             if let Some(l) = attr.meta_item_list() {
167                 for item in l {
168                     opts.attrs.push(pprust::meta_list_item_to_string(item));
169                 }
170             }
171         }
172     }
173
174     opts
175 }
176
177 fn run_test(test: &str, cratename: &str, filename: &str, cfgs: Vec<String>, libs: SearchPaths,
178             externs: Externs,
179             should_panic: bool, no_run: bool, as_test_harness: bool,
180             compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
181             maybe_sysroot: Option<PathBuf>) {
182     // the test harness wants its own `main` & top level functions, so
183     // never wrap the test in `fn main() { ... }`
184     let test = make_test(test, Some(cratename), as_test_harness, opts);
185     let input = config::Input::Str {
186         name: filename.to_owned(),
187         input: test.to_owned(),
188     };
189     let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
190
191     let sessopts = config::Options {
192         maybe_sysroot: maybe_sysroot.or_else(
193             || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
194         search_paths: libs,
195         crate_types: vec![config::CrateTypeExecutable],
196         output_types: outputs,
197         externs,
198         cg: config::CodegenOptions {
199             prefer_dynamic: true,
200             .. config::basic_codegen_options()
201         },
202         test: as_test_harness,
203         unstable_features: UnstableFeatures::from_environment(),
204         ..config::basic_options().clone()
205     };
206
207     // Shuffle around a few input and output handles here. We're going to pass
208     // an explicit handle into rustc to collect output messages, but we also
209     // want to catch the error message that rustc prints when it fails.
210     //
211     // We take our thread-local stderr (likely set by the test runner) and replace
212     // it with a sink that is also passed to rustc itself. When this function
213     // returns the output of the sink is copied onto the output of our own thread.
214     //
215     // The basic idea is to not use a default Handler for rustc, and then also
216     // not print things by default to the actual stderr.
217     struct Sink(Arc<Mutex<Vec<u8>>>);
218     impl Write for Sink {
219         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
220             Write::write(&mut *self.0.lock().unwrap(), data)
221         }
222         fn flush(&mut self) -> io::Result<()> { Ok(()) }
223     }
224     struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
225     impl Drop for Bomb {
226         fn drop(&mut self) {
227             let _ = self.1.write_all(&self.0.lock().unwrap());
228         }
229     }
230     let data = Arc::new(Mutex::new(Vec::new()));
231     let codemap = Rc::new(CodeMap::new(sessopts.file_path_mapping()));
232     let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
233                                                       Some(codemap.clone()));
234     let old = io::set_panic(Some(box Sink(data.clone())));
235     let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
236
237     // Compile the code
238     let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
239
240     let dep_graph = DepGraph::new(false);
241     let cstore = Rc::new(CStore::new(box rustc_trans::LlvmMetadataLoader));
242     let mut sess = session::build_session_(
243         sessopts, &dep_graph, None, diagnostic_handler, codemap
244     );
245     rustc_trans::init(&sess);
246     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
247
248     let outdir = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
249     let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
250     let mut control = driver::CompileController::basic();
251     sess.parse_sess.config =
252         config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
253     let out = Some(outdir.lock().unwrap().path().to_path_buf());
254
255     if no_run {
256         control.after_analysis.stop = Compilation::Stop;
257     }
258
259     let res = panic::catch_unwind(AssertUnwindSafe(|| {
260         driver::compile_input(&sess, &cstore, &input, &out, &None, None, &control)
261     }));
262
263     let compile_result = match res {
264         Ok(Ok(())) | Ok(Err(CompileIncomplete::Stopped)) => Ok(()),
265         Err(_) | Ok(Err(CompileIncomplete::Errored(_))) => Err(())
266     };
267
268     match (compile_result, compile_fail) {
269         (Ok(()), true) => {
270             panic!("test compiled while it wasn't supposed to")
271         }
272         (Ok(()), false) => {}
273         (Err(()), true) => {
274             if error_codes.len() > 0 {
275                 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
276                 error_codes.retain(|err| !out.contains(err));
277             }
278         }
279         (Err(()), false) => {
280             panic!("couldn't compile the test")
281         }
282     }
283
284     if error_codes.len() > 0 {
285         panic!("Some expected error codes were not found: {:?}", error_codes);
286     }
287
288     if no_run { return }
289
290     // Run the code!
291     //
292     // We're careful to prepend the *target* dylib search path to the child's
293     // environment to ensure that the target loads the right libraries at
294     // runtime. It would be a sad day if the *host* libraries were loaded as a
295     // mistake.
296     let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
297     let var = DynamicLibrary::envvar();
298     let newpath = {
299         let path = env::var_os(var).unwrap_or(OsString::new());
300         let mut path = env::split_paths(&path).collect::<Vec<_>>();
301         path.insert(0, libdir.clone());
302         env::join_paths(path).unwrap()
303     };
304     cmd.env(var, &newpath);
305
306     match cmd.output() {
307         Err(e) => panic!("couldn't run the test: {}{}", e,
308                         if e.kind() == io::ErrorKind::PermissionDenied {
309                             " - maybe your tempdir is mounted with noexec?"
310                         } else { "" }),
311         Ok(out) => {
312             if should_panic && out.status.success() {
313                 panic!("test executable succeeded when it should have failed");
314             } else if !should_panic && !out.status.success() {
315                 panic!("test executable failed:\n{}\n{}\n",
316                        str::from_utf8(&out.stdout).unwrap_or(""),
317                        str::from_utf8(&out.stderr).unwrap_or(""));
318             }
319         }
320     }
321 }
322
323 pub fn make_test(s: &str,
324                  cratename: Option<&str>,
325                  dont_insert_main: bool,
326                  opts: &TestOptions)
327                  -> String {
328     let (crate_attrs, everything_else) = partition_source(s);
329
330     let mut prog = String::new();
331
332     // First push any outer attributes from the example, assuming they
333     // are intended to be crate attributes.
334     prog.push_str(&crate_attrs);
335
336     // Next, any attributes for other aspects such as lints.
337     for attr in &opts.attrs {
338         prog.push_str(&format!("#![{}]\n", attr));
339     }
340
341     // Don't inject `extern crate std` because it's already injected by the
342     // compiler.
343     if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
344         if let Some(cratename) = cratename {
345             if s.contains(cratename) {
346                 prog.push_str(&format!("extern crate {};\n", cratename));
347             }
348         }
349     }
350     if dont_insert_main || s.contains("fn main") {
351         prog.push_str(&everything_else);
352     } else {
353         prog.push_str("fn main() {\n");
354         prog.push_str(&everything_else);
355         prog = prog.trim().into();
356         prog.push_str("\n}");
357     }
358
359     info!("final test program: {}", prog);
360
361     prog
362 }
363
364 // FIXME(aburka): use a real parser to deal with multiline attributes
365 fn partition_source(s: &str) -> (String, String) {
366     use std_unicode::str::UnicodeStr;
367
368     let mut after_header = false;
369     let mut before = String::new();
370     let mut after = String::new();
371
372     for line in s.lines() {
373         let trimline = line.trim();
374         let header = trimline.is_whitespace() ||
375             trimline.starts_with("#![");
376         if !header || after_header {
377             after_header = true;
378             after.push_str(line);
379             after.push_str("\n");
380         } else {
381             before.push_str(line);
382             before.push_str("\n");
383         }
384     }
385
386     (before, after)
387 }
388
389 pub struct Collector {
390     pub tests: Vec<testing::TestDescAndFn>,
391     // to be removed when hoedown will be definitely gone
392     pub old_tests: HashMap<String, Vec<String>>,
393     names: Vec<String>,
394     cfgs: Vec<String>,
395     libs: SearchPaths,
396     externs: Externs,
397     cnt: usize,
398     use_headers: bool,
399     current_header: Option<String>,
400     cratename: String,
401     opts: TestOptions,
402     maybe_sysroot: Option<PathBuf>,
403     position: Span,
404     codemap: Option<Rc<CodeMap>>,
405     filename: Option<String>,
406     // to be removed when hoedown will be removed as well
407     pub render_type: RenderType,
408 }
409
410 impl Collector {
411     pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
412                use_headers: bool, opts: TestOptions, maybe_sysroot: Option<PathBuf>,
413                codemap: Option<Rc<CodeMap>>, filename: Option<String>,
414                render_type: RenderType) -> Collector {
415         Collector {
416             tests: Vec::new(),
417             old_tests: HashMap::new(),
418             names: Vec::new(),
419             cfgs,
420             libs,
421             externs,
422             cnt: 0,
423             use_headers,
424             current_header: None,
425             cratename,
426             opts,
427             maybe_sysroot,
428             position: DUMMY_SP,
429             codemap,
430             filename,
431             render_type,
432         }
433     }
434
435     fn generate_name(&self, line: usize, filename: &str) -> String {
436         if self.use_headers {
437             if let Some(ref header) = self.current_header {
438                 format!("{} - {} (line {})", filename, header, line)
439             } else {
440                 format!("{} - (line {})", filename, line)
441             }
442         } else {
443             format!("{} - {} (line {})", filename, self.names.join("::"), line)
444         }
445     }
446
447     // to be removed once hoedown is gone
448     fn generate_name_beginning(&self, filename: &str) -> String {
449         if self.use_headers {
450             if let Some(ref header) = self.current_header {
451                 format!("{} - {} (line", filename, header)
452             } else {
453                 format!("{} - (line", filename)
454             }
455         } else {
456             format!("{} - {} (line", filename, self.names.join("::"))
457         }
458     }
459
460     pub fn add_old_test(&mut self, test: String, filename: String) {
461         let name_beg = self.generate_name_beginning(&filename);
462         let entry = self.old_tests.entry(name_beg)
463                                   .or_insert(Vec::new());
464         entry.push(test.trim().to_owned());
465     }
466
467     pub fn add_test(&mut self, test: String,
468                     should_panic: bool, no_run: bool, should_ignore: bool,
469                     as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>,
470                     line: usize, filename: String, allow_fail: bool) {
471         let name = self.generate_name(line, &filename);
472         // to be removed when hoedown is removed
473         if self.render_type == RenderType::Pulldown {
474             let name_beg = self.generate_name_beginning(&filename);
475             let mut found = false;
476             let test = test.trim().to_owned();
477             if let Some(entry) = self.old_tests.get_mut(&name_beg) {
478                 found = entry.remove_item(&test).is_some();
479             }
480             if !found {
481                 let _ = writeln!(&mut io::stderr(),
482                                  "WARNING: {} Code block is not currently run as a test, but will \
483                                   in future versions of rustdoc. Please ensure this code block is \
484                                   a runnable test, or use the `ignore` directive.",
485                                  name);
486                 return
487             }
488         }
489         let cfgs = self.cfgs.clone();
490         let libs = self.libs.clone();
491         let externs = self.externs.clone();
492         let cratename = self.cratename.to_string();
493         let opts = self.opts.clone();
494         let maybe_sysroot = self.maybe_sysroot.clone();
495         debug!("Creating test {}: {}", name, test);
496         self.tests.push(testing::TestDescAndFn {
497             desc: testing::TestDesc {
498                 name: testing::DynTestName(name),
499                 ignore: should_ignore,
500                 // compiler failures are test failures
501                 should_panic: testing::ShouldPanic::No,
502                 allow_fail,
503             },
504             testfn: testing::DynTestFn(box move |()| {
505                 let panic = io::set_panic(None);
506                 let print = io::set_print(None);
507                 match {
508                     rustc_driver::in_rustc_thread(move || {
509                         io::set_panic(panic);
510                         io::set_print(print);
511                         run_test(&test,
512                                  &cratename,
513                                  &filename,
514                                  cfgs,
515                                  libs,
516                                  externs,
517                                  should_panic,
518                                  no_run,
519                                  as_test_harness,
520                                  compile_fail,
521                                  error_codes,
522                                  &opts,
523                                  maybe_sysroot)
524                     })
525                 } {
526                     Ok(()) => (),
527                     Err(err) => panic::resume_unwind(err),
528                 }
529             }),
530         });
531     }
532
533     pub fn get_line(&self) -> usize {
534         if let Some(ref codemap) = self.codemap {
535             let line = self.position.lo().to_usize();
536             let line = codemap.lookup_char_pos(BytePos(line as u32)).line;
537             if line > 0 { line - 1 } else { line }
538         } else {
539             0
540         }
541     }
542
543     pub fn set_position(&mut self, position: Span) {
544         self.position = position;
545     }
546
547     pub fn get_filename(&self) -> String {
548         if let Some(ref codemap) = self.codemap {
549             let filename = codemap.span_to_filename(self.position);
550             if let Ok(cur_dir) = env::current_dir() {
551                 if let Ok(path) = Path::new(&filename).strip_prefix(&cur_dir) {
552                     if let Some(path) = path.to_str() {
553                         return path.to_owned();
554                     }
555                 }
556             }
557             filename
558         } else if let Some(ref filename) = self.filename {
559             filename.clone()
560         } else {
561             "<input>".to_owned()
562         }
563     }
564
565     pub fn register_header(&mut self, name: &str, level: u32) {
566         if self.use_headers && level == 1 {
567             // we use these headings as test names, so it's good if
568             // they're valid identifiers.
569             let name = name.chars().enumerate().map(|(i, c)| {
570                     if (i == 0 && c.is_xid_start()) ||
571                         (i != 0 && c.is_xid_continue()) {
572                         c
573                     } else {
574                         '_'
575                     }
576                 }).collect::<String>();
577
578             // new header => reset count.
579             self.cnt = 0;
580             self.current_header = Some(name);
581         }
582     }
583 }
584
585 struct HirCollector<'a, 'hir: 'a> {
586     sess: &'a session::Session,
587     collector: &'a mut Collector,
588     map: &'a hir::map::Map<'hir>
589 }
590
591 impl<'a, 'hir> HirCollector<'a, 'hir> {
592     fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
593                                             name: String,
594                                             attrs: &[ast::Attribute],
595                                             nested: F) {
596         let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
597         if let Some(ref cfg) = attrs.cfg {
598             if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features.borrow())) {
599                 return;
600             }
601         }
602
603         let has_name = !name.is_empty();
604         if has_name {
605             self.collector.names.push(name);
606         }
607
608         attrs.collapse_doc_comments();
609         attrs.unindent_doc_comments();
610         if let Some(doc) = attrs.doc_value() {
611             self.collector.cnt = 0;
612             if self.collector.render_type == RenderType::Pulldown {
613                 markdown::old_find_testable_code(doc, self.collector,
614                                                  attrs.span.unwrap_or(DUMMY_SP));
615                 markdown::find_testable_code(doc, self.collector,
616                                              attrs.span.unwrap_or(DUMMY_SP));
617             } else {
618                 markdown::old_find_testable_code(doc, self.collector,
619                                                  attrs.span.unwrap_or(DUMMY_SP));
620             }
621         }
622
623         nested(self);
624
625         if has_name {
626             self.collector.names.pop();
627         }
628     }
629 }
630
631 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
632     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
633         intravisit::NestedVisitorMap::All(&self.map)
634     }
635
636     fn visit_item(&mut self, item: &'hir hir::Item) {
637         let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
638             self.map.node_to_pretty_string(ty.id)
639         } else {
640             item.name.to_string()
641         };
642
643         self.visit_testable(name, &item.attrs, |this| {
644             intravisit::walk_item(this, item);
645         });
646     }
647
648     fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
649         self.visit_testable(item.name.to_string(), &item.attrs, |this| {
650             intravisit::walk_trait_item(this, item);
651         });
652     }
653
654     fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
655         self.visit_testable(item.name.to_string(), &item.attrs, |this| {
656             intravisit::walk_impl_item(this, item);
657         });
658     }
659
660     fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
661         self.visit_testable(item.name.to_string(), &item.attrs, |this| {
662             intravisit::walk_foreign_item(this, item);
663         });
664     }
665
666     fn visit_variant(&mut self,
667                      v: &'hir hir::Variant,
668                      g: &'hir hir::Generics,
669                      item_id: ast::NodeId) {
670         self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
671             intravisit::walk_variant(this, v, g, item_id);
672         });
673     }
674
675     fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
676         self.visit_testable(f.name.to_string(), &f.attrs, |this| {
677             intravisit::walk_struct_field(this, f);
678         });
679     }
680
681     fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
682         self.visit_testable(macro_def.name.to_string(), &macro_def.attrs, |_| ());
683     }
684 }