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::{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,
111 let dep_graph = DepGraph::new(false);
112 let _ignore = dep_graph.in_ignore();
113 let map = hir::map::map_crate(&mut hir_forest, defs);
114 let krate = map.krate();
115 let mut hir_collector = HirCollector {
116 collector: &mut collector,
119 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
120 intravisit::walk_crate(this, krate);
124 test_args.insert(0, "rustdoctest".to_string());
126 testing::test_main(&test_args,
127 collector.tests.into_iter().collect());
131 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
132 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
133 use syntax::print::pprust;
135 let mut opts = TestOptions {
136 no_crate_inject: false,
140 let test_attrs: Vec<_> = krate.attrs.iter()
141 .filter(|a| a.check_name("doc"))
142 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
143 .filter(|a| a.check_name("test"))
145 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
148 if attr.check_name("no_crate_inject") {
149 opts.no_crate_inject = true;
151 if attr.check_name("attr") {
152 if let Some(l) = attr.meta_item_list() {
154 opts.attrs.push(pprust::meta_list_item_to_string(item));
163 fn runtest(test: &str, cratename: &str, cfgs: Vec<String>, libs: SearchPaths,
165 should_panic: bool, no_run: bool, as_test_harness: bool,
166 compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
167 maybe_sysroot: Option<PathBuf>) {
168 // the test harness wants its own `main` & top level functions, so
169 // never wrap the test in `fn main() { ... }`
170 let test = maketest(test, Some(cratename), as_test_harness, opts);
171 let input = config::Input::Str {
172 name: driver::anon_src(),
173 input: test.to_owned(),
175 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
177 let sessopts = config::Options {
178 maybe_sysroot: maybe_sysroot.or_else(
179 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
181 crate_types: vec![config::CrateTypeExecutable],
182 output_types: outputs,
184 cg: config::CodegenOptions {
185 prefer_dynamic: true,
186 .. config::basic_codegen_options()
188 test: as_test_harness,
189 unstable_features: UnstableFeatures::from_environment(),
190 ..config::basic_options().clone()
193 // Shuffle around a few input and output handles here. We're going to pass
194 // an explicit handle into rustc to collect output messages, but we also
195 // want to catch the error message that rustc prints when it fails.
197 // We take our thread-local stderr (likely set by the test runner) and replace
198 // it with a sink that is also passed to rustc itself. When this function
199 // returns the output of the sink is copied onto the output of our own thread.
201 // The basic idea is to not use a default Handler for rustc, and then also
202 // not print things by default to the actual stderr.
203 struct Sink(Arc<Mutex<Vec<u8>>>);
204 impl Write for Sink {
205 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
206 Write::write(&mut *self.0.lock().unwrap(), data)
208 fn flush(&mut self) -> io::Result<()> { Ok(()) }
210 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
213 let _ = self.1.write_all(&self.0.lock().unwrap());
216 let data = Arc::new(Mutex::new(Vec::new()));
217 let codemap = Rc::new(CodeMap::new());
218 let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
219 Some(codemap.clone()));
220 let old = io::set_panic(Some(box Sink(data.clone())));
221 let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
224 let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
226 let dep_graph = DepGraph::new(false);
227 let cstore = Rc::new(CStore::new(&dep_graph));
228 let mut sess = session::build_session_(
229 sessopts, &dep_graph, None, diagnostic_handler, codemap, cstore.clone(),
231 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
233 let outdir = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
234 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
235 let mut control = driver::CompileController::basic();
236 sess.parse_sess.config =
237 config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
238 let out = Some(outdir.lock().unwrap().path().to_path_buf());
241 control.after_analysis.stop = Compilation::Stop;
244 let res = panic::catch_unwind(AssertUnwindSafe(|| {
245 driver::compile_input(&sess, &cstore, &input, &out, &None, None, &control)
252 if count > 0 && !compile_fail {
253 sess.fatal("aborting due to previous error(s)")
254 } else if count == 0 && compile_fail {
255 panic!("test compiled while it wasn't supposed to")
257 if count > 0 && error_codes.len() > 0 {
258 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
259 error_codes.retain(|err| !out.contains(err));
262 Ok(()) if compile_fail => {
263 panic!("test compiled while it wasn't supposed to")
270 panic!("couldn't compile the test");
272 if error_codes.len() > 0 {
273 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
274 error_codes.retain(|err| !out.contains(err));
279 if error_codes.len() > 0 {
280 panic!("Some expected error codes were not found: {:?}", error_codes);
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{}\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);
347 prog = prog.trim().into();
348 prog.push_str("\n}");
351 info!("final test program: {}", prog);
356 // FIXME(aburka): use a real parser to deal with multiline attributes
357 fn partition_source(s: &str) -> (String, String) {
358 use std_unicode::str::UnicodeStr;
360 let mut after_header = false;
361 let mut before = String::new();
362 let mut after = String::new();
364 for line in s.lines() {
365 let trimline = line.trim();
366 let header = trimline.is_whitespace() ||
367 trimline.starts_with("#![");
368 if !header || after_header {
370 after.push_str(line);
371 after.push_str("\n");
373 before.push_str(line);
374 before.push_str("\n");
381 pub struct Collector {
382 pub tests: Vec<testing::TestDescAndFn>,
389 current_header: Option<String>,
392 maybe_sysroot: Option<PathBuf>,
394 codemap: Option<Rc<CodeMap>>,
395 filename: Option<String>,
399 pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
400 use_headers: bool, opts: TestOptions, maybe_sysroot: Option<PathBuf>,
401 codemap: Option<Rc<CodeMap>>, filename: Option<String>) -> Collector {
409 use_headers: use_headers,
410 current_header: None,
411 cratename: cratename,
413 maybe_sysroot: maybe_sysroot,
420 pub fn add_test(&mut self, test: String,
421 should_panic: bool, no_run: bool, should_ignore: bool,
422 as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>,
423 line: usize, filename: String) {
424 let name = if self.use_headers {
425 if let Some(ref header) = self.current_header {
426 format!("{} - {} (line {})", filename, header, line)
428 format!("{} - (line {})", filename, line)
431 format!("{} - {} (line {})", filename, self.names.join("::"), line)
433 let cfgs = self.cfgs.clone();
434 let libs = self.libs.clone();
435 let externs = self.externs.clone();
436 let cratename = self.cratename.to_string();
437 let opts = self.opts.clone();
438 let maybe_sysroot = self.maybe_sysroot.clone();
439 debug!("Creating test {}: {}", name, test);
440 self.tests.push(testing::TestDescAndFn {
441 desc: testing::TestDesc {
442 name: testing::DynTestName(name),
443 ignore: should_ignore,
444 // compiler failures are test failures
445 should_panic: testing::ShouldPanic::No,
447 testfn: testing::DynTestFn(box move |()| {
448 let panic = io::set_panic(None);
449 let print = io::set_print(None);
451 rustc_driver::in_rustc_thread(move || {
452 io::set_panic(panic);
453 io::set_print(print);
469 Err(err) => panic::resume_unwind(err),
475 pub fn get_line(&self) -> usize {
476 if let Some(ref codemap) = self.codemap {
477 let line = self.position.lo.to_usize();
478 let line = codemap.lookup_char_pos(BytePos(line as u32)).line;
479 if line > 0 { line - 1 } else { line }
485 pub fn set_position(&mut self, position: Span) {
486 self.position = position;
489 pub fn get_filename(&self) -> String {
490 if let Some(ref codemap) = self.codemap {
491 let filename = codemap.span_to_filename(self.position);
492 if let Ok(cur_dir) = env::current_dir() {
493 if let Ok(path) = Path::new(&filename).strip_prefix(&cur_dir) {
494 if let Some(path) = path.to_str() {
495 return path.to_owned();
500 } else if let Some(ref filename) = self.filename {
507 pub fn register_header(&mut self, name: &str, level: u32) {
508 if self.use_headers && level == 1 {
509 // we use these headings as test names, so it's good if
510 // they're valid identifiers.
511 let name = name.chars().enumerate().map(|(i, c)| {
512 if (i == 0 && c.is_xid_start()) ||
513 (i != 0 && c.is_xid_continue()) {
518 }).collect::<String>();
520 // new header => reset count.
522 self.current_header = Some(name);
527 struct HirCollector<'a, 'hir: 'a> {
528 collector: &'a mut Collector,
529 map: &'a hir::map::Map<'hir>
532 impl<'a, 'hir> HirCollector<'a, 'hir> {
533 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
535 attrs: &[ast::Attribute],
537 let has_name = !name.is_empty();
539 self.collector.names.push(name);
542 let mut attrs = Attributes::from_ast(attrs);
543 attrs.collapse_doc_comments();
544 attrs.unindent_doc_comments();
545 if let Some(doc) = attrs.doc_value() {
546 self.collector.cnt = 0;
547 markdown::find_testable_code(doc, self.collector,
548 attrs.span.unwrap_or(DUMMY_SP));
554 self.collector.names.pop();
559 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
560 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
561 intravisit::NestedVisitorMap::All(&self.map)
564 fn visit_item(&mut self, item: &'hir hir::Item) {
565 let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
566 self.map.node_to_pretty_string(ty.id)
568 item.name.to_string()
571 self.visit_testable(name, &item.attrs, |this| {
572 intravisit::walk_item(this, item);
576 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
577 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
578 intravisit::walk_trait_item(this, item);
582 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
583 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
584 intravisit::walk_impl_item(this, item);
588 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
589 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
590 intravisit::walk_foreign_item(this, item);
594 fn visit_variant(&mut self,
595 v: &'hir hir::Variant,
596 g: &'hir hir::Generics,
597 item_id: ast::NodeId) {
598 self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
599 intravisit::walk_variant(this, v, g, item_id);
603 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
604 self.visit_testable(f.name.to_string(), &f.attrs, |this| {
605 intravisit::walk_struct_field(this, f);
609 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
610 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());