]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/test.rs
Auto merge of #61212 - alexcrichton:skip-rustc, r=pietroalbini
[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 HasTestSignature::*;
7
8 use std::iter;
9 use std::slice;
10 use std::mem;
11 use std::vec;
12
13 use log::debug;
14 use smallvec::{smallvec, SmallVec};
15 use syntax_pos::{DUMMY_SP, NO_EXPANSION, Span, SourceFile, BytePos};
16
17 use crate::attr::{self, HasAttrs};
18 use crate::source_map::{self, SourceMap, ExpnInfo, MacroAttribute, dummy_spanned, respan};
19 use crate::config;
20 use crate::entry::{self, EntryPointType};
21 use crate::ext::base::{ExtCtxt, Resolver};
22 use crate::ext::build::AstBuilder;
23 use crate::ext::expand::ExpansionConfig;
24 use crate::ext::hygiene::{self, Mark, SyntaxContext};
25 use crate::mut_visit::{*, ExpectOne};
26 use crate::feature_gate::Features;
27 use crate::util::map_in_place::MapInPlace;
28 use crate::parse::{token, ParseSess};
29 use crate::print::pprust;
30 use crate::ast::{self, Ident};
31 use crate::ptr::P;
32 use crate::symbol::{self, Symbol, kw, sym};
33 use crate::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: &mut ast::Crate,
61                           span_diagnostic: &errors::Handler,
62                           features: &Features) {
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, sym::reexport_test_harness_main);
69
70     // Do this here so that the test_runner crate attribute gets marked as used
71     // even in non-test builds
72     let test_runner = get_test_runner(span_diagnostic, &krate);
73
74     if should_test {
75         generate_test_harness(sess, resolver, reexport_test_harness_main,
76                               krate, span_diagnostic, features, test_runner)
77     }
78 }
79
80 struct TestHarnessGenerator<'a> {
81     cx: TestCtxt<'a>,
82     tests: Vec<Ident>,
83
84     // submodule name, gensym'd identifier for re-exports
85     tested_submods: Vec<(Ident, Ident)>,
86 }
87
88 impl<'a> MutVisitor for TestHarnessGenerator<'a> {
89     fn visit_crate(&mut self, c: &mut ast::Crate) {
90         noop_visit_crate(c, self);
91
92         // Create a main function to run our tests
93         let test_main = {
94             let unresolved = mk_main(&mut self.cx);
95             self.cx.ext_cx.monotonic_expander().flat_map_item(unresolved).pop().unwrap()
96         };
97
98         c.module.items.push(test_main);
99     }
100
101     fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
102         let ident = i.ident;
103         if ident.name != kw::Invalid {
104             self.cx.path.push(ident);
105         }
106         debug!("current path: {}", path_name_i(&self.cx.path));
107
108         let mut item = i.into_inner();
109         if is_test_case(&item) {
110             debug!("this is a test item");
111
112             let test = Test {
113                 span: item.span,
114                 path: self.cx.path.clone(),
115             };
116             self.cx.test_cases.push(test);
117             self.tests.push(item.ident);
118         }
119
120         // We don't want to recurse into anything other than mods, since
121         // mods or tests inside of functions will break things
122         if let ast::ItemKind::Mod(mut module) = item.node {
123             let tests = mem::replace(&mut self.tests, Vec::new());
124             let tested_submods = mem::replace(&mut self.tested_submods, Vec::new());
125             noop_visit_mod(&mut module, self);
126             let tests = mem::replace(&mut self.tests, tests);
127             let tested_submods = mem::replace(&mut self.tested_submods, tested_submods);
128
129             if !tests.is_empty() || !tested_submods.is_empty() {
130                 let (it, sym) = mk_reexport_mod(&mut self.cx, item.id, tests, tested_submods);
131                 module.items.push(it);
132
133                 if !self.cx.path.is_empty() {
134                     self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym));
135                 } else {
136                     debug!("pushing nothing, sym: {:?}", sym);
137                     self.cx.toplevel_reexport = Some(sym);
138                 }
139             }
140             item.node = ast::ItemKind::Mod(module);
141         }
142         if ident.name != kw::Invalid {
143             self.cx.path.pop();
144         }
145         smallvec![P(item)]
146     }
147
148     fn visit_mac(&mut self, _mac: &mut ast::Mac) {
149         // Do nothing.
150     }
151 }
152
153 /// A folder used to remove any entry points (like fn main) because the harness
154 /// generator will provide its own
155 struct EntryPointCleaner {
156     // Current depth in the ast
157     depth: usize,
158 }
159
160 impl MutVisitor for EntryPointCleaner {
161     fn flat_map_item(&mut self, i: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
162         self.depth += 1;
163         let item = noop_flat_map_item(i, self).expect_one("noop did something");
164         self.depth -= 1;
165
166         // Remove any #[main] or #[start] from the AST so it doesn't
167         // clash with the one we're going to add, but mark it as
168         // #[allow(dead_code)] to avoid printing warnings.
169         let item = match entry::entry_point_type(&item, self.depth) {
170             EntryPointType::MainNamed |
171             EntryPointType::MainAttr |
172             EntryPointType::Start =>
173                 item.map(|ast::Item {id, ident, attrs, node, vis, span, tokens}| {
174                     let allow_ident = Ident::with_empty_ctxt(sym::allow);
175                     let dc_nested = attr::mk_nested_word_item(Ident::from_str("dead_code"));
176                     let allow_dead_code_item = attr::mk_list_item(DUMMY_SP, allow_ident,
177                                                                   vec![dc_nested]);
178                     let allow_dead_code = attr::mk_attr_outer(DUMMY_SP,
179                                                               attr::mk_attr_id(),
180                                                               allow_dead_code_item);
181
182                     ast::Item {
183                         id,
184                         ident,
185                         attrs: attrs.into_iter()
186                             .filter(|attr| {
187                                 !attr.check_name(sym::main) && !attr.check_name(sym::start)
188                             })
189                             .chain(iter::once(allow_dead_code))
190                             .collect(),
191                         node,
192                         vis,
193                         span,
194                         tokens,
195                     }
196                 }),
197             EntryPointType::None |
198             EntryPointType::OtherMain => item,
199         };
200
201         smallvec![item]
202     }
203
204     fn visit_mac(&mut self, _mac: &mut ast::Mac) {
205         // Do nothing.
206     }
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::with_empty_ctxt(kw::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 name = Ident::from_str("__test_reexports").gensym();
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().flat_map_item(P(ast::Item {
239         ident: name,
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, name)
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: &mut ast::Crate,
256                          sd: &errors::Handler,
257                          features: &Features,
258                          test_runner: Option<ast::Path>) {
259     // Remove the entry points
260     let mut cleaner = EntryPointCleaner { depth: 0 };
261     cleaner.visit_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)
276             .map(|s| s == sym::test).unwrap_or(false),
277         toplevel_reexport: None,
278         ctxt: SyntaxContext::empty().apply_mark(mark),
279         features,
280         test_runner
281     };
282
283     mark.set_expn_info(ExpnInfo {
284         call_site: DUMMY_SP,
285         def_site: None,
286         format: MacroAttribute(sym::test_case),
287         allow_internal_unstable: Some(vec![sym::main, sym::test, sym::rustc_attrs].into()),
288         allow_internal_unsafe: false,
289         local_inner_macros: false,
290         edition: sess.edition,
291     });
292
293     TestHarnessGenerator {
294         cx,
295         tests: Vec::new(),
296         tested_submods: Vec::new(),
297     }.visit_crate(krate);
298 }
299
300 /// Craft a span that will be ignored by the stability lint's
301 /// call to source_map's `is_internal` check.
302 /// The expanded code calls some unstable functions in the test crate.
303 fn ignored_span(cx: &TestCtxt<'_>, sp: Span) -> Span {
304     sp.with_ctxt(cx.ctxt)
305 }
306
307 enum HasTestSignature {
308     Yes,
309     No(BadTestSignature),
310 }
311
312 #[derive(PartialEq)]
313 enum BadTestSignature {
314     NotEvenAFunction,
315     WrongTypeSignature,
316     NoArgumentsAllowed,
317     ShouldPanicOnlyWithNoArgs,
318 }
319
320 /// Creates a function item for use as the main function of a test build.
321 /// This function will call the `test_runner` as specified by the crate attribute
322 fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
323     // Writing this out by hand with 'ignored_span':
324     //        pub fn main() {
325     //            #![main]
326     //            test::test_main_static(&[..tests]);
327     //        }
328     let sp = ignored_span(cx, DUMMY_SP);
329     let ecx = &cx.ext_cx;
330     let test_id = ecx.ident_of("test").gensym();
331
332     // test::test_main_static(...)
333     let mut test_runner = cx.test_runner.clone().unwrap_or(
334         ecx.path(sp, vec![
335             test_id, ecx.ident_of("test_main_static")
336         ]));
337
338     test_runner.span = sp;
339
340     let test_main_path_expr = ecx.expr_path(test_runner);
341     let call_test_main = ecx.expr_call(sp, test_main_path_expr,
342                                        vec![mk_tests_slice(cx)]);
343     let call_test_main = ecx.stmt_expr(call_test_main);
344
345     // #![main]
346     let main_meta = ecx.meta_word(sp, sym::main);
347     let main_attr = ecx.attribute(sp, main_meta);
348
349     // extern crate test as test_gensym
350     let test_extern_stmt = ecx.stmt_item(sp, ecx.item(sp,
351         test_id,
352         vec![],
353         ast::ItemKind::ExternCrate(Some(sym::test))
354     ));
355
356     // pub fn main() { ... }
357     let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![]));
358
359     // If no test runner is provided we need to import the test crate
360     let main_body = if cx.test_runner.is_none() {
361         ecx.block(sp, vec![test_extern_stmt, call_test_main])
362     } else {
363         ecx.block(sp, vec![call_test_main])
364     };
365
366     let main = ast::ItemKind::Fn(ecx.fn_decl(vec![], ast::FunctionRetTy::Ty(main_ret_ty)),
367                            ast::FnHeader::default(),
368                            ast::Generics::default(),
369                            main_body);
370
371     // Honor the reexport_test_harness_main attribute
372     let main_id = match cx.reexport_test_harness_main {
373         Some(sym) => Ident::new(sym, sp),
374         None => Ident::from_str_and_span("main", sp).gensym(),
375     };
376
377     P(ast::Item {
378         ident: main_id,
379         attrs: vec![main_attr],
380         id: ast::DUMMY_NODE_ID,
381         node: main,
382         vis: dummy_spanned(ast::VisibilityKind::Public),
383         span: sp,
384         tokens: None,
385     })
386
387 }
388
389 fn path_name_i(idents: &[Ident]) -> String {
390     let mut path_name = "".to_string();
391     let mut idents_iter = idents.iter().peekable();
392     while let Some(ident) = idents_iter.next() {
393         path_name.push_str(&ident.as_str());
394         if idents_iter.peek().is_some() {
395             path_name.push_str("::")
396         }
397     }
398     path_name
399 }
400
401 /// Creates a slice containing every test like so:
402 /// &[path::to::test1, path::to::test2]
403 fn mk_tests_slice(cx: &TestCtxt<'_>) -> P<ast::Expr> {
404     debug!("building test vector from {} tests", cx.test_cases.len());
405     let ref ecx = cx.ext_cx;
406
407     ecx.expr_vec_slice(DUMMY_SP,
408         cx.test_cases.iter().map(|test| {
409             ecx.expr_addr_of(test.span,
410                 ecx.expr_path(ecx.path(test.span, visible_path(cx, &test.path))))
411         }).collect())
412 }
413
414 /// Creates a path from the top-level __test module to the test via __test_reexports
415 fn visible_path(cx: &TestCtxt<'_>, path: &[Ident]) -> Vec<Ident>{
416     let mut visible_path = vec![];
417     match cx.toplevel_reexport {
418         Some(id) => visible_path.push(id),
419         None => {
420             cx.span_diagnostic.bug("expected to find top-level re-export name, but found None");
421         }
422     }
423     visible_path.extend_from_slice(path);
424     visible_path
425 }
426
427 fn is_test_case(i: &ast::Item) -> bool {
428     attr::contains_name(&i.attrs, sym::rustc_test_marker)
429 }
430
431 fn get_test_runner(sd: &errors::Handler, krate: &ast::Crate) -> Option<ast::Path> {
432     let test_attr = attr::find_by_name(&krate.attrs, sym::test_runner)?;
433     test_attr.meta_item_list().map(|meta_list| {
434         if meta_list.len() != 1 {
435             sd.span_fatal(test_attr.span,
436                 "#![test_runner(..)] accepts exactly 1 argument").raise()
437         }
438         match meta_list[0].meta_item() {
439             Some(meta_item) if meta_item.is_word() => meta_item.path.clone(),
440             _ => sd.span_fatal(test_attr.span, "`test_runner` argument must be a path").raise()
441         }
442     })
443 }