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.
11 use std::collections::HashMap;
13 use std::ffi::OsString;
14 use std::io::prelude::*;
16 use std::path::{Path, PathBuf};
17 use std::panic::{self, AssertUnwindSafe};
18 use std::process::Command;
21 use std::sync::{Arc, Mutex};
26 use rustc::hir::intravisit;
27 use rustc::session::{self, CompileIncomplete, 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_driver::pretty::ReplaceBodyWithLoop;
35 use rustc_metadata::cstore::CStore;
36 use rustc_resolve::MakeGlobMap;
38 use rustc_trans::back::link;
40 use syntax::codemap::CodeMap;
41 use syntax::feature_gate::UnstableFeatures;
42 use syntax::fold::Folder;
43 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span};
45 use errors::emitter::ColorConfig;
47 use clean::Attributes;
48 use html::markdown::{self, RenderType};
50 #[derive(Clone, Default)]
51 pub struct TestOptions {
52 pub no_crate_inject: bool,
53 pub attrs: Vec<String>,
56 pub fn run(input: &str,
60 mut test_args: Vec<String>,
61 crate_name: Option<String>,
62 maybe_sysroot: Option<PathBuf>,
63 render_type: RenderType,
64 display_warnings: bool)
66 let input_path = PathBuf::from(input);
67 let input = config::Input::File(input_path.clone());
69 let sessopts = config::Options {
70 maybe_sysroot: maybe_sysroot.clone().or_else(
71 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
72 search_paths: libs.clone(),
73 crate_types: vec![config::CrateTypeDylib],
74 externs: externs.clone(),
75 unstable_features: UnstableFeatures::from_environment(),
76 lint_cap: Some(::rustc::lint::Level::Allow),
77 actually_rustdoc: true,
78 ..config::basic_options().clone()
81 let codemap = Rc::new(CodeMap::new(sessopts.file_path_mapping()));
83 errors::Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
85 let cstore = Rc::new(CStore::new(box rustc_trans::LlvmMetadataLoader));
86 let mut sess = session::build_session_(
87 sessopts, Some(input_path.clone()), handler, codemap.clone(),
89 rustc_trans::init(&sess);
90 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
91 sess.parse_sess.config =
92 config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
94 let krate = panictry!(driver::phase_1_parse_input(&driver::CompileController::basic(),
97 let krate = ReplaceBodyWithLoop::new().fold_crate(krate);
98 let driver::ExpansionResult { defs, mut hir_forest, .. } = {
99 phase_2_configure_and_expand(
108 ).expect("phase_2_configure_and_expand aborted in rustdoc!")
111 let crate_name = crate_name.unwrap_or_else(|| {
112 link::find_crate_name(None, &hir_forest.krate().attrs, &input)
114 let opts = scrape_test_config(hir_forest.krate());
115 let mut collector = Collector::new(crate_name,
127 let map = hir::map::map_crate(&mut hir_forest, defs);
128 let krate = map.krate();
129 let mut hir_collector = HirCollector {
131 collector: &mut collector,
134 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
135 intravisit::walk_crate(this, krate);
139 test_args.insert(0, "rustdoctest".to_string());
141 testing::test_main(&test_args,
142 collector.tests.into_iter().collect(),
143 testing::Options::new().display_output(display_warnings));
147 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
148 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
149 use syntax::print::pprust;
151 let mut opts = TestOptions {
152 no_crate_inject: false,
156 let test_attrs: Vec<_> = krate.attrs.iter()
157 .filter(|a| a.check_name("doc"))
158 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
159 .filter(|a| a.check_name("test"))
161 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
164 if attr.check_name("no_crate_inject") {
165 opts.no_crate_inject = true;
167 if attr.check_name("attr") {
168 if let Some(l) = attr.meta_item_list() {
170 opts.attrs.push(pprust::meta_list_item_to_string(item));
179 fn run_test(test: &str, cratename: &str, filename: &str, cfgs: Vec<String>, libs: SearchPaths,
181 should_panic: bool, no_run: bool, as_test_harness: bool,
182 compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
183 maybe_sysroot: Option<PathBuf>) {
184 // the test harness wants its own `main` & top level functions, so
185 // never wrap the test in `fn main() { ... }`
186 let test = make_test(test, Some(cratename), as_test_harness, opts);
187 let input = config::Input::Str {
188 name: filename.to_owned(),
189 input: test.to_owned(),
191 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
193 let sessopts = config::Options {
194 maybe_sysroot: maybe_sysroot.or_else(
195 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
197 crate_types: vec![config::CrateTypeExecutable],
198 output_types: outputs,
200 cg: config::CodegenOptions {
201 prefer_dynamic: true,
202 .. config::basic_codegen_options()
204 test: as_test_harness,
205 unstable_features: UnstableFeatures::from_environment(),
206 ..config::basic_options().clone()
209 // Shuffle around a few input and output handles here. We're going to pass
210 // an explicit handle into rustc to collect output messages, but we also
211 // want to catch the error message that rustc prints when it fails.
213 // We take our thread-local stderr (likely set by the test runner) and replace
214 // it with a sink that is also passed to rustc itself. When this function
215 // returns the output of the sink is copied onto the output of our own thread.
217 // The basic idea is to not use a default Handler for rustc, and then also
218 // not print things by default to the actual stderr.
219 struct Sink(Arc<Mutex<Vec<u8>>>);
220 impl Write for Sink {
221 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
222 Write::write(&mut *self.0.lock().unwrap(), data)
224 fn flush(&mut self) -> io::Result<()> { Ok(()) }
226 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
229 let _ = self.1.write_all(&self.0.lock().unwrap());
232 let data = Arc::new(Mutex::new(Vec::new()));
233 let codemap = Rc::new(CodeMap::new(sessopts.file_path_mapping()));
234 let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
235 Some(codemap.clone()));
236 let old = io::set_panic(Some(box Sink(data.clone())));
237 let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
240 let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
242 let cstore = Rc::new(CStore::new(box rustc_trans::LlvmMetadataLoader));
243 let mut sess = session::build_session_(
244 sessopts, None, diagnostic_handler, codemap,
246 rustc_trans::init(&sess);
247 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
249 let outdir = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
250 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
251 let mut control = driver::CompileController::basic();
252 sess.parse_sess.config =
253 config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
254 let out = Some(outdir.lock().unwrap().path().to_path_buf());
257 control.after_analysis.stop = Compilation::Stop;
260 let res = panic::catch_unwind(AssertUnwindSafe(|| {
261 driver::compile_input(&sess, &cstore, &input, &out, &None, None, &control)
264 let compile_result = match res {
265 Ok(Ok(())) | Ok(Err(CompileIncomplete::Stopped)) => Ok(()),
266 Err(_) | Ok(Err(CompileIncomplete::Errored(_))) => Err(())
269 match (compile_result, compile_fail) {
271 panic!("test compiled while it wasn't supposed to")
273 (Ok(()), false) => {}
275 if error_codes.len() > 0 {
276 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
277 error_codes.retain(|err| !out.contains(err));
280 (Err(()), false) => {
281 panic!("couldn't compile the test")
285 if error_codes.len() > 0 {
286 panic!("Some expected error codes were not found: {:?}", error_codes);
293 // We're careful to prepend the *target* dylib search path to the child's
294 // environment to ensure that the target loads the right libraries at
295 // runtime. It would be a sad day if the *host* libraries were loaded as a
297 let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
298 let var = DynamicLibrary::envvar();
300 let path = env::var_os(var).unwrap_or(OsString::new());
301 let mut path = env::split_paths(&path).collect::<Vec<_>>();
302 path.insert(0, libdir.clone());
303 env::join_paths(path).unwrap()
305 cmd.env(var, &newpath);
308 Err(e) => panic!("couldn't run the test: {}{}", e,
309 if e.kind() == io::ErrorKind::PermissionDenied {
310 " - maybe your tempdir is mounted with noexec?"
313 if should_panic && out.status.success() {
314 panic!("test executable succeeded when it should have failed");
315 } else if !should_panic && !out.status.success() {
316 panic!("test executable failed:\n{}\n{}\n",
317 str::from_utf8(&out.stdout).unwrap_or(""),
318 str::from_utf8(&out.stderr).unwrap_or(""));
324 pub fn make_test(s: &str,
325 cratename: Option<&str>,
326 dont_insert_main: bool,
329 let (crate_attrs, everything_else) = partition_source(s);
331 let mut prog = String::new();
333 // First push any outer attributes from the example, assuming they
334 // are intended to be crate attributes.
335 prog.push_str(&crate_attrs);
337 // Next, any attributes for other aspects such as lints.
338 for attr in &opts.attrs {
339 prog.push_str(&format!("#![{}]\n", attr));
342 // Don't inject `extern crate std` because it's already injected by the
344 if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
345 if let Some(cratename) = cratename {
346 if s.contains(cratename) {
347 prog.push_str(&format!("extern crate {};\n", cratename));
351 if dont_insert_main || s.contains("fn main") {
352 prog.push_str(&everything_else);
354 prog.push_str("fn main() {\n");
355 prog.push_str(&everything_else);
356 prog = prog.trim().into();
357 prog.push_str("\n}");
360 info!("final test program: {}", prog);
365 // FIXME(aburka): use a real parser to deal with multiline attributes
366 fn partition_source(s: &str) -> (String, String) {
367 use std_unicode::str::UnicodeStr;
369 let mut after_header = false;
370 let mut before = String::new();
371 let mut after = String::new();
373 for line in s.lines() {
374 let trimline = line.trim();
375 let header = trimline.is_whitespace() ||
376 trimline.starts_with("#![");
377 if !header || after_header {
379 after.push_str(line);
380 after.push_str("\n");
382 before.push_str(line);
383 before.push_str("\n");
390 pub struct Collector {
391 pub tests: Vec<testing::TestDescAndFn>,
392 // to be removed when hoedown will be definitely gone
393 pub old_tests: HashMap<String, Vec<String>>,
400 current_header: Option<String>,
403 maybe_sysroot: Option<PathBuf>,
405 codemap: Option<Rc<CodeMap>>,
406 filename: Option<String>,
407 // to be removed when hoedown will be removed as well
408 pub render_type: RenderType,
412 pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
413 use_headers: bool, opts: TestOptions, maybe_sysroot: Option<PathBuf>,
414 codemap: Option<Rc<CodeMap>>, filename: Option<String>,
415 render_type: RenderType) -> Collector {
418 old_tests: HashMap::new(),
425 current_header: None,
436 fn generate_name(&self, line: usize, filename: &str) -> String {
437 if self.use_headers {
438 if let Some(ref header) = self.current_header {
439 format!("{} - {} (line {})", filename, header, line)
441 format!("{} - (line {})", filename, line)
444 format!("{} - {} (line {})", filename, self.names.join("::"), line)
448 // to be removed once hoedown is gone
449 fn generate_name_beginning(&self, filename: &str) -> String {
450 if self.use_headers {
451 if let Some(ref header) = self.current_header {
452 format!("{} - {} (line", filename, header)
454 format!("{} - (line", filename)
457 format!("{} - {} (line", filename, self.names.join("::"))
461 pub fn add_old_test(&mut self, test: String, filename: String) {
462 let name_beg = self.generate_name_beginning(&filename);
463 let entry = self.old_tests.entry(name_beg)
464 .or_insert(Vec::new());
465 entry.push(test.trim().to_owned());
468 pub fn add_test(&mut self, test: String,
469 should_panic: bool, no_run: bool, should_ignore: bool,
470 as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>,
471 line: usize, filename: String, allow_fail: bool) {
472 let name = self.generate_name(line, &filename);
473 // to be removed when hoedown is removed
474 if self.render_type == RenderType::Pulldown {
475 let name_beg = self.generate_name_beginning(&filename);
476 let mut found = false;
477 let test = test.trim().to_owned();
478 if let Some(entry) = self.old_tests.get_mut(&name_beg) {
479 found = entry.remove_item(&test).is_some();
482 let _ = writeln!(&mut io::stderr(),
483 "WARNING: {} Code block is not currently run as a test, but will \
484 in future versions of rustdoc. Please ensure this code block is \
485 a runnable test, or use the `ignore` directive.",
490 let cfgs = self.cfgs.clone();
491 let libs = self.libs.clone();
492 let externs = self.externs.clone();
493 let cratename = self.cratename.to_string();
494 let opts = self.opts.clone();
495 let maybe_sysroot = self.maybe_sysroot.clone();
496 debug!("Creating test {}: {}", name, test);
497 self.tests.push(testing::TestDescAndFn {
498 desc: testing::TestDesc {
499 name: testing::DynTestName(name),
500 ignore: should_ignore,
501 // compiler failures are test failures
502 should_panic: testing::ShouldPanic::No,
505 testfn: testing::DynTestFn(box move |()| {
506 let panic = io::set_panic(None);
507 let print = io::set_print(None);
509 rustc_driver::in_rustc_thread(move || {
510 io::set_panic(panic);
511 io::set_print(print);
528 Err(err) => panic::resume_unwind(err),
534 pub fn get_line(&self) -> usize {
535 if let Some(ref codemap) = self.codemap {
536 let line = self.position.lo().to_usize();
537 let line = codemap.lookup_char_pos(BytePos(line as u32)).line;
538 if line > 0 { line - 1 } else { line }
544 pub fn set_position(&mut self, position: Span) {
545 self.position = position;
548 pub fn get_filename(&self) -> String {
549 if let Some(ref codemap) = self.codemap {
550 let filename = codemap.span_to_filename(self.position);
551 if let Ok(cur_dir) = env::current_dir() {
552 if let Ok(path) = Path::new(&filename).strip_prefix(&cur_dir) {
553 if let Some(path) = path.to_str() {
554 return path.to_owned();
559 } else if let Some(ref filename) = self.filename {
566 pub fn register_header(&mut self, name: &str, level: u32) {
567 if self.use_headers && level == 1 {
568 // we use these headings as test names, so it's good if
569 // they're valid identifiers.
570 let name = name.chars().enumerate().map(|(i, c)| {
571 if (i == 0 && c.is_xid_start()) ||
572 (i != 0 && c.is_xid_continue()) {
577 }).collect::<String>();
579 // new header => reset count.
581 self.current_header = Some(name);
586 struct HirCollector<'a, 'hir: 'a> {
587 sess: &'a session::Session,
588 collector: &'a mut Collector,
589 map: &'a hir::map::Map<'hir>
592 impl<'a, 'hir> HirCollector<'a, 'hir> {
593 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
595 attrs: &[ast::Attribute],
597 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
598 if let Some(ref cfg) = attrs.cfg {
599 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features.borrow())) {
604 let has_name = !name.is_empty();
606 self.collector.names.push(name);
609 attrs.collapse_doc_comments();
610 attrs.unindent_doc_comments();
611 if let Some(doc) = attrs.doc_value() {
612 self.collector.cnt = 0;
613 if self.collector.render_type == RenderType::Pulldown {
614 markdown::old_find_testable_code(doc, self.collector,
615 attrs.span.unwrap_or(DUMMY_SP));
616 markdown::find_testable_code(doc, self.collector,
617 attrs.span.unwrap_or(DUMMY_SP));
619 markdown::old_find_testable_code(doc, self.collector,
620 attrs.span.unwrap_or(DUMMY_SP));
627 self.collector.names.pop();
632 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
633 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
634 intravisit::NestedVisitorMap::All(&self.map)
637 fn visit_item(&mut self, item: &'hir hir::Item) {
638 let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
639 self.map.node_to_pretty_string(ty.id)
641 item.name.to_string()
644 self.visit_testable(name, &item.attrs, |this| {
645 intravisit::walk_item(this, item);
649 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
650 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
651 intravisit::walk_trait_item(this, item);
655 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
656 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
657 intravisit::walk_impl_item(this, item);
661 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
662 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
663 intravisit::walk_foreign_item(this, item);
667 fn visit_variant(&mut self,
668 v: &'hir hir::Variant,
669 g: &'hir hir::Generics,
670 item_id: ast::NodeId) {
671 self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
672 intravisit::walk_variant(this, v, g, item_id);
676 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
677 self.visit_testable(f.name.to_string(), &f.attrs, |this| {
678 intravisit::walk_struct_field(this, f);
682 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
683 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());