44
55## Getting the type of an expression
66
7- To get the type of an expression, use the ` global_ctxt ` to get a ` TyCtxt ` :
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 `
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
812
913``` rust
10- // See https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-interacting-with-the-ast.rs for complete program.
1114let config = rustc_interface :: Config {
1215 input : config :: Input :: Str {
1316 name : source_map :: FileName :: Custom (" main.rs" . to_string ()),
@@ -21,17 +24,17 @@ rustc_interface::run_compiler(config, |compiler| {
2124 // Analyze the crate and inspect the types under the cursor.
2225 queries . global_ctxt (). unwrap (). take (). enter (| tcx | {
2326 // Every compilation contains a single crate.
24- let krate = tcx . hir (). krate ();
27+ let hir_krate = tcx . hir (). krate ();
2528 // Iterate over the top-level items in the crate, looking for the main function.
26- for (_ , item ) in & krate . items {
29+ for (_ , item ) in & hir_krate . items {
2730 // Use pattern-matching to find a specific node inside the main function.
2831 if let rustc_hir :: ItemKind :: Fn (_ , _ , body_id ) = item . kind {
2932 let expr = & tcx . hir (). body (body_id ). value;
3033 if let rustc_hir :: ExprKind :: Block (block , _ ) = expr . kind {
3134 if let rustc_hir :: StmtKind :: Local (local ) = block . stmts[0 ]. kind {
3235 if let Some (expr ) = local . init {
3336 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
37+ let def_id = tcx . hir (). local_def_id (item . hir_id () ); // def_id identifies the main function
3538 let ty = tcx . typeck (def_id ). node_type (hir_id );
3639 println! (" {:?}: {:?}" , expr , ty ); // prints expr(HirId { owner: DefIndex(3), local_id: 4 }: "Hello, world!"): &'static str
3740 }
0 commit comments