Skip to content

Commit 0a1da4f

Browse files
jyn514Joshua Nelson
authored andcommitted
Add some more examples of using the compiler
1 parent b4acbb9 commit 0a1da4f

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

examples/rustc-driver-interacting-with-the-ast.rs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
#![feature(rustc_private)]
22

33
// NOTE: For the example to compile, you will need to first run the following:
4-
// rustup component add rustc-dev
4+
// rustup component add rustc-dev llvm-tools-preview
55

6+
extern crate rustc_ast_pretty;
67
extern crate rustc_error_codes;
78
extern crate rustc_errors;
89
extern crate rustc_hash;
@@ -11,8 +12,11 @@ extern crate rustc_interface;
1112
extern crate rustc_session;
1213
extern crate rustc_span;
1314

15+
use rustc_ast_pretty::pprust::item_to_string;
1416
use rustc_errors::registry;
1517
use rustc_session::config;
18+
use rustc_session::config::PpMode::PpmSource;
19+
use rustc_session::config::PpSourceMode::PpmExpanded;
1620
use rustc_span::source_map;
1721
use std::path;
1822
use std::process;
@@ -46,16 +50,24 @@ fn main() {
4650
lint_caps: rustc_hash::FxHashMap::default(),
4751
register_lints: None,
4852
override_queries: None,
53+
make_codegen_backend: None,
4954
registry: registry::Registry::new(&rustc_error_codes::DIAGNOSTICS),
5055
};
5156
rustc_interface::run_compiler(config, |compiler| {
5257
compiler.enter(|queries| {
58+
// TODO: add this to -Z unpretty
59+
let ast_krate = queries.parse().unwrap().take();
60+
let ast_krate_mod = ast_krate.module;
61+
for item in ast_krate_mod.items {
62+
println!("{}", item_to_string(&item));
63+
}
64+
5365
// Analyze the crate and inspect the types under the cursor.
5466
queries.global_ctxt().unwrap().take().enter(|tcx| {
5567
// Every compilation contains a single crate.
56-
let krate = tcx.hir().krate();
68+
let hir_krate = tcx.hir().krate();
5769
// Iterate over the top-level items in the crate, looking for the main function.
58-
for (_, item) in &krate.items {
70+
for (_, item) in &hir_krate.items {
5971
// Use pattern-matching to find a specific node inside the main function.
6072
if let rustc_hir::ItemKind::Fn(_, _, body_id) = item.kind {
6173
let expr = &tcx.hir().body(body_id).value;

0 commit comments

Comments
 (0)