]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/mut_visit/tests.rs
38ff594b6e9c12482e9443bbd11b5877ede20ac1
[rust.git] / compiler / rustc_expand / src / mut_visit / tests.rs
1 use crate::tests::{matches_codepattern, string_to_crate};
2
3 use rustc_ast as ast;
4 use rustc_ast::mut_visit::{self, MutVisitor};
5 use rustc_ast_pretty::pprust;
6 use rustc_span::symbol::Ident;
7 use rustc_span::with_default_session_globals;
8
9 // This version doesn't care about getting comments or doc-strings in.
10 fn fake_print_crate(s: &mut pprust::State<'_>, krate: &ast::Crate) {
11     s.print_mod(&krate.module, &krate.attrs)
12 }
13
14 // Change every identifier to "zz".
15 struct ToZzIdentMutVisitor;
16
17 impl MutVisitor for ToZzIdentMutVisitor {
18     fn visit_ident(&mut self, ident: &mut Ident) {
19         *ident = Ident::from_str("zz");
20     }
21     fn visit_mac(&mut self, mac: &mut ast::MacCall) {
22         mut_visit::noop_visit_mac(mac, self)
23     }
24 }
25
26 // Maybe add to `expand.rs`.
27 macro_rules! assert_pred {
28     ($pred:expr, $predname:expr, $a:expr , $b:expr) => {{
29         let pred_val = $pred;
30         let a_val = $a;
31         let b_val = $b;
32         if !(pred_val(&a_val, &b_val)) {
33             panic!("expected args satisfying {}, got {} and {}", $predname, a_val, b_val);
34         }
35     }};
36 }
37
38 // Make sure idents get transformed everywhere.
39 #[test]
40 fn ident_transformation() {
41     with_default_session_globals(|| {
42         let mut zz_visitor = ToZzIdentMutVisitor;
43         let mut krate =
44             string_to_crate("#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
45         zz_visitor.visit_crate(&mut krate);
46         assert_pred!(
47             matches_codepattern,
48             "matches_codepattern",
49             pprust::to_string(|s| fake_print_crate(s, &krate)),
50             "#[zz]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string()
51         );
52     })
53 }
54
55 // Make sure idents get transformed even inside macro defs.
56 #[test]
57 fn ident_transformation_in_defs() {
58     with_default_session_globals(|| {
59         let mut zz_visitor = ToZzIdentMutVisitor;
60         let mut krate = string_to_crate(
61             "macro_rules! a {(b $c:expr $(d $e:token)f+ => \
62             (g $(d $d $e)+))} "
63                 .to_string(),
64         );
65         zz_visitor.visit_crate(&mut krate);
66         assert_pred!(
67             matches_codepattern,
68             "matches_codepattern",
69             pprust::to_string(|s| fake_print_crate(s, &krate)),
70             "macro_rules! zz{(zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+))}".to_string()
71         );
72     })
73 }