]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
Doc says to avoid mixing allocator instead of forbiding it
[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::char;
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::string::String;
19
20 use std::collections::{HashSet, HashMap};
21 use testing;
22 use rustc::back::write;
23 use rustc::driver::config;
24 use rustc::driver::driver;
25 use rustc::driver::session;
26 use syntax::ast;
27 use syntax::codemap::{CodeMap, dummy_spanned};
28 use syntax::diagnostic;
29 use syntax::parse::token;
30 use syntax::ptr::P;
31
32 use core;
33 use clean;
34 use clean::Clean;
35 use fold::DocFolder;
36 use html::markdown;
37 use passes;
38 use visit_ast::RustdocVisitor;
39
40 pub fn run(input: &str,
41            cfgs: Vec<String>,
42            libs: Vec<Path>,
43            externs: core::Externs,
44            mut test_args: Vec<String>,
45            crate_name: Option<String>)
46            -> int {
47     let input_path = Path::new(input);
48     let input = driver::FileInput(input_path.clone());
49
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()
56     };
57
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);
62
63     let sess = session::build_session_(sessopts,
64                                       Some(input_path.clone()),
65                                       span_diagnostic_handler);
66
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_)))
71     }));
72     let krate = driver::phase_1_parse_input(&sess, cfg, &input);
73     let krate = driver::phase_2_configure_and_expand(&sess, krate,
74                                                      "rustdoc-test", None)
75         .expect("phase_2_configure_and_expand aborted in rustdoc!");
76
77     let ctx = core::DocContext {
78         krate: &krate,
79         maybe_typed: core::NotTyped(sess),
80         src: input_path,
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()),
86     };
87
88     let mut v = RustdocVisitor::new(&ctx, None);
89     v.visit(ctx.krate);
90     let mut krate = v.clean(&ctx);
91     match crate_name {
92         Some(name) => krate.name = name,
93         None => {}
94     }
95     let (krate, _) = passes::collapse_docs(krate);
96     let (krate, _) = passes::unindent_comments(krate);
97
98     let mut collector = Collector::new(krate.name.to_string(),
99                                        libs,
100                                        externs,
101                                        false);
102     collector.fold_crate(krate);
103
104     test_args.insert(0, "rustdoctest".to_string());
105
106     testing::test_main(test_args.as_slice(),
107                        collector.tests.move_iter().collect());
108     0
109 }
110
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());
117
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),
123         no_trans: no_run,
124         externs: externs,
125         cg: config::CodegenOptions {
126             prefer_dynamic: true,
127             .. config::basic_codegen_options()
128         },
129         test: as_test_harness,
130         ..config::basic_options().clone()
131     };
132
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.
136     //
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.
141     //
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);
146     let w2 = w1.clone();
147     let old = io::stdio::set_stderr(box w1);
148     spawn(proc() {
149         let mut p = io::ChanReader::new(rx);
150         let mut err = match old {
151             Some(old) => {
152                 // Chop off the `Send` bound.
153                 let old: Box<Writer> = old;
154                 old
155             }
156             None => box io::stderr() as Box<Writer>,
157         };
158         io::util::copy(&mut p, &mut err).unwrap();
159     });
160     let emitter = diagnostic::EmitterWriter::new(box w2, None);
161
162     // Compile the code
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);
167
168     let sess = session::build_session_(sessopts,
169                                       None,
170                                       span_diagnostic_handler);
171
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);
177
178     if no_run { return }
179
180     // Run the code!
181     //
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
185     // mistake.
186     let mut cmd = Command::new(outdir.path().join("rust_out"));
187     let newpath = {
188         let mut path = DynamicLibrary::search_path();
189         path.insert(0, libdir.clone());
190         DynamicLibrary::create_path(path.as_slice())
191     };
192     cmd.env(DynamicLibrary::envvar(), newpath.as_slice());
193
194     match cmd.output() {
195         Err(e) => fail!("couldn't run the test: {}{}", e,
196                         if e.kind == io::PermissionDenied {
197                             " - maybe your tempdir is mounted with noexec?"
198                         } else { "" }),
199         Ok(out) => {
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()));
205             }
206         }
207     }
208 }
209
210 pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String {
211     let mut prog = String::new();
212     if lints {
213         prog.push_str(r"
214 #![deny(warnings)]
215 #![allow(unused_variable, dead_assignment, unused_mut, unused_attribute, dead_code)]
216 ");
217     }
218
219     // Don't inject `extern crate std` because it's already injected by the
220     // compiler.
221     if !s.contains("extern crate") && cratename != Some("std") {
222         match cratename {
223             Some(cratename) => {
224                 if s.contains(cratename) {
225                     prog.push_str(format!("extern crate {};\n",
226                                           cratename).as_slice());
227                 }
228             }
229             None => {}
230         }
231     }
232     if dont_insert_main || s.contains("fn main") {
233         prog.push_str(s);
234     } else {
235         prog.push_str("fn main() {\n    ");
236         prog.push_str(s.replace("\n", "\n    ").as_slice());
237         prog.push_str("\n}");
238     }
239
240     return prog
241 }
242
243 pub struct Collector {
244     pub tests: Vec<testing::TestDescAndFn>,
245     names: Vec<String>,
246     libs: Vec<Path>,
247     externs: core::Externs,
248     cnt: uint,
249     use_headers: bool,
250     current_header: Option<String>,
251     cratename: String,
252 }
253
254 impl Collector {
255     pub fn new(cratename: String, libs: Vec<Path>, externs: core::Externs,
256                use_headers: bool) -> Collector {
257         Collector {
258             tests: Vec::new(),
259             names: Vec::new(),
260             libs: libs,
261             externs: externs,
262             cnt: 0,
263             use_headers: use_headers,
264             current_header: None,
265             cratename: cratename,
266         }
267     }
268
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)
274         } else {
275             format!("{}_{}", self.names.connect("::"), self.cnt)
276         };
277         self.cnt += 1;
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
287             },
288             testfn: testing::DynTestFn(proc() {
289                 runtest(test.as_slice(),
290                         cratename.as_slice(),
291                         libs,
292                         externs,
293                         should_fail,
294                         no_run,
295                         as_test_harness);
296             }),
297         });
298     }
299
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)) {
307                         c
308                     } else {
309                         '_'
310                     }
311                 }).collect::<String>();
312
313             // new header => reset count.
314             self.cnt = 0;
315             self.current_header = Some(name);
316         }
317     }
318 }
319
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 }
325             None => false
326         };
327         match item.doc_value() {
328             Some(doc) => {
329                 self.cnt = 0;
330                 markdown::find_testable_code(doc, &mut *self);
331             }
332             None => {}
333         }
334         let ret = self.fold_item_recur(item);
335         if pushed {
336             self.names.pop();
337         }
338         return ret;
339     }
340 }