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