How to add nodes to AST after macro expansion

#1

I am trying to write a little instrumentation tool for Rust.

For this purpose I’m using the compiler driver customisation APIs consisting of the CompilerCallstrait and the CompileController struct, which are explained very nicely in this project stupid-stats.
The CompileController struct provides the after_* fields to hook in after each phase of the compilation process. By specifying a callback function it is possible to execute code between these phases.

fn build_controller(
    self: Box<Self>,
    _: &Session,
    _: &getopts::Matches,
) -> CompileController<'a> {
    // Creates the default CompileController
    let mut controller = CompileController::basic();

    // Hook into the compilation after macro expansion and name resolution
    controller.after_expand.callback = Box::new(|state: &mut CompileState| {
        // Get the AST after expansion
        let expanded_crate = state.expanded_crate.unwrap();
        // Add a node to the AST...
    }

For this instrumentation tool to work it is important that the nodes are added to the AST after macro expansion, but when adding nodes to the AST I get the following error when compiling another program with my custom rustc compiler:

thread 'rustc' panicked at 'Trying to resolve dummy id', src/librustc_resolve/lib.rs:3841:29

Apparently the ids of the nodes I added do not fit in with the ids resolved by name resolution.

Is there any way I can easily (preferably not having to worry about name resolution) add nodes to the AST after macro expansion and name resolution?

0 Likes