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 should be compiled with <!-- date: 2021-03 --> ` nightly-2021-03-28 `
8
+ The following should be compiled with <!-- date: 2022-05 --> ` nightly-2022-04-30 `
9
9
(see [ here] [ example ] for the complete example):
10
10
11
11
[ example ] : https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-interacting-with-the-ast.rs
@@ -24,9 +24,10 @@ rustc_interface::run_compiler(config, |compiler| {
24
24
// Analyze the crate and inspect the types under the cursor.
25
25
queries . global_ctxt (). unwrap (). take (). enter (| tcx | {
26
26
// Every compilation contains a single crate.
27
- let hir_krate = tcx . hir (). krate () ;
27
+ let hir_krate = tcx . hir ();
28
28
// Iterate over the top-level items in the crate, looking for the main function.
29
- for (_ , item ) in & hir_krate . items {
29
+ for id in hir_krate . items () {
30
+ let item = hir_krate . item (id );
30
31
// Use pattern-matching to find a specific node inside the main function.
31
32
if let rustc_hir :: ItemKind :: Fn (_ , _ , body_id ) = item . kind {
32
33
let expr = & tcx . hir (). body (body_id ). value;
@@ -36,7 +37,7 @@ rustc_interface::run_compiler(config, |compiler| {
36
37
let hir_id = expr . hir_id; // hir_id identifies the string "Hello, world!"
37
38
let def_id = tcx . hir (). local_def_id (item . hir_id ()); // def_id identifies the main function
38
39
let ty = tcx . typeck (def_id ). node_type (hir_id );
39
- println! (" {:?}: {:?}" , expr , ty ); // prints expr(HirId { owner: DefIndex(3), local_id: 4 }: "Hello, world!"): &'static str
40
+ println! (" {:?}: {:?}" , expr , ty );
40
41
}
41
42
}
42
43
}
0 commit comments