Chapter 3.2. Code Analysis in The Backend

Developers can add a new query to the compiler and invoke the query during compilation. This requires rebuilding the compiler source code, which may take a little while.

Add A New Query

Refering to the official Rust compiler development guide, There are two steps to add a query:

  1. Declare the query name, its arguments and description in the compiler/rustc_middle/src/query/mod.rs.
rustc_queries! {
   query new_query(_: DefId) -> () {
        desc { "a new query with novel features" }
   }
}
  1. Supply query providers where needed in compiler/rustc_mir_transform/src/lib.rs.
pub fn provide(providers: &mut Providers) {
    *providers = Providers {
        new_query,
        ..*providers
    };
}
fn new_query<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> () {
    ...//implementation
}

Invoke The Query

In this step, we set an environment variable which is responsible for invoking the newly added query. The correponding file for managing such variables is compiler/rustc_interface/src/passes.rs.

if env::var_os("RUSTC_BOOTSTRAP").is_none() && env::var_os("NEW_QUERY").is_some() {
    sess.time("new_query", || {
    println!("Starting new_query...");
            tcx.hir().par_body_owners(|def_id| tcx.ensure().new_query(def_id));
    });
}