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