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