]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
Auto merge of #38049 - frewsxcv:libunicode, 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 use std::env;
12 use std::ffi::OsString;
13 use std::io::prelude::*;
14 use std::io;
15 use std::path::PathBuf;
16 use std::panic::{self, AssertUnwindSafe};
17 use std::process::Command;
18 use std::rc::Rc;
19 use std::str;
20 use std::sync::{Arc, Mutex};
21
22 use testing;
23 use rustc_lint;
24 use rustc::dep_graph::DepGraph;
25 use rustc::hir;
26 use rustc::hir::intravisit;
27 use rustc::session::{self, config};
28 use rustc::session::config::{OutputType, OutputTypes, Externs};
29 use rustc::session::search_paths::{SearchPaths, PathKind};
30 use rustc_back::dynamic_lib::DynamicLibrary;
31 use rustc_back::tempdir::TempDir;
32 use rustc_driver::{driver, Compilation};
33 use rustc_driver::driver::phase_2_configure_and_expand;
34 use rustc_metadata::cstore::CStore;
35 use rustc_resolve::MakeGlobMap;
36 use rustc_trans::back::link;
37 use syntax::ast;
38 use syntax::codemap::CodeMap;
39 use syntax::feature_gate::UnstableFeatures;
40 use errors;
41 use errors::emitter::ColorConfig;
42
43 use clean::Attributes;
44 use html::markdown;
45
46 #[derive(Clone, Default)]
47 pub struct TestOptions {
48     pub no_crate_inject: bool,
49     pub attrs: Vec<String>,
50 }
51
52 pub fn run(input: &str,
53            cfgs: Vec<String>,
54            libs: SearchPaths,
55            externs: Externs,
56            mut test_args: Vec<String>,
57            crate_name: Option<String>)
58            -> isize {
59     let input_path = PathBuf::from(input);
60     let input = config::Input::File(input_path.clone());
61
62     let sessopts = config::Options {
63         maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
64                                               .parent().unwrap().to_path_buf()),
65         search_paths: libs.clone(),
66         crate_types: vec![config::CrateTypeDylib],
67         externs: externs.clone(),
68         unstable_features: UnstableFeatures::from_environment(),
69         ..config::basic_options().clone()
70     };
71
72     let codemap = Rc::new(CodeMap::new());
73     let handler =
74         errors::Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
75
76     let dep_graph = DepGraph::new(false);
77     let _ignore = dep_graph.in_ignore();
78     let cstore = Rc::new(CStore::new(&dep_graph));
79     let mut sess = session::build_session_(
80         sessopts, &dep_graph, Some(input_path.clone()), handler, codemap, cstore.clone(),
81     );
82     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
83     sess.parse_sess.config =
84         config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
85
86     let krate = panictry!(driver::phase_1_parse_input(&sess, &input));
87     let driver::ExpansionResult { defs, mut hir_forest, .. } = {
88         phase_2_configure_and_expand(
89             &sess, &cstore, krate, None, "rustdoc-test", None, MakeGlobMap::No, |_| Ok(())
90         ).expect("phase_2_configure_and_expand aborted in rustdoc!")
91     };
92
93     let crate_name = crate_name.unwrap_or_else(|| {
94         link::find_crate_name(None, &hir_forest.krate().attrs, &input)
95     });
96     let opts = scrape_test_config(hir_forest.krate());
97     let mut collector = Collector::new(crate_name,
98                                        cfgs,
99                                        libs,
100                                        externs,
101                                        false,
102                                        opts);
103
104     {
105         let dep_graph = DepGraph::new(false);
106         let _ignore = dep_graph.in_ignore();
107         let map = hir::map::map_crate(&mut hir_forest, defs);
108         let krate = map.krate();
109         let mut hir_collector = HirCollector {
110             collector: &mut collector,
111             map: &map
112         };
113         hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
114             intravisit::walk_crate(this, krate);
115         });
116     }
117
118     test_args.insert(0, "rustdoctest".to_string());
119
120     testing::test_main(&test_args,
121                        collector.tests.into_iter().collect());
122     0
123 }
124
125 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
126 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
127     use syntax::print::pprust;
128
129     let mut opts = TestOptions {
130         no_crate_inject: false,
131         attrs: Vec::new(),
132     };
133
134     let attrs = krate.attrs.iter()
135                      .filter(|a| a.check_name("doc"))
136                      .filter_map(|a| a.meta_item_list())
137                      .flat_map(|l| l)
138                      .filter(|a| a.check_name("test"))
139                      .filter_map(|a| a.meta_item_list())
140                      .flat_map(|l| l);
141     for attr in attrs {
142         if attr.check_name("no_crate_inject") {
143             opts.no_crate_inject = true;
144         }
145         if attr.check_name("attr") {
146             if let Some(l) = attr.meta_item_list() {
147                 for item in l {
148                     opts.attrs.push(pprust::meta_list_item_to_string(item));
149                 }
150             }
151         }
152     }
153
154     opts
155 }
156
157 fn runtest(test: &str, cratename: &str, cfgs: Vec<String>, libs: SearchPaths,
158            externs: Externs,
159            should_panic: bool, no_run: bool, as_test_harness: bool,
160            compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions) {
161     // the test harness wants its own `main` & top level functions, so
162     // never wrap the test in `fn main() { ... }`
163     let test = maketest(test, Some(cratename), as_test_harness, opts);
164     let input = config::Input::Str {
165         name: driver::anon_src(),
166         input: test.to_owned(),
167     };
168     let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
169
170     let sessopts = config::Options {
171         maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
172                                               .parent().unwrap().to_path_buf()),
173         search_paths: libs,
174         crate_types: vec![config::CrateTypeExecutable],
175         output_types: outputs,
176         externs: externs,
177         cg: config::CodegenOptions {
178             prefer_dynamic: true,
179             .. config::basic_codegen_options()
180         },
181         test: as_test_harness,
182         unstable_features: UnstableFeatures::from_environment(),
183         ..config::basic_options().clone()
184     };
185
186     // Shuffle around a few input and output handles here. We're going to pass
187     // an explicit handle into rustc to collect output messages, but we also
188     // want to catch the error message that rustc prints when it fails.
189     //
190     // We take our thread-local stderr (likely set by the test runner) and replace
191     // it with a sink that is also passed to rustc itself. When this function
192     // returns the output of the sink is copied onto the output of our own thread.
193     //
194     // The basic idea is to not use a default Handler for rustc, and then also
195     // not print things by default to the actual stderr.
196     struct Sink(Arc<Mutex<Vec<u8>>>);
197     impl Write for Sink {
198         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
199             Write::write(&mut *self.0.lock().unwrap(), data)
200         }
201         fn flush(&mut self) -> io::Result<()> { Ok(()) }
202     }
203     struct Bomb(Arc<Mutex<Vec<u8>>>, Box<Write+Send>);
204     impl Drop for Bomb {
205         fn drop(&mut self) {
206             let _ = self.1.write_all(&self.0.lock().unwrap());
207         }
208     }
209     let data = Arc::new(Mutex::new(Vec::new()));
210     let codemap = Rc::new(CodeMap::new());
211     let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
212                                                       Some(codemap.clone()));
213     let old = io::set_panic(Some(box Sink(data.clone())));
214     let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
215
216     // Compile the code
217     let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
218
219     let dep_graph = DepGraph::new(false);
220     let cstore = Rc::new(CStore::new(&dep_graph));
221     let mut sess = session::build_session_(
222         sessopts, &dep_graph, None, diagnostic_handler, codemap, cstore.clone(),
223     );
224     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
225
226     let outdir = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
227     let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
228     let mut control = driver::CompileController::basic();
229     sess.parse_sess.config =
230         config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
231     let out = Some(outdir.lock().unwrap().path().to_path_buf());
232
233     if no_run {
234         control.after_analysis.stop = Compilation::Stop;
235     }
236
237     let res = panic::catch_unwind(AssertUnwindSafe(|| {
238         driver::compile_input(&sess, &cstore, &input, &out, &None, None, &control)
239     }));
240
241     match res {
242         Ok(r) => {
243             match r {
244                 Err(count) => {
245                     if count > 0 && !compile_fail {
246                         sess.fatal("aborting due to previous error(s)")
247                     } else if count == 0 && compile_fail {
248                         panic!("test compiled while it wasn't supposed to")
249                     }
250                     if count > 0 && error_codes.len() > 0 {
251                         let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
252                         error_codes.retain(|err| !out.contains(err));
253                     }
254                 }
255                 Ok(()) if compile_fail => panic!("test compiled while it wasn't supposed to"),
256                 _ => {}
257             }
258         }
259         Err(_) => {
260             if !compile_fail {
261                 panic!("couldn't compile the test");
262             }
263             if error_codes.len() > 0 {
264                 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
265                 error_codes.retain(|err| !out.contains(err));
266             }
267         }
268     }
269
270     if error_codes.len() > 0 {
271         panic!("Some expected error codes were not found: {:?}", error_codes);
272     }
273
274     if no_run { return }
275
276     // Run the code!
277     //
278     // We're careful to prepend the *target* dylib search path to the child's
279     // environment to ensure that the target loads the right libraries at
280     // runtime. It would be a sad day if the *host* libraries were loaded as a
281     // mistake.
282     let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
283     let var = DynamicLibrary::envvar();
284     let newpath = {
285         let path = env::var_os(var).unwrap_or(OsString::new());
286         let mut path = env::split_paths(&path).collect::<Vec<_>>();
287         path.insert(0, libdir.clone());
288         env::join_paths(path).unwrap()
289     };
290     cmd.env(var, &newpath);
291
292     match cmd.output() {
293         Err(e) => panic!("couldn't run the test: {}{}", e,
294                         if e.kind() == io::ErrorKind::PermissionDenied {
295                             " - maybe your tempdir is mounted with noexec?"
296                         } else { "" }),
297         Ok(out) => {
298             if should_panic && out.status.success() {
299                 panic!("test executable succeeded when it should have failed");
300             } else if !should_panic && !out.status.success() {
301                 panic!("test executable failed:\n{}\n{}",
302                        str::from_utf8(&out.stdout).unwrap_or(""),
303                        str::from_utf8(&out.stderr).unwrap_or(""));
304             }
305         }
306     }
307 }
308
309 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
310                 opts: &TestOptions) -> String {
311     let (crate_attrs, everything_else) = partition_source(s);
312
313     let mut prog = String::new();
314
315     // First push any outer attributes from the example, assuming they
316     // are intended to be crate attributes.
317     prog.push_str(&crate_attrs);
318
319     // Next, any attributes for other aspects such as lints.
320     for attr in &opts.attrs {
321         prog.push_str(&format!("#![{}]\n", attr));
322     }
323
324     // Don't inject `extern crate std` because it's already injected by the
325     // compiler.
326     if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
327         if let Some(cratename) = cratename {
328             if s.contains(cratename) {
329                 prog.push_str(&format!("extern crate {};\n", cratename));
330             }
331         }
332     }
333     if dont_insert_main || s.contains("fn main") {
334         prog.push_str(&everything_else);
335     } else {
336         prog.push_str("fn main() {\n");
337         prog.push_str(&everything_else);
338         prog = prog.trim().into();
339         prog.push_str("\n}");
340     }
341
342     info!("final test program: {}", prog);
343
344     prog
345 }
346
347 fn partition_source(s: &str) -> (String, String) {
348     use std_unicode::str::UnicodeStr;
349
350     let mut after_header = false;
351     let mut before = String::new();
352     let mut after = String::new();
353
354     for line in s.lines() {
355         let trimline = line.trim();
356         let header = trimline.is_whitespace() ||
357             trimline.starts_with("#![feature");
358         if !header || after_header {
359             after_header = true;
360             after.push_str(line);
361             after.push_str("\n");
362         } else {
363             before.push_str(line);
364             before.push_str("\n");
365         }
366     }
367
368     (before, after)
369 }
370
371 pub struct Collector {
372     pub tests: Vec<testing::TestDescAndFn>,
373     names: Vec<String>,
374     cfgs: Vec<String>,
375     libs: SearchPaths,
376     externs: Externs,
377     cnt: usize,
378     use_headers: bool,
379     current_header: Option<String>,
380     cratename: String,
381     opts: TestOptions,
382 }
383
384 impl Collector {
385     pub fn new(cratename: String, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
386                use_headers: bool, opts: TestOptions) -> Collector {
387         Collector {
388             tests: Vec::new(),
389             names: Vec::new(),
390             cfgs: cfgs,
391             libs: libs,
392             externs: externs,
393             cnt: 0,
394             use_headers: use_headers,
395             current_header: None,
396             cratename: cratename,
397             opts: opts,
398         }
399     }
400
401     pub fn add_test(&mut self, test: String,
402                     should_panic: bool, no_run: bool, should_ignore: bool,
403                     as_test_harness: bool, compile_fail: bool, error_codes: Vec<String>) {
404         let name = if self.use_headers {
405             let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
406             format!("{}_{}", s, self.cnt)
407         } else {
408             format!("{}_{}", self.names.join("::"), self.cnt)
409         };
410         self.cnt += 1;
411         let cfgs = self.cfgs.clone();
412         let libs = self.libs.clone();
413         let externs = self.externs.clone();
414         let cratename = self.cratename.to_string();
415         let opts = self.opts.clone();
416         debug!("Creating test {}: {}", name, test);
417         self.tests.push(testing::TestDescAndFn {
418             desc: testing::TestDesc {
419                 name: testing::DynTestName(name),
420                 ignore: should_ignore,
421                 // compiler failures are test failures
422                 should_panic: testing::ShouldPanic::No,
423             },
424             testfn: testing::DynTestFn(box move |()| {
425                 runtest(&test,
426                         &cratename,
427                         cfgs,
428                         libs,
429                         externs,
430                         should_panic,
431                         no_run,
432                         as_test_harness,
433                         compile_fail,
434                         error_codes,
435                         &opts);
436             })
437         });
438     }
439
440     pub fn register_header(&mut self, name: &str, level: u32) {
441         if self.use_headers && level == 1 {
442             // we use these headings as test names, so it's good if
443             // they're valid identifiers.
444             let name = name.chars().enumerate().map(|(i, c)| {
445                     if (i == 0 && c.is_xid_start()) ||
446                         (i != 0 && c.is_xid_continue()) {
447                         c
448                     } else {
449                         '_'
450                     }
451                 }).collect::<String>();
452
453             // new header => reset count.
454             self.cnt = 0;
455             self.current_header = Some(name);
456         }
457     }
458 }
459
460 struct HirCollector<'a, 'hir: 'a> {
461     collector: &'a mut Collector,
462     map: &'a hir::map::Map<'hir>
463 }
464
465 impl<'a, 'hir> HirCollector<'a, 'hir> {
466     fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
467                                             name: String,
468                                             attrs: &[ast::Attribute],
469                                             nested: F) {
470         let has_name = !name.is_empty();
471         if has_name {
472             self.collector.names.push(name);
473         }
474
475         let mut attrs = Attributes::from_ast(attrs);
476         attrs.collapse_doc_comments();
477         attrs.unindent_doc_comments();
478         if let Some(doc) = attrs.doc_value() {
479             self.collector.cnt = 0;
480             markdown::find_testable_code(doc, self.collector);
481         }
482
483         nested(self);
484
485         if has_name {
486             self.collector.names.pop();
487         }
488     }
489 }
490
491 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
492     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
493         intravisit::NestedVisitorMap::All(&self.map)
494     }
495
496     fn visit_item(&mut self, item: &'hir hir::Item) {
497         let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
498             hir::print::ty_to_string(ty)
499         } else {
500             item.name.to_string()
501         };
502
503         self.visit_testable(name, &item.attrs, |this| {
504             intravisit::walk_item(this, item);
505         });
506     }
507
508     fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
509         self.visit_testable(item.name.to_string(), &item.attrs, |this| {
510             intravisit::walk_trait_item(this, item);
511         });
512     }
513
514     fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
515         self.visit_testable(item.name.to_string(), &item.attrs, |this| {
516             intravisit::walk_impl_item(this, item);
517         });
518     }
519
520     fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
521         self.visit_testable(item.name.to_string(), &item.attrs, |this| {
522             intravisit::walk_foreign_item(this, item);
523         });
524     }
525
526     fn visit_variant(&mut self,
527                      v: &'hir hir::Variant,
528                      g: &'hir hir::Generics,
529                      item_id: ast::NodeId) {
530         self.visit_testable(v.node.name.to_string(), &v.node.attrs, |this| {
531             intravisit::walk_variant(this, v, g, item_id);
532         });
533     }
534
535     fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
536         self.visit_testable(f.name.to_string(), &f.attrs, |this| {
537             intravisit::walk_struct_field(this, f);
538         });
539     }
540
541     fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
542         self.visit_testable(macro_def.name.to_string(), &macro_def.attrs, |_| ());
543     }
544 }