]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
3e303b29d5c7ab2f5a9c1515e2ae9bf0651f9ea8
[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 #![allow(deprecated)]
12
13 use std::cell::{RefCell, Cell};
14 use std::collections::{HashSet, HashMap};
15 use std::dynamic_lib::DynamicLibrary;
16 use std::env;
17 use std::ffi::OsString;
18 use std::io::prelude::*;
19 use std::io;
20 use std::path::PathBuf;
21 use std::process::Command;
22 use std::rc::Rc;
23 use std::str;
24 use std::sync::{Arc, Mutex};
25
26 use testing;
27 use rustc_lint;
28 use rustc::front::map as hir_map;
29 use rustc::session::{self, config};
30 use rustc::session::config::{get_unstable_features_setting, OutputType};
31 use rustc::session::search_paths::{SearchPaths, PathKind};
32 use rustc_front::lowering::{lower_crate, LoweringContext};
33 use rustc_back::tempdir::TempDir;
34 use rustc_driver::{driver, Compilation};
35 use rustc_metadata::cstore::CStore;
36 use syntax::codemap::CodeMap;
37 use syntax::diagnostic;
38 use syntax::parse::token;
39
40 use core;
41 use clean;
42 use clean::Clean;
43 use fold::DocFolder;
44 use html::markdown;
45 use passes;
46 use visit_ast::RustdocVisitor;
47
48 #[derive(Clone, Default)]
49 pub struct TestOptions {
50     pub no_crate_inject: bool,
51     pub attrs: Vec<String>,
52 }
53
54 pub fn run(input: &str,
55            cfgs: Vec<String>,
56            libs: SearchPaths,
57            externs: core::Externs,
58            mut test_args: Vec<String>,
59            crate_name: Option<String>)
60            -> isize {
61     let input_path = PathBuf::from(input);
62     let input = config::Input::File(input_path.clone());
63
64     let sessopts = config::Options {
65         maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
66                                               .parent().unwrap().to_path_buf()),
67         search_paths: libs.clone(),
68         crate_types: vec!(config::CrateTypeDylib),
69         externs: externs.clone(),
70         unstable_features: get_unstable_features_setting(),
71         ..config::basic_options().clone()
72     };
73
74     let codemap = CodeMap::new();
75     let diagnostic_handler = diagnostic::Handler::new(diagnostic::Auto, None, true);
76     let span_diagnostic_handler =
77     diagnostic::SpanHandler::new(diagnostic_handler, codemap);
78
79     let cstore = Rc::new(CStore::new(token::get_ident_interner()));
80     let cstore_ = ::rustc_driver::cstore_to_cratestore(cstore.clone());
81     let sess = session::build_session_(sessopts,
82                                        Some(input_path.clone()),
83                                        span_diagnostic_handler,
84                                        cstore_);
85     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
86
87     let mut cfg = config::build_configuration(&sess);
88     cfg.extend(config::parse_cfgspecs(cfgs));
89     let krate = driver::phase_1_parse_input(&sess, cfg, &input);
90     let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate,
91                                                      "rustdoc-test", None)
92         .expect("phase_2_configure_and_expand aborted in rustdoc!");
93     let krate = driver::assign_node_ids(&sess, krate);
94     let lcx = LoweringContext::new(&sess, Some(&krate));
95     let krate = lower_crate(&lcx, &krate);
96
97     let opts = scrape_test_config(&krate);
98
99     let mut forest = hir_map::Forest::new(krate);
100     let map = hir_map::map_crate(&mut forest);
101
102     let ctx = core::DocContext {
103         map: &map,
104         maybe_typed: core::NotTyped(&sess),
105         input: input,
106         external_paths: RefCell::new(Some(HashMap::new())),
107         external_traits: RefCell::new(None),
108         external_typarams: RefCell::new(None),
109         inlined: RefCell::new(None),
110         populated_crate_impls: RefCell::new(HashSet::new()),
111         deref_trait_did: Cell::new(None),
112     };
113
114     let mut v = RustdocVisitor::new(&ctx, None);
115     v.visit(ctx.map.krate());
116     let mut krate = v.clean(&ctx);
117     match crate_name {
118         Some(name) => krate.name = name,
119         None => {}
120     }
121     let (krate, _) = passes::collapse_docs(krate);
122     let (krate, _) = passes::unindent_comments(krate);
123
124     let mut collector = Collector::new(krate.name.to_string(),
125                                        libs,
126                                        externs,
127                                        false,
128                                        opts);
129     collector.fold_crate(krate);
130
131     test_args.insert(0, "rustdoctest".to_string());
132
133     testing::test_main(&test_args,
134                        collector.tests.into_iter().collect());
135     0
136 }
137
138 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
139 fn scrape_test_config(krate: &::rustc_front::hir::Crate) -> TestOptions {
140     use syntax::attr::AttrMetaMethods;
141     use syntax::print::pprust;
142
143     let mut opts = TestOptions {
144         no_crate_inject: false,
145         attrs: Vec::new(),
146     };
147
148     let attrs = krate.attrs.iter()
149                      .filter(|a| a.check_name("doc"))
150                      .filter_map(|a| a.meta_item_list())
151                      .flat_map(|l| l)
152                      .filter(|a| a.check_name("test"))
153                      .filter_map(|a| a.meta_item_list())
154                      .flat_map(|l| l);
155     for attr in attrs {
156         if attr.check_name("no_crate_inject") {
157             opts.no_crate_inject = true;
158         }
159         if attr.check_name("attr") {
160             if let Some(l) = attr.meta_item_list() {
161                 for item in l {
162                     opts.attrs.push(pprust::meta_item_to_string(item));
163                 }
164             }
165         }
166     }
167
168     return opts;
169 }
170
171 fn runtest(test: &str, cratename: &str, libs: SearchPaths,
172            externs: core::Externs,
173            should_panic: bool, no_run: bool, as_test_harness: bool,
174            opts: &TestOptions) {
175     // the test harness wants its own `main` & top level functions, so
176     // never wrap the test in `fn main() { ... }`
177     let test = maketest(test, Some(cratename), as_test_harness, opts);
178     let input = config::Input::Str(test.to_string());
179     let mut outputs = HashMap::new();
180     outputs.insert(OutputType::Exe, None);
181
182     let sessopts = config::Options {
183         maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
184                                               .parent().unwrap().to_path_buf()),
185         search_paths: libs,
186         crate_types: vec!(config::CrateTypeExecutable),
187         output_types: outputs,
188         externs: externs,
189         cg: config::CodegenOptions {
190             prefer_dynamic: true,
191             .. config::basic_codegen_options()
192         },
193         test: as_test_harness,
194         unstable_features: get_unstable_features_setting(),
195         ..config::basic_options().clone()
196     };
197
198     // Shuffle around a few input and output handles here. We're going to pass
199     // an explicit handle into rustc to collect output messages, but we also
200     // want to catch the error message that rustc prints when it fails.
201     //
202     // We take our thread-local stderr (likely set by the test runner) and replace
203     // it with a sink that is also passed to rustc itself. When this function
204     // returns the output of the sink is copied onto the output of our own thread.
205     //
206     // The basic idea is to not use a default Handler for rustc, and then also
207     // not print things by default to the actual stderr.
208     struct Sink(Arc<Mutex<Vec<u8>>>);
209     impl Write for Sink {
210         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
211             Write::write(&mut *self.0.lock().unwrap(), data)
212         }
213         fn flush(&mut self) -> io::Result<()> { Ok(()) }
214     }
215     struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
216     impl Drop for Bomb {
217         fn drop(&mut self) {
218             let _ = self.1.write_all(&self.0.lock().unwrap());
219         }
220     }
221     let data = Arc::new(Mutex::new(Vec::new()));
222     let emitter = diagnostic::EmitterWriter::new(box Sink(data.clone()), None);
223     let old = io::set_panic(box Sink(data.clone()));
224     let _bomb = Bomb(data, old.unwrap_or(box io::stdout()));
225
226     // Compile the code
227     let codemap = CodeMap::new();
228     let diagnostic_handler = diagnostic::Handler::with_emitter(true, box emitter);
229     let span_diagnostic_handler =
230         diagnostic::SpanHandler::new(diagnostic_handler, codemap);
231
232     let cstore = Rc::new(CStore::new(token::get_ident_interner()));
233     let cstore_ = ::rustc_driver::cstore_to_cratestore(cstore.clone());
234     let sess = session::build_session_(sessopts,
235                                        None,
236                                        span_diagnostic_handler,
237                                        cstore_);
238     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
239
240     let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
241     let out = Some(outdir.path().to_path_buf());
242     let cfg = config::build_configuration(&sess);
243     let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
244     let mut control = driver::CompileController::basic();
245     if no_run {
246         control.after_analysis.stop = Compilation::Stop;
247     }
248     driver::compile_input(sess, &cstore, cfg, &input, &out, &None, None, control);
249
250     if no_run { return }
251
252     // Run the code!
253     //
254     // We're careful to prepend the *target* dylib search path to the child's
255     // environment to ensure that the target loads the right libraries at
256     // runtime. It would be a sad day if the *host* libraries were loaded as a
257     // mistake.
258     let mut cmd = Command::new(&outdir.path().join("rust_out"));
259     let var = DynamicLibrary::envvar();
260     let newpath = {
261         let path = env::var_os(var).unwrap_or(OsString::new());
262         let mut path = env::split_paths(&path).collect::<Vec<_>>();
263         path.insert(0, libdir.clone());
264         env::join_paths(path).unwrap()
265     };
266     cmd.env(var, &newpath);
267
268     match cmd.output() {
269         Err(e) => panic!("couldn't run the test: {}{}", e,
270                         if e.kind() == io::ErrorKind::PermissionDenied {
271                             " - maybe your tempdir is mounted with noexec?"
272                         } else { "" }),
273         Ok(out) => {
274             if should_panic && out.status.success() {
275                 panic!("test executable succeeded when it should have failed");
276             } else if !should_panic && !out.status.success() {
277                 panic!("test executable failed:\n{}\n{}",
278                        str::from_utf8(&out.stdout).unwrap_or(""),
279                        str::from_utf8(&out.stderr).unwrap_or(""));
280             }
281         }
282     }
283 }
284
285 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
286                 opts: &TestOptions) -> String {
287     let (crate_attrs, everything_else) = partition_source(s);
288
289     let mut prog = String::new();
290
291     // First push any outer attributes from the example, assuming they
292     // are intended to be crate attributes.
293     prog.push_str(&crate_attrs);
294
295     // Next, any attributes for other aspects such as lints.
296     for attr in &opts.attrs {
297         prog.push_str(&format!("#![{}]\n", attr));
298     }
299
300     // Don't inject `extern crate std` because it's already injected by the
301     // compiler.
302     if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
303         match cratename {
304             Some(cratename) => {
305                 if s.contains(cratename) {
306                     prog.push_str(&format!("extern crate {};\n", cratename));
307                 }
308             }
309             None => {}
310         }
311     }
312     if dont_insert_main || s.contains("fn main") {
313         prog.push_str(&everything_else);
314     } else {
315         prog.push_str("fn main() {\n    ");
316         prog.push_str(&everything_else.replace("\n", "\n    "));
317         prog.push_str("\n}");
318     }
319
320     info!("final test program: {}", prog);
321
322     return prog
323 }
324
325 fn partition_source(s: &str) -> (String, String) {
326     use rustc_unicode::str::UnicodeStr;
327
328     let mut after_header = false;
329     let mut before = String::new();
330     let mut after = String::new();
331
332     for line in s.lines() {
333         let trimline = line.trim();
334         let header = trimline.is_whitespace() ||
335             trimline.starts_with("#![feature");
336         if !header || after_header {
337             after_header = true;
338             after.push_str(line);
339             after.push_str("\n");
340         } else {
341             before.push_str(line);
342             before.push_str("\n");
343         }
344     }
345
346     return (before, after);
347 }
348
349 pub struct Collector {
350     pub tests: Vec<testing::TestDescAndFn>,
351     names: Vec<String>,
352     libs: SearchPaths,
353     externs: core::Externs,
354     cnt: usize,
355     use_headers: bool,
356     current_header: Option<String>,
357     cratename: String,
358     opts: TestOptions,
359 }
360
361 impl Collector {
362     pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
363                use_headers: bool, opts: TestOptions) -> Collector {
364         Collector {
365             tests: Vec::new(),
366             names: Vec::new(),
367             libs: libs,
368             externs: externs,
369             cnt: 0,
370             use_headers: use_headers,
371             current_header: None,
372             cratename: cratename,
373             opts: opts,
374         }
375     }
376
377     pub fn add_test(&mut self, test: String,
378                     should_panic: bool, no_run: bool, should_ignore: bool,
379                     as_test_harness: bool) {
380         let name = if self.use_headers {
381             let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
382             format!("{}_{}", s, self.cnt)
383         } else {
384             format!("{}_{}", self.names.join("::"), self.cnt)
385         };
386         self.cnt += 1;
387         let libs = self.libs.clone();
388         let externs = self.externs.clone();
389         let cratename = self.cratename.to_string();
390         let opts = self.opts.clone();
391         debug!("Creating test {}: {}", name, test);
392         self.tests.push(testing::TestDescAndFn {
393             desc: testing::TestDesc {
394                 name: testing::DynTestName(name),
395                 ignore: should_ignore,
396                 // compiler failures are test failures
397                 should_panic: testing::ShouldPanic::No,
398             },
399             testfn: testing::DynTestFn(Box::new(move|| {
400                 runtest(&test,
401                         &cratename,
402                         libs,
403                         externs,
404                         should_panic,
405                         no_run,
406                         as_test_harness,
407                         &opts);
408             }))
409         });
410     }
411
412     pub fn register_header(&mut self, name: &str, level: u32) {
413         if self.use_headers && level == 1 {
414             // we use these headings as test names, so it's good if
415             // they're valid identifiers.
416             let name = name.chars().enumerate().map(|(i, c)| {
417                     if (i == 0 && c.is_xid_start()) ||
418                         (i != 0 && c.is_xid_continue()) {
419                         c
420                     } else {
421                         '_'
422                     }
423                 }).collect::<String>();
424
425             // new header => reset count.
426             self.cnt = 0;
427             self.current_header = Some(name);
428         }
429     }
430 }
431
432 impl DocFolder for Collector {
433     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
434         let current_name = match item.name {
435             Some(ref name) if !name.is_empty() => Some(name.clone()),
436             _ => typename_if_impl(&item)
437         };
438
439         let pushed = if let Some(name) = current_name {
440             self.names.push(name);
441             true
442         } else {
443             false
444         };
445
446         if let Some(doc) = item.doc_value() {
447             self.cnt = 0;
448             markdown::find_testable_code(doc, &mut *self);
449         }
450
451         let ret = self.fold_item_recur(item);
452         if pushed {
453             self.names.pop();
454         }
455
456         return ret;
457
458         // FIXME: it would be better to not have the escaped version in the first place
459         fn unescape_for_testname(mut s: String) -> String {
460             // for refs `&foo`
461             if s.contains("&amp;") {
462                 s = s.replace("&amp;", "&");
463
464                 // `::&'a mut Foo::` looks weird, let's make it `::<&'a mut Foo>`::
465                 if let Some('&') = s.chars().nth(0) {
466                     s = format!("<{}>", s);
467                 }
468             }
469
470             // either `<..>` or `->`
471             if s.contains("&gt;") {
472                 s.replace("&gt;", ">")
473                  .replace("&lt;", "<")
474             } else {
475                 s
476             }
477         }
478
479         fn typename_if_impl(item: &clean::Item) -> Option<String> {
480             if let clean::ItemEnum::ImplItem(ref impl_) = item.inner {
481                 let path = impl_.for_.to_string();
482                 let unescaped_path = unescape_for_testname(path);
483                 Some(unescaped_path)
484             } else {
485                 None
486             }
487         }
488     }
489 }