DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Git (4fb54ed484)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
use crate::tests::{matches_codepattern, string_to_crate};

use rustc_ast::ast;
use rustc_ast::mut_visit::{self, MutVisitor};
use rustc_ast::with_default_globals;
use rustc_ast_pretty::pprust;
use rustc_span::symbol::Ident;

// This version doesn't care about getting comments or doc-strings in.
fn fake_print_crate(s: &mut pprust::State<'_>, krate: &ast::Crate) {
    s.print_mod(&krate.module, &krate.attrs)
}

// Change every identifier to "zz".
struct ToZzIdentMutVisitor;

impl MutVisitor for ToZzIdentMutVisitor {
    fn visit_ident(&mut self, ident: &mut Ident) {
        *ident = Ident::from_str("zz");
    }
    fn visit_mac(&mut self, mac: &mut ast::MacCall) {
        mut_visit::noop_visit_mac(mac, self)
    }
}

// Maybe add to `expand.rs`.
macro_rules! assert_pred {
    ($pred:expr, $predname:expr, $a:expr , $b:expr) => {{
        let pred_val = $pred;
        let a_val = $a;
        let b_val = $b;
        if !(pred_val(&a_val, &b_val)) {
            panic!("expected args satisfying {}, got {} and {}", $predname, a_val, b_val);
        }
    }};
}

// Make sure idents get transformed everywhere.
#[test]
fn ident_transformation() {
    with_default_globals(|| {
        let mut zz_visitor = ToZzIdentMutVisitor;
        let mut krate =
            string_to_crate("#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
        zz_visitor.visit_crate(&mut krate);
        assert_pred!(
            matches_codepattern,
            "matches_codepattern",
            pprust::to_string(|s| fake_print_crate(s, &krate)),
            "#[zz]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string()
        );
    })
}

// Make sure idents get transformed even inside macro defs.
#[test]
fn ident_transformation_in_defs() {
    with_default_globals(|| {
        let mut zz_visitor = ToZzIdentMutVisitor;
        let mut krate = string_to_crate(
            "macro_rules! a {(b $c:expr $(d $e:token)f+ => \
            (g $(d $d $e)+))} "
                .to_string(),
        );
        zz_visitor.visit_crate(&mut krate);
        assert_pred!(
            matches_codepattern,
            "matches_codepattern",
            pprust::to_string(|s| fake_print_crate(s, &krate)),
            "macro_rules! zz{(zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+))}".to_string()
        );
    })
}