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