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