improve rustc_interface examples a little (#1362)

This commit is contained in:
Tshepang Mbambo 2022-06-07 01:42:07 +02:00 committed by GitHub
parent 123efb6fc2
commit 6445e007fe
5 changed files with 35 additions and 21 deletions

View File

@ -13,13 +13,12 @@ extern crate rustc_interface;
extern crate rustc_session; extern crate rustc_session;
extern crate rustc_span; extern crate rustc_span;
use std::{path, process, str};
use rustc_errors::registry; use rustc_errors::registry;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use rustc_session::config::{self, CheckCfg}; use rustc_session::config::{self, CheckCfg};
use rustc_span::source_map; use rustc_span::source_map;
use std::path;
use std::process;
use std::str;
fn main() { fn main() {
let out = process::Command::new("rustc") let out = process::Command::new("rustc")
@ -38,9 +37,14 @@ fn main() {
crate_cfg: FxHashSet::default(), // FxHashSet<(String, Option<String>)> crate_cfg: FxHashSet::default(), // FxHashSet<(String, Option<String>)>
crate_check_cfg: CheckCfg::default(), // CheckCfg crate_check_cfg: CheckCfg::default(), // CheckCfg
input: config::Input::Str { input: config::Input::Str {
name: source_map::FileName::Custom("main.rs".to_string()), name: source_map::FileName::Custom("main.rs".into()),
input: "static HELLO: &str = \"Hello, world!\"; fn main() { println!(\"{}\", HELLO); }" input: r#"
.to_string(), static HELLO: &str = "Hello, world!";
fn main() {
println!("{HELLO}");
}
"#
.into(),
}, },
input_path: None, // Option<PathBuf> input_path: None, // Option<PathBuf>
output_dir: None, // Option<PathBuf> output_dir: None, // Option<PathBuf>
@ -69,16 +73,17 @@ fn main() {
compiler.enter(|queries| { compiler.enter(|queries| {
// Parse the program and print the syntax tree. // Parse the program and print the syntax tree.
let parse = queries.parse().unwrap().take(); let parse = queries.parse().unwrap().take();
println!("{:#?}", parse); println!("{parse:?}");
// Analyze the program and inspect the types of definitions. // Analyze the program and inspect the types of definitions.
queries.global_ctxt().unwrap().take().enter(|tcx| { queries.global_ctxt().unwrap().take().enter(|tcx| {
for id in tcx.hir().items() { for id in tcx.hir().items() {
let item = tcx.hir().item(id); let hir = tcx.hir();
let item = hir.item(id);
match item.kind { match item.kind {
rustc_hir::ItemKind::Static(_, _, _) | rustc_hir::ItemKind::Fn(_, _, _) => { rustc_hir::ItemKind::Static(_, _, _) | rustc_hir::ItemKind::Fn(_, _, _) => {
let name = item.ident; let name = item.ident;
let ty = tcx.type_of(tcx.hir().local_def_id(item.hir_id())); let ty = tcx.type_of(hir.local_def_id(item.hir_id()));
println!("{:?}:\t{:?}", name, ty) println!("{name:?}:\t{ty:?}")
} }
_ => (), _ => (),
} }

View File

@ -57,8 +57,13 @@ fn main() {
}, },
// This program contains a type error. // This program contains a type error.
input: config::Input::Str { input: config::Input::Str {
name: source_map::FileName::Custom("main.rs".to_string()), name: source_map::FileName::Custom("main.rs".into()),
input: "fn main() { let x: &str = 1; }".to_string(), input: "
fn main() {
let x: &str = 1;
}
"
.into(),
}, },
// Redirect the diagnostic output of the compiler to a buffer. // Redirect the diagnostic output of the compiler to a buffer.
diagnostic_output: rustc_session::DiagnosticOutput::Raw(Box::from(DiagnosticSink( diagnostic_output: rustc_session::DiagnosticOutput::Raw(Box::from(DiagnosticSink(
@ -87,5 +92,5 @@ fn main() {
}); });
// Read buffered diagnostics. // Read buffered diagnostics.
let diagnostics = String::from_utf8(buffer.lock().unwrap().clone()).unwrap(); let diagnostics = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
println!("{}", diagnostics); println!("{diagnostics}");
} }

View File

@ -14,13 +14,12 @@ extern crate rustc_interface;
extern crate rustc_session; extern crate rustc_session;
extern crate rustc_span; extern crate rustc_span;
use std::{path, process, str};
use rustc_ast_pretty::pprust::item_to_string; use rustc_ast_pretty::pprust::item_to_string;
use rustc_errors::registry; use rustc_errors::registry;
use rustc_session::config::{self, CheckCfg}; use rustc_session::config::{self, CheckCfg};
use rustc_span::source_map; use rustc_span::source_map;
use std::path;
use std::process;
use std::str;
fn main() { fn main() {
let out = process::Command::new("rustc") let out = process::Command::new("rustc")
@ -36,7 +35,12 @@ fn main() {
}, },
input: config::Input::Str { input: config::Input::Str {
name: source_map::FileName::Custom("main.rs".to_string()), name: source_map::FileName::Custom("main.rs".to_string()),
input: "fn main() { let message = \"Hello, world!\"; println!(\"{}\", message); }" input: r#"
fn main() {
let message = "Hello, World!";
println!("{message}");
}
"#
.to_string(), .to_string(),
}, },
diagnostic_output: rustc_session::DiagnosticOutput::Default, diagnostic_output: rustc_session::DiagnosticOutput::Default,
@ -77,7 +81,7 @@ fn main() {
let hir_id = expr.hir_id; // hir_id identifies the string "Hello, world!" let hir_id = expr.hir_id; // hir_id identifies the string "Hello, world!"
let def_id = tcx.hir().local_def_id(item.hir_id()); // def_id identifies the main function let def_id = tcx.hir().local_def_id(item.hir_id()); // def_id identifies the main function
let ty = tcx.typeck(def_id).node_type(hir_id); let ty = tcx.typeck(def_id).node_type(hir_id);
println!("{:?}: {:?}", expr, ty); println!("{expr:#?}: {ty:?}");
} }
} }
} }

View File

@ -7,7 +7,7 @@
To get diagnostics from the compiler, To get diagnostics from the compiler,
configure `rustc_interface::Config` to output diagnostic to a buffer, configure `rustc_interface::Config` to output diagnostic to a buffer,
and run `TyCtxt.analysis`. The following should be compiled and run `TyCtxt.analysis`. The following should be compiled
with <!-- date: 2022-05 --> `nightly-2021-04-30` (See [here][example] with <!-- date: 2022-06 --> `nightly-2022-06-05` (See [here][example]
for the complete example): for the complete example):
[example]: https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-getting-diagnostics.rs [example]: https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-getting-diagnostics.rs

View File

@ -5,7 +5,7 @@
## Getting the type of an expression ## Getting the type of an expression
To get the type of an expression, use the `global_ctxt` to get a `TyCtxt`. To get the type of an expression, use the `global_ctxt` to get a `TyCtxt`.
The following should be compiled with <!-- date: 2022-05 --> `nightly-2022-04-30` The following should be compiled with <!-- date: 2022-06 --> `nightly-2022-06-05`
(see [here][example] for the complete example): (see [here][example] for the complete example):
[example]: https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-interacting-with-the-ast.rs [example]: https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-interacting-with-the-ast.rs