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::{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;
41 use errors::emitter::ColorConfig;
43 use clean::Attributes;
46 #[derive(Clone, Default)]
47 pub struct TestOptions {
48 pub no_crate_inject: bool,
49 pub attrs: Vec<String>,
52 pub fn run(input: &str,
56 mut test_args: Vec<String>,
57 crate_name: Option<String>)
59 let input_path = PathBuf::from(input);
60 let input = config::Input::File(input_path.clone());
62 let sessopts = config::Options {
63 maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
64 .parent().unwrap().to_path_buf()),
65 search_paths: libs.clone(),
66 crate_types: vec![config::CrateTypeDylib],
67 externs: externs.clone(),
68 unstable_features: UnstableFeatures::from_environment(),
69 ..config::basic_options().clone()
72 let codemap = Rc::new(CodeMap::new());
74 errors::Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
76 let dep_graph = DepGraph::new(false);
77 let _ignore = dep_graph.in_ignore();
78 let cstore = Rc::new(CStore::new(&dep_graph));
79 let mut sess = session::build_session_(
80 sessopts, &dep_graph, Some(input_path.clone()), handler, codemap, cstore.clone(),
82 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
83 sess.parse_sess.config =
84 config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
86 let krate = panictry!(driver::phase_1_parse_input(&sess, &input));
87 let driver::ExpansionResult { defs, mut hir_forest, .. } = {
88 phase_2_configure_and_expand(
89 &sess, &cstore, krate, None, "rustdoc-test", None, MakeGlobMap::No, |_| Ok(())
90 ).expect("phase_2_configure_and_expand aborted in rustdoc!")
93 let crate_name = crate_name.unwrap_or_else(|| {
94 link::find_crate_name(None, &hir_forest.krate().attrs, &input)
96 let opts = scrape_test_config(hir_forest.krate());
97 let mut collector = Collector::new(crate_name,
105 let dep_graph = DepGraph::new(false);
106 let _ignore = dep_graph.in_ignore();
107 let map = hir::map::map_crate(&mut hir_forest, defs);
108 let krate = map.krate();
109 let mut hir_collector = HirCollector {
110 collector: &mut collector,
113 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
114 intravisit::walk_crate(this, krate);
118 test_args.insert(0, "rustdoctest".to_string());
120 testing::test_main(&test_args,
121 collector.tests.into_iter().collect());
125 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
126 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
127 use syntax::print::pprust;
129 let mut opts = TestOptions {
130 no_crate_inject: false,
134 let attrs = krate.attrs.iter()
135 .filter(|a| a.check_name("doc"))
136 .filter_map(|a| a.meta_item_list())
138 .filter(|a| a.check_name("test"))
139 .filter_map(|a| a.meta_item_list())
142 if attr.check_name("no_crate_inject") {
143 opts.no_crate_inject = true;
145 if attr.check_name("attr") {
146 if let Some(l) = attr.meta_item_list() {
148 opts.attrs.push(pprust::meta_list_item_to_string(item));
157 fn runtest(test: &str, cratename: &str, cfgs: Vec<String>, libs: SearchPaths,
159 should_panic: bool, no_run: bool, as_test_harness: bool,
160 compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions) {
161 // the test harness wants its own `main` & top level functions, so
162 // never wrap the test in `fn main() { ... }`
163 let test = maketest(test, Some(cratename), as_test_harness, opts);
164 let input = config::Input::Str {
165 name: driver::anon_src(),
166 input: test.to_owned(),
168 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
170 let sessopts = config::Options {
171 maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
172 .parent().unwrap().to_path_buf()),
174 crate_types: vec![config::CrateTypeExecutable],
175 output_types: outputs,
177 cg: config::CodegenOptions {
178 prefer_dynamic: true,
179 .. config::basic_codegen_options()
181 test: as_test_harness,
182 unstable_features: UnstableFeatures::from_environment(),
183 ..config::basic_options().clone()
186 // Shuffle around a few input and output handles here. We're going to pass
187 // an explicit handle into rustc to collect output messages, but we also
188 // want to catch the error message that rustc prints when it fails.
190 // We take our thread-local stderr (likely set by the test runner) and replace
191 // it with a sink that is also passed to rustc itself. When this function
192 // returns the output of the sink is copied onto the output of our own thread.
194 // The basic idea is to not use a default Handler for rustc, and then also
195 // not print things by default to the actual stderr.
196 struct Sink(Arc<Mutex<Vec<u8>>>);
197 impl Write for Sink {
198 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
199 Write::write(&mut *self.0.lock().unwrap(), data)
201 fn flush(&mut self) -> io::Result<()> { Ok(()) }
203 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
206 let _ = self.1.write_all(&self.0.lock().unwrap());
209 let data = Arc::new(Mutex::new(Vec::new()));
210 let codemap = Rc::new(CodeMap::new());
211 let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
212 Some(codemap.clone()));
213 let old = io::set_panic(Some(box Sink(data.clone())));
214 let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
217 let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
219 let dep_graph = DepGraph::new(false);
220 let cstore = Rc::new(CStore::new(&dep_graph));
221 let mut sess = session::build_session_(
222 sessopts, &dep_graph, None, diagnostic_handler, codemap, cstore.clone(),
224 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
226 let outdir = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
227 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
228 let mut control = driver::CompileController::basic();
229 sess.parse_sess.config =
230 config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
231 let out = Some(outdir.lock().unwrap().path().to_path_buf());
234 control.after_analysis.stop = Compilation::Stop;
237 let res = panic::catch_unwind(AssertUnwindSafe(|| {
238 driver::compile_input(&sess, &cstore, &input, &out, &None, None, &control)
245 if count > 0 && !compile_fail {
246 sess.fatal("aborting due to previous error(s)")
247 } else if count == 0 && compile_fail {
248 panic!("test compiled while it wasn't supposed to")
250 if count > 0 && error_codes.len() > 0 {
251 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
252 error_codes.retain(|err| !out.contains(err));
255 Ok(()) if compile_fail => panic!("test compiled while it wasn't supposed to"),
261 panic!("couldn't compile the test");
263 if error_codes.len() > 0 {
264 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
265 error_codes.retain(|err| !out.contains(err));
270 if error_codes.len() > 0 {
271 panic!("Some expected error codes were not found: {:?}", error_codes);
278 // We're careful to prepend the *target* dylib search path to the child's
279 // environment to ensure that the target loads the right libraries at
280 // runtime. It would be a sad day if the *host* libraries were loaded as a
282 let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
283 let var = DynamicLibrary::envvar();
285 let path = env::var_os(var).unwrap_or(OsString::new());
286 let mut path = env::split_paths(&path).collect::<Vec<_>>();
287 path.insert(0, libdir.clone());
288 env::join_paths(path).unwrap()
290 cmd.env(var, &newpath);
293 Err(e) => panic!("couldn't run the test: {}{}", e,
294 if e.kind() == io::ErrorKind::PermissionDenied {
295 " - maybe your tempdir is mounted with noexec?"
298 if should_panic && out.status.success() {
299 panic!("test executable succeeded when it should have failed");
300 } else if !should_panic && !out.status.success() {
301 panic!("test executable failed:\n{}\n{}",
302 str::from_utf8(&out.stdout).unwrap_or(""),
303 str::from_utf8(&out.stderr).unwrap_or(""));
309 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
310 opts: &TestOptions) -> String {
311 let (crate_attrs, everything_else) = partition_source(s);
313 let mut prog = String::new();
315 // First push any outer attributes from the example, assuming they
316 // are intended to be crate attributes.
317 prog.push_str(&crate_attrs);
319 // Next, any attributes for other aspects such as lints.
320 for attr in &opts.attrs {
321 prog.push_str(&format!("#![{}]\n", attr));
324 // Don't inject `extern crate std` because it's already injected by the
326 if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
327 if let Some(cratename) = cratename {
328 if s.contains(cratename) {
329 prog.push_str(&format!("extern crate {};\n", cratename));
333 if dont_insert_main || s.contains("fn main") {
334 prog.push_str(&everything_else);
336 prog.push_str("fn main() {\n");
337 prog.push_str(&everything_else);
338 prog = prog.trim().into();
339 prog.push_str("\n}");
342 info!("final test program: {}", prog);
347 fn partition_source(s: &str) -> (String, String) {
348 use std_unicode::str::UnicodeStr;
350 let mut after_header = false;
351 let mut before = String::new();
352 let mut after = String::new();
354 for line in s.lines() {
355 let trimline = line.trim();
356 let header = trimline.is_whitespace() ||
357 trimline.starts_with("#![feature");
358 if !header || after_header {
360 after.push_str(line);
361 after.push_str("\n");
363 before.push_str(line);
364 before.push_str("\n");
371 pub struct Collector {
372 pub tests: Vec<testing::TestDescAndFn>,
379 current_header: Option<String>,
385 pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
386 use_headers: bool, opts: TestOptions) -> Collector {
394 use_headers: use_headers,
395 current_header: None,
396 cratename: cratename,
401 pub fn add_test(&mut self, test: String,
402 should_panic: bool, no_run: bool, should_ignore: bool,
403 as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>) {
404 let name = if self.use_headers {
405 let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
406 format!("{}_{}", s, self.cnt)
408 format!("{}_{}", self.names.join("::"), self.cnt)
411 let cfgs = self.cfgs.clone();
412 let libs = self.libs.clone();
413 let externs = self.externs.clone();
414 let cratename = self.cratename.to_string();
415 let opts = self.opts.clone();
416 debug!("Creating test {}: {}", name, test);
417 self.tests.push(testing::TestDescAndFn {
418 desc: testing::TestDesc {
419 name: testing::DynTestName(name),
420 ignore: should_ignore,
421 // compiler failures are test failures
422 should_panic: testing::ShouldPanic::No,
424 testfn: testing::DynTestFn(box move |()| {
440 pub fn register_header(&mut self, name: &str, level: u32) {
441 if self.use_headers && level == 1 {
442 // we use these headings as test names, so it's good if
443 // they're valid identifiers.
444 let name = name.chars().enumerate().map(|(i, c)| {
445 if (i == 0 && c.is_xid_start()) ||
446 (i != 0 && c.is_xid_continue()) {
451 }).collect::<String>();
453 // new header => reset count.
455 self.current_header = Some(name);
460 struct HirCollector<'a, 'hir: 'a> {
461 collector: &'a mut Collector,
462 map: &'a hir::map::Map<'hir>
465 impl<'a, 'hir> HirCollector<'a, 'hir> {
466 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
468 attrs: &[ast::Attribute],
470 let has_name = !name.is_empty();
472 self.collector.names.push(name);
475 let mut attrs = Attributes::from_ast(attrs);
476 attrs.collapse_doc_comments();
477 attrs.unindent_doc_comments();
478 if let Some(doc) = attrs.doc_value() {
479 self.collector.cnt = 0;
480 markdown::find_testable_code(doc, self.collector);
486 self.collector.names.pop();
491 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
492 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
493 intravisit::NestedVisitorMap::All(&self.map)
496 fn visit_item(&mut self, item: &'hir hir::Item) {
497 let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
498 hir::print::ty_to_string(ty)
500 item.name.to_string()
503 self.visit_testable(name, &item.attrs, |this| {
504 intravisit::walk_item(this, item);
508 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
509 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
510 intravisit::walk_trait_item(this, item);
514 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
515 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
516 intravisit::walk_impl_item(this, item);
520 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
521 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
522 intravisit::walk_foreign_item(this, item);
526 fn visit_variant(&mut self,
527 v: &'hir hir::Variant,
528 g: &'hir hir::Generics,
529 item_id: ast::NodeId) {
530 self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
531 intravisit::walk_variant(this, v, g, item_id);
535 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
536 self.visit_testable(f.name.to_string(), &f.attrs, |this| {
537 intravisit::walk_struct_field(this, f);
541 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
542 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());