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::cell::{RefCell, Cell};
12 use std::collections::{HashSet, HashMap};
13 use std::dynamic_lib::DynamicLibrary;
15 use std::ffi::OsString;
16 use std::io::prelude::*;
18 use std::path::PathBuf;
19 use std::process::Command;
21 use std::sync::{Arc, Mutex};
25 use rustc::front::map as hir_map;
26 use rustc::session::{self, config};
27 use rustc::session::config::{get_unstable_features_setting, OutputType};
28 use rustc::session::search_paths::{SearchPaths, PathKind};
29 use rustc_front::lowering::lower_crate;
30 use rustc_back::tempdir::TempDir;
31 use rustc_driver::{driver, Compilation};
32 use syntax::codemap::CodeMap;
33 use syntax::diagnostic;
41 use visit_ast::RustdocVisitor;
43 #[derive(Clone, Default)]
44 pub struct TestOptions {
45 pub no_crate_inject: bool,
46 pub attrs: Vec<String>,
49 pub fn run(input: &str,
52 externs: core::Externs,
53 mut test_args: Vec<String>,
54 crate_name: Option<String>)
56 let input_path = PathBuf::from(input);
57 let input = config::Input::File(input_path.clone());
59 let sessopts = config::Options {
60 maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
61 .parent().unwrap().to_path_buf()),
62 search_paths: libs.clone(),
63 crate_types: vec!(config::CrateTypeDylib),
64 externs: externs.clone(),
65 unstable_features: get_unstable_features_setting(),
66 ..config::basic_options().clone()
69 let codemap = CodeMap::new();
70 let diagnostic_handler = diagnostic::Handler::new(diagnostic::Auto, None, true);
71 let span_diagnostic_handler =
72 diagnostic::SpanHandler::new(diagnostic_handler, codemap);
74 let sess = session::build_session_(sessopts,
75 Some(input_path.clone()),
76 span_diagnostic_handler);
77 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
79 let mut cfg = config::build_configuration(&sess);
80 cfg.extend(config::parse_cfgspecs(cfgs));
81 let krate = driver::phase_1_parse_input(&sess, cfg, &input);
82 let krate = driver::phase_2_configure_and_expand(&sess, krate,
84 .expect("phase_2_configure_and_expand aborted in rustdoc!");
85 let krate = driver::assign_node_ids(&sess, krate);
86 let krate = lower_crate(&krate);
88 let opts = scrape_test_config(&krate);
90 let mut forest = hir_map::Forest::new(krate);
91 let map = hir_map::map_crate(&mut forest);
93 let ctx = core::DocContext {
95 maybe_typed: core::NotTyped(sess),
97 external_paths: RefCell::new(Some(HashMap::new())),
98 external_traits: RefCell::new(None),
99 external_typarams: RefCell::new(None),
100 inlined: RefCell::new(None),
101 populated_crate_impls: RefCell::new(HashSet::new()),
102 deref_trait_did: Cell::new(None),
105 let mut v = RustdocVisitor::new(&ctx, None);
106 v.visit(ctx.map.krate());
107 let mut krate = v.clean(&ctx);
109 Some(name) => krate.name = name,
112 let (krate, _) = passes::collapse_docs(krate);
113 let (krate, _) = passes::unindent_comments(krate);
115 let mut collector = Collector::new(krate.name.to_string(),
120 collector.fold_crate(krate);
122 test_args.insert(0, "rustdoctest".to_string());
124 testing::test_main(&test_args,
125 collector.tests.into_iter().collect());
129 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
130 fn scrape_test_config(krate: &::rustc_front::hir::Crate) -> TestOptions {
131 use syntax::attr::AttrMetaMethods;
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_item_to_string(item));
162 fn runtest(test: &str, cratename: &str, libs: SearchPaths,
163 externs: core::Externs,
164 should_panic: bool, no_run: bool, as_test_harness: bool,
165 opts: &TestOptions) {
166 // the test harness wants its own `main` & top level functions, so
167 // never wrap the test in `fn main() { ... }`
168 let test = maketest(test, Some(cratename), as_test_harness, opts);
169 let input = config::Input::Str(test.to_string());
170 let mut outputs = HashMap::new();
171 outputs.insert(OutputType::Exe, None);
173 let sessopts = config::Options {
174 maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
175 .parent().unwrap().to_path_buf()),
177 crate_types: vec!(config::CrateTypeExecutable),
178 output_types: outputs,
180 cg: config::CodegenOptions {
181 prefer_dynamic: true,
182 .. config::basic_codegen_options()
184 test: as_test_harness,
185 unstable_features: get_unstable_features_setting(),
186 ..config::basic_options().clone()
189 // Shuffle around a few input and output handles here. We're going to pass
190 // an explicit handle into rustc to collect output messages, but we also
191 // want to catch the error message that rustc prints when it fails.
193 // We take our thread-local stderr (likely set by the test runner) and replace
194 // it with a sink that is also passed to rustc itself. When this function
195 // returns the output of the sink is copied onto the output of our own thread.
197 // The basic idea is to not use a default Handler for rustc, and then also
198 // not print things by default to the actual stderr.
199 struct Sink(Arc<Mutex<Vec<u8>>>);
200 impl Write for Sink {
201 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
202 Write::write(&mut *self.0.lock().unwrap(), data)
204 fn flush(&mut self) -> io::Result<()> { Ok(()) }
206 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
209 let _ = self.1.write_all(&self.0.lock().unwrap());
212 let data = Arc::new(Mutex::new(Vec::new()));
213 let emitter = diagnostic::EmitterWriter::new(box Sink(data.clone()), None);
214 let old = io::set_panic(box Sink(data.clone()));
215 let _bomb = Bomb(data, old.unwrap_or(box io::stdout()));
218 let codemap = CodeMap::new();
219 let diagnostic_handler = diagnostic::Handler::with_emitter(true, box emitter);
220 let span_diagnostic_handler =
221 diagnostic::SpanHandler::new(diagnostic_handler, codemap);
223 let sess = session::build_session_(sessopts,
225 span_diagnostic_handler);
226 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
228 let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
229 let out = Some(outdir.path().to_path_buf());
230 let cfg = config::build_configuration(&sess);
231 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
232 let mut control = driver::CompileController::basic();
234 control.after_analysis.stop = Compilation::Stop;
236 driver::compile_input(sess, cfg, &input, &out, &None, None, control);
242 // We're careful to prepend the *target* dylib search path to the child's
243 // environment to ensure that the target loads the right libraries at
244 // runtime. It would be a sad day if the *host* libraries were loaded as a
246 let mut cmd = Command::new(&outdir.path().join("rust_out"));
247 let var = DynamicLibrary::envvar();
249 let path = env::var_os(var).unwrap_or(OsString::new());
250 let mut path = env::split_paths(&path).collect::<Vec<_>>();
251 path.insert(0, libdir.clone());
252 env::join_paths(path).unwrap()
254 cmd.env(var, &newpath);
257 Err(e) => panic!("couldn't run the test: {}{}", e,
258 if e.kind() == io::ErrorKind::PermissionDenied {
259 " - maybe your tempdir is mounted with noexec?"
262 if should_panic && out.status.success() {
263 panic!("test executable succeeded when it should have failed");
264 } else if !should_panic && !out.status.success() {
265 panic!("test executable failed:\n{}\n{}",
266 str::from_utf8(&out.stdout).unwrap_or(""),
267 str::from_utf8(&out.stderr).unwrap_or(""));
273 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
274 opts: &TestOptions) -> String {
275 let (crate_attrs, everything_else) = partition_source(s);
277 let mut prog = String::new();
279 // First push any outer attributes from the example, assuming they
280 // are intended to be crate attributes.
281 prog.push_str(&crate_attrs);
283 // Next, any attributes for other aspects such as lints.
284 for attr in &opts.attrs {
285 prog.push_str(&format!("#![{}]\n", attr));
288 // Don't inject `extern crate std` because it's already injected by the
290 if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
293 if s.contains(cratename) {
294 prog.push_str(&format!("extern crate {};\n", cratename));
300 if dont_insert_main || s.contains("fn main") {
301 prog.push_str(&everything_else);
303 prog.push_str("fn main() {\n ");
304 prog.push_str(&everything_else.replace("\n", "\n "));
305 prog.push_str("\n}");
308 info!("final test program: {}", prog);
313 fn partition_source(s: &str) -> (String, String) {
314 use rustc_unicode::str::UnicodeStr;
316 let mut after_header = false;
317 let mut before = String::new();
318 let mut after = String::new();
320 for line in s.lines() {
321 let trimline = line.trim();
322 let header = trimline.is_whitespace() ||
323 trimline.starts_with("#![feature");
324 if !header || after_header {
326 after.push_str(line);
327 after.push_str("\n");
329 before.push_str(line);
330 before.push_str("\n");
334 return (before, after);
337 pub struct Collector {
338 pub tests: Vec<testing::TestDescAndFn>,
341 externs: core::Externs,
344 current_header: Option<String>,
350 pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
351 use_headers: bool, opts: TestOptions) -> Collector {
358 use_headers: use_headers,
359 current_header: None,
360 cratename: cratename,
365 pub fn add_test(&mut self, test: String,
366 should_panic: bool, no_run: bool, should_ignore: bool,
367 as_test_harness: bool) {
368 let name = if self.use_headers {
369 let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
370 format!("{}_{}", s, self.cnt)
372 format!("{}_{}", self.names.join("::"), self.cnt)
375 let libs = self.libs.clone();
376 let externs = self.externs.clone();
377 let cratename = self.cratename.to_string();
378 let opts = self.opts.clone();
379 debug!("Creating test {}: {}", name, test);
380 self.tests.push(testing::TestDescAndFn {
381 desc: testing::TestDesc {
382 name: testing::DynTestName(name),
383 ignore: should_ignore,
384 // compiler failures are test failures
385 should_panic: testing::ShouldPanic::No,
387 testfn: testing::DynTestFn(Box::new(move|| {
400 pub fn register_header(&mut self, name: &str, level: u32) {
401 if self.use_headers && level == 1 {
402 // we use these headings as test names, so it's good if
403 // they're valid identifiers.
404 let name = name.chars().enumerate().map(|(i, c)| {
405 if (i == 0 && c.is_xid_start()) ||
406 (i != 0 && c.is_xid_continue()) {
411 }).collect::<String>();
413 // new header => reset count.
415 self.current_header = Some(name);
420 impl DocFolder for Collector {
421 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
422 let pushed = match item.name {
423 Some(ref name) if name.is_empty() => false,
424 Some(ref name) => { self.names.push(name.to_string()); true }
427 match item.doc_value() {
430 markdown::find_testable_code(doc, &mut *self);
434 let ret = self.fold_item_recur(item);