55## Getting the type of an expression
66
77To 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 `
99(see [ here] [ example ] for the complete example):
1010
1111[ 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| {
2424 // Analyze the crate and inspect the types under the cursor.
2525 queries . global_ctxt (). unwrap (). take (). enter (| tcx | {
2626 // Every compilation contains a single crate.
27- let hir_krate = tcx . hir (). krate () ;
27+ let hir_krate = tcx . hir ();
2828 // 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 );
3031 // Use pattern-matching to find a specific node inside the main function.
3132 if let rustc_hir :: ItemKind :: Fn (_ , _ , body_id ) = item . kind {
3233 let expr = & tcx . hir (). body (body_id ). value;
@@ -36,7 +37,7 @@ rustc_interface::run_compiler(config, |compiler| {
3637 let hir_id = expr . hir_id; // hir_id identifies the string "Hello, world!"
3738 let def_id = tcx . hir (). local_def_id (item . hir_id ()); // def_id identifies the main function
3839 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 );
4041 }
4142 }
4243 }
0 commit comments