]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/test.rs
Rollup merge of #57494 - dotdash:expand, r=nikomatsakis
[rust.git] / src / libsyntax / test.rs
1 // Code that generates a test runner to run all the tests in a crate
2
3 #![allow(dead_code)]
4 #![allow(unused_imports)]
5
6 use self::HasTestSignature::*;
7
8 use std::iter;
9 use std::slice;
10 use std::mem;
11 use std::vec;
12 use attr::{self, HasAttrs};
13 use syntax_pos::{self, DUMMY_SP, NO_EXPANSION, Span, SourceFile, BytePos};
14
15 use source_map::{self, SourceMap, ExpnInfo, MacroAttribute, dummy_spanned, respan};
16 use errors;
17 use config;
18 use entry::{self, EntryPointType};
19 use ext::base::{ExtCtxt, Resolver};
20 use ext::build::AstBuilder;
21 use ext::expand::ExpansionConfig;
22 use ext::hygiene::{self, Mark, SyntaxContext};
23 use fold::Folder;
24 use feature_gate::Features;
25 use util::move_map::MoveMap;
26 use fold::{self, ExpectOne};
27 use parse::{token, ParseSess};
28 use print::pprust;
29 use ast::{self, Ident};
30 use ptr::P;
31 use smallvec::SmallVec;
32 use symbol::{self, Symbol, keywords};
33 use ThinVec;
34
35 struct Test {
36     span: Span,
37     path: Vec<Ident>,
38 }
39
40 struct TestCtxt<'a> {
41     span_diagnostic: &'a errors::Handler,
42     path: Vec<Ident>,
43     ext_cx: ExtCtxt<'a>,
44     test_cases: Vec<Test>,
45     reexport_test_harness_main: Option<Symbol>,
46     is_libtest: bool,
47     ctxt: SyntaxContext,
48     features: &'a Features,
49     test_runner: Option<ast::Path>,
50
51     // top-level re-export submodule, filled out after folding is finished
52     toplevel_reexport: Option<Ident>,
53 }
54
55 // Traverse the crate, collecting all the test functions, eliding any
56 // existing main functions, and synthesizing a main test harness
57 pub fn modify_for_testing(sess: &ParseSess,
58                           resolver: &mut dyn Resolver,
59                           should_test: bool,
60                           krate: ast::Crate,
61                           span_diagnostic: &errors::Handler,
62                           features: &Features) -> ast::Crate {
63     // Check for #[reexport_test_harness_main = "some_name"] which
64     // creates a `use __test::main as some_name;`. This needs to be
65     // unconditional, so that the attribute is still marked as used in
66     // non-test builds.
67     let reexport_test_harness_main =
68         attr::first_attr_value_str_by_name(&krate.attrs,
69                                            "reexport_test_harness_main");
70
71     // Do this here so that the test_runner crate attribute gets marked as used
72     // even in non-test builds
73     let test_runner = get_test_runner(span_diagnostic, &krate);
74
75     if should_test {
76         generate_test_harness(sess, resolver, reexport_test_harness_main,
77                               krate, span_diagnostic, features, test_runner)
78     } else {
79         krate
80     }
81 }
82
83 struct TestHarnessGenerator<'a> {
84     cx: TestCtxt<'a>,
85     tests: Vec<Ident>,
86
87     // submodule name, gensym'd identifier for re-exports
88     tested_submods: Vec<(Ident, Ident)>,
89 }
90
91 impl<'a> fold::Folder for TestHarnessGenerator<'a> {
92     fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
93         let mut folded = fold::noop_fold_crate(c, self);
94
95         // Create a main function to run our tests
96         let test_main = {
97             let unresolved = mk_main(&mut self.cx);
98             self.cx.ext_cx.monotonic_expander().fold_item(unresolved).pop().unwrap()
99         };
100
101         folded.module.items.push(test_main);
102         folded
103     }
104
105     fn fold_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
106         let ident = i.ident;
107         if ident.name != keywords::Invalid.name() {
108             self.cx.path.push(ident);
109         }
110         debug!("current path: {}", path_name_i(&self.cx.path));
111
112         let mut item = i.into_inner();
113         if is_test_case(&item) {
114             debug!("this is a test item");
115
116             let test = Test {
117                 span: item.span,
118                 path: self.cx.path.clone(),
119             };
120             self.cx.test_cases.push(test);
121             self.tests.push(item.ident);
122         }
123
124         // We don't want to recurse into anything other than mods, since
125         // mods or tests inside of functions will break things
126         if let ast::ItemKind::Mod(module) = item.node {
127             let tests = mem::replace(&mut self.tests, Vec::new());
128             let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
129             let mut mod_folded = fold::noop_fold_mod(module, self);
130             let tests = mem::replace(&mut self.tests, tests);
131             let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
132
133             if !tests.is_empty() || !tested_submods.is_empty() {
134                 let (it, sym) = mk_reexport_mod(&mut self.cx, item.id, tests, tested_submods);
135                 mod_folded.items.push(it);
136
137                 if !self.cx.path.is_empty() {
138                     self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
139                 } else {
140                     debug!("pushing nothing, sym: {:?}", sym);
141                     self.cx.toplevel_reexport = Some(sym);
142                 }
143             }
144             item.node = ast::ItemKind::Mod(mod_folded);
145         }
146         if ident.name != keywords::Invalid.name() {
147             self.cx.path.pop();
148         }
149         smallvec![P(item)]
150     }
151
152     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
153 }
154
155 /// A folder used to remove any entry points (like fn main) because the harness
156 /// generator will provide its own
157 struct EntryPointCleaner {
158     // Current depth in the ast
159     depth: usize,
160 }
161
162 impl fold::Folder for EntryPointCleaner {
163     fn fold_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
164         self.depth += 1;
165         let folded = fold::noop_fold_item(i, self).expect_one("noop did something");
166         self.depth -= 1;
167
168         // Remove any #[main] or #[start] from the AST so it doesn't
169         // clash with the one we're going to add, but mark it as
170         // #[allow(dead_code)] to avoid printing warnings.
171         let folded = match entry::entry_point_type(&folded, self.depth) {
172             EntryPointType::MainNamed |
173             EntryPointType::MainAttr |
174             EntryPointType::Start =>
175                 folded.map(|ast::Item {id, ident, attrs, node, vis, span, tokens}| {
176                     let allow_ident = Ident::from_str("allow");
177                     let dc_nested = attr::mk_nested_word_item(Ident::from_str("dead_code"));
178                     let allow_dead_code_item = attr::mk_list_item(DUMMY_SP, allow_ident,
179                                                                   vec![dc_nested]);
180                     let allow_dead_code = attr::mk_attr_outer(DUMMY_SP,
181                                                               attr::mk_attr_id(),
182                                                               allow_dead_code_item);
183
184                     ast::Item {
185                         id,
186                         ident,
187                         attrs: attrs.into_iter()
188                             .filter(|attr| {
189                                 !attr.check_name("main") && !attr.check_name("start")
190                             })
191                             .chain(iter::once(allow_dead_code))
192                             .collect(),
193                         node,
194                         vis,
195                         span,
196                         tokens,
197                     }
198                 }),
199             EntryPointType::None |
200             EntryPointType::OtherMain => folded,
201         };
202
203         smallvec![folded]
204     }
205
206     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { mac }
207 }
208
209 /// Creates an item (specifically a module) that "pub use"s the tests passed in.
210 /// Each tested submodule will contain a similar reexport module that we will export
211 /// under the name of the original module. That is, `submod::__test_reexports` is
212 /// reexported like so `pub use submod::__test_reexports as submod`.
213 fn mk_reexport_mod(cx: &mut TestCtxt,
214                    parent: ast::NodeId,
215                    tests: Vec<Ident>,
216                    tested_submods: Vec<(Ident, Ident)>)
217                    -> (P<ast::Item>, Ident) {
218     let super_ = Ident::from_str("super");
219
220     let items = tests.into_iter().map(|r| {
221         cx.ext_cx.item_use_simple(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
222                                   cx.ext_cx.path(DUMMY_SP, vec![super_, r]))
223     }).chain(tested_submods.into_iter().map(|(r, sym)| {
224         let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]);
225         cx.ext_cx.item_use_simple_(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
226                                    Some(r), path)
227     })).collect();
228
229     let reexport_mod = ast::Mod {
230         inline: true,
231         inner: DUMMY_SP,
232         items,
233     };
234
235     let sym = Ident::with_empty_ctxt(Symbol::gensym("__test_reexports"));
236     let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
237     cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent);
238     let it = cx.ext_cx.monotonic_expander().fold_item(P(ast::Item {
239         ident: sym,
240         attrs: Vec::new(),
241         id: ast::DUMMY_NODE_ID,
242         node: ast::ItemKind::Mod(reexport_mod),
243         vis: dummy_spanned(ast::VisibilityKind::Public),
244         span: DUMMY_SP,
245         tokens: None,
246     })).pop().unwrap();
247
248     (it, sym)
249 }
250
251 /// Crawl over the crate, inserting test reexports and the test main function
252 fn generate_test_harness(sess: &ParseSess,
253                          resolver: &mut dyn Resolver,
254                          reexport_test_harness_main: Option<Symbol>,
255                          krate: ast::Crate,
256                          sd: &errors::Handler,
257                          features: &Features,
258                          test_runner: Option<ast::Path>) -> ast::Crate {
259     // Remove the entry points
260     let mut cleaner = EntryPointCleaner { depth: 0 };
261     let krate = cleaner.fold_crate(krate);
262
263     let mark = Mark::fresh(Mark::root());
264
265     let mut econfig = ExpansionConfig::default("test".to_string());
266     econfig.features = Some(features);
267
268     let cx = TestCtxt {
269         span_diagnostic: sd,
270         ext_cx: ExtCtxt::new(sess, econfig, resolver),
271         path: Vec::new(),
272         test_cases: Vec::new(),
273         reexport_test_harness_main,
274         // N.B., doesn't consider the value of `--crate-name` passed on the command line.
275         is_libtest: attr::find_crate_name(&krate.attrs).map(|s| s == "test").unwrap_or(false),
276         toplevel_reexport: None,
277         ctxt: SyntaxContext::empty().apply_mark(mark),
278         features,
279         test_runner
280     };
281
282     mark.set_expn_info(ExpnInfo {
283         call_site: DUMMY_SP,
284         def_site: None,
285         format: MacroAttribute(Symbol::intern("test_case")),
286         allow_internal_unstable: true,
287         allow_internal_unsafe: false,
288         local_inner_macros: false,
289         edition: hygiene::default_edition(),
290     });
291
292     TestHarnessGenerator {
293         cx,
294         tests: Vec::new(),
295         tested_submods: Vec::new(),
296     }.fold_crate(krate)
297 }
298
299 /// Craft a span that will be ignored by the stability lint's
300 /// call to source_map's `is_internal` check.
301 /// The expanded code calls some unstable functions in the test crate.
302 fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
303     sp.with_ctxt(cx.ctxt)
304 }
305
306 enum HasTestSignature {
307     Yes,
308     No(BadTestSignature),
309 }
310
311 #[derive(PartialEq)]
312 enum BadTestSignature {
313     NotEvenAFunction,
314     WrongTypeSignature,
315     NoArgumentsAllowed,
316     ShouldPanicOnlyWithNoArgs,
317 }
318
319 /// Creates a function item for use as the main function of a test build.
320 /// This function will call the `test_runner` as specified by the crate attribute
321 fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
322     // Writing this out by hand with 'ignored_span':
323     //        pub fn main() {
324     //            #![main]
325     //            test::test_main_static(::std::os::args().as_slice(), &[..tests]);
326     //        }
327     let sp = ignored_span(cx, DUMMY_SP);
328     let ecx = &cx.ext_cx;
329     let test_id = ecx.ident_of("test").gensym();
330
331     // test::test_main_static(...)
332     let mut test_runner = cx.test_runner.clone().unwrap_or(
333         ecx.path(sp, vec![
334             test_id, ecx.ident_of("test_main_static")
335         ]));
336
337     test_runner.span = sp;
338
339     let test_main_path_expr = ecx.expr_path(test_runner);
340     let call_test_main = ecx.expr_call(sp, test_main_path_expr,
341                                        vec![mk_tests_slice(cx)]);
342     let call_test_main = ecx.stmt_expr(call_test_main);
343
344     // #![main]
345     let main_meta = ecx.meta_word(sp, Symbol::intern("main"));
346     let main_attr = ecx.attribute(sp, main_meta);
347
348     // extern crate test as test_gensym
349     let test_extern_stmt = ecx.stmt_item(sp, ecx.item(sp,
350         test_id,
351         vec![],
352         ast::ItemKind::ExternCrate(Some(Symbol::intern("test")))
353     ));
354
355     // pub fn main() { ... }
356     let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
357
358     // If no test runner is provided we need to import the test crate
359     let main_body = if cx.test_runner.is_none() {
360         ecx.block(sp, vec![test_extern_stmt, call_test_main])
361     } else {
362         ecx.block(sp, vec![call_test_main])
363     };
364
365     let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], ast::FunctionRetTy::Ty(main_ret_ty)),
366                            ast::FnHeader::default(),
367                            ast::Generics::default(),
368                            main_body);
369
370     // Honor the reexport_test_harness_main attribute
371     let main_id = Ident::new(
372         cx.reexport_test_harness_main.unwrap_or(Symbol::gensym("main")),
373         sp);
374
375     P(ast::Item {
376         ident: main_id,
377         attrs: vec![main_attr],
378         id: ast::DUMMY_NODE_ID,
379         node: main,
380         vis: dummy_spanned(ast::VisibilityKind::Public),
381         span: sp,
382         tokens: None,
383     })
384
385 }
386
387 fn path_name_i(idents: &[Ident]) -> String {
388     let mut path_name = "".to_string();
389     let mut idents_iter = idents.iter().peekable();
390     while let Some(ident) = idents_iter.next() {
391         path_name.push_str(&ident.as_str());
392         if idents_iter.peek().is_some() {
393             path_name.push_str("::")
394         }
395     }
396     path_name
397 }
398
399 /// Creates a slice containing every test like so:
400 /// &[path::to::test1, path::to::test2]
401 fn mk_tests_slice(cx: &TestCtxt) -> P<ast::Expr> {
402     debug!("building test vector from {} tests", cx.test_cases.len());
403     let ref ecx = cx.ext_cx;
404
405     ecx.expr_vec_slice(DUMMY_SP,
406         cx.test_cases.iter().map(|test| {
407             ecx.expr_addr_of(test.span,
408                 ecx.expr_path(ecx.path(test.span, visible_path(cx, &test.path))))
409         }).collect())
410 }
411
412 /// Creates a path from the top-level __test module to the test via __test_reexports
413 fn visible_path(cx: &TestCtxt, path: &[Ident]) -> Vec<Ident>{
414     let mut visible_path = vec![];
415     match cx.toplevel_reexport {
416         Some(id) => visible_path.push(id),
417         None => {
418             cx.span_diagnostic.bug("expected to find top-level re-export name, but found None");
419         }
420     }
421     visible_path.extend_from_slice(path);
422     visible_path
423 }
424
425 fn is_test_case(i: &ast::Item) -> bool {
426     attr::contains_name(&i.attrs, "rustc_test_marker")
427 }
428
429 fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path> {
430     let test_attr = attr::find_by_name(&krate.attrs, "test_runner")?;
431     if let Some(meta_list) = test_attr.meta_item_list() {
432         if meta_list.len() != 1 {
433             sd.span_fatal(test_attr.span(),
434                 "#![test_runner(..)] accepts exactly 1 argument").raise()
435         }
436         Some(meta_list[0].word().as_ref().unwrap().ident.clone())
437     } else {
438         sd.span_fatal(test_attr.span(),
439             "test_runner must be of the form #[test_runner(..)]").raise()
440     }
441 }