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