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};
25 use rustc::dep_graph::DepGraph;
27 use rustc::hir::intravisit;
28 use rustc::session::{self, config};
29 use rustc::session::config::{OutputType, OutputTypes, Externs};
30 use rustc::session::search_paths::{SearchPaths, PathKind};
31 use rustc_back::dynamic_lib::DynamicLibrary;
32 use rustc_back::tempdir::TempDir;
33 use rustc_driver::{self, driver, Compilation};
34 use rustc_driver::driver::phase_2_configure_and_expand;
35 use rustc_metadata::cstore::CStore;
36 use rustc_resolve::MakeGlobMap;
37 use rustc_trans::back::link;
39 use syntax::codemap::CodeMap;
40 use syntax::feature_gate::UnstableFeatures;
41 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span};
43 use errors::emitter::ColorConfig;
45 use clean::Attributes;
46 use html::markdown::{self, RenderType};
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,
58 mut test_args: Vec<String>,
59 crate_name: Option<String>,
60 maybe_sysroot: Option<PathBuf>,
61 render_type: RenderType)
63 let input_path = PathBuf::from(input);
64 let input = config::Input::File(input_path.clone());
66 let sessopts = config::Options {
67 maybe_sysroot: maybe_sysroot.clone().or_else(
68 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
69 search_paths: libs.clone(),
70 crate_types: vec![config::CrateTypeDylib],
71 externs: externs.clone(),
72 unstable_features: UnstableFeatures::from_environment(),
73 actually_rustdoc: true,
74 ..config::basic_options().clone()
77 let codemap = Rc::new(CodeMap::new());
79 errors::Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
81 let dep_graph = DepGraph::new(false);
82 let _ignore = dep_graph.in_ignore();
83 let cstore = Rc::new(CStore::new(&dep_graph));
84 let mut sess = session::build_session_(
85 sessopts, &dep_graph, Some(input_path.clone()), handler, codemap.clone(), cstore.clone(),
87 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
88 sess.parse_sess.config =
89 config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
91 let krate = panictry!(driver::phase_1_parse_input(&sess, &input));
92 let driver::ExpansionResult { defs, mut hir_forest, .. } = {
93 phase_2_configure_and_expand(
94 &sess, &cstore, krate, None, "rustdoc-test", None, MakeGlobMap::No, |_| Ok(())
95 ).expect("phase_2_configure_and_expand aborted in rustdoc!")
98 let crate_name = crate_name.unwrap_or_else(|| {
99 link::find_crate_name(None, &hir_forest.krate().attrs, &input)
101 let opts = scrape_test_config(hir_forest.krate());
102 let mut collector = Collector::new(crate_name,
114 let dep_graph = DepGraph::new(false);
115 let _ignore = dep_graph.in_ignore();
116 let map = hir::map::map_crate(&mut hir_forest, defs);
117 let krate = map.krate();
118 let mut hir_collector = HirCollector {
119 collector: &mut collector,
122 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
123 intravisit::walk_crate(this, krate);
127 test_args.insert(0, "rustdoctest".to_string());
129 testing::test_main(&test_args,
130 collector.tests.into_iter().collect());
134 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
135 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
136 use syntax::print::pprust;
138 let mut opts = TestOptions {
139 no_crate_inject: false,
143 let test_attrs: Vec<_> = krate.attrs.iter()
144 .filter(|a| a.check_name("doc"))
145 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
146 .filter(|a| a.check_name("test"))
148 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
151 if attr.check_name("no_crate_inject") {
152 opts.no_crate_inject = true;
154 if attr.check_name("attr") {
155 if let Some(l) = attr.meta_item_list() {
157 opts.attrs.push(pprust::meta_list_item_to_string(item));
166 fn runtest(test: &str, cratename: &str, cfgs: Vec<String>, libs: SearchPaths,
168 should_panic: bool, no_run: bool, as_test_harness: bool,
169 compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
170 maybe_sysroot: Option<PathBuf>) {
171 // the test harness wants its own `main` & top level functions, so
172 // never wrap the test in `fn main() { ... }`
173 let test = maketest(test, Some(cratename), as_test_harness, opts);
174 let input = config::Input::Str {
175 name: driver::anon_src(),
176 input: test.to_owned(),
178 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
180 let sessopts = config::Options {
181 maybe_sysroot: maybe_sysroot.or_else(
182 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
184 crate_types: vec![config::CrateTypeExecutable],
185 output_types: outputs,
187 cg: config::CodegenOptions {
188 prefer_dynamic: true,
189 .. config::basic_codegen_options()
191 test: as_test_harness,
192 unstable_features: UnstableFeatures::from_environment(),
193 ..config::basic_options().clone()
196 // Shuffle around a few input and output handles here. We're going to pass
197 // an explicit handle into rustc to collect output messages, but we also
198 // want to catch the error message that rustc prints when it fails.
200 // We take our thread-local stderr (likely set by the test runner) and replace
201 // it with a sink that is also passed to rustc itself. When this function
202 // returns the output of the sink is copied onto the output of our own thread.
204 // The basic idea is to not use a default Handler for rustc, and then also
205 // not print things by default to the actual stderr.
206 struct Sink(Arc<Mutex<Vec<u8>>>);
207 impl Write for Sink {
208 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
209 Write::write(&mut *self.0.lock().unwrap(), data)
211 fn flush(&mut self) -> io::Result<()> { Ok(()) }
213 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
216 let _ = self.1.write_all(&self.0.lock().unwrap());
219 let data = Arc::new(Mutex::new(Vec::new()));
220 let codemap = Rc::new(CodeMap::new());
221 let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
222 Some(codemap.clone()));
223 let old = io::set_panic(Some(box Sink(data.clone())));
224 let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
227 let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
229 let dep_graph = DepGraph::new(false);
230 let cstore = Rc::new(CStore::new(&dep_graph));
231 let mut sess = session::build_session_(
232 sessopts, &dep_graph, None, diagnostic_handler, codemap, cstore.clone(),
234 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
236 let outdir = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
237 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
238 let mut control = driver::CompileController::basic();
239 sess.parse_sess.config =
240 config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
241 let out = Some(outdir.lock().unwrap().path().to_path_buf());
244 control.after_analysis.stop = Compilation::Stop;
247 let res = panic::catch_unwind(AssertUnwindSafe(|| {
248 driver::compile_input(&sess, &cstore, &input, &out, &None, None, &control)
255 if count > 0 && !compile_fail {
256 sess.fatal("aborting due to previous error(s)")
257 } else if count == 0 && compile_fail {
258 panic!("test compiled while it wasn't supposed to")
260 if count > 0 && error_codes.len() > 0 {
261 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
262 error_codes.retain(|err| !out.contains(err));
265 Ok(()) if compile_fail => {
266 panic!("test compiled while it wasn't supposed to")
273 panic!("couldn't compile the test");
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));
282 if error_codes.len() > 0 {
283 panic!("Some expected error codes were not found: {:?}", error_codes);
290 // We're careful to prepend the *target* dylib search path to the child's
291 // environment to ensure that the target loads the right libraries at
292 // runtime. It would be a sad day if the *host* libraries were loaded as a
294 let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
295 let var = DynamicLibrary::envvar();
297 let path = env::var_os(var).unwrap_or(OsString::new());
298 let mut path = env::split_paths(&path).collect::<Vec<_>>();
299 path.insert(0, libdir.clone());
300 env::join_paths(path).unwrap()
302 cmd.env(var, &newpath);
305 Err(e) => panic!("couldn't run the test: {}{}", e,
306 if e.kind() == io::ErrorKind::PermissionDenied {
307 " - maybe your tempdir is mounted with noexec?"
310 if should_panic && out.status.success() {
311 panic!("test executable succeeded when it should have failed");
312 } else if !should_panic && !out.status.success() {
313 panic!("test executable failed:\n{}\n{}\n",
314 str::from_utf8(&out.stdout).unwrap_or(""),
315 str::from_utf8(&out.stderr).unwrap_or(""));
321 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
322 opts: &TestOptions) -> String {
323 let (crate_attrs, everything_else) = partition_source(s);
325 let mut prog = String::new();
327 // First push any outer attributes from the example, assuming they
328 // are intended to be crate attributes.
329 prog.push_str(&crate_attrs);
331 // Next, any attributes for other aspects such as lints.
332 for attr in &opts.attrs {
333 prog.push_str(&format!("#![{}]\n", attr));
336 // Don't inject `extern crate std` because it's already injected by the
338 if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
339 if let Some(cratename) = cratename {
340 if s.contains(cratename) {
341 prog.push_str(&format!("extern crate {};\n", cratename));
345 if dont_insert_main || s.contains("fn main") {
346 prog.push_str(&everything_else);
348 prog.push_str("fn main() {\n");
349 prog.push_str(&everything_else);
350 prog = prog.trim().into();
351 prog.push_str("\n}");
354 info!("final test program: {}", prog);
359 // FIXME(aburka): use a real parser to deal with multiline attributes
360 fn partition_source(s: &str) -> (String, String) {
361 use std_unicode::str::UnicodeStr;
363 let mut after_header = false;
364 let mut before = String::new();
365 let mut after = String::new();
367 for line in s.lines() {
368 let trimline = line.trim();
369 let header = trimline.is_whitespace() ||
370 trimline.starts_with("#![");
371 if !header || after_header {
373 after.push_str(line);
374 after.push_str("\n");
376 before.push_str(line);
377 before.push_str("\n");
384 pub struct Collector {
385 pub tests: Vec<testing::TestDescAndFn>,
386 // to be removed when hoedown will be definitely gone
387 pub old_tests: HashMap<String, Vec<String>>,
394 current_header: Option<String>,
397 maybe_sysroot: Option<PathBuf>,
399 codemap: Option<Rc<CodeMap>>,
400 filename: Option<String>,
401 // to be removed when hoedown will be removed as well
402 pub render_type: RenderType,
406 pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
407 use_headers: bool, opts: TestOptions, maybe_sysroot: Option<PathBuf>,
408 codemap: Option<Rc<CodeMap>>, filename: Option<String>,
409 render_type: RenderType) -> Collector {
412 old_tests: HashMap::new(),
418 use_headers: use_headers,
419 current_header: None,
420 cratename: cratename,
422 maybe_sysroot: maybe_sysroot,
426 render_type: render_type,
430 fn generate_name(&self, line: usize, filename: &str) -> String {
431 if self.use_headers {
432 if let Some(ref header) = self.current_header {
433 format!("{} - {} (line {})", filename, header, line)
435 format!("{} - (line {})", filename, line)
438 format!("{} - {} (line {})", filename, self.names.join("::"), line)
442 // to be removed once hoedown is gone
443 fn generate_name_beginning(&self, filename: &str) -> String {
444 if self.use_headers {
445 if let Some(ref header) = self.current_header {
446 format!("{} - {} (line", filename, header)
448 format!("{} - (line", filename)
451 format!("{} - {} (line", filename, self.names.join("::"))
455 pub fn add_old_test(&mut self, test: String, filename: String) {
456 let name_beg = self.generate_name_beginning(&filename);
457 let entry = self.old_tests.entry(name_beg)
458 .or_insert(Vec::new());
459 entry.push(test.trim().to_owned());
462 pub fn add_test(&mut self, test: String,
463 should_panic: bool, no_run: bool, should_ignore: bool,
464 as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>,
465 line: usize, filename: String) {
466 let name = self.generate_name(line, &filename);
467 // to be removed when hoedown is removed
468 if self.render_type == RenderType::Pulldown {
469 let name_beg = self.generate_name_beginning(&filename);
470 let mut found = false;
471 let test = test.trim().to_owned();
472 if let Some(entry) = self.old_tests.get_mut(&name_beg) {
473 found = entry.remove_item(&test).is_some();
476 let _ = writeln!(&mut io::stderr(),
477 "WARNING: {} Code block is not currently run as a test, but will \
478 in future versions of rustdoc. Please ensure this code block is \
479 a runnable test, or use the `ignore` directive.",
484 let cfgs = self.cfgs.clone();
485 let libs = self.libs.clone();
486 let externs = self.externs.clone();
487 let cratename = self.cratename.to_string();
488 let opts = self.opts.clone();
489 let maybe_sysroot = self.maybe_sysroot.clone();
490 debug!("Creating test {}: {}", name, test);
491 self.tests.push(testing::TestDescAndFn {
492 desc: testing::TestDesc {
493 name: testing::DynTestName(name),
494 ignore: should_ignore,
495 // compiler failures are test failures
496 should_panic: testing::ShouldPanic::No,
498 testfn: testing::DynTestFn(box move |()| {
499 let panic = io::set_panic(None);
500 let print = io::set_print(None);
502 rustc_driver::in_rustc_thread(move || {
503 io::set_panic(panic);
504 io::set_print(print);
520 Err(err) => panic::resume_unwind(err),
526 pub fn get_line(&self) -> usize {
527 if let Some(ref codemap) = self.codemap {
528 let line = self.position.lo.to_usize();
529 let line = codemap.lookup_char_pos(BytePos(line as u32)).line;
530 if line > 0 { line - 1 } else { line }
536 pub fn set_position(&mut self, position: Span) {
537 self.position = position;
540 pub fn get_filename(&self) -> String {
541 if let Some(ref codemap) = self.codemap {
542 let filename = codemap.span_to_filename(self.position);
543 if let Ok(cur_dir) = env::current_dir() {
544 if let Ok(path) = Path::new(&filename).strip_prefix(&cur_dir) {
545 if let Some(path) = path.to_str() {
546 return path.to_owned();
551 } else if let Some(ref filename) = self.filename {
558 pub fn register_header(&mut self, name: &str, level: u32) {
559 if self.use_headers && level == 1 {
560 // we use these headings as test names, so it's good if
561 // they're valid identifiers.
562 let name = name.chars().enumerate().map(|(i, c)| {
563 if (i == 0 && c.is_xid_start()) ||
564 (i != 0 && c.is_xid_continue()) {
569 }).collect::<String>();
571 // new header => reset count.
573 self.current_header = Some(name);
578 struct HirCollector<'a, 'hir: 'a> {
579 collector: &'a mut Collector,
580 map: &'a hir::map::Map<'hir>
583 impl<'a, 'hir> HirCollector<'a, 'hir> {
584 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
586 attrs: &[ast::Attribute],
588 let has_name = !name.is_empty();
590 self.collector.names.push(name);
593 let mut attrs = Attributes::from_ast(attrs);
594 attrs.collapse_doc_comments();
595 attrs.unindent_doc_comments();
596 if let Some(doc) = attrs.doc_value() {
597 self.collector.cnt = 0;
598 if self.collector.render_type == RenderType::Pulldown {
599 markdown::old_find_testable_code(doc, self.collector,
600 attrs.span.unwrap_or(DUMMY_SP));
601 markdown::find_testable_code(doc, self.collector,
602 attrs.span.unwrap_or(DUMMY_SP));
604 markdown::old_find_testable_code(doc, self.collector,
605 attrs.span.unwrap_or(DUMMY_SP));
612 self.collector.names.pop();
617 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
618 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
619 intravisit::NestedVisitorMap::All(&self.map)
622 fn visit_item(&mut self, item: &'hir hir::Item) {
623 let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
624 self.map.node_to_pretty_string(ty.id)
626 item.name.to_string()
629 self.visit_testable(name, &item.attrs, |this| {
630 intravisit::walk_item(this, item);
634 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
635 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
636 intravisit::walk_trait_item(this, item);
640 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
641 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
642 intravisit::walk_impl_item(this, item);
646 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
647 self.visit_testable(item.name.to_string(), &item.attrs, |this| {
648 intravisit::walk_foreign_item(this, item);
652 fn visit_variant(&mut self,
653 v: &'hir hir::Variant,
654 g: &'hir hir::Generics,
655 item_id: ast::NodeId) {
656 self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
657 intravisit::walk_variant(this, v, g, item_id);
661 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
662 self.visit_testable(f.name.to_string(), &f.attrs, |this| {
663 intravisit::walk_struct_field(this, f);
667 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
668 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());