]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
6f126a1ed63060054885455f06eed474e5c7c9e4
[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::hir;
26 use rustc::hir::intravisit;
27 use rustc::session::{self, CompileIncomplete, config};
28 use rustc::session::config::{OutputType, OutputTypes, Externs};
29 use rustc::session::search_paths::{SearchPaths, PathKind};
30 use rustc_metadata::dynamic_lib::DynamicLibrary;
31 use tempdir::TempDir;
32 use rustc_driver::{self, driver, Compilation};
33 use rustc_driver::driver::phase_2_configure_and_expand;
34 use rustc_metadata::cstore::CStore;
35 use rustc_resolve::MakeGlobMap;
36 use syntax::ast;
37 use syntax::codemap::CodeMap;
38 use syntax::feature_gate::UnstableFeatures;
39 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span, FileName};
40 use errors;
41 use errors::emitter::ColorConfig;
42
43 use clean::Attributes;
44 use html::markdown::{self, RenderType};
45
46 #[derive(Clone, Default)]
47 pub struct TestOptions {
48     pub no_crate_inject: bool,
49     pub attrs: Vec<String>,
50 }
51
52 pub fn run(input_path: &Path,
53            cfgs: Vec<String>,
54            libs: SearchPaths,
55            externs: Externs,
56            mut test_args: Vec<String>,
57            crate_name: Option<String>,
58            maybe_sysroot: Option<PathBuf>,
59            render_type: RenderType,
60            display_warnings: bool,
61            linker: Option<PathBuf>)
62            -> isize {
63     let input = config::Input::File(input_path.to_owned());
64
65     let sessopts = config::Options {
66         maybe_sysroot: maybe_sysroot.clone().or_else(
67             || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
68         search_paths: libs.clone(),
69         crate_types: vec![config::CrateTypeDylib],
70         externs: externs.clone(),
71         unstable_features: UnstableFeatures::from_environment(),
72         lint_cap: Some(::rustc::lint::Level::Allow),
73         actually_rustdoc: true,
74         ..config::basic_options().clone()
75     };
76
77     let codemap = Rc::new(CodeMap::new(sessopts.file_path_mapping()));
78     let handler =
79         errors::Handler::with_tty_emitter(ColorConfig::Auto,
80                                           true, false,
81                                           Some(codemap.clone()));
82
83     let mut sess = session::build_session_(
84         sessopts, Some(input_path.to_owned()), handler, codemap.clone(),
85     );
86     let trans = rustc_driver::get_trans(&sess);
87     let cstore = Rc::new(CStore::new(trans.metadata_loader()));
88     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
89     sess.parse_sess.config =
90         config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
91
92     let krate = panictry!(driver::phase_1_parse_input(&driver::CompileController::basic(),
93                                                       &sess,
94                                                       &input));
95     let driver::ExpansionResult { defs, mut hir_forest, .. } = {
96         phase_2_configure_and_expand(
97             &sess,
98             &cstore,
99             krate,
100             None,
101             "rustdoc-test",
102             None,
103             MakeGlobMap::No,
104             |_| Ok(()),
105         ).expect("phase_2_configure_and_expand aborted in rustdoc!")
106     };
107
108     let crate_name = crate_name.unwrap_or_else(|| {
109         ::rustc_trans_utils::link::find_crate_name(None, &hir_forest.krate().attrs, &input)
110     });
111     let opts = scrape_test_config(hir_forest.krate());
112     let mut collector = Collector::new(crate_name,
113                                        cfgs,
114                                        libs,
115                                        externs,
116                                        false,
117                                        opts,
118                                        maybe_sysroot,
119                                        Some(codemap),
120                                        None,
121                                        render_type,
122                                        linker);
123
124     {
125         let map = hir::map::map_crate(&sess, &*cstore, &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: &FileName, line: usize,
178             cfgs: Vec<String>, libs: SearchPaths,
179             externs: Externs,
180             should_panic: bool, no_run: bool, as_test_harness: bool,
181             compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
182             maybe_sysroot: Option<PathBuf>,
183             linker: Option<PathBuf>) {
184     // the test harness wants its own `main` & top level functions, so
185     // never wrap the test in `fn main() { ... }`
186     let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
187     // FIXME(#44940): if doctests ever support path remapping, then this filename
188     // needs to be the result of CodeMap::span_to_unmapped_path
189     let input = config::Input::Str {
190         name: filename.to_owned(),
191         input: test.to_owned(),
192     };
193     let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
194
195     let sessopts = config::Options {
196         maybe_sysroot: maybe_sysroot.or_else(
197             || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
198         search_paths: libs,
199         crate_types: vec![config::CrateTypeExecutable],
200         output_types: outputs,
201         externs,
202         cg: config::CodegenOptions {
203             prefer_dynamic: true,
204             linker,
205             .. config::basic_codegen_options()
206         },
207         test: as_test_harness,
208         unstable_features: UnstableFeatures::from_environment(),
209         ..config::basic_options().clone()
210     };
211
212     // Shuffle around a few input and output handles here. We're going to pass
213     // an explicit handle into rustc to collect output messages, but we also
214     // want to catch the error message that rustc prints when it fails.
215     //
216     // We take our thread-local stderr (likely set by the test runner) and replace
217     // it with a sink that is also passed to rustc itself. When this function
218     // returns the output of the sink is copied onto the output of our own thread.
219     //
220     // The basic idea is to not use a default Handler for rustc, and then also
221     // not print things by default to the actual stderr.
222     struct Sink(Arc<Mutex<Vec<u8>>>);
223     impl Write for Sink {
224         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
225             Write::write(&mut *self.0.lock().unwrap(), data)
226         }
227         fn flush(&mut self) -> io::Result<()> { Ok(()) }
228     }
229     struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
230     impl Drop for Bomb {
231         fn drop(&mut self) {
232             let _ = self.1.write_all(&self.0.lock().unwrap());
233         }
234     }
235     let data = Arc::new(Mutex::new(Vec::new()));
236     let codemap = Rc::new(CodeMap::new_doctest(
237         sessopts.file_path_mapping(), filename.clone(), line as isize - line_offset as isize
238     ));
239     let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
240                                                       Some(codemap.clone()),
241                                                       false,
242                                                       false);
243     let old = io::set_panic(Some(box Sink(data.clone())));
244     let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
245
246     // Compile the code
247     let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
248
249     let mut sess = session::build_session_(
250         sessopts, None, diagnostic_handler, codemap,
251     );
252     let trans = rustc_driver::get_trans(&sess);
253     let cstore = Rc::new(CStore::new(trans.metadata_loader()));
254     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
255
256     let outdir = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
257     let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
258     let mut control = driver::CompileController::basic();
259     sess.parse_sess.config =
260         config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
261     let out = Some(outdir.lock().unwrap().path().to_path_buf());
262
263     if no_run {
264         control.after_analysis.stop = Compilation::Stop;
265     }
266
267     let res = panic::catch_unwind(AssertUnwindSafe(|| {
268         driver::compile_input(
269             trans,
270             &sess,
271             &cstore,
272             &None,
273             &input,
274             &out,
275             &None,
276             None,
277             &control
278         )
279     }));
280
281     let compile_result = match res {
282         Ok(Ok(())) | Ok(Err(CompileIncomplete::Stopped)) => Ok(()),
283         Err(_) | Ok(Err(CompileIncomplete::Errored(_))) => Err(())
284     };
285
286     match (compile_result, compile_fail) {
287         (Ok(()), true) => {
288             panic!("test compiled while it wasn't supposed to")
289         }
290         (Ok(()), false) => {}
291         (Err(()), true) => {
292             if error_codes.len() > 0 {
293                 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
294                 error_codes.retain(|err| !out.contains(err));
295             }
296         }
297         (Err(()), false) => {
298             panic!("couldn't compile the test")
299         }
300     }
301
302     if error_codes.len() > 0 {
303         panic!("Some expected error codes were not found: {:?}", error_codes);
304     }
305
306     if no_run { return }
307
308     // Run the code!
309     //
310     // We're careful to prepend the *target* dylib search path to the child's
311     // environment to ensure that the target loads the right libraries at
312     // runtime. It would be a sad day if the *host* libraries were loaded as a
313     // mistake.
314     let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
315     let var = DynamicLibrary::envvar();
316     let newpath = {
317         let path = env::var_os(var).unwrap_or(OsString::new());
318         let mut path = env::split_paths(&path).collect::<Vec<_>>();
319         path.insert(0, libdir.clone());
320         env::join_paths(path).unwrap()
321     };
322     cmd.env(var, &newpath);
323
324     match cmd.output() {
325         Err(e) => panic!("couldn't run the test: {}{}", e,
326                         if e.kind() == io::ErrorKind::PermissionDenied {
327                             " - maybe your tempdir is mounted with noexec?"
328                         } else { "" }),
329         Ok(out) => {
330             if should_panic && out.status.success() {
331                 panic!("test executable succeeded when it should have failed");
332             } else if !should_panic && !out.status.success() {
333                 panic!("test executable failed:\n{}\n{}\n",
334                        str::from_utf8(&out.stdout).unwrap_or(""),
335                        str::from_utf8(&out.stderr).unwrap_or(""));
336             }
337         }
338     }
339 }
340
341 /// Makes the test file. Also returns the number of lines before the code begins
342 pub fn make_test(s: &str,
343                  cratename: Option<&str>,
344                  dont_insert_main: bool,
345                  opts: &TestOptions)
346                  -> (String, usize) {
347     let (crate_attrs, everything_else) = partition_source(s);
348     let everything_else = everything_else.trim();
349     let mut line_offset = 0;
350     let mut prog = String::new();
351
352     if opts.attrs.is_empty() {
353         // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
354         // lints that are commonly triggered in doctests. The crate-level test attributes are
355         // commonly used to make tests fail in case they trigger warnings, so having this there in
356         // that case may cause some tests to pass when they shouldn't have.
357         prog.push_str("#![allow(unused)]\n");
358         line_offset += 1;
359     }
360
361     // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
362     for attr in &opts.attrs {
363         prog.push_str(&format!("#![{}]\n", attr));
364         line_offset += 1;
365     }
366
367     // Now push any outer attributes from the example, assuming they
368     // are intended to be crate attributes.
369     prog.push_str(&crate_attrs);
370
371     // Don't inject `extern crate std` because it's already injected by the
372     // compiler.
373     if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
374         if let Some(cratename) = cratename {
375             if s.contains(cratename) {
376                 prog.push_str(&format!("extern crate {};\n", cratename));
377                 line_offset += 1;
378             }
379         }
380     }
381
382     // FIXME (#21299): prefer libsyntax or some other actual parser over this
383     // best-effort ad hoc approach
384     let already_has_main = s.lines()
385         .map(|line| {
386             let comment = line.find("//");
387             if let Some(comment_begins) = comment {
388                 &line[0..comment_begins]
389             } else {
390                 line
391             }
392         })
393         .any(|code| code.contains("fn main"));
394
395     if dont_insert_main || already_has_main {
396         prog.push_str(everything_else);
397     } else {
398         prog.push_str("fn main() {\n");
399         line_offset += 1;
400         prog.push_str(everything_else);
401         prog.push_str("\n}");
402     }
403
404     info!("final test program: {}", prog);
405
406     (prog, line_offset)
407 }
408
409 // FIXME(aburka): use a real parser to deal with multiline attributes
410 fn partition_source(s: &str) -> (String, String) {
411     use std_unicode::str::UnicodeStr;
412
413     let mut after_header = false;
414     let mut before = String::new();
415     let mut after = String::new();
416
417     for line in s.lines() {
418         let trimline = line.trim();
419         let header = trimline.is_whitespace() ||
420             trimline.starts_with("#![");
421         if !header || after_header {
422             after_header = true;
423             after.push_str(line);
424             after.push_str("\n");
425         } else {
426             before.push_str(line);
427             before.push_str("\n");
428         }
429     }
430
431     (before, after)
432 }
433
434 pub struct Collector {
435     pub tests: Vec<testing::TestDescAndFn>,
436     // to be removed when hoedown will be definitely gone
437     pub old_tests: HashMap<String, Vec<String>>,
438
439     // The name of the test displayed to the user, separated by `::`.
440     //
441     // In tests from Rust source, this is the path to the item
442     // e.g. `["std", "vec", "Vec", "push"]`.
443     //
444     // In tests from a markdown file, this is the titles of all headers (h1~h6)
445     // of the sections that contain the code block, e.g. if the markdown file is
446     // written as:
447     //
448     // ``````markdown
449     // # Title
450     //
451     // ## Subtitle
452     //
453     // ```rust
454     // assert!(true);
455     // ```
456     // ``````
457     //
458     // the `names` vector of that test will be `["Title", "Subtitle"]`.
459     names: Vec<String>,
460
461     cfgs: Vec<String>,
462     libs: SearchPaths,
463     externs: Externs,
464     use_headers: bool,
465     cratename: String,
466     opts: TestOptions,
467     maybe_sysroot: Option<PathBuf>,
468     position: Span,
469     codemap: Option<Rc<CodeMap>>,
470     filename: Option<PathBuf>,
471     // to be removed when hoedown will be removed as well
472     pub render_type: RenderType,
473     linker: Option<PathBuf>,
474 }
475
476 impl Collector {
477     pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
478                use_headers: bool, opts: TestOptions, maybe_sysroot: Option<PathBuf>,
479                codemap: Option<Rc<CodeMap>>, filename: Option<PathBuf>,
480                render_type: RenderType, linker: Option<PathBuf>) -> Collector {
481         Collector {
482             tests: Vec::new(),
483             old_tests: HashMap::new(),
484             names: Vec::new(),
485             cfgs,
486             libs,
487             externs,
488             use_headers,
489             cratename,
490             opts,
491             maybe_sysroot,
492             position: DUMMY_SP,
493             codemap,
494             filename,
495             render_type,
496             linker,
497         }
498     }
499
500     fn generate_name(&self, line: usize, filename: &FileName) -> String {
501         format!("{} - {} (line {})", filename, self.names.join("::"), line)
502     }
503
504     // to be removed once hoedown is gone
505     fn generate_name_beginning(&self, filename: &FileName) -> String {
506         format!("{} - {} (line", filename, self.names.join("::"))
507     }
508
509     pub fn add_old_test(&mut self, test: String, filename: FileName) {
510         let name_beg = self.generate_name_beginning(&filename);
511         let entry = self.old_tests.entry(name_beg)
512                                   .or_insert(Vec::new());
513         entry.push(test.trim().to_owned());
514     }
515
516     pub fn add_test(&mut self, test: String,
517                     should_panic: bool, no_run: bool, should_ignore: bool,
518                     as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>,
519                     line: usize, filename: FileName, allow_fail: bool) {
520         let name = self.generate_name(line, &filename);
521         // to be removed when hoedown is removed
522         if self.render_type == RenderType::Pulldown {
523             let name_beg = self.generate_name_beginning(&filename);
524             let mut found = false;
525             let test = test.trim().to_owned();
526             if let Some(entry) = self.old_tests.get_mut(&name_beg) {
527                 found = entry.remove_item(&test).is_some();
528             }
529             if !found {
530                 eprintln!("WARNING: {} Code block is not currently run as a test, but will \
531                            in future versions of rustdoc. Please ensure this code block is \
532                            a runnable test, or use the `ignore` directive.",
533                           name);
534                 return
535             }
536         }
537         let cfgs = self.cfgs.clone();
538         let libs = self.libs.clone();
539         let externs = self.externs.clone();
540         let cratename = self.cratename.to_string();
541         let opts = self.opts.clone();
542         let maybe_sysroot = self.maybe_sysroot.clone();
543         let linker = self.linker.clone();
544         debug!("Creating test {}: {}", name, test);
545         self.tests.push(testing::TestDescAndFn {
546             desc: testing::TestDesc {
547                 name: testing::DynTestName(name),
548                 ignore: should_ignore,
549                 // compiler failures are test failures
550                 should_panic: testing::ShouldPanic::No,
551                 allow_fail,
552             },
553             testfn: testing::DynTestFn(box move || {
554                 let panic = io::set_panic(None);
555                 let print = io::set_print(None);
556                 match {
557                     rustc_driver::in_rustc_thread(move || {
558                         io::set_panic(panic);
559                         io::set_print(print);
560                         run_test(&test,
561                                  &cratename,
562                                  &filename,
563                                  line,
564                                  cfgs,
565                                  libs,
566                                  externs,
567                                  should_panic,
568                                  no_run,
569                                  as_test_harness,
570                                  compile_fail,
571                                  error_codes,
572                                  &opts,
573                                  maybe_sysroot,
574                                  linker)
575                     })
576                 } {
577                     Ok(()) => (),
578                     Err(err) => panic::resume_unwind(err),
579                 }
580             }),
581         });
582     }
583
584     pub fn get_line(&self) -> usize {
585         if let Some(ref codemap) = self.codemap {
586             let line = self.position.lo().to_usize();
587             let line = codemap.lookup_char_pos(BytePos(line as u32)).line;
588             if line > 0 { line - 1 } else { line }
589         } else {
590             0
591         }
592     }
593
594     pub fn set_position(&mut self, position: Span) {
595         self.position = position;
596     }
597
598     pub fn get_filename(&self) -> FileName {
599         if let Some(ref codemap) = self.codemap {
600             let filename = codemap.span_to_filename(self.position);
601             if let FileName::Real(ref filename) = filename {
602                 if let Ok(cur_dir) = env::current_dir() {
603                     if let Ok(path) = filename.strip_prefix(&cur_dir) {
604                         return path.to_owned().into();
605                     }
606                 }
607             }
608             filename
609         } else if let Some(ref filename) = self.filename {
610             filename.clone().into()
611         } else {
612             FileName::Custom("input".to_owned())
613         }
614     }
615
616     pub fn register_header(&mut self, name: &str, level: u32) {
617         if self.use_headers {
618             // we use these headings as test names, so it's good if
619             // they're valid identifiers.
620             let name = name.chars().enumerate().map(|(i, c)| {
621                     if (i == 0 && c.is_xid_start()) ||
622                         (i != 0 && c.is_xid_continue()) {
623                         c
624                     } else {
625                         '_'
626                     }
627                 }).collect::<String>();
628
629             // Here we try to efficiently assemble the header titles into the
630             // test name in the form of `h1::h2::h3::h4::h5::h6`.
631             //
632             // Suppose originally `self.names` contains `[h1, h2, h3]`...
633             let level = level as usize;
634             if level <= self.names.len() {
635                 // ... Consider `level == 2`. All headers in the lower levels
636                 // are irrelevant in this new level. So we should reset
637                 // `self.names` to contain headers until <h2>, and replace that
638                 // slot with the new name: `[h1, name]`.
639                 self.names.truncate(level);
640                 self.names[level - 1] = name;
641             } else {
642                 // ... On the other hand, consider `level == 5`. This means we
643                 // need to extend `self.names` to contain five headers. We fill
644                 // in the missing level (<h4>) with `_`. Thus `self.names` will
645                 // become `[h1, h2, h3, "_", name]`.
646                 if level - 1 > self.names.len() {
647                     self.names.resize(level - 1, "_".to_owned());
648                 }
649                 self.names.push(name);
650             }
651         }
652     }
653 }
654
655 struct HirCollector<'a, 'hir: 'a> {
656     sess: &'a session::Session,
657     collector: &'a mut Collector,
658     map: &'a hir::map::Map<'hir>
659 }
660
661 impl<'a, 'hir> HirCollector<'a, 'hir> {
662     fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
663                                             name: String,
664                                             attrs: &[ast::Attribute],
665                                             nested: F) {
666         let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
667         if let Some(ref cfg) = attrs.cfg {
668             if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features.borrow())) {
669                 return;
670             }
671         }
672
673         let has_name = !name.is_empty();
674         if has_name {
675             self.collector.names.push(name);
676         }
677
678         attrs.collapse_doc_comments();
679         attrs.unindent_doc_comments();
680         // the collapse-docs pass won't combine sugared/raw doc attributes, or included files with
681         // anything else, this will combine them for us
682         if let Some(doc) = attrs.collapsed_doc_value() {
683             if self.collector.render_type == RenderType::Pulldown {
684                 markdown::old_find_testable_code(&doc, self.collector,
685                                                  attrs.span.unwrap_or(DUMMY_SP));
686                 markdown::find_testable_code(&doc, self.collector,
687                                              attrs.span.unwrap_or(DUMMY_SP));
688             } else {
689                 markdown::old_find_testable_code(&doc, self.collector,
690                                                  attrs.span.unwrap_or(DUMMY_SP));
691             }
692         }
693
694         nested(self);
695
696         if has_name {
697             self.collector.names.pop();
698         }
699     }
700 }
701
702 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
703     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
704         intravisit::NestedVisitorMap::All(&self.map)
705     }
706
707     fn visit_item(&mut self, item: &'hir hir::Item) {
708         let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
709             self.map.node_to_pretty_string(ty.id)
710         } else {
711             item.name.to_string()
712         };
713
714         self.visit_testable(name, &item.attrs, |this| {
715             intravisit::walk_item(this, item);
716         });
717     }
718
719     fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
720         self.visit_testable(item.name.to_string(), &item.attrs, |this| {
721             intravisit::walk_trait_item(this, item);
722         });
723     }
724
725     fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
726         self.visit_testable(item.name.to_string(), &item.attrs, |this| {
727             intravisit::walk_impl_item(this, item);
728         });
729     }
730
731     fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
732         self.visit_testable(item.name.to_string(), &item.attrs, |this| {
733             intravisit::walk_foreign_item(this, item);
734         });
735     }
736
737     fn visit_variant(&mut self,
738                      v: &'hir hir::Variant,
739                      g: &'hir hir::Generics,
740                      item_id: ast::NodeId) {
741         self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
742             intravisit::walk_variant(this, v, g, item_id);
743         });
744     }
745
746     fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
747         self.visit_testable(f.name.to_string(), &f.attrs, |this| {
748             intravisit::walk_struct_field(this, f);
749         });
750     }
751
752     fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
753         self.visit_testable(macro_def.name.to_string(), &macro_def.attrs, |_| ());
754     }
755 }