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