Skip to content

Commit f63b600

Browse files
committed
How to get the type of an expression using rustc_interface
1 parent 506d2d3 commit f63b600

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
- [High-level overview of the compiler source](./high-level-overview.md)
3737
- [The Rustc Driver and Interface](./rustc-driver.md)
3838
- [Rustdoc](./rustdoc.md)
39+
- [Interacting with the AST](./rustc-driver-interacting-with-the-ast.md)
3940
- [Queries: demand-driven compilation](./query.md)
4041
- [The Query Evaluation Model in Detail](./queries/query-evaluation-model-in-detail.md)
4142
- [Incremental compilation](./queries/incremental-compilation.md)
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Interacting with the AST
2+
3+
`rustc_interface` allows you to interact with Rust code at various stages of compilation.
4+
5+
## Getting the type of an expression
6+
7+
To get the type of an expression, use the `global_ctxt` to get a `TyCtxt`:
8+
9+
```rust
10+
// In this example, config specifies the rust program:
11+
// fn main() { let message = \"Hello, world!\"; println!(\"{}\", message); }
12+
// Our goal is to get the type of the string literal "Hello, world!".
13+
//
14+
// See https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-example.rs for a complete example of configuring rustc_interface
15+
rustc_interface::run_compiler(config, |compiler| {
16+
compiler.enter(|queries| {
17+
// Analyze the crate and inspect the types under the cursor.
18+
queries.global_ctxt().unwrap().take().enter(|tcx| {
19+
// Every compilation contains a single crate.
20+
let krate = tcx.hir().krate();
21+
// Iterate over the top-level items in the crate, looking for the main function.
22+
for (_, item) in &krate.items {
23+
// Use pattern-matching to find a specific node inside the main function.
24+
if let rustc_hir::ItemKind::Fn(_, _, body_id) = item.kind {
25+
let expr = &tcx.hir().body(body_id).value;
26+
if let rustc_hir::ExprKind::Block(block, _) = expr.kind {
27+
if let rustc_hir::StmtKind::Local(local) = block.stmts[0].kind {
28+
if let Some(expr) = local.init {
29+
let hir_id = expr.hir_id; // hir_id identifies the string "Hello, world!"
30+
let def_id = tcx.hir().local_def_id(item.hir_id); // def_id identifies the main function
31+
let ty = tcx.typeck_tables_of(def_id).node_type(hir_id);
32+
println!("{:?}: {:?}", expr, ty); // prints expr(HirId { owner: DefIndex(3), local_id: 4 }: "Hello, world!"): &'static str
33+
}
34+
}
35+
}
36+
}
37+
}
38+
})
39+
});
40+
});
41+
```

0 commit comments

Comments
 (0)