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