]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
rollup merge of #21438: taralx/kill-racycell
[rust.git] / src / librustdoc / test.rs
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.
4 //
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.
10
11 use std::cell::RefCell;
12 use std::sync::mpsc::channel;
13 use std::dynamic_lib::DynamicLibrary;
14 use std::io::{Command, TempDir};
15 use std::io;
16 use std::os;
17 use std::str;
18 use std::thread::Thread;
19 use std::thunk::Thunk;
20
21 use std::collections::{HashSet, HashMap};
22 use testing;
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;
27 use syntax::ast;
28 use syntax::codemap::{CodeMap, dummy_spanned};
29 use syntax::diagnostic;
30 use syntax::parse::token;
31 use syntax::ptr::P;
32
33 use core;
34 use clean;
35 use clean::Clean;
36 use fold::DocFolder;
37 use html::markdown;
38 use passes;
39 use visit_ast::RustdocVisitor;
40
41 pub fn run(input: &str,
42            cfgs: Vec<String>,
43            libs: SearchPaths,
44            externs: core::Externs,
45            mut test_args: Vec<String>,
46            crate_name: Option<String>)
47            -> int {
48     let input_path = Path::new(input);
49     let input = config::Input::File(input_path.clone());
50
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()
58     };
59
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);
64
65     let sess = session::build_session_(sessopts,
66                                       Some(input_path.clone()),
67                                       span_diagnostic_handler);
68
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_)))
73     }));
74     let krate = driver::phase_1_parse_input(&sess, cfg, &input);
75     let krate = driver::phase_2_configure_and_expand(&sess, krate,
76                                                      "rustdoc-test", None)
77         .expect("phase_2_configure_and_expand aborted in rustdoc!");
78
79     let ctx = core::DocContext {
80         krate: &krate,
81         maybe_typed: core::NotTyped(sess),
82         input: input,
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()),
88     };
89
90     let mut v = RustdocVisitor::new(&ctx, None);
91     v.visit(ctx.krate);
92     let mut krate = v.clean(&ctx);
93     match crate_name {
94         Some(name) => krate.name = name,
95         None => {}
96     }
97     let (krate, _) = passes::collapse_docs(krate);
98     let (krate, _) = passes::unindent_comments(krate);
99
100     let mut collector = Collector::new(krate.name.to_string(),
101                                        libs,
102                                        externs,
103                                        false);
104     collector.fold_crate(krate);
105
106     test_args.insert(0, "rustdoctest".to_string());
107
108     testing::test_main(test_args.as_slice(),
109                        collector.tests.into_iter().collect());
110     0
111 }
112
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());
120
121     let sessopts = config::Options {
122         maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
123         search_paths: libs,
124         crate_types: vec!(config::CrateTypeExecutable),
125         output_types: vec!(config::OutputTypeExe),
126         externs: externs,
127         cg: config::CodegenOptions {
128             prefer_dynamic: true,
129             .. config::basic_codegen_options()
130         },
131         test: as_test_harness,
132         unstable_features: get_unstable_features_setting(),
133         ..config::basic_options().clone()
134     };
135
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.
139     //
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.
144     //
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);
149     let w2 = w1.clone();
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 {
154             Some(old) => {
155                 // Chop off the `Send` bound.
156                 let old: Box<Writer> = old;
157                 old
158             }
159             None => box io::stderr() as Box<Writer>,
160         };
161         io::util::copy(&mut p, &mut err).unwrap();
162     });
163     let emitter = diagnostic::EmitterWriter::new(box w2, None);
164
165     // Compile the code
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);
170
171     let sess = session::build_session_(sessopts,
172                                        None,
173                                        span_diagnostic_handler);
174
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();
180     if no_run {
181         control.after_analysis.stop = true;
182     }
183     driver::compile_input(sess, cfg, &input, &out, &None, None, control);
184
185     if no_run { return }
186
187     // Run the code!
188     //
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
192     // mistake.
193     let mut cmd = Command::new(outdir.path().join("rust-out"));
194     let newpath = {
195         let mut path = DynamicLibrary::search_path();
196         path.insert(0, libdir.clone());
197         DynamicLibrary::create_path(path.as_slice())
198     };
199     cmd.env(DynamicLibrary::envvar(), newpath.as_slice());
200
201     match cmd.output() {
202         Err(e) => panic!("couldn't run the test: {}{}", e,
203                         if e.kind == io::PermissionDenied {
204                             " - maybe your tempdir is mounted with noexec?"
205                         } else { "" }),
206         Ok(out) => {
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()));
212             }
213         }
214     }
215 }
216
217 pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String {
218     let mut prog = String::new();
219     if lints {
220         prog.push_str(r"
221 #![allow(unused_variables, unused_assignments, unused_mut, unused_attributes, dead_code)]
222 ");
223     }
224
225     // Don't inject `extern crate std` because it's already injected by the
226     // compiler.
227     if !s.contains("extern crate") && cratename != Some("std") {
228         match cratename {
229             Some(cratename) => {
230                 if s.contains(cratename) {
231                     prog.push_str(format!("extern crate {};\n",
232                                           cratename).as_slice());
233                 }
234             }
235             None => {}
236         }
237     }
238     if dont_insert_main || s.contains("fn main") {
239         prog.push_str(s);
240     } else {
241         prog.push_str("fn main() {\n    ");
242         prog.push_str(s.replace("\n", "\n    ").as_slice());
243         prog.push_str("\n}");
244     }
245
246     return prog
247 }
248
249 pub struct Collector {
250     pub tests: Vec<testing::TestDescAndFn>,
251     names: Vec<String>,
252     libs: SearchPaths,
253     externs: core::Externs,
254     cnt: uint,
255     use_headers: bool,
256     current_header: Option<String>,
257     cratename: String,
258 }
259
260 impl Collector {
261     pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
262                use_headers: bool) -> Collector {
263         Collector {
264             tests: Vec::new(),
265             names: Vec::new(),
266             libs: libs,
267             externs: externs,
268             cnt: 0,
269             use_headers: use_headers,
270             current_header: None,
271             cratename: cratename,
272         }
273     }
274
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)
280         } else {
281             format!("{}_{}", self.names.connect("::"), self.cnt)
282         };
283         self.cnt += 1;
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
293             },
294             testfn: testing::DynTestFn(Thunk::new(move|| {
295                 runtest(test.as_slice(),
296                         cratename.as_slice(),
297                         libs,
298                         externs,
299                         should_fail,
300                         no_run,
301                         as_test_harness);
302             }))
303         });
304     }
305
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()) {
313                         c
314                     } else {
315                         '_'
316                     }
317                 }).collect::<String>();
318
319             // new header => reset count.
320             self.cnt = 0;
321             self.current_header = Some(name);
322         }
323     }
324 }
325
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 }
331             None => false
332         };
333         match item.doc_value() {
334             Some(doc) => {
335                 self.cnt = 0;
336                 markdown::find_testable_code(doc, &mut *self);
337             }
338             None => {}
339         }
340         let ret = self.fold_item_recur(item);
341         if pushed {
342             self.names.pop();
343         }
344         return ret;
345     }
346 }