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