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.
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.
13 use std::cell::{RefCell, Cell};
14 use std::collections::{HashSet, HashMap};
15 use std::dynamic_lib::DynamicLibrary;
17 use std::ffi::OsString;
18 use std::io::prelude::*;
20 use std::path::PathBuf;
21 use std::panic::{self, AssertRecoverSafe};
22 use std::process::Command;
25 use std::sync::{Arc, Mutex};
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;
40 use syntax::errors::emitter::ColorConfig;
41 use syntax::parse::token;
49 use visit_ast::RustdocVisitor;
51 #[derive(Clone, Default)]
52 pub struct TestOptions {
53 pub no_crate_inject: bool,
54 pub attrs: Vec<String>,
57 pub fn run(input: &str,
60 externs: core::Externs,
61 mut test_args: Vec<String>,
62 crate_name: Option<String>)
64 let input_path = PathBuf::from(input);
65 let input = config::Input::File(input_path.clone());
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()
77 let codemap = Rc::new(CodeMap::new());
78 let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto,
84 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
85 let sess = session::build_session_(sessopts,
86 Some(input_path.clone()),
90 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
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,
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);
102 let opts = scrape_test_config(&krate);
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);
109 let ctx = core::DocContext {
111 maybe_typed: core::NotTyped(&sess),
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),
121 let mut v = RustdocVisitor::new(&ctx, None);
122 v.visit(ctx.map.krate());
123 let mut krate = v.clean(&ctx);
125 Some(name) => krate.name = name,
128 let (krate, _) = passes::collapse_docs(krate);
129 let (krate, _) = passes::unindent_comments(krate);
131 let mut collector = Collector::new(krate.name.to_string(),
137 collector.fold_crate(krate);
139 test_args.insert(0, "rustdoctest".to_string());
141 testing::test_main(&test_args,
142 collector.tests.into_iter().collect());
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;
151 let mut opts = TestOptions {
152 no_crate_inject: false,
156 let attrs = krate.attrs.iter()
157 .filter(|a| a.check_name("doc"))
158 .filter_map(|a| a.meta_item_list())
160 .filter(|a| a.check_name("test"))
161 .filter_map(|a| a.meta_item_list())
164 if attr.check_name("no_crate_inject") {
165 opts.no_crate_inject = true;
167 if attr.check_name("attr") {
168 if let Some(l) = attr.meta_item_list() {
170 opts.attrs.push(pprust::meta_item_to_string(item));
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);
190 let sessopts = config::Options {
191 maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
192 .parent().unwrap().to_path_buf()),
194 crate_types: vec!(config::CrateTypeExecutable),
195 output_types: outputs,
197 cg: config::CodegenOptions {
198 prefer_dynamic: true,
199 .. config::basic_codegen_options()
201 test: as_test_harness,
202 unstable_features: get_unstable_features_setting(),
203 ..config::basic_options().clone()
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.
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.
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)
221 fn flush(&mut self) -> io::Result<()> { Ok(()) }
223 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
226 let _ = self.1.write_all(&self.0.lock().unwrap());
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()),
234 let old = io::set_panic(box Sink(data.clone()));
235 let _bomb = Bomb(data, old.unwrap_or(box io::stdout()));
238 let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
240 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
241 let sess = session::build_session_(sessopts,
246 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
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());
256 control.after_analysis.stop = Compilation::Stop;
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);
266 driver::compile_input(&b_sess, &b_cstore, (*b_cfg).clone(),
268 &None, None, &b_control)
273 Err(count) if count > 0 && compile_fail == false => {
274 sess.fatal("aborting due to previous error(s)")
276 Ok(()) if compile_fail => panic!("test compiled while it wasn't supposed to"),
280 Err(_) if compile_fail == false => panic!("couldn't compile the test"),
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
292 let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
293 let var = DynamicLibrary::envvar();
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()
300 cmd.env(var, &newpath);
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?"
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(""));
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);
323 let mut prog = String::new();
325 // First push any outer attributes from the example, assuming they
326 // are intended to be crate attributes.
327 prog.push_str(&crate_attrs);
329 // Next, any attributes for other aspects such as lints.
330 for attr in &opts.attrs {
331 prog.push_str(&format!("#![{}]\n", attr));
334 // Don't inject `extern crate std` because it's already injected by the
336 if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
339 if s.contains(cratename) {
340 prog.push_str(&format!("extern crate {};\n", cratename));
346 if dont_insert_main || s.contains("fn main") {
347 prog.push_str(&everything_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}");
355 info!("final test program: {}", prog);
360 fn partition_source(s: &str) -> (String, String) {
361 use rustc_unicode::str::UnicodeStr;
363 let mut after_header = false;
364 let mut before = String::new();
365 let mut after = String::new();
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 {
373 after.push_str(line);
374 after.push_str("\n");
376 before.push_str(line);
377 before.push_str("\n");
381 return (before, after);
384 pub struct Collector {
385 pub tests: Vec<testing::TestDescAndFn>,
389 externs: core::Externs,
392 current_header: Option<String>,
398 pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: core::Externs,
399 use_headers: bool, opts: TestOptions) -> Collector {
407 use_headers: use_headers,
408 current_header: None,
409 cratename: cratename,
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)
421 format!("{}_{}", self.names.join("::"), self.cnt)
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,
437 testfn: testing::DynTestFn(Box::new(move|| {
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()) {
463 }).collect::<String>();
465 // new header => reset count.
467 self.current_header = Some(name);
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)
479 let pushed = if let Some(name) = current_name {
480 self.names.push(name);
486 if let Some(doc) = item.doc_value() {
488 markdown::find_testable_code(doc, &mut *self);
491 let ret = self.fold_item_recur(item);
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 {
501 if s.contains("&") {
502 s = s.replace("&", "&");
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);
510 // either `<..>` or `->`
511 if s.contains(">") {
512 s.replace(">", ">")
513 .replace("<", "<")
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);