Getting the correct BodyId for an Expr/Local

I need to access type information for locals and expr, it seems that I need the BodyId for this.

I am not quite sure how to find the correct bodyid for a given expr/local and that is why I am currently iterating over every body in the crate.

fn visit_expr(&mut self, ex: &'v Expr) {
    let ty = self.map
        .krate()
        .bodies
        .iter()
        .filter_map(|(&id, _)| self.ty_ctx.body_tables(id).expr_ty_opt(ex))
        .nth(0);
    println!("ty = {:?}", ty);
    walk_expr(self, ex);
}

fn visit_local(&mut self, l: &'v Local) {
    walk_local(self, l);
    let ty: Vec<_> = self.map
        .krate()
        .bodies
        .iter()
        .filter_map(|(&id, _)| self.ty_ctx.body_tables(id).node_id_to_type_opt(l.hir_id))
        .collect();
    println!("ty = {:?}", ty);
}

But this sometimes results in more than one type and the first type is probably not always correct.

So I need to find the correct body for a given expr/local, how would I do that? Do I need to do this manually while traversing over the ast or is there something that maps from nodeid to bodyid?

self.map is a hir::map::Map

I have also seen self.map.walk_parent_nodes(..) but a Node doesn’t contain a body.

You can add an impl for visit_body, and store the body id (or even the body_tables) in Self

fn visit_body(...) {
    // take the old body_tables
    // insert new body_tables
    walk_body(...)
    // reinsert the old body_tables
}
1 Like

Thanks, I wasn’t quite sure if I needed to do that.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.