test.rs 10.2 KB
Newer Older
1
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11
use std::cell::RefCell;
12
use std::char;
13
use std::io;
14
use std::io::{Command, TempDir};
15 16
use std::os;
use std::str;
17
use std::strbuf::StrBuf;
18

19
use collections::{HashSet, HashMap};
L
Liigo Zhuang 已提交
20
use testing;
A
Alex Crichton 已提交
21
use rustc::back::link;
N
Nick Cameron 已提交
22
use rustc::driver::config;
23 24
use rustc::driver::driver;
use rustc::driver::session;
25
use rustc::metadata::creader::Loader;
26 27
use syntax::ast;
use syntax::codemap::{CodeMap, dummy_spanned};
28
use syntax::diagnostic;
29
use syntax::parse::token;
30 31 32 33 34 35 36 37 38

use core;
use clean;
use clean::Clean;
use fold::DocFolder;
use html::markdown;
use passes;
use visit_ast::RustdocVisitor;

39
pub fn run(input: &str,
40
           cfgs: Vec<StrBuf>,
41
           libs: HashSet<Path>,
42
           mut test_args: Vec<StrBuf>)
43
           -> int {
44 45
    let input_path = Path::new(input);
    let input = driver::FileInput(input_path.clone());
46

N
Nick Cameron 已提交
47
    let sessopts = config::Options {
E
Eduard Burtescu 已提交
48 49
        maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
        addl_lib_search_paths: RefCell::new(libs.clone()),
N
Nick Cameron 已提交
50 51
        crate_types: vec!(config::CrateTypeDylib),
        ..config::basic_options().clone()
52 53 54
    };


E
Eduard Burtescu 已提交
55
    let codemap = CodeMap::new();
56
    let diagnostic_handler = diagnostic::default_handler();
57
    let span_diagnostic_handler =
E
Eduard Burtescu 已提交
58
    diagnostic::mk_span_handler(diagnostic_handler, codemap);
59

N
Nick Cameron 已提交
60
    let sess = session::build_session_(sessopts,
61
                                      Some(input_path.clone()),
62 63
                                      span_diagnostic_handler);

N
Nick Cameron 已提交
64
    let mut cfg = config::build_configuration(&sess);
65
    cfg.extend(cfgs.move_iter().map(|cfg_| {
66
        let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
67 68
        @dummy_spanned(ast::MetaWord(cfg_))
    }));
E
Eduard Burtescu 已提交
69
    let krate = driver::phase_1_parse_input(&sess, cfg, &input);
E
Eduard Burtescu 已提交
70
    let (krate, _) = driver::phase_2_configure_and_expand(&sess, &mut Loader::new(&sess), krate,
E
Eduard Burtescu 已提交
71
                                                          &from_str("rustdoc-test").unwrap());
72 73

    let ctx = @core::DocContext {
74
        krate: krate,
E
Eduard Burtescu 已提交
75
        maybe_typed: core::NotTyped(sess),
76
        src: input_path,
77
        external_paths: RefCell::new(Some(HashMap::new())),
78
    };
79
    super::ctxtkey.replace(Some(ctx));
80

A
Alex Crichton 已提交
81
    let mut v = RustdocVisitor::new(ctx, None);
82 83 84 85
    v.visit(&ctx.krate);
    let krate = v.clean();
    let (krate, _) = passes::unindent_comments(krate);
    let (krate, _) = passes::collapse_docs(krate);
86

87
    let mut collector = Collector::new(krate.name.to_strbuf(),
88 89 90
                                       libs,
                                       false,
                                       false);
91
    collector.fold_crate(krate);
92

93
    test_args.unshift("rustdoctest".to_strbuf());
94

95
    testing::test_main(test_args.as_slice(),
96
                       collector.tests.move_iter().collect());
97 98 99
    0
}

100
fn runtest(test: &str, cratename: &str, libs: HashSet<Path>, should_fail: bool,
101 102
           no_run: bool, loose_feature_gating: bool) {
    let test = maketest(test, cratename, loose_feature_gating);
103
    let input = driver::StrInput(test.to_strbuf());
104

N
Nick Cameron 已提交
105
    let sessopts = config::Options {
E
Eduard Burtescu 已提交
106 107
        maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
        addl_lib_search_paths: RefCell::new(libs),
N
Nick Cameron 已提交
108
        crate_types: vec!(config::CrateTypeExecutable),
109
        output_types: vec!(link::OutputTypeExe),
110
        no_trans: no_run,
N
Nick Cameron 已提交
111
        cg: config::CodegenOptions {
112
            prefer_dynamic: true,
N
Nick Cameron 已提交
113
            .. config::basic_codegen_options()
114
        },
N
Nick Cameron 已提交
115
        ..config::basic_options().clone()
116 117
    };

118 119 120 121 122 123 124 125 126 127 128
    // Shuffle around a few input and output handles here. We're going to pass
    // an explicit handle into rustc to collect output messages, but we also
    // want to catch the error message that rustc prints when it fails.
    //
    // We take our task-local stderr (likely set by the test runner), and move
    // it into another task. This helper task then acts as a sink for both the
    // stderr of this task and stderr of rustc itself, copying all the info onto
    // the stderr channel we originally started with.
    //
    // The basic idea is to not use a default_handler() for rustc, and then also
    // not print things by default to the actual stderr.
129 130
    let (tx, rx) = channel();
    let w1 = io::ChanWriter::new(tx);
131
    let w2 = w1.clone();
132
    let old = io::stdio::set_stderr(box w1);
133
    spawn(proc() {
134
        let mut p = io::ChanReader::new(rx);
135
        let mut err = old.unwrap_or(box io::stderr() as Box<Writer:Send>);
136 137
        io::util::copy(&mut p, &mut err).unwrap();
    });
138
    let emitter = diagnostic::EmitterWriter::new(box w2);
139 140

    // Compile the code
E
Eduard Burtescu 已提交
141
    let codemap = CodeMap::new();
142
    let diagnostic_handler = diagnostic::mk_handler(box emitter);
143
    let span_diagnostic_handler =
E
Eduard Burtescu 已提交
144
        diagnostic::mk_span_handler(diagnostic_handler, codemap);
145

N
Nick Cameron 已提交
146
    let sess = session::build_session_(sessopts,
147
                                      None,
148 149 150 151
                                      span_diagnostic_handler);

    let outdir = TempDir::new("rustdoctest").expect("rustdoc needs a tempdir");
    let out = Some(outdir.path().clone());
N
Nick Cameron 已提交
152
    let cfg = config::build_configuration(&sess);
153 154
    driver::compile_input(sess, cfg, &input, &out, &None);

155 156
    if no_run { return }

157
    // Run the code!
158
    match Command::new(outdir.path().join("rust_out")).output() {
159 160 161 162
        Err(e) => fail!("couldn't run the test: {}{}", e,
                        if e.kind == io::PermissionDenied {
                            " - maybe your tempdir is mounted with noexec?"
                        } else { "" }),
A
Alex Crichton 已提交
163
        Ok(out) => {
164 165 166
            if should_fail && out.status.success() {
                fail!("test executable succeeded when it should have failed");
            } else if !should_fail && !out.status.success() {
S
Steven Fackler 已提交
167 168
                fail!("test executable failed:\n{}",
                      str::from_utf8(out.error.as_slice()));
169 170 171 172 173
            }
        }
    }
}

174
fn maketest(s: &str, cratename: &str, loose_feature_gating: bool) -> StrBuf {
175
    let mut prog = StrBuf::from_str(r"
176 177
#![deny(warnings)]
#![allow(unused_variable, dead_assignment, unused_mut, attribute_usage, dead_code)]
178
");
179 180 181 182

    if loose_feature_gating {
        // FIXME #12773: avoid inserting these when the tutorial & manual
        // etc. have been updated to not use them so prolifically.
183
        prog.push_str("#![feature(macro_rules, globs, struct_variant, managed_boxes) ]\n");
184 185
    }

186 187 188 189
    if !s.contains("extern crate") {
        if s.contains(cratename) {
            prog.push_str(format!("extern crate {};\n", cratename));
        }
190 191 192 193 194 195 196 197 198
    }
    if s.contains("fn main") {
        prog.push_str(s);
    } else {
        prog.push_str("fn main() {\n");
        prog.push_str(s);
        prog.push_str("\n}");
    }

199
    return prog
200 201 202
}

pub struct Collector {
203
    pub tests: Vec<testing::TestDescAndFn>,
204
    names: Vec<StrBuf>,
205 206 207
    libs: HashSet<Path>,
    cnt: uint,
    use_headers: bool,
208 209
    current_header: Option<StrBuf>,
    cratename: StrBuf,
210 211

    loose_feature_gating: bool
212 213 214
}

impl Collector {
215
    pub fn new(cratename: StrBuf, libs: HashSet<Path>,
216
               use_headers: bool, loose_feature_gating: bool) -> Collector {
217
        Collector {
218 219
            tests: Vec::new(),
            names: Vec::new(),
220 221 222 223
            libs: libs,
            cnt: 0,
            use_headers: use_headers,
            current_header: None,
224 225 226
            cratename: cratename,

            loose_feature_gating: loose_feature_gating
227 228 229
        }
    }

230
    pub fn add_test(&mut self, test: StrBuf, should_fail: bool, no_run: bool, should_ignore: bool) {
231 232
        let name = if self.use_headers {
            let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
233
            format_strbuf!("{}_{}", s, self.cnt)
234
        } else {
235
            format_strbuf!("{}_{}", self.names.connect("::"), self.cnt)
236
        };
237
        self.cnt += 1;
E
Eduard Burtescu 已提交
238
        let libs = self.libs.clone();
239
        let cratename = self.cratename.to_owned();
240
        let loose_feature_gating = self.loose_feature_gating;
241
        debug!("Creating test {}: {}", name, test);
L
Liigo Zhuang 已提交
242 243 244
        self.tests.push(testing::TestDescAndFn {
            desc: testing::TestDesc {
                name: testing::DynTestName(name),
245
                ignore: should_ignore,
246
                should_fail: false, // compiler failures are test failures
247
            },
L
Liigo Zhuang 已提交
248
            testfn: testing::DynTestFn(proc() {
249 250 251 252 253 254
                runtest(test.as_slice(),
                        cratename,
                        libs,
                        should_fail,
                        no_run,
                        loose_feature_gating);
255 256 257
            }),
        });
    }
258 259 260 261 262 263 264 265 266 267 268 269

    pub fn register_header(&mut self, name: &str, level: u32) {
        if self.use_headers && level == 1 {
            // we use these headings as test names, so it's good if
            // they're valid identifiers.
            let name = name.chars().enumerate().map(|(i, c)| {
                    if (i == 0 && char::is_XID_start(c)) ||
                        (i != 0 && char::is_XID_continue(c)) {
                        c
                    } else {
                        '_'
                    }
270
                }).collect::<StrBuf>();
271 272 273 274 275 276

            // new header => reset count.
            self.cnt = 0;
            self.current_header = Some(name);
        }
    }
277 278 279 280 281 282
}

impl DocFolder for Collector {
    fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
        let pushed = match item.name {
            Some(ref name) if name.len() == 0 => false,
283
            Some(ref name) => { self.names.push(name.to_strbuf()); true }
284 285 286 287 288
            None => false
        };
        match item.doc_value() {
            Some(doc) => {
                self.cnt = 0;
289
                markdown::find_testable_code(doc, &mut *self);
290 291 292 293 294 295 296 297 298 299
            }
            None => {}
        }
        let ret = self.fold_item_recur(item);
        if pushed {
            self.names.pop();
        }
        return ret;
    }
}