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;
12 use std::dynamic_lib::DynamicLibrary;
13 use std::io::{Command, TempDir};
17 use std::string::String;
19 use std::collections::{HashSet, HashMap};
21 use rustc::session::{mod, config};
22 use rustc_driver::driver;
24 use syntax::codemap::{CodeMap, dummy_spanned};
25 use syntax::diagnostic;
26 use syntax::parse::token;
35 use visit_ast::RustdocVisitor;
37 pub fn run(input: &str,
40 externs: core::Externs,
41 mut test_args: Vec<String>,
42 crate_name: Option<String>)
44 let input_path = Path::new(input);
45 let input = config::Input::File(input_path.clone());
47 let sessopts = config::Options {
48 maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
49 addl_lib_search_paths: RefCell::new(libs.clone()),
50 crate_types: vec!(config::CrateTypeDylib),
51 externs: externs.clone(),
52 ..config::basic_options().clone()
55 let codemap = CodeMap::new();
56 let diagnostic_handler = diagnostic::default_handler(diagnostic::Auto, None);
57 let span_diagnostic_handler =
58 diagnostic::mk_span_handler(diagnostic_handler, codemap);
60 let sess = session::build_session_(sessopts,
61 Some(input_path.clone()),
62 span_diagnostic_handler);
64 let mut cfg = config::build_configuration(&sess);
65 cfg.extend(cfgs.into_iter().map(|cfg_| {
66 let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
67 P(dummy_spanned(ast::MetaWord(cfg_)))
69 let krate = driver::phase_1_parse_input(&sess, cfg, &input);
70 let krate = driver::phase_2_configure_and_expand(&sess, krate,
72 .expect("phase_2_configure_and_expand aborted in rustdoc!");
74 let ctx = core::DocContext {
76 maybe_typed: core::NotTyped(sess),
78 external_paths: RefCell::new(Some(HashMap::new())),
79 external_traits: RefCell::new(None),
80 external_typarams: RefCell::new(None),
81 inlined: RefCell::new(None),
82 populated_crate_impls: RefCell::new(HashSet::new()),
85 let mut v = RustdocVisitor::new(&ctx, None);
87 let mut krate = v.clean(&ctx);
89 Some(name) => krate.name = name,
92 let (krate, _) = passes::collapse_docs(krate);
93 let (krate, _) = passes::unindent_comments(krate);
95 let mut collector = Collector::new(krate.name.to_string(),
99 collector.fold_crate(krate);
101 test_args.insert(0, "rustdoctest".to_string());
103 testing::test_main(test_args.as_slice(),
104 collector.tests.into_iter().collect());
108 fn runtest(test: &str, cratename: &str, libs: Vec<Path>, externs: core::Externs,
109 should_fail: bool, no_run: bool, as_test_harness: bool) {
110 // the test harness wants its own `main` & top level functions, so
111 // never wrap the test in `fn main() { ... }`
112 let test = maketest(test, Some(cratename), true, as_test_harness);
113 let input = config::Input::Str(test.to_string());
115 let sessopts = config::Options {
116 maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
117 addl_lib_search_paths: RefCell::new(libs),
118 crate_types: vec!(config::CrateTypeExecutable),
119 output_types: vec!(config::OutputTypeExe),
122 cg: config::CodegenOptions {
123 prefer_dynamic: true,
124 .. config::basic_codegen_options()
126 test: as_test_harness,
127 ..config::basic_options().clone()
130 // Shuffle around a few input and output handles here. We're going to pass
131 // an explicit handle into rustc to collect output messages, but we also
132 // want to catch the error message that rustc prints when it fails.
134 // We take our task-local stderr (likely set by the test runner), and move
135 // it into another task. This helper task then acts as a sink for both the
136 // stderr of this task and stderr of rustc itself, copying all the info onto
137 // the stderr channel we originally started with.
139 // The basic idea is to not use a default_handler() for rustc, and then also
140 // not print things by default to the actual stderr.
141 let (tx, rx) = channel();
142 let w1 = io::ChanWriter::new(tx);
144 let old = io::stdio::set_stderr(box w1);
146 let mut p = io::ChanReader::new(rx);
147 let mut err = match old {
149 // Chop off the `Send` bound.
150 let old: Box<Writer> = old;
153 None => box io::stderr() as Box<Writer>,
155 io::util::copy(&mut p, &mut err).unwrap();
157 let emitter = diagnostic::EmitterWriter::new(box w2, None);
160 let codemap = CodeMap::new();
161 let diagnostic_handler = diagnostic::mk_handler(box emitter);
162 let span_diagnostic_handler =
163 diagnostic::mk_span_handler(diagnostic_handler, codemap);
165 let sess = session::build_session_(sessopts,
167 span_diagnostic_handler);
169 let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
170 let out = Some(outdir.path().clone());
171 let cfg = config::build_configuration(&sess);
172 let libdir = sess.target_filesearch().get_lib_path();
173 driver::compile_input(sess, cfg, &input, &out, &None, None);
179 // We're careful to prepend the *target* dylib search path to the child's
180 // environment to ensure that the target loads the right libraries at
181 // runtime. It would be a sad day if the *host* libraries were loaded as a
183 let mut cmd = Command::new(outdir.path().join("rust-out"));
185 let mut path = DynamicLibrary::search_path();
186 path.insert(0, libdir.clone());
187 DynamicLibrary::create_path(path.as_slice())
189 cmd.env(DynamicLibrary::envvar(), newpath.as_slice());
192 Err(e) => panic!("couldn't run the test: {}{}", e,
193 if e.kind == io::PermissionDenied {
194 " - maybe your tempdir is mounted with noexec?"
197 if should_fail && out.status.success() {
198 panic!("test executable succeeded when it should have failed");
199 } else if !should_fail && !out.status.success() {
200 panic!("test executable failed:\n{}",
201 str::from_utf8(out.error.as_slice()));
207 pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String {
208 let mut prog = String::new();
212 #![allow(unused_variables, unused_assignments, unused_mut, unused_attributes, dead_code)]
216 // Don't inject `extern crate std` because it's already injected by the
218 if !s.contains("extern crate") && cratename != Some("std") {
221 if s.contains(cratename) {
222 prog.push_str(format!("extern crate {};\n",
223 cratename).as_slice());
229 if dont_insert_main || s.contains("fn main") {
232 prog.push_str("fn main() {\n ");
233 prog.push_str(s.replace("\n", "\n ").as_slice());
234 prog.push_str("\n}");
240 pub struct Collector {
241 pub tests: Vec<testing::TestDescAndFn>,
244 externs: core::Externs,
247 current_header: Option<String>,
252 pub fn new(cratename: String, libs: Vec<Path>, externs: core::Externs,
253 use_headers: bool) -> Collector {
260 use_headers: use_headers,
261 current_header: None,
262 cratename: cratename,
266 pub fn add_test(&mut self, test: String,
267 should_fail: bool, no_run: bool, should_ignore: bool, as_test_harness: bool) {
268 let name = if self.use_headers {
269 let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
270 format!("{}_{}", s, self.cnt)
272 format!("{}_{}", self.names.connect("::"), self.cnt)
275 let libs = self.libs.clone();
276 let externs = self.externs.clone();
277 let cratename = self.cratename.to_string();
278 debug!("Creating test {}: {}", name, test);
279 self.tests.push(testing::TestDescAndFn {
280 desc: testing::TestDesc {
281 name: testing::DynTestName(name),
282 ignore: should_ignore,
283 should_fail: false, // compiler failures are test failures
285 testfn: testing::DynTestFn(proc() {
286 runtest(test.as_slice(),
287 cratename.as_slice(),
297 pub fn register_header(&mut self, name: &str, level: u32) {
298 if self.use_headers && level == 1 {
299 // we use these headings as test names, so it's good if
300 // they're valid identifiers.
301 let name = name.chars().enumerate().map(|(i, c)| {
302 if (i == 0 && c.is_xid_start()) ||
303 (i != 0 && c.is_xid_continue()) {
308 }).collect::<String>();
310 // new header => reset count.
312 self.current_header = Some(name);
317 impl DocFolder for Collector {
318 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
319 let pushed = match item.name {
320 Some(ref name) if name.len() == 0 => false,
321 Some(ref name) => { self.names.push(name.to_string()); true }
324 match item.doc_value() {
327 markdown::find_testable_code(doc, &mut *self);
331 let ret = self.fold_item_recur(item);