]> git.proxmox.com Git - rustc.git/blame - src/doc/rustc-dev-guide/examples/rustc-driver-interacting-with-the-ast.rs
New upstream version 1.70.0+dfsg1
[rustc.git] / src / doc / rustc-dev-guide / examples / rustc-driver-interacting-with-the-ast.rs
CommitLineData
6a06907d
XL
1#![feature(rustc_private)]
2
6a06907d 3extern crate rustc_ast_pretty;
9ffffee4 4extern crate rustc_driver;
6a06907d
XL
5extern crate rustc_error_codes;
6extern crate rustc_errors;
7extern crate rustc_hash;
8extern crate rustc_hir;
9extern crate rustc_interface;
10extern crate rustc_session;
11extern crate rustc_span;
12
923072b8
FG
13use std::{path, process, str};
14
6a06907d
XL
15use rustc_ast_pretty::pprust::item_to_string;
16use rustc_errors::registry;
04454e1e 17use rustc_session::config::{self, CheckCfg};
6a06907d 18use rustc_span::source_map;
6a06907d
XL
19
20fn main() {
21 let out = process::Command::new("rustc")
22 .arg("--print=sysroot")
23 .current_dir(".")
24 .output()
25 .unwrap();
26 let sysroot = str::from_utf8(&out.stdout).unwrap().trim();
27 let config = rustc_interface::Config {
28 opts: config::Options {
29 maybe_sysroot: Some(path::PathBuf::from(sysroot)),
30 ..config::Options::default()
31 },
32 input: config::Input::Str {
33 name: source_map::FileName::Custom("main.rs".to_string()),
923072b8
FG
34 input: r#"
35fn main() {
36 let message = "Hello, World!";
37 println!("{message}");
38}
39"#
40 .to_string(),
6a06907d 41 },
6a06907d 42 crate_cfg: rustc_hash::FxHashSet::default(),
04454e1e 43 crate_check_cfg: CheckCfg::default(),
6a06907d
XL
44 output_dir: None,
45 output_file: None,
46 file_loader: None,
353b0b11 47 locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES,
6a06907d 48 lint_caps: rustc_hash::FxHashMap::default(),
cdc7bbd5 49 parse_sess_created: None,
6a06907d
XL
50 register_lints: None,
51 override_queries: None,
52 make_codegen_backend: None,
53 registry: registry::Registry::new(&rustc_error_codes::DIAGNOSTICS),
54 };
55 rustc_interface::run_compiler(config, |compiler| {
56 compiler.enter(|queries| {
57 // TODO: add this to -Z unpretty
9ffffee4 58 let ast_krate = queries.parse().unwrap().get_mut().clone();
cdc7bbd5 59 for item in ast_krate.items {
6a06907d
XL
60 println!("{}", item_to_string(&item));
61 }
6a06907d 62 // Analyze the crate and inspect the types under the cursor.
9ffffee4 63 queries.global_ctxt().unwrap().enter(|tcx| {
6a06907d 64 // Every compilation contains a single crate.
a2a8927a 65 let hir_krate = tcx.hir();
6a06907d 66 // Iterate over the top-level items in the crate, looking for the main function.
923072b8
FG
67 for id in hir_krate.items() {
68 let item = hir_krate.item(id);
6a06907d
XL
69 // Use pattern-matching to find a specific node inside the main function.
70 if let rustc_hir::ItemKind::Fn(_, _, body_id) = item.kind {
71 let expr = &tcx.hir().body(body_id).value;
72 if let rustc_hir::ExprKind::Block(block, _) = expr.kind {
73 if let rustc_hir::StmtKind::Local(local) = block.stmts[0].kind {
74 if let Some(expr) = local.init {
75 let hir_id = expr.hir_id; // hir_id identifies the string "Hello, world!"
9ffffee4 76 let def_id = item.hir_id().owner.def_id; // def_id identifies the main function
6a06907d 77 let ty = tcx.typeck(def_id).node_type(hir_id);
923072b8 78 println!("{expr:#?}: {ty:?}");
6a06907d
XL
79 }
80 }
81 }
82 }
83 }
84 })
85 });
86 });
87}