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