]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
doc: remove incomplete sentence
[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::{mod, config};
24 use rustc::session::search_paths::{SearchPaths, PathKind};
25 use rustc_driver::driver;
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: SearchPaths,
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 = config::Input::File(input_path.clone());
49
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()
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.into_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.into_iter().collect());
108     0
109 }
110
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());
118
119     let sessopts = config::Options {
120         maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
121         search_paths: libs,
122         crate_types: vec!(config::CrateTypeExecutable),
123         output_types: vec!(config::OutputTypeExe),
124         no_trans: no_run,
125         externs: externs,
126         cg: config::CodegenOptions {
127             prefer_dynamic: true,
128             .. config::basic_codegen_options()
129         },
130         test: as_test_harness,
131         ..config::basic_options().clone()
132     };
133
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.
137     //
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.
142     //
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);
147     let w2 = w1.clone();
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 {
152             Some(old) => {
153                 // Chop off the `Send` bound.
154                 let old: Box<Writer> = old;
155                 old
156             }
157             None => box io::stderr() as Box<Writer>,
158         };
159         io::util::copy(&mut p, &mut err).unwrap();
160     }).detach();
161     let emitter = diagnostic::EmitterWriter::new(box w2, None);
162
163     // Compile the code
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);
168
169     let sess = session::build_session_(sessopts,
170                                       None,
171                                       span_diagnostic_handler);
172
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);
178
179     if no_run { return }
180
181     // Run the code!
182     //
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
186     // mistake.
187     let mut cmd = Command::new(outdir.path().join("rust-out"));
188     let newpath = {
189         let mut path = DynamicLibrary::search_path();
190         path.insert(0, libdir.clone());
191         DynamicLibrary::create_path(path.as_slice())
192     };
193     cmd.env(DynamicLibrary::envvar(), newpath.as_slice());
194
195     match cmd.output() {
196         Err(e) => panic!("couldn't run the test: {}{}", e,
197                         if e.kind == io::PermissionDenied {
198                             " - maybe your tempdir is mounted with noexec?"
199                         } else { "" }),
200         Ok(out) => {
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()));
206             }
207         }
208     }
209 }
210
211 pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String {
212     let mut prog = String::new();
213     if lints {
214         prog.push_str(r"
215 #![deny(warnings)]
216 #![allow(unused_variables, unused_assignments, unused_mut, unused_attributes, dead_code)]
217 ");
218     }
219
220     // Don't inject `extern crate std` because it's already injected by the
221     // compiler.
222     if !s.contains("extern crate") && cratename != Some("std") {
223         match cratename {
224             Some(cratename) => {
225                 if s.contains(cratename) {
226                     prog.push_str(format!("extern crate {};\n",
227                                           cratename).as_slice());
228                 }
229             }
230             None => {}
231         }
232     }
233     if dont_insert_main || s.contains("fn main") {
234         prog.push_str(s);
235     } else {
236         prog.push_str("fn main() {\n    ");
237         prog.push_str(s.replace("\n", "\n    ").as_slice());
238         prog.push_str("\n}");
239     }
240
241     return prog
242 }
243
244 pub struct Collector {
245     pub tests: Vec<testing::TestDescAndFn>,
246     names: Vec<String>,
247     libs: SearchPaths,
248     externs: core::Externs,
249     cnt: uint,
250     use_headers: bool,
251     current_header: Option<String>,
252     cratename: String,
253 }
254
255 impl Collector {
256     pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
257                use_headers: bool) -> Collector {
258         Collector {
259             tests: Vec::new(),
260             names: Vec::new(),
261             libs: libs,
262             externs: externs,
263             cnt: 0,
264             use_headers: use_headers,
265             current_header: None,
266             cratename: cratename,
267         }
268     }
269
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)
275         } else {
276             format!("{}_{}", self.names.connect("::"), self.cnt)
277         };
278         self.cnt += 1;
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
288             },
289             testfn: testing::DynTestFn(Thunk::new(move|| {
290                 runtest(test.as_slice(),
291                         cratename.as_slice(),
292                         libs,
293                         externs,
294                         should_fail,
295                         no_run,
296                         as_test_harness);
297             }))
298         });
299     }
300
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()) {
308                         c
309                     } else {
310                         '_'
311                     }
312                 }).collect::<String>();
313
314             // new header => reset count.
315             self.cnt = 0;
316             self.current_header = Some(name);
317         }
318     }
319 }
320
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 }
326             None => false
327         };
328         match item.doc_value() {
329             Some(doc) => {
330                 self.cnt = 0;
331                 markdown::find_testable_code(doc, &mut *self);
332             }
333             None => {}
334         }
335         let ret = self.fold_item_recur(item);
336         if pushed {
337             self.names.pop();
338         }
339         return ret;
340     }
341 }