]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
Rollup merge of #52703 - ljedrz:vec_improvements, r=nikomatsakis
[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::env;
12 use std::ffi::OsString;
13 use std::io::prelude::*;
14 use std::io;
15 use std::path::{Path, PathBuf};
16 use std::panic::{self, AssertUnwindSafe};
17 use std::process::Command;
18 use std::str;
19 use rustc_data_structures::sync::Lrc;
20 use std::sync::{Arc, Mutex};
21
22 use testing;
23 use rustc_lint;
24 use rustc::hir;
25 use rustc::hir::intravisit;
26 use rustc::session::{self, CompileIncomplete, config};
27 use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions};
28 use rustc::session::search_paths::{SearchPaths, PathKind};
29 use rustc_metadata::dynamic_lib::DynamicLibrary;
30 use tempfile::Builder as TempFileBuilder;
31 use rustc_driver::{self, driver, target_features, Compilation};
32 use rustc_driver::driver::phase_2_configure_and_expand;
33 use rustc_metadata::cstore::CStore;
34 use rustc_resolve::MakeGlobMap;
35 use syntax::ast;
36 use syntax::codemap::CodeMap;
37 use syntax::edition::Edition;
38 use syntax::feature_gate::UnstableFeatures;
39 use syntax::with_globals;
40 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span, FileName, hygiene};
41 use errors;
42 use errors::emitter::ColorConfig;
43
44 use clean::Attributes;
45 use html::markdown;
46
47 #[derive(Clone, Default)]
48 pub struct TestOptions {
49     /// Whether to disable the default `extern crate my_crate;` when creating doctests.
50     pub no_crate_inject: bool,
51     /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
52     /// the default `#![allow(unused)]`.
53     pub display_warnings: bool,
54     /// Additional crate-level attributes to add to doctests.
55     pub attrs: Vec<String>,
56 }
57
58 pub fn run(input_path: &Path,
59            cfgs: Vec<String>,
60            libs: SearchPaths,
61            externs: Externs,
62            mut test_args: Vec<String>,
63            crate_name: Option<String>,
64            maybe_sysroot: Option<PathBuf>,
65            display_warnings: bool,
66            linker: Option<PathBuf>,
67            edition: Edition,
68            cg: CodegenOptions)
69            -> isize {
70     let input = config::Input::File(input_path.to_owned());
71
72     let sessopts = config::Options {
73         maybe_sysroot: maybe_sysroot.clone().or_else(
74             || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
75         search_paths: libs.clone(),
76         crate_types: vec![config::CrateTypeDylib],
77         cg: cg.clone(),
78         externs: externs.clone(),
79         unstable_features: UnstableFeatures::from_environment(),
80         lint_cap: Some(::rustc::lint::Level::Allow),
81         actually_rustdoc: true,
82         debugging_opts: config::DebuggingOptions {
83             ..config::basic_debugging_options()
84         },
85         edition,
86         ..config::basic_options().clone()
87     };
88     driver::spawn_thread_pool(sessopts, |sessopts| {
89         let codemap = Lrc::new(CodeMap::new(sessopts.file_path_mapping()));
90         let handler =
91             errors::Handler::with_tty_emitter(ColorConfig::Auto,
92                                             true, false,
93                                             Some(codemap.clone()));
94
95         let mut sess = session::build_session_(
96             sessopts, Some(input_path.to_owned()), handler, codemap.clone(),
97         );
98         let codegen_backend = rustc_driver::get_codegen_backend(&sess);
99         let cstore = CStore::new(codegen_backend.metadata_loader());
100         rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
101
102         let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
103         target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
104         sess.parse_sess.config = cfg;
105
106         let krate = panictry!(driver::phase_1_parse_input(&driver::CompileController::basic(),
107                                                         &sess,
108                                                         &input));
109         let driver::ExpansionResult { defs, mut hir_forest, .. } = {
110             phase_2_configure_and_expand(
111                 &sess,
112                 &cstore,
113                 krate,
114                 None,
115                 "rustdoc-test",
116                 None,
117                 MakeGlobMap::No,
118                 |_| Ok(()),
119             ).expect("phase_2_configure_and_expand aborted in rustdoc!")
120         };
121
122         let crate_name = crate_name.unwrap_or_else(|| {
123             ::rustc_codegen_utils::link::find_crate_name(None, &hir_forest.krate().attrs, &input)
124         });
125         let mut opts = scrape_test_config(hir_forest.krate());
126         opts.display_warnings |= display_warnings;
127         let mut collector = Collector::new(
128             crate_name,
129             cfgs,
130             libs,
131             cg,
132             externs,
133             false,
134             opts,
135             maybe_sysroot,
136             Some(codemap),
137              None,
138             linker,
139             edition
140         );
141
142         {
143             let map = hir::map::map_crate(&sess, &cstore, &mut hir_forest, &defs);
144             let krate = map.krate();
145             let mut hir_collector = HirCollector {
146                 sess: &sess,
147                 collector: &mut collector,
148                 map: &map
149             };
150             hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
151                 intravisit::walk_crate(this, krate);
152             });
153         }
154
155         test_args.insert(0, "rustdoctest".to_string());
156
157         testing::test_main(&test_args,
158                         collector.tests.into_iter().collect(),
159                         testing::Options::new().display_output(display_warnings));
160         0
161     })
162 }
163
164 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
165 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
166     use syntax::print::pprust;
167
168     let mut opts = TestOptions {
169         no_crate_inject: false,
170         display_warnings: false,
171         attrs: Vec::new(),
172     };
173
174     let test_attrs: Vec<_> = krate.attrs.iter()
175         .filter(|a| a.check_name("doc"))
176         .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
177         .filter(|a| a.check_name("test"))
178         .collect();
179     let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
180
181     for attr in attrs {
182         if attr.check_name("no_crate_inject") {
183             opts.no_crate_inject = true;
184         }
185         if attr.check_name("attr") {
186             if let Some(l) = attr.meta_item_list() {
187                 for item in l {
188                     opts.attrs.push(pprust::meta_list_item_to_string(item));
189                 }
190             }
191         }
192     }
193
194     opts
195 }
196
197 fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
198             cfgs: Vec<String>, libs: SearchPaths,
199             cg: CodegenOptions, externs: Externs,
200             should_panic: bool, no_run: bool, as_test_harness: bool,
201             compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
202             maybe_sysroot: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition) {
203     // the test harness wants its own `main` & top level functions, so
204     // never wrap the test in `fn main() { ... }`
205     let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
206     // FIXME(#44940): if doctests ever support path remapping, then this filename
207     // needs to be the result of CodeMap::span_to_unmapped_path
208     let input = config::Input::Str {
209         name: filename.to_owned(),
210         input: test.to_owned(),
211     };
212     let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
213
214     let sessopts = config::Options {
215         maybe_sysroot: maybe_sysroot.or_else(
216             || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
217         search_paths: libs,
218         crate_types: vec![config::CrateTypeExecutable],
219         output_types: outputs,
220         externs,
221         cg: config::CodegenOptions {
222             prefer_dynamic: true,
223             linker,
224             ..cg
225         },
226         test: as_test_harness,
227         unstable_features: UnstableFeatures::from_environment(),
228         debugging_opts: config::DebuggingOptions {
229             ..config::basic_debugging_options()
230         },
231         edition,
232         ..config::basic_options().clone()
233     };
234
235     // Shuffle around a few input and output handles here. We're going to pass
236     // an explicit handle into rustc to collect output messages, but we also
237     // want to catch the error message that rustc prints when it fails.
238     //
239     // We take our thread-local stderr (likely set by the test runner) and replace
240     // it with a sink that is also passed to rustc itself. When this function
241     // returns the output of the sink is copied onto the output of our own thread.
242     //
243     // The basic idea is to not use a default Handler for rustc, and then also
244     // not print things by default to the actual stderr.
245     struct Sink(Arc<Mutex<Vec<u8>>>);
246     impl Write for Sink {
247         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
248             Write::write(&mut *self.0.lock().unwrap(), data)
249         }
250         fn flush(&mut self) -> io::Result<()> { Ok(()) }
251     }
252     struct Bomb(Arc<Mutex<Vec<u8>>>, Box<dyn Write+Send>);
253     impl Drop for Bomb {
254         fn drop(&mut self) {
255             let _ = self.1.write_all(&self.0.lock().unwrap());
256         }
257     }
258     let data = Arc::new(Mutex::new(Vec::new()));
259
260     let old = io::set_panic(Some(box Sink(data.clone())));
261     let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
262
263     let (libdir, outdir, compile_result) = driver::spawn_thread_pool(sessopts, |sessopts| {
264         let codemap = Lrc::new(CodeMap::new_doctest(
265             sessopts.file_path_mapping(), filename.clone(), line as isize - line_offset as isize
266         ));
267         let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
268                                                         Some(codemap.clone()),
269                                                         false,
270                                                         false);
271
272         // Compile the code
273         let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
274
275         let mut sess = session::build_session_(
276             sessopts, None, diagnostic_handler, codemap,
277         );
278         let codegen_backend = rustc_driver::get_codegen_backend(&sess);
279         let cstore = CStore::new(codegen_backend.metadata_loader());
280         rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
281
282         let outdir = Mutex::new(
283             TempFileBuilder::new().prefix("rustdoctest").tempdir().expect("rustdoc needs a tempdir")
284         );
285         let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
286         let mut control = driver::CompileController::basic();
287
288         let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
289         target_features::add_configuration(&mut cfg, &sess, &*codegen_backend);
290         sess.parse_sess.config = cfg;
291
292         let out = Some(outdir.lock().unwrap().path().to_path_buf());
293
294         if no_run {
295             control.after_analysis.stop = Compilation::Stop;
296         }
297
298         let res = panic::catch_unwind(AssertUnwindSafe(|| {
299             driver::compile_input(
300                 codegen_backend,
301                 &sess,
302                 &cstore,
303                 &None,
304                 &input,
305                 &out,
306                 &None,
307                 None,
308                 &control
309             )
310         }));
311
312         let compile_result = match res {
313             Ok(Ok(())) | Ok(Err(CompileIncomplete::Stopped)) => Ok(()),
314             Err(_) | Ok(Err(CompileIncomplete::Errored(_))) => Err(())
315         };
316
317         (libdir, outdir, compile_result)
318     });
319
320     match (compile_result, compile_fail) {
321         (Ok(()), true) => {
322             panic!("test compiled while it wasn't supposed to")
323         }
324         (Ok(()), false) => {}
325         (Err(()), true) => {
326             if error_codes.len() > 0 {
327                 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
328                 error_codes.retain(|err| !out.contains(err));
329             }
330         }
331         (Err(()), false) => {
332             panic!("couldn't compile the test")
333         }
334     }
335
336     if error_codes.len() > 0 {
337         panic!("Some expected error codes were not found: {:?}", error_codes);
338     }
339
340     if no_run { return }
341
342     // Run the code!
343     //
344     // We're careful to prepend the *target* dylib search path to the child's
345     // environment to ensure that the target loads the right libraries at
346     // runtime. It would be a sad day if the *host* libraries were loaded as a
347     // mistake.
348     let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
349     let var = DynamicLibrary::envvar();
350     let newpath = {
351         let path = env::var_os(var).unwrap_or(OsString::new());
352         let mut path = env::split_paths(&path).collect::<Vec<_>>();
353         path.insert(0, libdir.clone());
354         env::join_paths(path).unwrap()
355     };
356     cmd.env(var, &newpath);
357
358     match cmd.output() {
359         Err(e) => panic!("couldn't run the test: {}{}", e,
360                         if e.kind() == io::ErrorKind::PermissionDenied {
361                             " - maybe your tempdir is mounted with noexec?"
362                         } else { "" }),
363         Ok(out) => {
364             if should_panic && out.status.success() {
365                 panic!("test executable succeeded when it should have failed");
366             } else if !should_panic && !out.status.success() {
367                 panic!("test executable failed:\n{}\n{}\n",
368                        str::from_utf8(&out.stdout).unwrap_or(""),
369                        str::from_utf8(&out.stderr).unwrap_or(""));
370             }
371         }
372     }
373 }
374
375 /// Makes the test file. Also returns the number of lines before the code begins
376 pub fn make_test(s: &str,
377                  cratename: Option<&str>,
378                  dont_insert_main: bool,
379                  opts: &TestOptions)
380                  -> (String, usize) {
381     let (crate_attrs, everything_else) = partition_source(s);
382     let everything_else = everything_else.trim();
383     let mut line_offset = 0;
384     let mut prog = String::new();
385
386     if opts.attrs.is_empty() && !opts.display_warnings {
387         // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
388         // lints that are commonly triggered in doctests. The crate-level test attributes are
389         // commonly used to make tests fail in case they trigger warnings, so having this there in
390         // that case may cause some tests to pass when they shouldn't have.
391         prog.push_str("#![allow(unused)]\n");
392         line_offset += 1;
393     }
394
395     // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
396     for attr in &opts.attrs {
397         prog.push_str(&format!("#![{}]\n", attr));
398         line_offset += 1;
399     }
400
401     // Now push any outer attributes from the example, assuming they
402     // are intended to be crate attributes.
403     prog.push_str(&crate_attrs);
404
405     // Don't inject `extern crate std` because it's already injected by the
406     // compiler.
407     if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
408         if let Some(cratename) = cratename {
409             if s.contains(cratename) {
410                 prog.push_str(&format!("extern crate {};\n", cratename));
411                 line_offset += 1;
412             }
413         }
414     }
415
416     // FIXME (#21299): prefer libsyntax or some other actual parser over this
417     // best-effort ad hoc approach
418     let already_has_main = s.lines()
419         .map(|line| {
420             let comment = line.find("//");
421             if let Some(comment_begins) = comment {
422                 &line[0..comment_begins]
423             } else {
424                 line
425             }
426         })
427         .any(|code| code.contains("fn main"));
428
429     if dont_insert_main || already_has_main {
430         prog.push_str(everything_else);
431     } else {
432         prog.push_str("fn main() {\n");
433         line_offset += 1;
434         prog.push_str(everything_else);
435         prog.push_str("\n}");
436     }
437
438     info!("final test program: {}", prog);
439
440     (prog, line_offset)
441 }
442
443 // FIXME(aburka): use a real parser to deal with multiline attributes
444 fn partition_source(s: &str) -> (String, String) {
445     let mut after_header = false;
446     let mut before = String::new();
447     let mut after = String::new();
448
449     for line in s.lines() {
450         let trimline = line.trim();
451         let header = trimline.chars().all(|c| c.is_whitespace()) ||
452             trimline.starts_with("#![") ||
453             trimline.starts_with("#[macro_use] extern crate") ||
454             trimline.starts_with("extern crate");
455         if !header || after_header {
456             after_header = true;
457             after.push_str(line);
458             after.push_str("\n");
459         } else {
460             before.push_str(line);
461             before.push_str("\n");
462         }
463     }
464
465     (before, after)
466 }
467
468 pub struct Collector {
469     pub tests: Vec<testing::TestDescAndFn>,
470
471     // The name of the test displayed to the user, separated by `::`.
472     //
473     // In tests from Rust source, this is the path to the item
474     // e.g. `["std", "vec", "Vec", "push"]`.
475     //
476     // In tests from a markdown file, this is the titles of all headers (h1~h6)
477     // of the sections that contain the code block, e.g. if the markdown file is
478     // written as:
479     //
480     // ``````markdown
481     // # Title
482     //
483     // ## Subtitle
484     //
485     // ```rust
486     // assert!(true);
487     // ```
488     // ``````
489     //
490     // the `names` vector of that test will be `["Title", "Subtitle"]`.
491     names: Vec<String>,
492
493     cfgs: Vec<String>,
494     libs: SearchPaths,
495     cg: CodegenOptions,
496     externs: Externs,
497     use_headers: bool,
498     cratename: String,
499     opts: TestOptions,
500     maybe_sysroot: Option<PathBuf>,
501     position: Span,
502     codemap: Option<Lrc<CodeMap>>,
503     filename: Option<PathBuf>,
504     linker: Option<PathBuf>,
505     edition: Edition,
506 }
507
508 impl Collector {
509     pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, cg: CodegenOptions,
510                externs: Externs, use_headers: bool, opts: TestOptions,
511                maybe_sysroot: Option<PathBuf>, codemap: Option<Lrc<CodeMap>>,
512                filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition) -> Collector {
513         Collector {
514             tests: Vec::new(),
515             names: Vec::new(),
516             cfgs,
517             libs,
518             cg,
519             externs,
520             use_headers,
521             cratename,
522             opts,
523             maybe_sysroot,
524             position: DUMMY_SP,
525             codemap,
526             filename,
527             linker,
528             edition,
529         }
530     }
531
532     fn generate_name(&self, line: usize, filename: &FileName) -> String {
533         format!("{} - {} (line {})", filename, self.names.join("::"), line)
534     }
535
536     pub fn add_test(&mut self, test: String,
537                     should_panic: bool, no_run: bool, should_ignore: bool,
538                     as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>,
539                     line: usize, filename: FileName, allow_fail: bool) {
540         let name = self.generate_name(line, &filename);
541         let cfgs = self.cfgs.clone();
542         let libs = self.libs.clone();
543         let cg = self.cg.clone();
544         let externs = self.externs.clone();
545         let cratename = self.cratename.to_string();
546         let opts = self.opts.clone();
547         let maybe_sysroot = self.maybe_sysroot.clone();
548         let linker = self.linker.clone();
549         let edition = self.edition;
550         debug!("Creating test {}: {}", name, test);
551         self.tests.push(testing::TestDescAndFn {
552             desc: testing::TestDesc {
553                 name: testing::DynTestName(name.clone()),
554                 ignore: should_ignore,
555                 // compiler failures are test failures
556                 should_panic: testing::ShouldPanic::No,
557                 allow_fail,
558             },
559             testfn: testing::DynTestFn(box move || {
560                 let panic = io::set_panic(None);
561                 let print = io::set_print(None);
562                 match {
563                     rustc_driver::in_named_rustc_thread(name, move || with_globals(move || {
564                         io::set_panic(panic);
565                         io::set_print(print);
566                         hygiene::set_default_edition(edition);
567                         run_test(&test,
568                                  &cratename,
569                                  &filename,
570                                  line,
571                                  cfgs,
572                                  libs,
573                                  cg,
574                                  externs,
575                                  should_panic,
576                                  no_run,
577                                  as_test_harness,
578                                  compile_fail,
579                                  error_codes,
580                                  &opts,
581                                  maybe_sysroot,
582                                  linker,
583                                  edition)
584                     }))
585                 } {
586                     Ok(()) => (),
587                     Err(err) => panic::resume_unwind(err),
588                 }
589             }),
590         });
591     }
592
593     pub fn get_line(&self) -> usize {
594         if let Some(ref codemap) = self.codemap {
595             let line = self.position.lo().to_usize();
596             let line = codemap.lookup_char_pos(BytePos(line as u32)).line;
597             if line > 0 { line - 1 } else { line }
598         } else {
599             0
600         }
601     }
602
603     pub fn set_position(&mut self, position: Span) {
604         self.position = position;
605     }
606
607     pub fn get_filename(&self) -> FileName {
608         if let Some(ref codemap) = self.codemap {
609             let filename = codemap.span_to_filename(self.position);
610             if let FileName::Real(ref filename) = filename {
611                 if let Ok(cur_dir) = env::current_dir() {
612                     if let Ok(path) = filename.strip_prefix(&cur_dir) {
613                         return path.to_owned().into();
614                     }
615                 }
616             }
617             filename
618         } else if let Some(ref filename) = self.filename {
619             filename.clone().into()
620         } else {
621             FileName::Custom("input".to_owned())
622         }
623     }
624
625     pub fn register_header(&mut self, name: &str, level: u32) {
626         if self.use_headers {
627             // we use these headings as test names, so it's good if
628             // they're valid identifiers.
629             let name = name.chars().enumerate().map(|(i, c)| {
630                     if (i == 0 && c.is_xid_start()) ||
631                         (i != 0 && c.is_xid_continue()) {
632                         c
633                     } else {
634                         '_'
635                     }
636                 }).collect::<String>();
637
638             // Here we try to efficiently assemble the header titles into the
639             // test name in the form of `h1::h2::h3::h4::h5::h6`.
640             //
641             // Suppose originally `self.names` contains `[h1, h2, h3]`...
642             let level = level as usize;
643             if level <= self.names.len() {
644                 // ... Consider `level == 2`. All headers in the lower levels
645                 // are irrelevant in this new level. So we should reset
646                 // `self.names` to contain headers until <h2>, and replace that
647                 // slot with the new name: `[h1, name]`.
648                 self.names.truncate(level);
649                 self.names[level - 1] = name;
650             } else {
651                 // ... On the other hand, consider `level == 5`. This means we
652                 // need to extend `self.names` to contain five headers. We fill
653                 // in the missing level (<h4>) with `_`. Thus `self.names` will
654                 // become `[h1, h2, h3, "_", name]`.
655                 if level - 1 > self.names.len() {
656                     self.names.resize(level - 1, "_".to_owned());
657                 }
658                 self.names.push(name);
659             }
660         }
661     }
662 }
663
664 struct HirCollector<'a, 'hir: 'a> {
665     sess: &'a session::Session,
666     collector: &'a mut Collector,
667     map: &'a hir::map::Map<'hir>
668 }
669
670 impl<'a, 'hir> HirCollector<'a, 'hir> {
671     fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
672                                             name: String,
673                                             attrs: &[ast::Attribute],
674                                             nested: F) {
675         let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
676         if let Some(ref cfg) = attrs.cfg {
677             if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
678                 return;
679             }
680         }
681
682         let has_name = !name.is_empty();
683         if has_name {
684             self.collector.names.push(name);
685         }
686
687         attrs.collapse_doc_comments();
688         attrs.unindent_doc_comments();
689         // the collapse-docs pass won't combine sugared/raw doc attributes, or included files with
690         // anything else, this will combine them for us
691         if let Some(doc) = attrs.collapsed_doc_value() {
692             markdown::find_testable_code(&doc,
693                                          self.collector,
694                                          attrs.span.unwrap_or(DUMMY_SP),
695                                          Some(self.sess));
696         }
697
698         nested(self);
699
700         if has_name {
701             self.collector.names.pop();
702         }
703     }
704 }
705
706 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
707     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
708         intravisit::NestedVisitorMap::All(&self.map)
709     }
710
711     fn visit_item(&mut self, item: &'hir hir::Item) {
712         let name = if let hir::ItemKind::Impl(.., ref ty, _) = item.node {
713             self.map.node_to_pretty_string(ty.id)
714         } else {
715             item.name.to_string()
716         };
717
718         self.visit_testable(name, &item.attrs, |this| {
719             intravisit::walk_item(this, item);
720         });
721     }
722
723     fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
724         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
725             intravisit::walk_trait_item(this, item);
726         });
727     }
728
729     fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
730         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
731             intravisit::walk_impl_item(this, item);
732         });
733     }
734
735     fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
736         self.visit_testable(item.name.to_string(), &item.attrs, |this| {
737             intravisit::walk_foreign_item(this, item);
738         });
739     }
740
741     fn visit_variant(&mut self,
742                      v: &'hir hir::Variant,
743                      g: &'hir hir::Generics,
744                      item_id: ast::NodeId) {
745         self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
746             intravisit::walk_variant(this, v, g, item_id);
747         });
748     }
749
750     fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
751         self.visit_testable(f.ident.to_string(), &f.attrs, |this| {
752             intravisit::walk_struct_field(this, f);
753         });
754     }
755
756     fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
757         self.visit_testable(macro_def.name.to_string(), &macro_def.attrs, |_| ());
758     }
759 }
760
761 #[cfg(test)]
762 mod tests {
763     use super::{TestOptions, make_test};
764
765     #[test]
766     fn make_test_basic() {
767         //basic use: wraps with `fn main`, adds `#![allow(unused)]`
768         let opts = TestOptions::default();
769         let input =
770 "assert_eq!(2+2, 4);";
771         let expected =
772 "#![allow(unused)]
773 fn main() {
774 assert_eq!(2+2, 4);
775 }".to_string();
776         let output = make_test(input, None, false, &opts);
777         assert_eq!(output, (expected.clone(), 2));
778     }
779
780     #[test]
781     fn make_test_crate_name_no_use() {
782         //if you give a crate name but *don't* use it within the test, it won't bother inserting
783         //the `extern crate` statement
784         let opts = TestOptions::default();
785         let input =
786 "assert_eq!(2+2, 4);";
787         let expected =
788 "#![allow(unused)]
789 fn main() {
790 assert_eq!(2+2, 4);
791 }".to_string();
792         let output = make_test(input, Some("asdf"), false, &opts);
793         assert_eq!(output, (expected, 2));
794     }
795
796     #[test]
797     fn make_test_crate_name() {
798         //if you give a crate name and use it within the test, it will insert an `extern crate`
799         //statement before `fn main`
800         let opts = TestOptions::default();
801         let input =
802 "use asdf::qwop;
803 assert_eq!(2+2, 4);";
804         let expected =
805 "#![allow(unused)]
806 extern crate asdf;
807 fn main() {
808 use asdf::qwop;
809 assert_eq!(2+2, 4);
810 }".to_string();
811         let output = make_test(input, Some("asdf"), false, &opts);
812         assert_eq!(output, (expected, 3));
813     }
814
815     #[test]
816     fn make_test_no_crate_inject() {
817         //even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
818         //adding it anyway
819         let opts = TestOptions {
820             no_crate_inject: true,
821             display_warnings: false,
822             attrs: vec![],
823         };
824         let input =
825 "use asdf::qwop;
826 assert_eq!(2+2, 4);";
827         let expected =
828 "#![allow(unused)]
829 fn main() {
830 use asdf::qwop;
831 assert_eq!(2+2, 4);
832 }".to_string();
833         let output = make_test(input, Some("asdf"), false, &opts);
834         assert_eq!(output, (expected, 2));
835     }
836
837     #[test]
838     fn make_test_ignore_std() {
839         //even if you include a crate name, and use it in the doctest, we still won't include an
840         //`extern crate` statement if the crate is "std" - that's included already by the compiler!
841         let opts = TestOptions::default();
842         let input =
843 "use std::*;
844 assert_eq!(2+2, 4);";
845         let expected =
846 "#![allow(unused)]
847 fn main() {
848 use std::*;
849 assert_eq!(2+2, 4);
850 }".to_string();
851         let output = make_test(input, Some("std"), false, &opts);
852         assert_eq!(output, (expected, 2));
853     }
854
855     #[test]
856     fn make_test_manual_extern_crate() {
857         //when you manually include an `extern crate` statement in your doctest, make_test assumes
858         //you've included one for your own crate too
859         let opts = TestOptions::default();
860         let input =
861 "extern crate asdf;
862 use asdf::qwop;
863 assert_eq!(2+2, 4);";
864         let expected =
865 "#![allow(unused)]
866 extern crate asdf;
867 fn main() {
868 use asdf::qwop;
869 assert_eq!(2+2, 4);
870 }".to_string();
871         let output = make_test(input, Some("asdf"), false, &opts);
872         assert_eq!(output, (expected, 2));
873     }
874
875     #[test]
876     fn make_test_manual_extern_crate_with_macro_use() {
877         let opts = TestOptions::default();
878         let input =
879 "#[macro_use] extern crate asdf;
880 use asdf::qwop;
881 assert_eq!(2+2, 4);";
882         let expected =
883 "#![allow(unused)]
884 #[macro_use] extern crate asdf;
885 fn main() {
886 use asdf::qwop;
887 assert_eq!(2+2, 4);
888 }".to_string();
889         let output = make_test(input, Some("asdf"), false, &opts);
890         assert_eq!(output, (expected, 2));
891     }
892
893     #[test]
894     fn make_test_opts_attrs() {
895         //if you supplied some doctest attributes with #![doc(test(attr(...)))], it will use those
896         //instead of the stock #![allow(unused)]
897         let mut opts = TestOptions::default();
898         opts.attrs.push("feature(sick_rad)".to_string());
899         let input =
900 "use asdf::qwop;
901 assert_eq!(2+2, 4);";
902         let expected =
903 "#![feature(sick_rad)]
904 extern crate asdf;
905 fn main() {
906 use asdf::qwop;
907 assert_eq!(2+2, 4);
908 }".to_string();
909         let output = make_test(input, Some("asdf"), false, &opts);
910         assert_eq!(output, (expected, 3));
911
912         //adding more will also bump the returned line offset
913         opts.attrs.push("feature(hella_dope)".to_string());
914         let expected =
915 "#![feature(sick_rad)]
916 #![feature(hella_dope)]
917 extern crate asdf;
918 fn main() {
919 use asdf::qwop;
920 assert_eq!(2+2, 4);
921 }".to_string();
922         let output = make_test(input, Some("asdf"), false, &opts);
923         assert_eq!(output, (expected, 4));
924     }
925
926     #[test]
927     fn make_test_crate_attrs() {
928         //including inner attributes in your doctest will apply them to the whole "crate", pasting
929         //them outside the generated main function
930         let opts = TestOptions::default();
931         let input =
932 "#![feature(sick_rad)]
933 assert_eq!(2+2, 4);";
934         let expected =
935 "#![allow(unused)]
936 #![feature(sick_rad)]
937 fn main() {
938 assert_eq!(2+2, 4);
939 }".to_string();
940         let output = make_test(input, None, false, &opts);
941         assert_eq!(output, (expected, 2));
942     }
943
944     #[test]
945     fn make_test_with_main() {
946         //including your own `fn main` wrapper lets the test use it verbatim
947         let opts = TestOptions::default();
948         let input =
949 "fn main() {
950     assert_eq!(2+2, 4);
951 }";
952         let expected =
953 "#![allow(unused)]
954 fn main() {
955     assert_eq!(2+2, 4);
956 }".to_string();
957         let output = make_test(input, None, false, &opts);
958         assert_eq!(output, (expected, 1));
959     }
960
961     #[test]
962     fn make_test_fake_main() {
963         //...but putting it in a comment will still provide a wrapper
964         let opts = TestOptions::default();
965         let input =
966 "//Ceci n'est pas une `fn main`
967 assert_eq!(2+2, 4);";
968         let expected =
969 "#![allow(unused)]
970 fn main() {
971 //Ceci n'est pas une `fn main`
972 assert_eq!(2+2, 4);
973 }".to_string();
974         let output = make_test(input, None, false, &opts);
975         assert_eq!(output, (expected.clone(), 2));
976     }
977
978     #[test]
979     fn make_test_dont_insert_main() {
980         //even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper
981         let opts = TestOptions::default();
982         let input =
983 "//Ceci n'est pas une `fn main`
984 assert_eq!(2+2, 4);";
985         let expected =
986 "#![allow(unused)]
987 //Ceci n'est pas une `fn main`
988 assert_eq!(2+2, 4);".to_string();
989         let output = make_test(input, None, true, &opts);
990         assert_eq!(output, (expected.clone(), 1));
991     }
992
993     #[test]
994     fn make_test_display_warnings() {
995         //if the user is asking to display doctest warnings, suppress the default allow(unused)
996         let mut opts = TestOptions::default();
997         opts.display_warnings = true;
998         let input =
999 "assert_eq!(2+2, 4);";
1000         let expected =
1001 "fn main() {
1002 assert_eq!(2+2, 4);
1003 }".to_string();
1004         let output = make_test(input, None, false, &opts);
1005         assert_eq!(output, (expected.clone(), 1));
1006     }
1007 }