4
4
5
5
## Getting the type of an expression
6
6
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
8
12
9
13
``` rust
10
- // See https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-interacting-with-the-ast.rs for complete program.
11
14
let config = rustc_interface :: Config {
12
15
input : config :: Input :: Str {
13
16
name : source_map :: FileName :: Custom (" main.rs" . to_string ()),
@@ -21,17 +24,17 @@ rustc_interface::run_compiler(config, |compiler| {
21
24
// Analyze the crate and inspect the types under the cursor.
22
25
queries . global_ctxt (). unwrap (). take (). enter (| tcx | {
23
26
// Every compilation contains a single crate.
24
- let krate = tcx . hir (). krate ();
27
+ let hir_krate = tcx . hir (). krate ();
25
28
// 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 {
27
30
// Use pattern-matching to find a specific node inside the main function.
28
31
if let rustc_hir :: ItemKind :: Fn (_ , _ , body_id ) = item . kind {
29
32
let expr = & tcx . hir (). body (body_id ). value;
30
33
if let rustc_hir :: ExprKind :: Block (block , _ ) = expr . kind {
31
34
if let rustc_hir :: StmtKind :: Local (local ) = block . stmts[0 ]. kind {
32
35
if let Some (expr ) = local . init {
33
36
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
35
38
let ty = tcx . typeck (def_id ). node_type (hir_id );
36
39
println! (" {:?}: {:?}" , expr , ty ); // prints expr(HirId { owner: DefIndex(3), local_id: 4 }: "Hello, world!"): &'static str
37
40
}
0 commit comments