]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
Auto merge of #31468 - pitdicker:fs_tests_cleanup, r=alexcrichton
[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 #![allow(deprecated)]
12
13 use std::cell::{RefCell, Cell};
14 use std::collections::{HashSet, HashMap};
15 use std::dynamic_lib::DynamicLibrary;
16 use std::env;
17 use std::ffi::OsString;
18 use std::io::prelude::*;
19 use std::io;
20 use std::path::PathBuf;
21 use std::process::Command;
22 use std::rc::Rc;
23 use std::str;
24 use std::sync::{Arc, Mutex};
25
26 use testing;
27 use rustc_lint;
28 use rustc::dep_graph::DepGraph;
29 use rustc::front::map as hir_map;
30 use rustc::session::{self, config};
31 use rustc::session::config::{get_unstable_features_setting, OutputType};
32 use rustc::session::search_paths::{SearchPaths, PathKind};
33 use rustc_front::lowering::{lower_crate, LoweringContext};
34 use rustc_back::tempdir::TempDir;
35 use rustc_driver::{driver, Compilation};
36 use rustc_metadata::cstore::CStore;
37 use syntax::codemap::CodeMap;
38 use syntax::errors;
39 use syntax::errors::emitter::ColorConfig;
40 use syntax::parse::token;
41
42 use core;
43 use clean;
44 use clean::Clean;
45 use fold::DocFolder;
46 use html::markdown;
47 use passes;
48 use visit_ast::RustdocVisitor;
49
50 #[derive(Clone, Default)]
51 pub struct TestOptions {
52     pub no_crate_inject: bool,
53     pub attrs: Vec<String>,
54 }
55
56 pub fn run(input: &str,
57            cfgs: Vec<String>,
58            libs: SearchPaths,
59            externs: core::Externs,
60            mut test_args: Vec<String>,
61            crate_name: Option<String>)
62            -> isize {
63     let input_path = PathBuf::from(input);
64     let input = config::Input::File(input_path.clone());
65
66     let sessopts = config::Options {
67         maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
68                                               .parent().unwrap().to_path_buf()),
69         search_paths: libs.clone(),
70         crate_types: vec!(config::CrateTypeDylib),
71         externs: externs.clone(),
72         unstable_features: get_unstable_features_setting(),
73         ..config::basic_options().clone()
74     };
75
76     let codemap = Rc::new(CodeMap::new());
77     let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
78                                                                None,
79                                                                true,
80                                                                false,
81                                                                codemap.clone());
82
83     let cstore = Rc::new(CStore::new(token::get_ident_interner()));
84     let sess = session::build_session_(sessopts,
85                                        Some(input_path.clone()),
86                                        diagnostic_handler,
87                                        codemap,
88                                        cstore.clone());
89     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
90
91     let mut cfg = config::build_configuration(&sess);
92     cfg.extend(config::parse_cfgspecs(cfgs.clone()));
93     let krate = driver::phase_1_parse_input(&sess, cfg, &input);
94     let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate,
95                                                      "rustdoc-test", None)
96         .expect("phase_2_configure_and_expand aborted in rustdoc!");
97     let krate = driver::assign_node_ids(&sess, krate);
98     let lcx = LoweringContext::new(&sess, Some(&krate));
99     let krate = lower_crate(&lcx, &krate);
100
101     let opts = scrape_test_config(&krate);
102
103     let dep_graph = DepGraph::new(false);
104     let _ignore = dep_graph.in_ignore();
105     let mut forest = hir_map::Forest::new(krate, dep_graph.clone());
106     let map = hir_map::map_crate(&mut forest);
107
108     let ctx = core::DocContext {
109         map: &map,
110         maybe_typed: core::NotTyped(&sess),
111         input: input,
112         external_paths: RefCell::new(Some(HashMap::new())),
113         external_traits: RefCell::new(None),
114         external_typarams: RefCell::new(None),
115         inlined: RefCell::new(None),
116         populated_crate_impls: RefCell::new(HashSet::new()),
117         deref_trait_did: Cell::new(None),
118     };
119
120     let mut v = RustdocVisitor::new(&ctx, None);
121     v.visit(ctx.map.krate());
122     let mut krate = v.clean(&ctx);
123     match crate_name {
124         Some(name) => krate.name = name,
125         None => {}
126     }
127     let (krate, _) = passes::collapse_docs(krate);
128     let (krate, _) = passes::unindent_comments(krate);
129
130     let mut collector = Collector::new(krate.name.to_string(),
131                                        cfgs,
132                                        libs,
133                                        externs,
134                                        false,
135                                        opts);
136     collector.fold_crate(krate);
137
138     test_args.insert(0, "rustdoctest".to_string());
139
140     testing::test_main(&test_args,
141                        collector.tests.into_iter().collect());
142     0
143 }
144
145 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
146 fn scrape_test_config(krate: &::rustc_front::hir::Crate) -> TestOptions {
147     use syntax::attr::AttrMetaMethods;
148     use syntax::print::pprust;
149
150     let mut opts = TestOptions {
151         no_crate_inject: false,
152         attrs: Vec::new(),
153     };
154
155     let attrs = krate.attrs.iter()
156                      .filter(|a| a.check_name("doc"))
157                      .filter_map(|a| a.meta_item_list())
158                      .flat_map(|l| l)
159                      .filter(|a| a.check_name("test"))
160                      .filter_map(|a| a.meta_item_list())
161                      .flat_map(|l| l);
162     for attr in attrs {
163         if attr.check_name("no_crate_inject") {
164             opts.no_crate_inject = true;
165         }
166         if attr.check_name("attr") {
167             if let Some(l) = attr.meta_item_list() {
168                 for item in l {
169                     opts.attrs.push(pprust::meta_item_to_string(item));
170                 }
171             }
172         }
173     }
174
175     return opts;
176 }
177
178 fn runtest(test: &str, cratename: &str, cfgs: Vec<String>, libs: SearchPaths,
179            externs: core::Externs,
180            should_panic: bool, no_run: bool, as_test_harness: bool,
181            opts: &TestOptions) {
182     // the test harness wants its own `main` & top level functions, so
183     // never wrap the test in `fn main() { ... }`
184     let test = maketest(test, Some(cratename), as_test_harness, opts);
185     let input = config::Input::Str(test.to_string());
186     let mut outputs = HashMap::new();
187     outputs.insert(OutputType::Exe, None);
188
189     let sessopts = config::Options {
190         maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
191                                               .parent().unwrap().to_path_buf()),
192         search_paths: libs,
193         crate_types: vec!(config::CrateTypeExecutable),
194         output_types: outputs,
195         externs: externs,
196         cg: config::CodegenOptions {
197             prefer_dynamic: true,
198             .. config::basic_codegen_options()
199         },
200         test: as_test_harness,
201         unstable_features: get_unstable_features_setting(),
202         ..config::basic_options().clone()
203     };
204
205     // Shuffle around a few input and output handles here. We're going to pass
206     // an explicit handle into rustc to collect output messages, but we also
207     // want to catch the error message that rustc prints when it fails.
208     //
209     // We take our thread-local stderr (likely set by the test runner) and replace
210     // it with a sink that is also passed to rustc itself. When this function
211     // returns the output of the sink is copied onto the output of our own thread.
212     //
213     // The basic idea is to not use a default Handler for rustc, and then also
214     // not print things by default to the actual stderr.
215     struct Sink(Arc<Mutex<Vec<u8>>>);
216     impl Write for Sink {
217         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
218             Write::write(&mut *self.0.lock().unwrap(), data)
219         }
220         fn flush(&mut self) -> io::Result<()> { Ok(()) }
221     }
222     struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
223     impl Drop for Bomb {
224         fn drop(&mut self) {
225             let _ = self.1.write_all(&self.0.lock().unwrap());
226         }
227     }
228     let data = Arc::new(Mutex::new(Vec::new()));
229     let codemap = Rc::new(CodeMap::new());
230     let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
231                                                       None,
232                                                       codemap.clone());
233     let old = io::set_panic(box Sink(data.clone()));
234     let _bomb = Bomb(data, old.unwrap_or(box io::stdout()));
235
236     // Compile the code
237     let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
238
239     let cstore = Rc::new(CStore::new(token::get_ident_interner()));
240     let sess = session::build_session_(sessopts,
241                                        None,
242                                        diagnostic_handler,
243                                        codemap,
244                                        cstore.clone());
245     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
246
247     let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
248     let out = Some(outdir.path().to_path_buf());
249     let mut cfg = config::build_configuration(&sess);
250     cfg.extend(config::parse_cfgspecs(cfgs));
251     let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
252     let mut control = driver::CompileController::basic();
253     if no_run {
254         control.after_analysis.stop = Compilation::Stop;
255     }
256     let result = driver::compile_input(&sess, &cstore, cfg, &input,
257                                        &out, &None, None, control);
258     match result {
259         Err(count) if count > 0 => sess.fatal("aborting due to previous error(s)"),
260         _ => {}
261     }
262
263     if no_run { return }
264
265     // Run the code!
266     //
267     // We're careful to prepend the *target* dylib search path to the child's
268     // environment to ensure that the target loads the right libraries at
269     // runtime. It would be a sad day if the *host* libraries were loaded as a
270     // mistake.
271     let mut cmd = Command::new(&outdir.path().join("rust_out"));
272     let var = DynamicLibrary::envvar();
273     let newpath = {
274         let path = env::var_os(var).unwrap_or(OsString::new());
275         let mut path = env::split_paths(&path).collect::<Vec<_>>();
276         path.insert(0, libdir.clone());
277         env::join_paths(path).unwrap()
278     };
279     cmd.env(var, &newpath);
280
281     match cmd.output() {
282         Err(e) => panic!("couldn't run the test: {}{}", e,
283                         if e.kind() == io::ErrorKind::PermissionDenied {
284                             " - maybe your tempdir is mounted with noexec?"
285                         } else { "" }),
286         Ok(out) => {
287             if should_panic && out.status.success() {
288                 panic!("test executable succeeded when it should have failed");
289             } else if !should_panic && !out.status.success() {
290                 panic!("test executable failed:\n{}\n{}",
291                        str::from_utf8(&out.stdout).unwrap_or(""),
292                        str::from_utf8(&out.stderr).unwrap_or(""));
293             }
294         }
295     }
296 }
297
298 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
299                 opts: &TestOptions) -> String {
300     let (crate_attrs, everything_else) = partition_source(s);
301
302     let mut prog = String::new();
303
304     // First push any outer attributes from the example, assuming they
305     // are intended to be crate attributes.
306     prog.push_str(&crate_attrs);
307
308     // Next, any attributes for other aspects such as lints.
309     for attr in &opts.attrs {
310         prog.push_str(&format!("#![{}]\n", attr));
311     }
312
313     // Don't inject `extern crate std` because it's already injected by the
314     // compiler.
315     if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
316         match cratename {
317             Some(cratename) => {
318                 if s.contains(cratename) {
319                     prog.push_str(&format!("extern crate {};\n", cratename));
320                 }
321             }
322             None => {}
323         }
324     }
325     if dont_insert_main || s.contains("fn main") {
326         prog.push_str(&everything_else);
327     } else {
328         prog.push_str("fn main() {\n    ");
329         prog.push_str(&everything_else.replace("\n", "\n    "));
330         prog = prog.trim().into();
331         prog.push_str("\n}");
332     }
333
334     info!("final test program: {}", prog);
335
336     return prog
337 }
338
339 fn partition_source(s: &str) -> (String, String) {
340     use rustc_unicode::str::UnicodeStr;
341
342     let mut after_header = false;
343     let mut before = String::new();
344     let mut after = String::new();
345
346     for line in s.lines() {
347         let trimline = line.trim();
348         let header = trimline.is_whitespace() ||
349             trimline.starts_with("#![feature");
350         if !header || after_header {
351             after_header = true;
352             after.push_str(line);
353             after.push_str("\n");
354         } else {
355             before.push_str(line);
356             before.push_str("\n");
357         }
358     }
359
360     return (before, after);
361 }
362
363 pub struct Collector {
364     pub tests: Vec<testing::TestDescAndFn>,
365     names: Vec<String>,
366     cfgs: Vec<String>,
367     libs: SearchPaths,
368     externs: core::Externs,
369     cnt: usize,
370     use_headers: bool,
371     current_header: Option<String>,
372     cratename: String,
373     opts: TestOptions,
374 }
375
376 impl Collector {
377     pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: core::Externs,
378                use_headers: bool, opts: TestOptions) -> Collector {
379         Collector {
380             tests: Vec::new(),
381             names: Vec::new(),
382             cfgs: cfgs,
383             libs: libs,
384             externs: externs,
385             cnt: 0,
386             use_headers: use_headers,
387             current_header: None,
388             cratename: cratename,
389             opts: opts,
390         }
391     }
392
393     pub fn add_test(&mut self, test: String,
394                     should_panic: bool, no_run: bool, should_ignore: bool,
395                     as_test_harness: bool) {
396         let name = if self.use_headers {
397             let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
398             format!("{}_{}", s, self.cnt)
399         } else {
400             format!("{}_{}", self.names.join("::"), self.cnt)
401         };
402         self.cnt += 1;
403         let cfgs = self.cfgs.clone();
404         let libs = self.libs.clone();
405         let externs = self.externs.clone();
406         let cratename = self.cratename.to_string();
407         let opts = self.opts.clone();
408         debug!("Creating test {}: {}", name, test);
409         self.tests.push(testing::TestDescAndFn {
410             desc: testing::TestDesc {
411                 name: testing::DynTestName(name),
412                 ignore: should_ignore,
413                 // compiler failures are test failures
414                 should_panic: testing::ShouldPanic::No,
415             },
416             testfn: testing::DynTestFn(Box::new(move|| {
417                 runtest(&test,
418                         &cratename,
419                         cfgs,
420                         libs,
421                         externs,
422                         should_panic,
423                         no_run,
424                         as_test_harness,
425                         &opts);
426             }))
427         });
428     }
429
430     pub fn register_header(&mut self, name: &str, level: u32) {
431         if self.use_headers && level == 1 {
432             // we use these headings as test names, so it's good if
433             // they're valid identifiers.
434             let name = name.chars().enumerate().map(|(i, c)| {
435                     if (i == 0 && c.is_xid_start()) ||
436                         (i != 0 && c.is_xid_continue()) {
437                         c
438                     } else {
439                         '_'
440                     }
441                 }).collect::<String>();
442
443             // new header => reset count.
444             self.cnt = 0;
445             self.current_header = Some(name);
446         }
447     }
448 }
449
450 impl DocFolder for Collector {
451     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
452         let current_name = match item.name {
453             Some(ref name) if !name.is_empty() => Some(name.clone()),
454             _ => typename_if_impl(&item)
455         };
456
457         let pushed = if let Some(name) = current_name {
458             self.names.push(name);
459             true
460         } else {
461             false
462         };
463
464         if let Some(doc) = item.doc_value() {
465             self.cnt = 0;
466             markdown::find_testable_code(doc, &mut *self);
467         }
468
469         let ret = self.fold_item_recur(item);
470         if pushed {
471             self.names.pop();
472         }
473
474         return ret;
475
476         // FIXME: it would be better to not have the escaped version in the first place
477         fn unescape_for_testname(mut s: String) -> String {
478             // for refs `&foo`
479             if s.contains("&amp;") {
480                 s = s.replace("&amp;", "&");
481
482                 // `::&'a mut Foo::` looks weird, let's make it `::<&'a mut Foo>`::
483                 if let Some('&') = s.chars().nth(0) {
484                     s = format!("<{}>", s);
485                 }
486             }
487
488             // either `<..>` or `->`
489             if s.contains("&gt;") {
490                 s.replace("&gt;", ">")
491                  .replace("&lt;", "<")
492             } else {
493                 s
494             }
495         }
496
497         fn typename_if_impl(item: &clean::Item) -> Option<String> {
498             if let clean::ItemEnum::ImplItem(ref impl_) = item.inner {
499                 let path = impl_.for_.to_string();
500                 let unescaped_path = unescape_for_testname(path);
501                 Some(unescaped_path)
502             } else {
503                 None
504             }
505         }
506     }
507 }