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;
13 use std::dynamic_lib::DynamicLibrary;
14 use std::io::{Command, TempDir};
18 use std::string::String;
20 use std::collections::{HashSet, HashMap};
22 use rustc::back::write;
23 use rustc::driver::config;
24 use rustc::driver::driver;
25 use rustc::driver::session;
27 use syntax::codemap::{CodeMap, dummy_spanned};
28 use syntax::diagnostic;
29 use syntax::parse::token;
38 use visit_ast::RustdocVisitor;
40 pub fn run(input: &str,
43 externs: core::Externs,
44 mut test_args: Vec<String>,
45 crate_name: Option<String>)
47 let input_path = Path::new(input);
48 let input = driver::FileInput(input_path.clone());
50 let sessopts = config::Options {
51 maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
52 addl_lib_search_paths: RefCell::new(libs.clone()),
53 crate_types: vec!(config::CrateTypeDylib),
54 externs: externs.clone(),
55 ..config::basic_options().clone()
58 let codemap = CodeMap::new();
59 let diagnostic_handler = diagnostic::default_handler(diagnostic::Auto, None);
60 let span_diagnostic_handler =
61 diagnostic::mk_span_handler(diagnostic_handler, codemap);
63 let sess = session::build_session_(sessopts,
64 Some(input_path.clone()),
65 span_diagnostic_handler);
67 let mut cfg = config::build_configuration(&sess);
68 cfg.extend(cfgs.move_iter().map(|cfg_| {
69 let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
70 P(dummy_spanned(ast::MetaWord(cfg_)))
72 let krate = driver::phase_1_parse_input(&sess, cfg, &input);
73 let krate = driver::phase_2_configure_and_expand(&sess, krate,
75 .expect("phase_2_configure_and_expand aborted in rustdoc!");
77 let ctx = core::DocContext {
79 maybe_typed: core::NotTyped(sess),
81 external_paths: RefCell::new(Some(HashMap::new())),
82 external_traits: RefCell::new(None),
83 external_typarams: RefCell::new(None),
84 inlined: RefCell::new(None),
85 populated_crate_impls: RefCell::new(HashSet::new()),
88 let mut v = RustdocVisitor::new(&ctx, None);
90 let mut krate = v.clean(&ctx);
92 Some(name) => krate.name = name,
95 let (krate, _) = passes::collapse_docs(krate);
96 let (krate, _) = passes::unindent_comments(krate);
98 let mut collector = Collector::new(krate.name.to_string(),
102 collector.fold_crate(krate);
104 test_args.insert(0, "rustdoctest".to_string());
106 testing::test_main(test_args.as_slice(),
107 collector.tests.move_iter().collect());
111 fn runtest(test: &str, cratename: &str, libs: Vec<Path>, externs: core::Externs,
112 should_fail: bool, no_run: bool, as_test_harness: bool) {
113 // the test harness wants its own `main` & top level functions, so
114 // never wrap the test in `fn main() { ... }`
115 let test = maketest(test, Some(cratename), true, as_test_harness);
116 let input = driver::StrInput(test.to_string());
118 let sessopts = config::Options {
119 maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
120 addl_lib_search_paths: RefCell::new(libs),
121 crate_types: vec!(config::CrateTypeExecutable),
122 output_types: vec!(write::OutputTypeExe),
125 cg: config::CodegenOptions {
126 prefer_dynamic: true,
127 .. config::basic_codegen_options()
129 test: as_test_harness,
130 ..config::basic_options().clone()
133 // Shuffle around a few input and output handles here. We're going to pass
134 // an explicit handle into rustc to collect output messages, but we also
135 // want to catch the error message that rustc prints when it fails.
137 // We take our task-local stderr (likely set by the test runner), and move
138 // it into another task. This helper task then acts as a sink for both the
139 // stderr of this task and stderr of rustc itself, copying all the info onto
140 // the stderr channel we originally started with.
142 // The basic idea is to not use a default_handler() for rustc, and then also
143 // not print things by default to the actual stderr.
144 let (tx, rx) = channel();
145 let w1 = io::ChanWriter::new(tx);
147 let old = io::stdio::set_stderr(box w1);
149 let mut p = io::ChanReader::new(rx);
150 let mut err = match old {
152 // Chop off the `Send` bound.
153 let old: Box<Writer> = old;
156 None => box io::stderr() as Box<Writer>,
158 io::util::copy(&mut p, &mut err).unwrap();
160 let emitter = diagnostic::EmitterWriter::new(box w2, None);
163 let codemap = CodeMap::new();
164 let diagnostic_handler = diagnostic::mk_handler(box emitter);
165 let span_diagnostic_handler =
166 diagnostic::mk_span_handler(diagnostic_handler, codemap);
168 let sess = session::build_session_(sessopts,
170 span_diagnostic_handler);
172 let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
173 let out = Some(outdir.path().clone());
174 let cfg = config::build_configuration(&sess);
175 let libdir = sess.target_filesearch().get_lib_path();
176 driver::compile_input(sess, cfg, &input, &out, &None, None);
182 // We're careful to prepend the *target* dylib search path to the child's
183 // environment to ensure that the target loads the right libraries at
184 // runtime. It would be a sad day if the *host* libraries were loaded as a
186 let mut cmd = Command::new(outdir.path().join("rust_out"));
188 let mut path = DynamicLibrary::search_path();
189 path.insert(0, libdir.clone());
190 DynamicLibrary::create_path(path.as_slice())
192 cmd.env(DynamicLibrary::envvar(), newpath.as_slice());
195 Err(e) => fail!("couldn't run the test: {}{}", e,
196 if e.kind == io::PermissionDenied {
197 " - maybe your tempdir is mounted with noexec?"
200 if should_fail && out.status.success() {
201 fail!("test executable succeeded when it should have failed");
202 } else if !should_fail && !out.status.success() {
203 fail!("test executable failed:\n{}",
204 str::from_utf8(out.error.as_slice()));
210 pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String {
211 let mut prog = String::new();
215 #![allow(unused_variable, dead_assignment, unused_mut, unused_attribute, dead_code)]
219 // Don't inject `extern crate std` because it's already injected by the
221 if !s.contains("extern crate") && cratename != Some("std") {
224 if s.contains(cratename) {
225 prog.push_str(format!("extern crate {};\n",
226 cratename).as_slice());
232 if dont_insert_main || s.contains("fn main") {
235 prog.push_str("fn main() {\n ");
236 prog.push_str(s.replace("\n", "\n ").as_slice());
237 prog.push_str("\n}");
243 pub struct Collector {
244 pub tests: Vec<testing::TestDescAndFn>,
247 externs: core::Externs,
250 current_header: Option<String>,
255 pub fn new(cratename: String, libs: Vec<Path>, externs: core::Externs,
256 use_headers: bool) -> Collector {
263 use_headers: use_headers,
264 current_header: None,
265 cratename: cratename,
269 pub fn add_test(&mut self, test: String,
270 should_fail: bool, no_run: bool, should_ignore: bool, as_test_harness: bool) {
271 let name = if self.use_headers {
272 let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
273 format!("{}_{}", s, self.cnt)
275 format!("{}_{}", self.names.connect("::"), self.cnt)
278 let libs = self.libs.clone();
279 let externs = self.externs.clone();
280 let cratename = self.cratename.to_string();
281 debug!("Creating test {}: {}", name, test);
282 self.tests.push(testing::TestDescAndFn {
283 desc: testing::TestDesc {
284 name: testing::DynTestName(name),
285 ignore: should_ignore,
286 should_fail: false, // compiler failures are test failures
288 testfn: testing::DynTestFn(proc() {
289 runtest(test.as_slice(),
290 cratename.as_slice(),
300 pub fn register_header(&mut self, name: &str, level: u32) {
301 if self.use_headers && level == 1 {
302 // we use these headings as test names, so it's good if
303 // they're valid identifiers.
304 let name = name.chars().enumerate().map(|(i, c)| {
305 if (i == 0 && char::is_XID_start(c)) ||
306 (i != 0 && char::is_XID_continue(c)) {
311 }).collect::<String>();
313 // new header => reset count.
315 self.current_header = Some(name);
320 impl DocFolder for Collector {
321 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
322 let pushed = match item.name {
323 Some(ref name) if name.len() == 0 => false,
324 Some(ref name) => { self.names.push(name.to_string()); true }
327 match item.doc_value() {
330 markdown::find_testable_code(doc, &mut *self);
334 let ret = self.fold_item_recur(item);