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