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