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, LoweringContext};
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);
87 let lcx = LoweringContext::new(foo, &sess, &krate);
88 let krate = lower_crate(&lcx, &krate);
90 let opts = scrape_test_config(&krate);
92 let mut forest = hir_map::Forest::new(krate);
93 let map = hir_map::map_crate(&mut forest);
95 let ctx = core::DocContext {
98 maybe_typed: core::NotTyped(sess),
101 maybe_typed: core::NotTyped(&sess),
102 >>>>>>> Fixes to rustdoc, etc.
104 external_paths: RefCell::new(Some(HashMap::new())),
105 external_traits: RefCell::new(None),
106 external_typarams: RefCell::new(None),
107 inlined: RefCell::new(None),
108 populated_crate_impls: RefCell::new(HashSet::new()),
109 deref_trait_did: Cell::new(None),
112 let mut v = RustdocVisitor::new(&ctx, None);
113 v.visit(ctx.map.krate());
114 let mut krate = v.clean(&ctx);
116 Some(name) => krate.name = name,
119 let (krate, _) = passes::collapse_docs(krate);
120 let (krate, _) = passes::unindent_comments(krate);
122 let mut collector = Collector::new(krate.name.to_string(),
127 collector.fold_crate(krate);
129 test_args.insert(0, "rustdoctest".to_string());
131 testing::test_main(&test_args,
132 collector.tests.into_iter().collect());
136 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
137 fn scrape_test_config(krate: &::rustc_front::hir::Crate) -> TestOptions {
138 use syntax::attr::AttrMetaMethods;
139 use syntax::print::pprust;
141 let mut opts = TestOptions {
142 no_crate_inject: false,
146 let attrs = krate.attrs.iter()
147 .filter(|a| a.check_name("doc"))
148 .filter_map(|a| a.meta_item_list())
150 .filter(|a| a.check_name("test"))
151 .filter_map(|a| a.meta_item_list())
154 if attr.check_name("no_crate_inject") {
155 opts.no_crate_inject = true;
157 if attr.check_name("attr") {
158 if let Some(l) = attr.meta_item_list() {
160 opts.attrs.push(pprust::meta_item_to_string(item));
169 fn runtest(test: &str, cratename: &str, libs: SearchPaths,
170 externs: core::Externs,
171 should_panic: bool, no_run: bool, as_test_harness: bool,
172 opts: &TestOptions) {
173 // the test harness wants its own `main` & top level functions, so
174 // never wrap the test in `fn main() { ... }`
175 let test = maketest(test, Some(cratename), as_test_harness, opts);
176 let input = config::Input::Str(test.to_string());
177 let mut outputs = HashMap::new();
178 outputs.insert(OutputType::Exe, None);
180 let sessopts = config::Options {
181 maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
182 .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: get_unstable_features_setting(),
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 emitter = diagnostic::EmitterWriter::new(box Sink(data.clone()), None);
221 let old = io::set_panic(box Sink(data.clone()));
222 let _bomb = Bomb(data, old.unwrap_or(box io::stdout()));
225 let codemap = CodeMap::new();
226 let diagnostic_handler = diagnostic::Handler::with_emitter(true, box emitter);
227 let span_diagnostic_handler =
228 diagnostic::SpanHandler::new(diagnostic_handler, codemap);
230 let sess = session::build_session_(sessopts,
232 span_diagnostic_handler);
233 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
235 let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
236 let out = Some(outdir.path().to_path_buf());
237 let cfg = config::build_configuration(&sess);
238 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
239 let mut control = driver::CompileController::basic();
241 control.after_analysis.stop = Compilation::Stop;
243 driver::compile_input(sess, cfg, &input, &out, &None, None, control);
249 // We're careful to prepend the *target* dylib search path to the child's
250 // environment to ensure that the target loads the right libraries at
251 // runtime. It would be a sad day if the *host* libraries were loaded as a
253 let mut cmd = Command::new(&outdir.path().join("rust_out"));
254 let var = DynamicLibrary::envvar();
256 let path = env::var_os(var).unwrap_or(OsString::new());
257 let mut path = env::split_paths(&path).collect::<Vec<_>>();
258 path.insert(0, libdir.clone());
259 env::join_paths(path).unwrap()
261 cmd.env(var, &newpath);
264 Err(e) => panic!("couldn't run the test: {}{}", e,
265 if e.kind() == io::ErrorKind::PermissionDenied {
266 " - maybe your tempdir is mounted with noexec?"
269 if should_panic && out.status.success() {
270 panic!("test executable succeeded when it should have failed");
271 } else if !should_panic && !out.status.success() {
272 panic!("test executable failed:\n{}\n{}",
273 str::from_utf8(&out.stdout).unwrap_or(""),
274 str::from_utf8(&out.stderr).unwrap_or(""));
280 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
281 opts: &TestOptions) -> String {
282 let (crate_attrs, everything_else) = partition_source(s);
284 let mut prog = String::new();
286 // First push any outer attributes from the example, assuming they
287 // are intended to be crate attributes.
288 prog.push_str(&crate_attrs);
290 // Next, any attributes for other aspects such as lints.
291 for attr in &opts.attrs {
292 prog.push_str(&format!("#![{}]\n", attr));
295 // Don't inject `extern crate std` because it's already injected by the
297 if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
300 if s.contains(cratename) {
301 prog.push_str(&format!("extern crate {};\n", cratename));
307 if dont_insert_main || s.contains("fn main") {
308 prog.push_str(&everything_else);
310 prog.push_str("fn main() {\n ");
311 prog.push_str(&everything_else.replace("\n", "\n "));
312 prog.push_str("\n}");
315 info!("final test program: {}", prog);
320 fn partition_source(s: &str) -> (String, String) {
321 use rustc_unicode::str::UnicodeStr;
323 let mut after_header = false;
324 let mut before = String::new();
325 let mut after = String::new();
327 for line in s.lines() {
328 let trimline = line.trim();
329 let header = trimline.is_whitespace() ||
330 trimline.starts_with("#![feature");
331 if !header || after_header {
333 after.push_str(line);
334 after.push_str("\n");
336 before.push_str(line);
337 before.push_str("\n");
341 return (before, after);
344 pub struct Collector {
345 pub tests: Vec<testing::TestDescAndFn>,
348 externs: core::Externs,
351 current_header: Option<String>,
357 pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
358 use_headers: bool, opts: TestOptions) -> Collector {
365 use_headers: use_headers,
366 current_header: None,
367 cratename: cratename,
372 pub fn add_test(&mut self, test: String,
373 should_panic: bool, no_run: bool, should_ignore: bool,
374 as_test_harness: bool) {
375 let name = if self.use_headers {
376 let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
377 format!("{}_{}", s, self.cnt)
379 format!("{}_{}", self.names.join("::"), self.cnt)
382 let libs = self.libs.clone();
383 let externs = self.externs.clone();
384 let cratename = self.cratename.to_string();
385 let opts = self.opts.clone();
386 debug!("Creating test {}: {}", name, test);
387 self.tests.push(testing::TestDescAndFn {
388 desc: testing::TestDesc {
389 name: testing::DynTestName(name),
390 ignore: should_ignore,
391 // compiler failures are test failures
392 should_panic: testing::ShouldPanic::No,
394 testfn: testing::DynTestFn(Box::new(move|| {
407 pub fn register_header(&mut self, name: &str, level: u32) {
408 if self.use_headers && level == 1 {
409 // we use these headings as test names, so it's good if
410 // they're valid identifiers.
411 let name = name.chars().enumerate().map(|(i, c)| {
412 if (i == 0 && c.is_xid_start()) ||
413 (i != 0 && c.is_xid_continue()) {
418 }).collect::<String>();
420 // new header => reset count.
422 self.current_header = Some(name);
427 impl DocFolder for Collector {
428 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
429 let pushed = match item.name {
430 Some(ref name) if name.is_empty() => false,
431 Some(ref name) => { self.names.push(name.to_string()); true }
434 match item.doc_value() {
437 markdown::find_testable_code(doc, &mut *self);
441 let ret = self.fold_item_recur(item);