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.
12 use std::ffi::OsString;
13 use std::io::prelude::*;
15 use std::path::PathBuf;
16 use std::panic::{self, AssertUnwindSafe};
17 use std::process::Command;
20 use std::sync::{Arc, Mutex};
24 use rustc::dep_graph::DepGraph;
26 use rustc::hir::intravisit;
27 use rustc::session::{self, config};
28 use rustc::session::config::{OutputType, OutputTypes, Externs};
29 use rustc::session::search_paths::{SearchPaths, PathKind};
30 use rustc_back::dynamic_lib::DynamicLibrary;
31 use rustc_back::tempdir::TempDir;
32 use rustc_driver::{self, driver, Compilation};
33 use rustc_driver::driver::phase_2_configure_and_expand;
34 use rustc_metadata::cstore::CStore;
35 use rustc_resolve::MakeGlobMap;
36 use rustc_trans::back::link;
38 use syntax::codemap::CodeMap;
39 use syntax::feature_gate::UnstableFeatures;
40 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span};
42 use errors::emitter::ColorConfig;
44 use clean::Attributes;
47 #[derive(Clone, Default)]
48 pub struct TestOptions {
49 pub no_crate_inject: bool,
50 pub attrs: Vec<String>,
53 pub fn run(input: &str,
57 mut test_args: Vec<String>,
58 crate_name: Option<String>,
59 maybe_sysroot: Option<PathBuf>)
61 let input_path = PathBuf::from(input);
62 let input = config::Input::File(input_path.clone());
64 let sessopts = config::Options {
65 maybe_sysroot: maybe_sysroot.clone().or_else(
66 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
67 search_paths: libs.clone(),
68 crate_types: vec![config::CrateTypeDylib],
69 externs: externs.clone(),
70 unstable_features: UnstableFeatures::from_environment(),
71 actually_rustdoc: true,
72 ..config::basic_options().clone()
75 let codemap = Rc::new(CodeMap::new());
77 errors::Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
79 let dep_graph = DepGraph::new(false);
80 let _ignore = dep_graph.in_ignore();
81 let cstore = Rc::new(CStore::new(&dep_graph));
82 let mut sess = session::build_session_(
83 sessopts, &dep_graph, Some(input_path.clone()), handler, codemap.clone(), cstore.clone(),
85 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
86 sess.parse_sess.config =
87 config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
89 let krate = panictry!(driver::phase_1_parse_input(&sess, &input));
90 let driver::ExpansionResult { defs, mut hir_forest, .. } = {
91 phase_2_configure_and_expand(
92 &sess, &cstore, krate, None, "rustdoc-test", None, MakeGlobMap::No, |_| Ok(())
93 ).expect("phase_2_configure_and_expand aborted in rustdoc!")
96 let crate_name = crate_name.unwrap_or_else(|| {
97 link::find_crate_name(None, &hir_forest.krate().attrs, &input)
99 let opts = scrape_test_config(hir_forest.krate());
100 let mut collector = Collector::new(crate_name,
110 let dep_graph = DepGraph::new(false);
111 let _ignore = dep_graph.in_ignore();
112 let map = hir::map::map_crate(&mut hir_forest, defs);
113 let krate = map.krate();
114 let mut hir_collector = HirCollector {
115 collector: &mut collector,
118 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
119 intravisit::walk_crate(this, krate);
123 test_args.insert(0, "rustdoctest".to_string());
125 testing::test_main(&test_args,
126 collector.tests.into_iter().collect());
130 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
131 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
132 use syntax::print::pprust;
134 let mut opts = TestOptions {
135 no_crate_inject: false,
139 let attrs = krate.attrs.iter()
140 .filter(|a| a.check_name("doc"))
141 .filter_map(|a| a.meta_item_list())
143 .filter(|a| a.check_name("test"))
144 .filter_map(|a| a.meta_item_list())
147 if attr.check_name("no_crate_inject") {
148 opts.no_crate_inject = true;
150 if attr.check_name("attr") {
151 if let Some(l) = attr.meta_item_list() {
153 opts.attrs.push(pprust::meta_list_item_to_string(item));
162 fn runtest(test: &str, cratename: &str, cfgs: Vec<String>, libs: SearchPaths,
164 should_panic: bool, no_run: bool, as_test_harness: bool,
165 compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
166 maybe_sysroot: Option<PathBuf>) {
167 // the test harness wants its own `main` & top level functions, so
168 // never wrap the test in `fn main() { ... }`
169 let test = maketest(test, Some(cratename), as_test_harness, opts);
170 let input = config::Input::Str {
171 name: driver::anon_src(),
172 input: test.to_owned(),
174 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
176 let sessopts = config::Options {
177 maybe_sysroot: maybe_sysroot.or_else(
178 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
180 crate_types: vec![config::CrateTypeExecutable],
181 output_types: outputs,
183 cg: config::CodegenOptions {
184 prefer_dynamic: true,
185 .. config::basic_codegen_options()
187 test: as_test_harness,
188 unstable_features: UnstableFeatures::from_environment(),
189 ..config::basic_options().clone()
192 // Shuffle around a few input and output handles here. We're going to pass
193 // an explicit handle into rustc to collect output messages, but we also
194 // want to catch the error message that rustc prints when it fails.
196 // We take our thread-local stderr (likely set by the test runner) and replace
197 // it with a sink that is also passed to rustc itself. When this function
198 // returns the output of the sink is copied onto the output of our own thread.
200 // The basic idea is to not use a default Handler for rustc, and then also
201 // not print things by default to the actual stderr.
202 struct Sink(Arc<Mutex<Vec<u8>>>);
203 impl Write for Sink {
204 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
205 Write::write(&mut *self.0.lock().unwrap(), data)
207 fn flush(&mut self) -> io::Result<()> { Ok(()) }
209 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
212 let _ = self.1.write_all(&self.0.lock().unwrap());
215 let data = Arc::new(Mutex::new(Vec::new()));
216 let codemap = Rc::new(CodeMap::new());
217 let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
218 Some(codemap.clone()));
219 let old = io::set_panic(Some(box Sink(data.clone())));
220 let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
223 let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
225 let dep_graph = DepGraph::new(false);
226 let cstore = Rc::new(CStore::new(&dep_graph));
227 let mut sess = session::build_session_(
228 sessopts, &dep_graph, None, diagnostic_handler, codemap, cstore.clone(),
230 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
232 let outdir = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
233 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
234 let mut control = driver::CompileController::basic();
235 sess.parse_sess.config =
236 config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
237 let out = Some(outdir.lock().unwrap().path().to_path_buf());
240 control.after_analysis.stop = Compilation::Stop;
243 let res = panic::catch_unwind(AssertUnwindSafe(|| {
244 driver::compile_input(&sess, &cstore, &input, &out, &None, None, &control)
251 if count > 0 && !compile_fail {
252 sess.fatal("aborting due to previous error(s)")
253 } else if count == 0 && compile_fail {
254 panic!("test compiled while it wasn't supposed to")
256 if count > 0 && error_codes.len() > 0 {
257 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
258 error_codes.retain(|err| !out.contains(err));
261 Ok(()) if compile_fail => {
262 panic!("test compiled while it wasn't supposed to")
269 panic!("couldn't compile the test");
271 if error_codes.len() > 0 {
272 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
273 error_codes.retain(|err| !out.contains(err));
278 if error_codes.len() > 0 {
279 panic!("Some expected error codes were not found: {:?}", error_codes);
286 // We're careful to prepend the *target* dylib search path to the child's
287 // environment to ensure that the target loads the right libraries at
288 // runtime. It would be a sad day if the *host* libraries were loaded as a
290 let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
291 let var = DynamicLibrary::envvar();
293 let path = env::var_os(var).unwrap_or(OsString::new());
294 let mut path = env::split_paths(&path).collect::<Vec<_>>();
295 path.insert(0, libdir.clone());
296 env::join_paths(path).unwrap()
298 cmd.env(var, &newpath);
301 Err(e) => panic!("couldn't run the test: {}{}", e,
302 if e.kind() == io::ErrorKind::PermissionDenied {
303 " - maybe your tempdir is mounted with noexec?"
306 if should_panic && out.status.success() {
307 panic!("test executable succeeded when it should have failed");
308 } else if !should_panic && !out.status.success() {
309 panic!("test executable failed:\n{}\n{}\n",
310 str::from_utf8(&out.stdout).unwrap_or(""),
311 str::from_utf8(&out.stderr).unwrap_or(""));
317 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
318 opts: &TestOptions) -> String {
319 let (crate_attrs, everything_else) = partition_source(s);
321 let mut prog = String::new();
323 // First push any outer attributes from the example, assuming they
324 // are intended to be crate attributes.
325 prog.push_str(&crate_attrs);
327 // Next, any attributes for other aspects such as lints.
328 for attr in &opts.attrs {
329 prog.push_str(&format!("#![{}]\n", attr));
332 // Don't inject `extern crate std` because it's already injected by the
334 if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
335 if let Some(cratename) = cratename {
336 if s.contains(cratename) {
337 prog.push_str(&format!("extern crate {};\n", cratename));
341 if dont_insert_main || s.contains("fn main") {
342 prog.push_str(&everything_else);
344 prog.push_str("fn main() {\n");
345 prog.push_str(&everything_else);
346 prog = prog.trim().into();
347 prog.push_str("\n}");
350 info!("final test program: {}", prog);
355 // FIXME(aburka): use a real parser to deal with multiline attributes
356 fn partition_source(s: &str) -> (String, String) {
357 use std_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("#![");
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");
380 pub struct Collector {
381 pub tests: Vec<testing::TestDescAndFn>,
388 current_header: Option<String>,
391 maybe_sysroot: Option<PathBuf>,
393 codemap: Option<Rc<CodeMap>>,
397 pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
398 use_headers: bool, opts: TestOptions, maybe_sysroot: Option<PathBuf>,
399 codemap: Option<Rc<CodeMap>>) -> Collector {
407 use_headers: use_headers,
408 current_header: None,
409 cratename: cratename,
411 maybe_sysroot: maybe_sysroot,
417 pub fn add_test(&mut self, test: String,
418 should_panic: bool, no_run: bool, should_ignore: bool,
419 as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>,
420 line: usize, filename: String) {
421 let name = format!("{} - line {}", filename, line);
423 let cfgs = self.cfgs.clone();
424 let libs = self.libs.clone();
425 let externs = self.externs.clone();
426 let cratename = self.cratename.to_string();
427 let opts = self.opts.clone();
428 let maybe_sysroot = self.maybe_sysroot.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 move |()| {
438 let panic = io::set_panic(None);
439 let print = io::set_print(None);
441 rustc_driver::in_rustc_thread(move || {
442 io::set_panic(panic);
443 io::set_print(print);
459 Err(err) => panic::resume_unwind(err),
465 pub fn get_line(&self) -> usize {
466 if let Some(ref codemap) = self.codemap {
467 let line = self.position.lo.to_usize();
468 let line = codemap.lookup_char_pos(BytePos(line as u32)).line;
469 if line > 0 { line - 1 } else { line }
475 pub fn set_position(&mut self, position: Span) {
476 self.position = position;
479 pub fn get_filename(&self) -> String {
480 if let Some(ref codemap) = self.codemap {
481 codemap.span_to_filename(self.position)
487 pub fn register_header(&mut self, name: &str, level: u32) {
488 if self.use_headers && level == 1 {
489 // we use these headings as test names, so it's good if
490 // they're valid identifiers.
491 let name = name.chars().enumerate().map(|(i, c)| {
492 if (i == 0 && c.is_xid_start()) ||
493 (i != 0 && c.is_xid_continue()) {
498 }).collect::<String>();
500 // new header => reset count.
502 self.current_header = Some(name);
507 struct HirCollector<'a, 'hir: 'a> {
508 collector: &'a mut Collector,
509 map: &'a hir::map::Map<'hir>
512 impl<'a, 'hir> HirCollector<'a, 'hir> {
513 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
515 attrs: &[ast::Attribute],
517 let has_name = !name.is_empty();
519 self.collector.names.push(name);
522 let mut attrs = Attributes::from_ast(attrs);
523 attrs.collapse_doc_comments();
524 attrs.unindent_doc_comments();
525 if let Some(doc) = attrs.doc_value() {
526 self.collector.cnt = 0;
527 markdown::find_testable_code(doc, self.collector,
528 attrs.span.unwrap_or(DUMMY_SP));
534 self.collector.names.pop();
539 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
540 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
541 intravisit::NestedVisitorMap::All(&self.map)
544 fn visit_item(&mut self, item: &'hir hir::Item) {
545 let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
546 self.map.node_to_pretty_string(ty.id)
548 item.name.to_string()
551 self.visit_testable(name, &item.attrs, |this| {
552 intravisit::walk_item(this, item);
556 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
557 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
558 intravisit::walk_trait_item(this, item);
562 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
563 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
564 intravisit::walk_impl_item(this, item);
568 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
569 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
570 intravisit::walk_foreign_item(this, item);
574 fn visit_variant(&mut self,
575 v: &'hir hir::Variant,
576 g: &'hir hir::Generics,
577 item_id: ast::NodeId) {
578 self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
579 intravisit::walk_variant(this, v, g, item_id);
583 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
584 self.visit_testable(f.name.to_string(), &f.attrs, |this| {
585 intravisit::walk_struct_field(this, f);
589 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
590 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());