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::get_unstable_features_setting;
26 use rustc_driver::driver;
28 use syntax::codemap::{CodeMap, dummy_spanned};
29 use syntax::diagnostic;
30 use syntax::parse::token;
39 use visit_ast::RustdocVisitor;
41 pub fn run(input: &str,
44 externs: core::Externs,
45 mut test_args: Vec<String>,
46 crate_name: Option<String>)
48 let input_path = Path::new(input);
49 let input = config::Input::File(input_path.clone());
51 let sessopts = config::Options {
52 maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
53 search_paths: libs.clone(),
54 crate_types: vec!(config::CrateTypeDylib),
55 externs: externs.clone(),
56 unstable_features: get_unstable_features_setting(),
57 ..config::basic_options().clone()
60 let codemap = CodeMap::new();
61 let diagnostic_handler = diagnostic::default_handler(diagnostic::Auto, None);
62 let span_diagnostic_handler =
63 diagnostic::mk_span_handler(diagnostic_handler, codemap);
65 let sess = session::build_session_(sessopts,
66 Some(input_path.clone()),
67 span_diagnostic_handler);
69 let mut cfg = config::build_configuration(&sess);
70 cfg.extend(cfgs.into_iter().map(|cfg_| {
71 let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
72 P(dummy_spanned(ast::MetaWord(cfg_)))
74 let krate = driver::phase_1_parse_input(&sess, cfg, &input);
75 let krate = driver::phase_2_configure_and_expand(&sess, krate,
77 .expect("phase_2_configure_and_expand aborted in rustdoc!");
79 let ctx = core::DocContext {
81 maybe_typed: core::NotTyped(sess),
83 external_paths: RefCell::new(Some(HashMap::new())),
84 external_traits: RefCell::new(None),
85 external_typarams: RefCell::new(None),
86 inlined: RefCell::new(None),
87 populated_crate_impls: RefCell::new(HashSet::new()),
90 let mut v = RustdocVisitor::new(&ctx, None);
92 let mut krate = v.clean(&ctx);
94 Some(name) => krate.name = name,
97 let (krate, _) = passes::collapse_docs(krate);
98 let (krate, _) = passes::unindent_comments(krate);
100 let mut collector = Collector::new(krate.name.to_string(),
104 collector.fold_crate(krate);
106 test_args.insert(0, "rustdoctest".to_string());
108 testing::test_main(test_args.as_slice(),
109 collector.tests.into_iter().collect());
113 fn runtest(test: &str, cratename: &str, libs: SearchPaths,
114 externs: core::Externs,
115 should_fail: bool, no_run: bool, as_test_harness: bool) {
116 // the test harness wants its own `main` & top level functions, so
117 // never wrap the test in `fn main() { ... }`
118 let test = maketest(test, Some(cratename), true, as_test_harness);
119 let input = config::Input::Str(test.to_string());
121 let sessopts = config::Options {
122 maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
124 crate_types: vec!(config::CrateTypeExecutable),
125 output_types: vec!(config::OutputTypeExe),
127 cg: config::CodegenOptions {
128 prefer_dynamic: true,
129 .. config::basic_codegen_options()
131 test: as_test_harness,
132 unstable_features: get_unstable_features_setting(),
133 ..config::basic_options().clone()
136 // Shuffle around a few input and output handles here. We're going to pass
137 // an explicit handle into rustc to collect output messages, but we also
138 // want to catch the error message that rustc prints when it fails.
140 // We take our task-local stderr (likely set by the test runner), and move
141 // it into another task. This helper task then acts as a sink for both the
142 // stderr of this task and stderr of rustc itself, copying all the info onto
143 // the stderr channel we originally started with.
145 // The basic idea is to not use a default_handler() for rustc, and then also
146 // not print things by default to the actual stderr.
147 let (tx, rx) = channel();
148 let w1 = io::ChanWriter::new(tx);
150 let old = io::stdio::set_stderr(box w1);
151 Thread::spawn(move |:| {
152 let mut p = io::ChanReader::new(rx);
153 let mut err = match old {
155 // Chop off the `Send` bound.
156 let old: Box<Writer> = old;
159 None => box io::stderr() as Box<Writer>,
161 io::util::copy(&mut p, &mut err).unwrap();
163 let emitter = diagnostic::EmitterWriter::new(box w2, None);
166 let codemap = CodeMap::new();
167 let diagnostic_handler = diagnostic::mk_handler(box emitter);
168 let span_diagnostic_handler =
169 diagnostic::mk_span_handler(diagnostic_handler, codemap);
171 let sess = session::build_session_(sessopts,
173 span_diagnostic_handler);
175 let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
176 let out = Some(outdir.path().clone());
177 let cfg = config::build_configuration(&sess);
178 let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
179 let mut control = driver::CompileController::basic();
181 control.after_analysis.stop = true;
183 driver::compile_input(sess, cfg, &input, &out, &None, None, control);
189 // We're careful to prepend the *target* dylib search path to the child's
190 // environment to ensure that the target loads the right libraries at
191 // runtime. It would be a sad day if the *host* libraries were loaded as a
193 let mut cmd = Command::new(outdir.path().join("rust-out"));
195 let mut path = DynamicLibrary::search_path();
196 path.insert(0, libdir.clone());
197 DynamicLibrary::create_path(path.as_slice())
199 cmd.env(DynamicLibrary::envvar(), newpath.as_slice());
202 Err(e) => panic!("couldn't run the test: {}{}", e,
203 if e.kind == io::PermissionDenied {
204 " - maybe your tempdir is mounted with noexec?"
207 if should_fail && out.status.success() {
208 panic!("test executable succeeded when it should have failed");
209 } else if !should_fail && !out.status.success() {
210 panic!("test executable failed:\n{:?}",
211 str::from_utf8(out.error.as_slice()));
217 pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String {
218 let mut prog = String::new();
221 #![allow(unused_variables, unused_assignments, unused_mut, unused_attributes, dead_code)]
225 // Don't inject `extern crate std` because it's already injected by the
227 if !s.contains("extern crate") && cratename != Some("std") {
230 if s.contains(cratename) {
231 prog.push_str(format!("extern crate {};\n",
232 cratename).as_slice());
238 if dont_insert_main || s.contains("fn main") {
241 prog.push_str("fn main() {\n ");
242 prog.push_str(s.replace("\n", "\n ").as_slice());
243 prog.push_str("\n}");
249 pub struct Collector {
250 pub tests: Vec<testing::TestDescAndFn>,
253 externs: core::Externs,
256 current_header: Option<String>,
261 pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
262 use_headers: bool) -> Collector {
269 use_headers: use_headers,
270 current_header: None,
271 cratename: cratename,
275 pub fn add_test(&mut self, test: String,
276 should_fail: bool, no_run: bool, should_ignore: bool, as_test_harness: bool) {
277 let name = if self.use_headers {
278 let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
279 format!("{}_{}", s, self.cnt)
281 format!("{}_{}", self.names.connect("::"), self.cnt)
284 let libs = self.libs.clone();
285 let externs = self.externs.clone();
286 let cratename = self.cratename.to_string();
287 debug!("Creating test {}: {}", name, test);
288 self.tests.push(testing::TestDescAndFn {
289 desc: testing::TestDesc {
290 name: testing::DynTestName(name),
291 ignore: should_ignore,
292 should_fail: testing::ShouldFail::No, // compiler failures are test failures
294 testfn: testing::DynTestFn(Thunk::new(move|| {
295 runtest(test.as_slice(),
296 cratename.as_slice(),
306 pub fn register_header(&mut self, name: &str, level: u32) {
307 if self.use_headers && level == 1 {
308 // we use these headings as test names, so it's good if
309 // they're valid identifiers.
310 let name = name.chars().enumerate().map(|(i, c)| {
311 if (i == 0 && c.is_xid_start()) ||
312 (i != 0 && c.is_xid_continue()) {
317 }).collect::<String>();
319 // new header => reset count.
321 self.current_header = Some(name);
326 impl DocFolder for Collector {
327 fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
328 let pushed = match item.name {
329 Some(ref name) if name.len() == 0 => false,
330 Some(ref name) => { self.names.push(name.to_string()); true }
333 match item.doc_value() {
336 markdown::find_testable_code(doc, &mut *self);
340 let ret = self.fold_item_recur(item);