]>
git.proxmox.com Git - rustc.git/blob - src/doc/rustc-dev-guide/examples/rustc-driver-example.rs
1 #![feature(rustc_private)]
4 extern crate rustc_error_codes
;
5 extern crate rustc_errors
;
6 extern crate rustc_hash
;
7 extern crate rustc_hir
;
8 extern crate rustc_interface
;
9 extern crate rustc_span
;
12 use rustc
::session
::config
;
13 use rustc_errors
::registry
;
14 use rustc_hash
::{FxHashMap, FxHashSet}
;
15 use rustc_span
::source_map
;
21 let out
= process
::Command
::new("rustc")
22 .arg("--print=sysroot")
26 let sysroot
= str::from_utf8(&out
.stdout
).unwrap().trim();
27 let filename
= "main.rs";
28 let contents
= "static HELLO: &str = \"Hello, world!\"; fn main() { println!(\"{}\", HELLO); }";
29 let errors
= registry
::Registry
::new(&rustc_error_codes
::DIAGNOSTICS
);
30 let config
= rustc_interface
::Config
{
31 // Command line options
32 opts
: config
::Options
{
33 maybe_sysroot
: Some(path
::PathBuf
::from(sysroot
)),
34 ..config
::Options
::default()
37 // cfg! configuration in addition to the default ones
38 // FxHashSet<(String, Option<String>)>
39 crate_cfg
: FxHashSet
::default(),
41 input
: config
::Input
::Str
{
42 name
: source_map
::FileName
::Custom(String
::from(filename
)),
43 input
: String
::from(contents
),
51 // Option<Box<dyn FileLoader + Send + Sync>>
53 diagnostic_output
: session
::DiagnosticOutput
::Default
,
55 // Set to capture stderr output during compiler execution
56 // Option<Arc<Mutex<Vec<u8>>>>
61 // FxHashMap<lint::LintId, lint::Level>
62 lint_caps
: FxHashMap
::default(),
64 // This is a callback from the driver that is called when we're registering lints;
65 // it is called during plugin registration when we have the LintStore in a non-shared state.
67 // Note that if you find a Some here you probably want to call that function in the new
68 // function being registered.
69 // Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>
72 // This is a callback from the driver that is called just after we have populated
73 // the list of queries.
75 // The second parameter is local providers and the third parameter is external providers.
76 // Option<fn(&Session, &mut ty::query::Providers<'_>, &mut ty::query::Providers<'_>)>
77 override_queries
: None
,
79 // Registry of diagnostics codes.
82 rustc_interface
::run_compiler(config
, |compiler
| {
83 compiler
.enter(|queries
| {
84 // Parse the program and print the syntax tree.
85 let parse
= queries
.parse().unwrap().take();
86 println
!("{:#?}", parse
);
87 // Analyze the program and inspect the types of definitions.
88 queries
.global_ctxt().unwrap().take().enter(|tcx
| {
89 for (_
, item
) in &tcx
.hir().krate().items
{
91 rustc_hir
::ItemKind
::Static(_
, _
, _
) | rustc_hir
::ItemKind
::Fn(_
, _
, _
) => {
92 let name
= item
.ident
;
93 let ty
= tcx
.type_of(tcx
.hir().local_def_id(item
.hir_id
));
94 println
!("{:?}:\t{:?}", name
, ty
)