]> git.proxmox.com Git - rustc.git/blob - src/doc/rustc-dev-guide/src/rustc-driver-interacting-with-the-ast.md
New upstream version 1.63.0+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 To get the type of an expression, use the `global_ctxt` to get a `TyCtxt`.
8 The following was tested with <!-- date: 2022-06 --> `nightly-2022-06-05`
9 (see [here][example] for the complete example):
10
11 [example]: https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-interacting-with-the-ast.rs
12
13 ```rust
14 let config = rustc_interface::Config {
15 input: config::Input::Str {
16 name: source_map::FileName::Custom("main.rs".to_string()),
17 input: "fn main() { let message = \"Hello, world!\"; println!(\"{}\", message); }"
18 .to_string(),
19 },
20 /* other config */
21 };
22 rustc_interface::run_compiler(config, |compiler| {
23 compiler.enter(|queries| {
24 // Analyze the crate and inspect the types under the cursor.
25 queries.global_ctxt().unwrap().take().enter(|tcx| {
26 // Every compilation contains a single crate.
27 let hir_krate = tcx.hir();
28 // Iterate over the top-level items in the crate, looking for the main function.
29 for id in hir_krate.items() {
30 let item = hir_krate.item(id);
31 // Use pattern-matching to find a specific node inside the main function.
32 if let rustc_hir::ItemKind::Fn(_, _, body_id) = item.kind {
33 let expr = &tcx.hir().body(body_id).value;
34 if let rustc_hir::ExprKind::Block(block, _) = expr.kind {
35 if let rustc_hir::StmtKind::Local(local) = block.stmts[0].kind {
36 if let Some(expr) = local.init {
37 let hir_id = expr.hir_id; // hir_id identifies the string "Hello, world!"
38 let def_id = tcx.hir().local_def_id(item.hir_id()); // def_id identifies the main function
39 let ty = tcx.typeck(def_id).node_type(hir_id);
40 println!("{:?}: {:?}", expr, ty);
41 }
42 }
43 }
44 }
45 }
46 })
47 });
48 });
49 ```