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::sync::mpsc::channel;
13 use std::dynamic_lib::DynamicLibrary;
14 use std::io::{Command, TempDir};
18 use std::thread::Thread;
19 use std::thunk::Thunk;
21 use std::collections::{HashSet, HashMap};
23 use rustc::session::{self, config};
24 use rustc::session::search_paths::{SearchPaths, PathKind};
25 use rustc_driver::driver;
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 = config::Input::File(input_path.clone());
50 let sessopts = config::Options {
51 maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
52 search_paths: 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.into_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.into_iter().collect());
111 fn runtest(test: &str, cratename: &str, libs: SearchPaths,
112 externs: core::Externs,
113 should_fail: bool, no_run: bool, as_test_harness: bool) {
114 // the test harness wants its own `main` & top level functions, so
115 // never wrap the test in `fn main() { ... }`
116 let test = maketest(test, Some(cratename), true, as_test_harness);
117 let input = config::Input::Str(test.to_string());
119 let sessopts = config::Options {
120 maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
122 crate_types: vec!(config::CrateTypeExecutable),
123 output_types: vec!(config::OutputTypeExe),
126 cg: config::CodegenOptions {
127 prefer_dynamic: true,
128 .. config::basic_codegen_options()
130 test: as_test_harness,
131 ..config::basic_options().clone()
134 // Shuffle around a few input and output handles here. We're going to pass
135 // an explicit handle into rustc to collect output messages, but we also
136 // want to catch the error message that rustc prints when it fails.
138 // We take our task-local stderr (likely set by the test runner), and move
139 // it into another task. This helper task then acts as a sink for both the
140 // stderr of this task and stderr of rustc itself, copying all the info onto
141 // the stderr channel we originally started with.
143 // The basic idea is to not use a default_handler() for rustc, and then also
144 // not print things by default to the actual stderr.
145 let (tx, rx) = channel();
146 let w1 = io::ChanWriter::new(tx);
148 let old = io::stdio::set_stderr(box w1);
149 Thread::spawn(move |:| {
150 let mut p = io::ChanReader::new(rx);
151 let mut err = match old {
153 // Chop off the `Send` bound.
154 let old: Box<Writer> = old;
157 None => box io::stderr() as Box<Writer>,
159 io::util::copy(&mut p, &mut err).unwrap();
161 let emitter = diagnostic::EmitterWriter::new(box w2, None);
164 let codemap = CodeMap::new();
165 let diagnostic_handler = diagnostic::mk_handler(box emitter);
166 let span_diagnostic_handler =
167 diagnostic::mk_span_handler(diagnostic_handler, codemap);
169 let sess = session::build_session_(sessopts,
171 span_diagnostic_handler);
173 let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
174 let out = Some(outdir.path().clone());
175 let cfg = config::build_configuration(&sess);
176 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
177 driver::compile_input(sess, cfg, &input, &out, &None, None);
183 // We're careful to prepend the *target* dylib search path to the child's
184 // environment to ensure that the target loads the right libraries at
185 // runtime. It would be a sad day if the *host* libraries were loaded as a
187 let mut cmd = Command::new(outdir.path().join("rust-out"));
189 let mut path = DynamicLibrary::search_path();
190 path.insert(0, libdir.clone());
191 DynamicLibrary::create_path(path.as_slice())
193 cmd.env(DynamicLibrary::envvar(), newpath.as_slice());
196 Err(e) => panic!("couldn't run the test: {}{}", e,
197 if e.kind == io::PermissionDenied {
198 " - maybe your tempdir is mounted with noexec?"
201 if should_fail && out.status.success() {
202 panic!("test executable succeeded when it should have failed");
203 } else if !should_fail && !out.status.success() {
204 panic!("test executable failed:\n{}",
205 str::from_utf8(out.error.as_slice()));
211 pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String {
212 let mut prog = String::new();
216 #![allow(unused_variables, unused_assignments, unused_mut, unused_attributes, dead_code)]
220 // Don't inject `extern crate std` because it's already injected by the
222 if !s.contains("extern crate") && cratename != Some("std") {
225 if s.contains(cratename) {
226 prog.push_str(format!("extern crate {};\n",
227 cratename).as_slice());
233 if dont_insert_main || s.contains("fn main") {
236 prog.push_str("fn main() {\n ");
237 prog.push_str(s.replace("\n", "\n ").as_slice());
238 prog.push_str("\n}");
244 pub struct Collector {
245 pub tests: Vec<testing::TestDescAndFn>,
248 externs: core::Externs,
251 current_header: Option<String>,
256 pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
257 use_headers: bool) -> Collector {
264 use_headers: use_headers,
265 current_header: None,
266 cratename: cratename,
270 pub fn add_test(&mut self, test: String,
271 should_fail: bool, no_run: bool, should_ignore: bool, as_test_harness: bool) {
272 let name = if self.use_headers {
273 let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
274 format!("{}_{}", s, self.cnt)
276 format!("{}_{}", self.names.connect("::"), self.cnt)
279 let libs = self.libs.clone();
280 let externs = self.externs.clone();
281 let cratename = self.cratename.to_string();
282 debug!("Creating test {}: {}", name, test);
283 self.tests.push(testing::TestDescAndFn {
284 desc: testing::TestDesc {
285 name: testing::DynTestName(name),
286 ignore: should_ignore,
287 should_fail: testing::ShouldFail::No, // compiler failures are test failures
289 testfn: testing::DynTestFn(Thunk::new(move|| {
290 runtest(test.as_slice(),
291 cratename.as_slice(),
301 pub fn register_header(&mut self, name: &str, level: u32) {
302 if self.use_headers && level == 1 {
303 // we use these headings as test names, so it's good if
304 // they're valid identifiers.
305 let name = name.chars().enumerate().map(|(i, c)| {
306 if (i == 0 && c.is_xid_start()) ||
307 (i != 0 && c.is_xid_continue()) {
312 }).collect::<String>();
314 // new header => reset count.
316 self.current_header = Some(name);
321 impl DocFolder for Collector {
322 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
323 let pushed = match item.name {
324 Some(ref name) if name.len() == 0 => false,
325 Some(ref name) => { self.names.push(name.to_string()); true }
328 match item.doc_value() {
331 markdown::find_testable_code(doc, &mut *self);
335 let ret = self.fold_item_recur(item);