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 = panictry!(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);
124 if let Some(name) = crate_name {
127 let (krate, _) = passes::collapse_docs(krate);
128 let (krate, _) = passes::unindent_comments(krate);
130 let mut collector = Collector::new(krate.name.to_string(),
136 collector.fold_crate(krate);
138 test_args.insert(0, "rustdoctest".to_string());
140 testing::test_main(&test_args,
141 collector.tests.into_iter().collect());
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;
150 let mut opts = TestOptions {
151 no_crate_inject: false,
155 let attrs = krate.attrs.iter()
156 .filter(|a| a.check_name("doc"))
157 .filter_map(|a| a.meta_item_list())
159 .filter(|a| a.check_name("test"))
160 .filter_map(|a| a.meta_item_list())
163 if attr.check_name("no_crate_inject") {
164 opts.no_crate_inject = true;
166 if attr.check_name("attr") {
167 if let Some(l) = attr.meta_item_list() {
169 opts.attrs.push(pprust::meta_item_to_string(item));
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);
189 let sessopts = config::Options {
190 maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
191 .parent().unwrap().to_path_buf()),
193 crate_types: vec!(config::CrateTypeExecutable),
194 output_types: outputs,
196 cg: config::CodegenOptions {
197 prefer_dynamic: true,
198 .. config::basic_codegen_options()
200 test: as_test_harness,
201 unstable_features: get_unstable_features_setting(),
202 ..config::basic_options().clone()
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.
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.
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)
220 fn flush(&mut self) -> io::Result<()> { Ok(()) }
222 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
225 let _ = self.1.write_all(&self.0.lock().unwrap());
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()),
233 let old = io::set_panic(box Sink(data.clone()));
234 let _bomb = Bomb(data, old.unwrap_or(box io::stdout()));
237 let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
239 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
240 let sess = session::build_session_(sessopts,
245 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
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());
255 control.after_analysis.stop = Compilation::Stop;
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);
265 driver::compile_input(&b_sess, &b_cstore, (*b_cfg).clone(),
267 &None, None, &b_control)
272 Err(count) if count > 0 && compile_fail == false => {
273 sess.fatal("aborting due to previous error(s)")
275 Ok(()) if compile_fail => panic!("test compiled while it wasn't supposed to"),
279 Err(_) if compile_fail == false => panic!("couldn't compile the test"),
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
291 let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
292 let var = DynamicLibrary::envvar();
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()
299 cmd.env(var, &newpath);
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?"
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(""));
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);
322 let mut prog = String::new();
324 // First push any outer attributes from the example, assuming they
325 // are intended to be crate attributes.
326 prog.push_str(&crate_attrs);
328 // Next, any attributes for other aspects such as lints.
329 for attr in &opts.attrs {
330 prog.push_str(&format!("#![{}]\n", attr));
333 // Don't inject `extern crate std` because it's already injected by the
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));
342 if dont_insert_main || s.contains("fn main") {
343 prog.push_str(&everything_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}");
351 info!("final test program: {}", prog);
356 fn partition_source(s: &str) -> (String, String) {
357 use rustc_unicode::str::UnicodeStr;
359 let mut after_header = false;
360 let mut before = String::new();
361 let mut after = String::new();
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 {
369 after.push_str(line);
370 after.push_str("\n");
372 before.push_str(line);
373 before.push_str("\n");
377 return (before, after);
380 pub struct Collector {
381 pub tests: Vec<testing::TestDescAndFn>,
385 externs: core::Externs,
388 current_header: Option<String>,
394 pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: core::Externs,
395 use_headers: bool, opts: TestOptions) -> Collector {
403 use_headers: use_headers,
404 current_header: None,
405 cratename: cratename,
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)
417 format!("{}_{}", self.names.join("::"), self.cnt)
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,
433 testfn: testing::DynTestFn(Box::new(move|| {
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()) {
459 }).collect::<String>();
461 // new header => reset count.
463 self.current_header = Some(name);
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)
475 let pushed = current_name.map(|name| self.names.push(name)).is_some();
477 if let Some(doc) = item.doc_value() {
479 markdown::find_testable_code(doc, &mut *self);
482 let ret = self.fold_item_recur(item);
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 {
492 if s.contains("&") {
493 s = s.replace("&", "&");
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);
501 // either `<..>` or `->`
502 if s.contains(">") {
503 s.replace(">", ">")
504 .replace("<", "<")
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);