]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
Rollup merge of #32180 - srinivasreddy:type_check_lib, r=steveklabnik
[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::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::panic::{self, AssertRecoverSafe};
22 use std::process::Command;
23 use std::rc::Rc;
24 use std::str;
25 use std::sync::{Arc, Mutex};
26
27 use testing;
28 use rustc_lint;
29 use rustc::dep_graph::DepGraph;
30 use rustc::front::map as hir_map;
31 use rustc::session::{self, config};
32 use rustc::session::config::{get_unstable_features_setting, OutputType};
33 use rustc::session::search_paths::{SearchPaths, PathKind};
34 use rustc_front::lowering::{lower_crate, LoweringContext};
35 use rustc_back::tempdir::TempDir;
36 use rustc_driver::{driver, Compilation};
37 use rustc_metadata::cstore::CStore;
38 use syntax::codemap::CodeMap;
39 use syntax::errors;
40 use syntax::errors::emitter::ColorConfig;
41 use syntax::parse::token;
42
43 use core;
44 use clean;
45 use clean::Clean;
46 use fold::DocFolder;
47 use html::markdown;
48 use passes;
49 use visit_ast::RustdocVisitor;
50
51 #[derive(Clone, Default)]
52 pub struct TestOptions {
53     pub no_crate_inject: bool,
54     pub attrs: Vec<String>,
55 }
56
57 pub fn run(input: &str,
58            cfgs: Vec<String>,
59            libs: SearchPaths,
60            externs: core::Externs,
61            mut test_args: Vec<String>,
62            crate_name: Option<String>)
63            -> isize {
64     let input_path = PathBuf::from(input);
65     let input = config::Input::File(input_path.clone());
66
67     let sessopts = config::Options {
68         maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
69                                               .parent().unwrap().to_path_buf()),
70         search_paths: libs.clone(),
71         crate_types: vec!(config::CrateTypeDylib),
72         externs: externs.clone(),
73         unstable_features: get_unstable_features_setting(),
74         ..config::basic_options().clone()
75     };
76
77     let codemap = Rc::new(CodeMap::new());
78     let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
79                                                                None,
80                                                                true,
81                                                                false,
82                                                                codemap.clone());
83
84     let cstore = Rc::new(CStore::new(token::get_ident_interner()));
85     let sess = session::build_session_(sessopts,
86                                        Some(input_path.clone()),
87                                        diagnostic_handler,
88                                        codemap,
89                                        cstore.clone());
90     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
91
92     let mut cfg = config::build_configuration(&sess);
93     cfg.extend(config::parse_cfgspecs(cfgs.clone()));
94     let krate = panictry!(driver::phase_1_parse_input(&sess, cfg, &input));
95     let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate,
96                                                      "rustdoc-test", None)
97         .expect("phase_2_configure_and_expand aborted in rustdoc!");
98     let krate = driver::assign_node_ids(&sess, krate);
99     let lcx = LoweringContext::new(&sess, Some(&krate));
100     let krate = lower_crate(&lcx, &krate);
101
102     let opts = scrape_test_config(&krate);
103
104     let dep_graph = DepGraph::new(false);
105     let _ignore = dep_graph.in_ignore();
106     let mut forest = hir_map::Forest::new(krate, dep_graph.clone());
107     let map = hir_map::map_crate(&mut forest);
108
109     let ctx = core::DocContext {
110         map: &map,
111         maybe_typed: core::NotTyped(&sess),
112         input: input,
113         external_paths: RefCell::new(Some(HashMap::new())),
114         external_traits: RefCell::new(None),
115         external_typarams: RefCell::new(None),
116         inlined: RefCell::new(None),
117         all_crate_impls: RefCell::new(HashMap::new()),
118         deref_trait_did: Cell::new(None),
119     };
120
121     let mut v = RustdocVisitor::new(&ctx, None);
122     v.visit(ctx.map.krate());
123     let mut krate = v.clean(&ctx);
124     if let Some(name) = crate_name {
125         krate.name = name;
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            compile_fail: bool, 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 = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
248     let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
249     let mut control = driver::CompileController::basic();
250     let mut cfg = config::build_configuration(&sess);
251     cfg.extend(config::parse_cfgspecs(cfgs.clone()));
252     let out = Some(outdir.lock().unwrap().path().to_path_buf());
253
254     if no_run {
255         control.after_analysis.stop = Compilation::Stop;
256     }
257
258     match {
259         let b_sess = AssertRecoverSafe::new(&sess);
260         let b_cstore = AssertRecoverSafe::new(&cstore);
261         let b_cfg = AssertRecoverSafe::new(cfg.clone());
262         let b_control = AssertRecoverSafe::new(&control);
263
264         panic::recover(|| {
265             driver::compile_input(&b_sess, &b_cstore, (*b_cfg).clone(),
266                                   &input, &out,
267                                   &None, None, &b_control)
268         })
269     } {
270         Ok(r) => {
271             match r {
272                 Err(count) if count > 0 && compile_fail == false => {
273                     sess.fatal("aborting due to previous error(s)")
274                 }
275                 Ok(()) if compile_fail => panic!("test compiled while it wasn't supposed to"),
276                 _ => {}
277             }
278         }
279         Err(_) if compile_fail == false => panic!("couldn't compile the test"),
280         _ => {}
281     }
282
283     if no_run { return }
284
285     // Run the code!
286     //
287     // We're careful to prepend the *target* dylib search path to the child's
288     // environment to ensure that the target loads the right libraries at
289     // runtime. It would be a sad day if the *host* libraries were loaded as a
290     // mistake.
291     let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
292     let var = DynamicLibrary::envvar();
293     let newpath = {
294         let path = env::var_os(var).unwrap_or(OsString::new());
295         let mut path = env::split_paths(&path).collect::<Vec<_>>();
296         path.insert(0, libdir.clone());
297         env::join_paths(path).unwrap()
298     };
299     cmd.env(var, &newpath);
300
301     match cmd.output() {
302         Err(e) => panic!("couldn't run the test: {}{}", e,
303                         if e.kind() == io::ErrorKind::PermissionDenied {
304                             " - maybe your tempdir is mounted with noexec?"
305                         } else { "" }),
306         Ok(out) => {
307             if should_panic && out.status.success() {
308                 panic!("test executable succeeded when it should have failed");
309             } else if !should_panic && !out.status.success() {
310                 panic!("test executable failed:\n{}\n{}",
311                        str::from_utf8(&out.stdout).unwrap_or(""),
312                        str::from_utf8(&out.stderr).unwrap_or(""));
313             }
314         }
315     }
316 }
317
318 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
319                 opts: &TestOptions) -> String {
320     let (crate_attrs, everything_else) = partition_source(s);
321
322     let mut prog = String::new();
323
324     // First push any outer attributes from the example, assuming they
325     // are intended to be crate attributes.
326     prog.push_str(&crate_attrs);
327
328     // Next, any attributes for other aspects such as lints.
329     for attr in &opts.attrs {
330         prog.push_str(&format!("#![{}]\n", attr));
331     }
332
333     // Don't inject `extern crate std` because it's already injected by the
334     // compiler.
335     if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
336         if let Some(cratename) = cratename {
337             if s.contains(cratename) {
338                 prog.push_str(&format!("extern crate {};\n", cratename));
339             }
340         }
341     }
342     if dont_insert_main || s.contains("fn main") {
343         prog.push_str(&everything_else);
344     } else {
345         prog.push_str("fn main() {\n    ");
346         prog.push_str(&everything_else.replace("\n", "\n    "));
347         prog = prog.trim().into();
348         prog.push_str("\n}");
349     }
350
351     info!("final test program: {}", prog);
352
353     return prog
354 }
355
356 fn partition_source(s: &str) -> (String, String) {
357     use rustc_unicode::str::UnicodeStr;
358
359     let mut after_header = false;
360     let mut before = String::new();
361     let mut after = String::new();
362
363     for line in s.lines() {
364         let trimline = line.trim();
365         let header = trimline.is_whitespace() ||
366             trimline.starts_with("#![feature");
367         if !header || after_header {
368             after_header = true;
369             after.push_str(line);
370             after.push_str("\n");
371         } else {
372             before.push_str(line);
373             before.push_str("\n");
374         }
375     }
376
377     return (before, after);
378 }
379
380 pub struct Collector {
381     pub tests: Vec<testing::TestDescAndFn>,
382     names: Vec<String>,
383     cfgs: Vec<String>,
384     libs: SearchPaths,
385     externs: core::Externs,
386     cnt: usize,
387     use_headers: bool,
388     current_header: Option<String>,
389     cratename: String,
390     opts: TestOptions,
391 }
392
393 impl Collector {
394     pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: core::Externs,
395                use_headers: bool, opts: TestOptions) -> Collector {
396         Collector {
397             tests: Vec::new(),
398             names: Vec::new(),
399             cfgs: cfgs,
400             libs: libs,
401             externs: externs,
402             cnt: 0,
403             use_headers: use_headers,
404             current_header: None,
405             cratename: cratename,
406             opts: opts,
407         }
408     }
409
410     pub fn add_test(&mut self, test: String,
411                     should_panic: bool, no_run: bool, should_ignore: bool,
412                     as_test_harness: bool, compile_fail: bool) {
413         let name = if self.use_headers {
414             let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
415             format!("{}_{}", s, self.cnt)
416         } else {
417             format!("{}_{}", self.names.join("::"), self.cnt)
418         };
419         self.cnt += 1;
420         let cfgs = self.cfgs.clone();
421         let libs = self.libs.clone();
422         let externs = self.externs.clone();
423         let cratename = self.cratename.to_string();
424         let opts = self.opts.clone();
425         debug!("Creating test {}: {}", name, test);
426         self.tests.push(testing::TestDescAndFn {
427             desc: testing::TestDesc {
428                 name: testing::DynTestName(name),
429                 ignore: should_ignore,
430                 // compiler failures are test failures
431                 should_panic: testing::ShouldPanic::No,
432             },
433             testfn: testing::DynTestFn(Box::new(move|| {
434                 runtest(&test,
435                         &cratename,
436                         cfgs,
437                         libs,
438                         externs,
439                         should_panic,
440                         no_run,
441                         as_test_harness,
442                         compile_fail,
443                         &opts);
444             }))
445         });
446     }
447
448     pub fn register_header(&mut self, name: &str, level: u32) {
449         if self.use_headers && level == 1 {
450             // we use these headings as test names, so it's good if
451             // they're valid identifiers.
452             let name = name.chars().enumerate().map(|(i, c)| {
453                     if (i == 0 && c.is_xid_start()) ||
454                         (i != 0 && c.is_xid_continue()) {
455                         c
456                     } else {
457                         '_'
458                     }
459                 }).collect::<String>();
460
461             // new header => reset count.
462             self.cnt = 0;
463             self.current_header = Some(name);
464         }
465     }
466 }
467
468 impl DocFolder for Collector {
469     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
470         let current_name = match item.name {
471             Some(ref name) if !name.is_empty() => Some(name.clone()),
472             _ => typename_if_impl(&item)
473         };
474
475         let pushed = current_name.map(|name| self.names.push(name)).is_some();
476
477         if let Some(doc) = item.doc_value() {
478             self.cnt = 0;
479             markdown::find_testable_code(doc, &mut *self);
480         }
481
482         let ret = self.fold_item_recur(item);
483         if pushed {
484             self.names.pop();
485         }
486
487         return ret;
488
489         // FIXME: it would be better to not have the escaped version in the first place
490         fn unescape_for_testname(mut s: String) -> String {
491             // for refs `&foo`
492             if s.contains("&amp;") {
493                 s = s.replace("&amp;", "&");
494
495                 // `::&'a mut Foo::` looks weird, let's make it `::<&'a mut Foo>`::
496                 if let Some('&') = s.chars().nth(0) {
497                     s = format!("<{}>", s);
498                 }
499             }
500
501             // either `<..>` or `->`
502             if s.contains("&gt;") {
503                 s.replace("&gt;", ">")
504                  .replace("&lt;", "<")
505             } else {
506                 s
507             }
508         }
509
510         fn typename_if_impl(item: &clean::Item) -> Option<String> {
511             if let clean::ItemEnum::ImplItem(ref impl_) = item.inner {
512                 let path = impl_.for_.to_string();
513                 let unescaped_path = unescape_for_testname(path);
514                 Some(unescaped_path)
515             } else {
516                 None
517             }
518         }
519     }
520 }