]> git.proxmox.com Git - rustc.git/blob - src/doc/rustc-dev-guide/src/rustc-driver-interacting-with-the-ast.md
New upstream version 1.44.1+dfsg1
[rustc.git] / src / doc / rustc-dev-guide / src / rustc-driver-interacting-with-the-ast.md
1 # Example: Type checking through `rustc_interface`
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 NOTE: For the example to compile, you will need to first run the following:
8
9 rustup component add rustc-dev
10
11 To get the type of an expression, use the `global_ctxt` to get a `TyCtxt`:
12
13 ```rust
14 // In this example, config specifies the rust program:
15 // fn main() { let message = \"Hello, world!\"; println!(\"{}\", message); }
16 // Our goal is to get the type of the string literal "Hello, world!".
17 //
18 // See https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-example.rs for a complete example of configuring rustc_interface
19 rustc_interface::run_compiler(config, |compiler| {
20 compiler.enter(|queries| {
21 // Analyze the crate and inspect the types under the cursor.
22 queries.global_ctxt().unwrap().take().enter(|tcx| {
23 // Every compilation contains a single crate.
24 let krate = tcx.hir().krate();
25 // Iterate over the top-level items in the crate, looking for the main function.
26 for (_, item) in &krate.items {
27 // Use pattern-matching to find a specific node inside the main function.
28 if let rustc_hir::ItemKind::Fn(_, _, body_id) = item.kind {
29 let expr = &tcx.hir().body(body_id).value;
30 if let rustc_hir::ExprKind::Block(block, _) = expr.kind {
31 if let rustc_hir::StmtKind::Local(local) = block.stmts[0].kind {
32 if let Some(expr) = local.init {
33 let hir_id = expr.hir_id; // hir_id identifies the string "Hello, world!"
34 let def_id = tcx.hir().local_def_id(item.hir_id); // def_id identifies the main function
35 let ty = tcx.typeck_tables_of(def_id).node_type(hir_id);
36 println!("{:?}: {:?}", expr, ty); // prints expr(HirId { owner: DefIndex(3), local_id: 4 }: "Hello, world!"): &'static str
37 }
38 }
39 }
40 }
41 }
42 })
43 });
44 });
45 ```