]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
Register new snapshots
[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;
12 use std::char;
13 use std::dynamic_lib::DynamicLibrary;
14 use std::gc::GC;
15 use std::io::{Command, TempDir};
16 use std::io;
17 use std::os;
18 use std::str;
19 use std::string::String;
20
21 use std::collections::{HashSet, HashMap};
22 use testing;
23 use rustc::back::link;
24 use rustc::driver::config;
25 use rustc::driver::driver;
26 use rustc::driver::session;
27 use syntax::ast;
28 use syntax::codemap::{CodeMap, dummy_spanned};
29 use syntax::diagnostic;
30 use syntax::parse::token;
31
32 use core;
33 use clean;
34 use clean::Clean;
35 use fold::DocFolder;
36 use html::markdown;
37 use passes;
38 use visit_ast::RustdocVisitor;
39
40 pub fn run(input: &str,
41            cfgs: Vec<String>,
42            libs: HashSet<Path>,
43            mut test_args: Vec<String>)
44            -> int {
45     let input_path = Path::new(input);
46     let input = driver::FileInput(input_path.clone());
47
48     let sessopts = config::Options {
49         maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
50         addl_lib_search_paths: RefCell::new(libs.clone()),
51         crate_types: vec!(config::CrateTypeDylib),
52         ..config::basic_options().clone()
53     };
54
55
56     let codemap = CodeMap::new();
57     let diagnostic_handler = diagnostic::default_handler(diagnostic::Auto);
58     let span_diagnostic_handler =
59     diagnostic::mk_span_handler(diagnostic_handler, codemap);
60
61     let sess = session::build_session_(sessopts,
62                                       Some(input_path.clone()),
63                                       span_diagnostic_handler);
64
65     let mut cfg = config::build_configuration(&sess);
66     cfg.extend(cfgs.move_iter().map(|cfg_| {
67         let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
68         box(GC) dummy_spanned(ast::MetaWord(cfg_))
69     }));
70     let krate = driver::phase_1_parse_input(&sess, cfg, &input);
71     let (krate, _) = driver::phase_2_configure_and_expand(&sess, krate,
72                                                           &from_str("rustdoc-test").unwrap());
73
74     let ctx = box(GC) core::DocContext {
75         krate: krate,
76         maybe_typed: core::NotTyped(sess),
77         src: input_path,
78         external_paths: RefCell::new(Some(HashMap::new())),
79         external_traits: RefCell::new(None),
80         external_typarams: RefCell::new(None),
81         inlined: RefCell::new(None),
82         populated_crate_impls: RefCell::new(HashSet::new()),
83     };
84     super::ctxtkey.replace(Some(ctx));
85
86     let mut v = RustdocVisitor::new(&*ctx, None);
87     v.visit(&ctx.krate);
88     let krate = v.clean();
89     let (krate, _) = passes::unindent_comments(krate);
90     let (krate, _) = passes::collapse_docs(krate);
91
92     let mut collector = Collector::new(krate.name.to_string(),
93                                        libs,
94                                        false);
95     collector.fold_crate(krate);
96
97     test_args.unshift("rustdoctest".to_string());
98
99     testing::test_main(test_args.as_slice(),
100                        collector.tests.move_iter().collect());
101     0
102 }
103
104 fn runtest(test: &str, cratename: &str, libs: HashSet<Path>, should_fail: bool,
105            no_run: bool) {
106     let test = maketest(test, Some(cratename), true);
107     let input = driver::StrInput(test.to_string());
108
109     let sessopts = config::Options {
110         maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
111         addl_lib_search_paths: RefCell::new(libs),
112         crate_types: vec!(config::CrateTypeExecutable),
113         output_types: vec!(link::OutputTypeExe),
114         no_trans: no_run,
115         cg: config::CodegenOptions {
116             prefer_dynamic: true,
117             .. config::basic_codegen_options()
118         },
119         ..config::basic_options().clone()
120     };
121
122     // Shuffle around a few input and output handles here. We're going to pass
123     // an explicit handle into rustc to collect output messages, but we also
124     // want to catch the error message that rustc prints when it fails.
125     //
126     // We take our task-local stderr (likely set by the test runner), and move
127     // it into another task. This helper task then acts as a sink for both the
128     // stderr of this task and stderr of rustc itself, copying all the info onto
129     // the stderr channel we originally started with.
130     //
131     // The basic idea is to not use a default_handler() for rustc, and then also
132     // not print things by default to the actual stderr.
133     let (tx, rx) = channel();
134     let w1 = io::ChanWriter::new(tx);
135     let w2 = w1.clone();
136     let old = io::stdio::set_stderr(box w1);
137     spawn(proc() {
138         let mut p = io::ChanReader::new(rx);
139         let mut err = old.unwrap_or(box io::stderr() as Box<Writer + Send>);
140         io::util::copy(&mut p, &mut err).unwrap();
141     });
142     let emitter = diagnostic::EmitterWriter::new(box w2);
143
144     // Compile the code
145     let codemap = CodeMap::new();
146     let diagnostic_handler = diagnostic::mk_handler(box emitter);
147     let span_diagnostic_handler =
148         diagnostic::mk_span_handler(diagnostic_handler, codemap);
149
150     let sess = session::build_session_(sessopts,
151                                       None,
152                                       span_diagnostic_handler);
153
154     let outdir = TempDir::new("rustdoctest").expect("rustdoc needs a tempdir");
155     let out = Some(outdir.path().clone());
156     let cfg = config::build_configuration(&sess);
157     let libdir = sess.target_filesearch().get_lib_path();
158     driver::compile_input(sess, cfg, &input, &out, &None);
159
160     if no_run { return }
161
162     // Run the code!
163     //
164     // We're careful to prepend the *target* dylib search path to the child's
165     // environment to ensure that the target loads the right libraries at
166     // runtime. It would be a sad day if the *host* libraries were loaded as a
167     // mistake.
168     let exe = outdir.path().join("rust_out");
169     let env = {
170         let mut path = DynamicLibrary::search_path();
171         path.insert(0, libdir.clone());
172
173         // Remove the previous dylib search path var
174         let var = DynamicLibrary::envvar();
175         let mut env: Vec<(String,String)> = os::env().move_iter().collect();
176         match env.iter().position(|&(ref k, _)| k.as_slice() == var) {
177             Some(i) => { env.remove(i); }
178             None => {}
179         };
180
181         // Add the new dylib search path var
182         let newpath = DynamicLibrary::create_path(path.as_slice());
183         env.push((var.to_string(),
184                   str::from_utf8(newpath.as_slice()).unwrap().to_string()));
185         env
186     };
187     match Command::new(exe).env(env.as_slice()).output() {
188         Err(e) => fail!("couldn't run the test: {}{}", e,
189                         if e.kind == io::PermissionDenied {
190                             " - maybe your tempdir is mounted with noexec?"
191                         } else { "" }),
192         Ok(out) => {
193             if should_fail && out.status.success() {
194                 fail!("test executable succeeded when it should have failed");
195             } else if !should_fail && !out.status.success() {
196                 fail!("test executable failed:\n{}",
197                       str::from_utf8(out.error.as_slice()));
198             }
199         }
200     }
201 }
202
203 pub fn maketest(s: &str, cratename: Option<&str>, lints: bool) -> String {
204     let mut prog = String::new();
205     if lints {
206         prog.push_str(r"
207 #![deny(warnings)]
208 #![allow(unused_variable, dead_assignment, unused_mut, unused_attribute, dead_code)]
209 ");
210     }
211
212     if !s.contains("extern crate") {
213         match cratename {
214             Some(cratename) => {
215                 if s.contains(cratename) {
216                     prog.push_str(format!("extern crate {};\n",
217                                           cratename).as_slice());
218                 }
219             }
220             None => {}
221         }
222     }
223     if s.contains("fn main") {
224         prog.push_str(s);
225     } else {
226         prog.push_str("fn main() {\n    ");
227         prog.push_str(s.replace("\n", "\n    ").as_slice());
228         prog.push_str("\n}");
229     }
230
231     return prog
232 }
233
234 pub struct Collector {
235     pub tests: Vec<testing::TestDescAndFn>,
236     names: Vec<String>,
237     libs: HashSet<Path>,
238     cnt: uint,
239     use_headers: bool,
240     current_header: Option<String>,
241     cratename: String,
242 }
243
244 impl Collector {
245     pub fn new(cratename: String, libs: HashSet<Path>,
246                use_headers: bool) -> Collector {
247         Collector {
248             tests: Vec::new(),
249             names: Vec::new(),
250             libs: libs,
251             cnt: 0,
252             use_headers: use_headers,
253             current_header: None,
254             cratename: cratename,
255         }
256     }
257
258     pub fn add_test(&mut self, test: String, should_fail: bool, no_run: bool, should_ignore: bool) {
259         let name = if self.use_headers {
260             let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
261             format!("{}_{}", s, self.cnt)
262         } else {
263             format!("{}_{}", self.names.connect("::"), self.cnt)
264         };
265         self.cnt += 1;
266         let libs = self.libs.clone();
267         let cratename = self.cratename.to_string();
268         debug!("Creating test {}: {}", name, test);
269         self.tests.push(testing::TestDescAndFn {
270             desc: testing::TestDesc {
271                 name: testing::DynTestName(name),
272                 ignore: should_ignore,
273                 should_fail: false, // compiler failures are test failures
274             },
275             testfn: testing::DynTestFn(proc() {
276                 runtest(test.as_slice(),
277                         cratename.as_slice(),
278                         libs,
279                         should_fail,
280                         no_run);
281             }),
282         });
283     }
284
285     pub fn register_header(&mut self, name: &str, level: u32) {
286         if self.use_headers && level == 1 {
287             // we use these headings as test names, so it's good if
288             // they're valid identifiers.
289             let name = name.chars().enumerate().map(|(i, c)| {
290                     if (i == 0 && char::is_XID_start(c)) ||
291                         (i != 0 && char::is_XID_continue(c)) {
292                         c
293                     } else {
294                         '_'
295                     }
296                 }).collect::<String>();
297
298             // new header => reset count.
299             self.cnt = 0;
300             self.current_header = Some(name);
301         }
302     }
303 }
304
305 impl DocFolder for Collector {
306     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
307         let pushed = match item.name {
308             Some(ref name) if name.len() == 0 => false,
309             Some(ref name) => { self.names.push(name.to_string()); true }
310             None => false
311         };
312         match item.doc_value() {
313             Some(doc) => {
314                 self.cnt = 0;
315                 markdown::find_testable_code(doc, &mut *self);
316             }
317             None => {}
318         }
319         let ret = self.fold_item_recur(item);
320         if pushed {
321             self.names.pop();
322         }
323         return ret;
324     }
325 }