|
5 | 5 | ## Getting the type of an expression
|
6 | 6 |
|
7 | 7 | To get the type of an expression, use the `global_ctxt` to get a `TyCtxt`.
|
8 |
| -The following was tested with <!-- date-check: Feb 2023 --> `nightly-2023-02-06` |
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 |
| 8 | +The following was tested with <!-- date-check: Feb 2023 --> `nightly-2023-02-13`: |
12 | 9 |
|
13 | 10 | ```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().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 = item.hir_id().owner.def_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 |
| -}); |
| 11 | +{{#include ../examples/rustc-driver-interacting-with-the-ast.rs}} |
49 | 12 | ```
|
0 commit comments