]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
Fixes to rustdoc, etc.
[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::cell::{RefCell, Cell};
12 use std::collections::{HashSet, HashMap};
13 use std::dynamic_lib::DynamicLibrary;
14 use std::env;
15 use std::ffi::OsString;
16 use std::io::prelude::*;
17 use std::io;
18 use std::path::PathBuf;
19 use std::process::Command;
20 use std::str;
21 use std::sync::{Arc, Mutex};
22
23 use testing;
24 use rustc_lint;
25 use rustc::front::map as hir_map;
26 use rustc::session::{self, config};
27 use rustc::session::config::{get_unstable_features_setting, OutputType};
28 use rustc::session::search_paths::{SearchPaths, PathKind};
29 use rustc_front::lowering::{lower_crate, LoweringContext};
30 use rustc_back::tempdir::TempDir;
31 use rustc_driver::{driver, Compilation};
32 use syntax::codemap::CodeMap;
33 use syntax::diagnostic;
34
35 use core;
36 use clean;
37 use clean::Clean;
38 use fold::DocFolder;
39 use html::markdown;
40 use passes;
41 use visit_ast::RustdocVisitor;
42
43 #[derive(Clone, Default)]
44 pub struct TestOptions {
45     pub no_crate_inject: bool,
46     pub attrs: Vec<String>,
47 }
48
49 pub fn run(input: &str,
50            cfgs: Vec<String>,
51            libs: SearchPaths,
52            externs: core::Externs,
53            mut test_args: Vec<String>,
54            crate_name: Option<String>)
55            -> isize {
56     let input_path = PathBuf::from(input);
57     let input = config::Input::File(input_path.clone());
58
59     let sessopts = config::Options {
60         maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
61                                               .parent().unwrap().to_path_buf()),
62         search_paths: libs.clone(),
63         crate_types: vec!(config::CrateTypeDylib),
64         externs: externs.clone(),
65         unstable_features: get_unstable_features_setting(),
66         ..config::basic_options().clone()
67     };
68
69     let codemap = CodeMap::new();
70     let diagnostic_handler = diagnostic::Handler::new(diagnostic::Auto, None, true);
71     let span_diagnostic_handler =
72     diagnostic::SpanHandler::new(diagnostic_handler, codemap);
73
74     let sess = session::build_session_(sessopts,
75                                       Some(input_path.clone()),
76                                       span_diagnostic_handler);
77     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
78
79     let mut cfg = config::build_configuration(&sess);
80     cfg.extend(config::parse_cfgspecs(cfgs));
81     let krate = driver::phase_1_parse_input(&sess, cfg, &input);
82     let krate = driver::phase_2_configure_and_expand(&sess, krate,
83                                                      "rustdoc-test", None)
84         .expect("phase_2_configure_and_expand aborted in rustdoc!");
85     let krate = driver::assign_node_ids(&sess, krate);
86     let foo = &42;
87     let lcx = LoweringContext::new(foo, &sess, &krate);
88     let krate = lower_crate(&lcx, &krate);
89
90     let opts = scrape_test_config(&krate);
91
92     let mut forest = hir_map::Forest::new(krate);
93     let map = hir_map::map_crate(&mut forest);
94
95     let ctx = core::DocContext {
96 <<<<<<< HEAD
97         map: &map,
98         maybe_typed: core::NotTyped(sess),
99 =======
100         krate: &krate,
101         maybe_typed: core::NotTyped(&sess),
102 >>>>>>> Fixes to rustdoc, etc.
103         input: input,
104         external_paths: RefCell::new(Some(HashMap::new())),
105         external_traits: RefCell::new(None),
106         external_typarams: RefCell::new(None),
107         inlined: RefCell::new(None),
108         populated_crate_impls: RefCell::new(HashSet::new()),
109         deref_trait_did: Cell::new(None),
110     };
111
112     let mut v = RustdocVisitor::new(&ctx, None);
113     v.visit(ctx.map.krate());
114     let mut krate = v.clean(&ctx);
115     match crate_name {
116         Some(name) => krate.name = name,
117         None => {}
118     }
119     let (krate, _) = passes::collapse_docs(krate);
120     let (krate, _) = passes::unindent_comments(krate);
121
122     let mut collector = Collector::new(krate.name.to_string(),
123                                        libs,
124                                        externs,
125                                        false,
126                                        opts);
127     collector.fold_crate(krate);
128
129     test_args.insert(0, "rustdoctest".to_string());
130
131     testing::test_main(&test_args,
132                        collector.tests.into_iter().collect());
133     0
134 }
135
136 // Look for #![doc(test(no_crate_inject))], used by crates in the std facade
137 fn scrape_test_config(krate: &::rustc_front::hir::Crate) -> TestOptions {
138     use syntax::attr::AttrMetaMethods;
139     use syntax::print::pprust;
140
141     let mut opts = TestOptions {
142         no_crate_inject: false,
143         attrs: Vec::new(),
144     };
145
146     let attrs = krate.attrs.iter()
147                      .filter(|a| a.check_name("doc"))
148                      .filter_map(|a| a.meta_item_list())
149                      .flat_map(|l| l)
150                      .filter(|a| a.check_name("test"))
151                      .filter_map(|a| a.meta_item_list())
152                      .flat_map(|l| l);
153     for attr in attrs {
154         if attr.check_name("no_crate_inject") {
155             opts.no_crate_inject = true;
156         }
157         if attr.check_name("attr") {
158             if let Some(l) = attr.meta_item_list() {
159                 for item in l {
160                     opts.attrs.push(pprust::meta_item_to_string(item));
161                 }
162             }
163         }
164     }
165
166     return opts;
167 }
168
169 fn runtest(test: &str, cratename: &str, libs: SearchPaths,
170            externs: core::Externs,
171            should_panic: bool, no_run: bool, as_test_harness: bool,
172            opts: &TestOptions) {
173     // the test harness wants its own `main` & top level functions, so
174     // never wrap the test in `fn main() { ... }`
175     let test = maketest(test, Some(cratename), as_test_harness, opts);
176     let input = config::Input::Str(test.to_string());
177     let mut outputs = HashMap::new();
178     outputs.insert(OutputType::Exe, None);
179
180     let sessopts = config::Options {
181         maybe_sysroot: Some(env::current_exe().unwrap().parent().unwrap()
182                                               .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: get_unstable_features_setting(),
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 emitter = diagnostic::EmitterWriter::new(box Sink(data.clone()), None);
221     let old = io::set_panic(box Sink(data.clone()));
222     let _bomb = Bomb(data, old.unwrap_or(box io::stdout()));
223
224     // Compile the code
225     let codemap = CodeMap::new();
226     let diagnostic_handler = diagnostic::Handler::with_emitter(true, box emitter);
227     let span_diagnostic_handler =
228         diagnostic::SpanHandler::new(diagnostic_handler, codemap);
229
230     let sess = session::build_session_(sessopts,
231                                        None,
232                                        span_diagnostic_handler);
233     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
234
235     let outdir = TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir");
236     let out = Some(outdir.path().to_path_buf());
237     let cfg = config::build_configuration(&sess);
238     let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
239     let mut control = driver::CompileController::basic();
240     if no_run {
241         control.after_analysis.stop = Compilation::Stop;
242     }
243     driver::compile_input(sess, cfg, &input, &out, &None, None, control);
244
245     if no_run { return }
246
247     // Run the code!
248     //
249     // We're careful to prepend the *target* dylib search path to the child's
250     // environment to ensure that the target loads the right libraries at
251     // runtime. It would be a sad day if the *host* libraries were loaded as a
252     // mistake.
253     let mut cmd = Command::new(&outdir.path().join("rust_out"));
254     let var = DynamicLibrary::envvar();
255     let newpath = {
256         let path = env::var_os(var).unwrap_or(OsString::new());
257         let mut path = env::split_paths(&path).collect::<Vec<_>>();
258         path.insert(0, libdir.clone());
259         env::join_paths(path).unwrap()
260     };
261     cmd.env(var, &newpath);
262
263     match cmd.output() {
264         Err(e) => panic!("couldn't run the test: {}{}", e,
265                         if e.kind() == io::ErrorKind::PermissionDenied {
266                             " - maybe your tempdir is mounted with noexec?"
267                         } else { "" }),
268         Ok(out) => {
269             if should_panic && out.status.success() {
270                 panic!("test executable succeeded when it should have failed");
271             } else if !should_panic && !out.status.success() {
272                 panic!("test executable failed:\n{}\n{}",
273                        str::from_utf8(&out.stdout).unwrap_or(""),
274                        str::from_utf8(&out.stderr).unwrap_or(""));
275             }
276         }
277     }
278 }
279
280 pub fn maketest(s: &str, cratename: Option<&str>, dont_insert_main: bool,
281                 opts: &TestOptions) -> String {
282     let (crate_attrs, everything_else) = partition_source(s);
283
284     let mut prog = String::new();
285
286     // First push any outer attributes from the example, assuming they
287     // are intended to be crate attributes.
288     prog.push_str(&crate_attrs);
289
290     // Next, any attributes for other aspects such as lints.
291     for attr in &opts.attrs {
292         prog.push_str(&format!("#![{}]\n", attr));
293     }
294
295     // Don't inject `extern crate std` because it's already injected by the
296     // compiler.
297     if !s.contains("extern crate") && !opts.no_crate_inject && cratename != Some("std") {
298         match cratename {
299             Some(cratename) => {
300                 if s.contains(cratename) {
301                     prog.push_str(&format!("extern crate {};\n", cratename));
302                 }
303             }
304             None => {}
305         }
306     }
307     if dont_insert_main || s.contains("fn main") {
308         prog.push_str(&everything_else);
309     } else {
310         prog.push_str("fn main() {\n    ");
311         prog.push_str(&everything_else.replace("\n", "\n    "));
312         prog.push_str("\n}");
313     }
314
315     info!("final test program: {}", prog);
316
317     return prog
318 }
319
320 fn partition_source(s: &str) -> (String, String) {
321     use rustc_unicode::str::UnicodeStr;
322
323     let mut after_header = false;
324     let mut before = String::new();
325     let mut after = String::new();
326
327     for line in s.lines() {
328         let trimline = line.trim();
329         let header = trimline.is_whitespace() ||
330             trimline.starts_with("#![feature");
331         if !header || after_header {
332             after_header = true;
333             after.push_str(line);
334             after.push_str("\n");
335         } else {
336             before.push_str(line);
337             before.push_str("\n");
338         }
339     }
340
341     return (before, after);
342 }
343
344 pub struct Collector {
345     pub tests: Vec<testing::TestDescAndFn>,
346     names: Vec<String>,
347     libs: SearchPaths,
348     externs: core::Externs,
349     cnt: usize,
350     use_headers: bool,
351     current_header: Option<String>,
352     cratename: String,
353     opts: TestOptions,
354 }
355
356 impl Collector {
357     pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
358                use_headers: bool, opts: TestOptions) -> Collector {
359         Collector {
360             tests: Vec::new(),
361             names: Vec::new(),
362             libs: libs,
363             externs: externs,
364             cnt: 0,
365             use_headers: use_headers,
366             current_header: None,
367             cratename: cratename,
368             opts: opts,
369         }
370     }
371
372     pub fn add_test(&mut self, test: String,
373                     should_panic: bool, no_run: bool, should_ignore: bool,
374                     as_test_harness: bool) {
375         let name = if self.use_headers {
376             let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
377             format!("{}_{}", s, self.cnt)
378         } else {
379             format!("{}_{}", self.names.join("::"), self.cnt)
380         };
381         self.cnt += 1;
382         let libs = self.libs.clone();
383         let externs = self.externs.clone();
384         let cratename = self.cratename.to_string();
385         let opts = self.opts.clone();
386         debug!("Creating test {}: {}", name, test);
387         self.tests.push(testing::TestDescAndFn {
388             desc: testing::TestDesc {
389                 name: testing::DynTestName(name),
390                 ignore: should_ignore,
391                 // compiler failures are test failures
392                 should_panic: testing::ShouldPanic::No,
393             },
394             testfn: testing::DynTestFn(Box::new(move|| {
395                 runtest(&test,
396                         &cratename,
397                         libs,
398                         externs,
399                         should_panic,
400                         no_run,
401                         as_test_harness,
402                         &opts);
403             }))
404         });
405     }
406
407     pub fn register_header(&mut self, name: &str, level: u32) {
408         if self.use_headers && level == 1 {
409             // we use these headings as test names, so it's good if
410             // they're valid identifiers.
411             let name = name.chars().enumerate().map(|(i, c)| {
412                     if (i == 0 && c.is_xid_start()) ||
413                         (i != 0 && c.is_xid_continue()) {
414                         c
415                     } else {
416                         '_'
417                     }
418                 }).collect::<String>();
419
420             // new header => reset count.
421             self.cnt = 0;
422             self.current_header = Some(name);
423         }
424     }
425 }
426
427 impl DocFolder for Collector {
428     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
429         let pushed = match item.name {
430             Some(ref name) if name.is_empty() => false,
431             Some(ref name) => { self.names.push(name.to_string()); true }
432             None => false
433         };
434         match item.doc_value() {
435             Some(doc) => {
436                 self.cnt = 0;
437                 markdown::find_testable_code(doc, &mut *self);
438             }
439             None => {}
440         }
441         let ret = self.fold_item_recur(item);
442         if pushed {
443             self.names.pop();
444         }
445         return ret;
446     }
447 }