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