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::process::Command;
24 use std::sync::{Arc, Mutex};
28 use rustc::front::map as hir_map;
29 use rustc::session::{self, config};
30 use rustc::session::config::{get_unstable_features_setting, OutputType};
31 use rustc::session::search_paths::{SearchPaths, PathKind};
32 use rustc_front::lowering::{lower_crate, LoweringContext};
33 use rustc_back::tempdir::TempDir;
34 use rustc_driver::{driver, Compilation};
35 use rustc_metadata::cstore::CStore;
36 use syntax::codemap::CodeMap;
37 use syntax::diagnostic;
38 use syntax::parse::token;
46 use visit_ast::RustdocVisitor;
48 #[derive(Clone, Default)]
49 pub struct TestOptions {
50 pub no_crate_inject: bool,
51 pub attrs: Vec<String>,
54 pub fn run(input: &str,
57 externs: core::Externs,
58 mut test_args: Vec<String>,
59 crate_name: Option<String>)
61 let input_path = PathBuf::from(input);
62 let input = config::Input::File(input_path.clone());
64 let sessopts = config::Options {
65 maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
66 .parent().unwrap().to_path_buf()),
67 search_paths: libs.clone(),
68 crate_types: vec!(config::CrateTypeDylib),
69 externs: externs.clone(),
70 unstable_features: get_unstable_features_setting(),
71 ..config::basic_options().clone()
74 let codemap = CodeMap::new();
75 let diagnostic_handler = diagnostic::Handler::new(diagnostic::Auto, None, true);
76 let span_diagnostic_handler =
77 diagnostic::SpanHandler::new(diagnostic_handler, codemap);
79 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
80 let cstore_ = ::rustc_driver::cstore_to_cratestore(cstore.clone());
81 let sess = session::build_session_(sessopts,
82 Some(input_path.clone()),
83 span_diagnostic_handler,
85 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
87 let mut cfg = config::build_configuration(&sess);
88 cfg.extend(config::parse_cfgspecs(cfgs));
89 let krate = driver::phase_1_parse_input(&sess, cfg, &input);
90 let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate,
92 .expect("phase_2_configure_and_expand aborted in rustdoc!");
93 let krate = driver::assign_node_ids(&sess, krate);
94 let lcx = LoweringContext::new(&sess, Some(&krate));
95 let krate = lower_crate(&lcx, &krate);
97 let opts = scrape_test_config(&krate);
99 let mut forest = hir_map::Forest::new(krate);
100 let map = hir_map::map_crate(&mut forest);
102 let ctx = core::DocContext {
104 maybe_typed: core::NotTyped(&sess),
106 external_paths: RefCell::new(Some(HashMap::new())),
107 external_traits: RefCell::new(None),
108 external_typarams: RefCell::new(None),
109 inlined: RefCell::new(None),
110 populated_crate_impls: RefCell::new(HashSet::new()),
111 deref_trait_did: Cell::new(None),
114 let mut v = RustdocVisitor::new(&ctx, None);
115 v.visit(ctx.map.krate());
116 let mut krate = v.clean(&ctx);
118 Some(name) => krate.name = name,
121 let (krate, _) = passes::collapse_docs(krate);
122 let (krate, _) = passes::unindent_comments(krate);
124 let mut collector = Collector::new(krate.name.to_string(),
129 collector.fold_crate(krate);
131 test_args.insert(0, "rustdoctest".to_string());
133 testing::test_main(&test_args,
134 collector.tests.into_iter().collect());
138 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
139 fn scrape_test_config(krate: &::rustc_front::hir::Crate) -> TestOptions {
140 use syntax::attr::AttrMetaMethods;
141 use syntax::print::pprust;
143 let mut opts = TestOptions {
144 no_crate_inject: false,
148 let attrs = krate.attrs.iter()
149 .filter(|a| a.check_name("doc"))
150 .filter_map(|a| a.meta_item_list())
152 .filter(|a| a.check_name("test"))
153 .filter_map(|a| a.meta_item_list())
156 if attr.check_name("no_crate_inject") {
157 opts.no_crate_inject = true;
159 if attr.check_name("attr") {
160 if let Some(l) = attr.meta_item_list() {
162 opts.attrs.push(pprust::meta_item_to_string(item));
171 fn runtest(test: &str, cratename: &str, libs: SearchPaths,
172 externs: core::Externs,
173 should_panic: bool, no_run: bool, as_test_harness: bool,
174 opts: &TestOptions) {
175 // the test harness wants its own `main` & top level functions, so
176 // never wrap the test in `fn main() { ... }`
177 let test = maketest(test, Some(cratename), as_test_harness, opts);
178 let input = config::Input::Str(test.to_string());
179 let mut outputs = HashMap::new();
180 outputs.insert(OutputType::Exe, None);
182 let sessopts = config::Options {
183 maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
184 .parent().unwrap().to_path_buf()),
186 crate_types: vec!(config::CrateTypeExecutable),
187 output_types: outputs,
189 cg: config::CodegenOptions {
190 prefer_dynamic: true,
191 .. config::basic_codegen_options()
193 test: as_test_harness,
194 unstable_features: get_unstable_features_setting(),
195 ..config::basic_options().clone()
198 // Shuffle around a few input and output handles here. We're going to pass
199 // an explicit handle into rustc to collect output messages, but we also
200 // want to catch the error message that rustc prints when it fails.
202 // We take our thread-local stderr (likely set by the test runner) and replace
203 // it with a sink that is also passed to rustc itself. When this function
204 // returns the output of the sink is copied onto the output of our own thread.
206 // The basic idea is to not use a default Handler for rustc, and then also
207 // not print things by default to the actual stderr.
208 struct Sink(Arc<Mutex<Vec<u8>>>);
209 impl Write for Sink {
210 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
211 Write::write(&mut *self.0.lock().unwrap(), data)
213 fn flush(&mut self) -> io::Result<()> { Ok(()) }
215 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
218 let _ = self.1.write_all(&self.0.lock().unwrap());
221 let data = Arc::new(Mutex::new(Vec::new()));
222 let emitter = diagnostic::EmitterWriter::new(box Sink(data.clone()), None);
223 let old = io::set_panic(box Sink(data.clone()));
224 let _bomb = Bomb(data, old.unwrap_or(box io::stdout()));
227 let codemap = CodeMap::new();
228 let diagnostic_handler = diagnostic::Handler::with_emitter(true, box emitter);
229 let span_diagnostic_handler =
230 diagnostic::SpanHandler::new(diagnostic_handler, codemap);
232 let cstore = Rc::new(CStore::new(token::get_ident_interner()));
233 let cstore_ = ::rustc_driver::cstore_to_cratestore(cstore.clone());
234 let sess = session::build_session_(sessopts,
236 span_diagnostic_handler,
238 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
240 let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
241 let out = Some(outdir.path().to_path_buf());
242 let cfg = config::build_configuration(&sess);
243 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
244 let mut control = driver::CompileController::basic();
246 control.after_analysis.stop = Compilation::Stop;
248 driver::compile_input(sess, &cstore, cfg, &input, &out, &None, None, control);
254 // We're careful to prepend the *target* dylib search path to the child's
255 // environment to ensure that the target loads the right libraries at
256 // runtime. It would be a sad day if the *host* libraries were loaded as a
258 let mut cmd = Command::new(&outdir.path().join("rust_out"));
259 let var = DynamicLibrary::envvar();
261 let path = env::var_os(var).unwrap_or(OsString::new());
262 let mut path = env::split_paths(&path).collect::<Vec<_>>();
263 path.insert(0, libdir.clone());
264 env::join_paths(path).unwrap()
266 cmd.env(var, &newpath);
269 Err(e) => panic!("couldn't run the test: {}{}", e,
270 if e.kind() == io::ErrorKind::PermissionDenied {
271 " - maybe your tempdir is mounted with noexec?"
274 if should_panic && out.status.success() {
275 panic!("test executable succeeded when it should have failed");
276 } else if !should_panic && !out.status.success() {
277 panic!("test executable failed:\n{}\n{}",
278 str::from_utf8(&out.stdout).unwrap_or(""),
279 str::from_utf8(&out.stderr).unwrap_or(""));
285 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
286 opts: &TestOptions) -> String {
287 let (crate_attrs, everything_else) = partition_source(s);
289 let mut prog = String::new();
291 // First push any outer attributes from the example, assuming they
292 // are intended to be crate attributes.
293 prog.push_str(&crate_attrs);
295 // Next, any attributes for other aspects such as lints.
296 for attr in &opts.attrs {
297 prog.push_str(&format!("#![{}]\n", attr));
300 // Don't inject `extern crate std` because it's already injected by the
302 if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
305 if s.contains(cratename) {
306 prog.push_str(&format!("extern crate {};\n", cratename));
312 if dont_insert_main || s.contains("fn main") {
313 prog.push_str(&everything_else);
315 prog.push_str("fn main() {\n ");
316 prog.push_str(&everything_else.replace("\n", "\n "));
317 prog.push_str("\n}");
320 info!("final test program: {}", prog);
325 fn partition_source(s: &str) -> (String, String) {
326 use rustc_unicode::str::UnicodeStr;
328 let mut after_header = false;
329 let mut before = String::new();
330 let mut after = String::new();
332 for line in s.lines() {
333 let trimline = line.trim();
334 let header = trimline.is_whitespace() ||
335 trimline.starts_with("#![feature");
336 if !header || after_header {
338 after.push_str(line);
339 after.push_str("\n");
341 before.push_str(line);
342 before.push_str("\n");
346 return (before, after);
349 pub struct Collector {
350 pub tests: Vec<testing::TestDescAndFn>,
353 externs: core::Externs,
356 current_header: Option<String>,
362 pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
363 use_headers: bool, opts: TestOptions) -> Collector {
370 use_headers: use_headers,
371 current_header: None,
372 cratename: cratename,
377 pub fn add_test(&mut self, test: String,
378 should_panic: bool, no_run: bool, should_ignore: bool,
379 as_test_harness: bool) {
380 let name = if self.use_headers {
381 let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
382 format!("{}_{}", s, self.cnt)
384 format!("{}_{}", self.names.join("::"), self.cnt)
387 let libs = self.libs.clone();
388 let externs = self.externs.clone();
389 let cratename = self.cratename.to_string();
390 let opts = self.opts.clone();
391 debug!("Creating test {}: {}", name, test);
392 self.tests.push(testing::TestDescAndFn {
393 desc: testing::TestDesc {
394 name: testing::DynTestName(name),
395 ignore: should_ignore,
396 // compiler failures are test failures
397 should_panic: testing::ShouldPanic::No,
399 testfn: testing::DynTestFn(Box::new(move|| {
412 pub fn register_header(&mut self, name: &str, level: u32) {
413 if self.use_headers && level == 1 {
414 // we use these headings as test names, so it's good if
415 // they're valid identifiers.
416 let name = name.chars().enumerate().map(|(i, c)| {
417 if (i == 0 && c.is_xid_start()) ||
418 (i != 0 && c.is_xid_continue()) {
423 }).collect::<String>();
425 // new header => reset count.
427 self.current_header = Some(name);
432 impl DocFolder for Collector {
433 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
434 let current_name = match item.name {
435 Some(ref name) if !name.is_empty() => Some(name.clone()),
436 _ => typename_if_impl(&item)
439 let pushed = if let Some(name) = current_name {
440 self.names.push(name);
446 if let Some(doc) = item.doc_value() {
448 markdown::find_testable_code(doc, &mut *self);
451 let ret = self.fold_item_recur(item);
458 // FIXME: it would be better to not have the escaped version in the first place
459 fn unescape_for_testname(mut s: String) -> String {
461 if s.contains("&") {
462 s = s.replace("&", "&");
464 // `::&'a mut Foo::` looks weird, let's make it `::<&'a mut Foo>`::
465 if let Some('&') = s.chars().nth(0) {
466 s = format!("<{}>", s);
470 // either `<..>` or `->`
471 if s.contains(">") {
472 s.replace(">", ">")
473 .replace("<", "<")
479 fn typename_if_impl(item: &clean::Item) -> Option<String> {
480 if let clean::ItemEnum::ImplItem(ref impl_) = item.inner {
481 let path = impl_.for_.to_string();
482 let unescaped_path = unescape_for_testname(path);