]>
git.proxmox.com Git - rustc.git/blob - src/doc/rustc-dev-guide/examples/rustc-driver-getting-diagnostics.rs
1 #![feature(rustc_private)]
3 extern crate rustc_driver
;
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_session
;
10 extern crate rustc_span
;
12 use rustc_errors
::registry
;
13 use rustc_session
::config
::{self, CheckCfg}
;
14 use rustc_span
::source_map
;
21 // Buffer diagnostics in a Vec<u8>.
23 pub struct DiagnosticSink(sync
::Arc
<sync
::Mutex
<Vec
<u8>>>);
25 impl io
::Write
for DiagnosticSink
{
26 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
27 self.0.lock().unwrap().write(buf
)
29 fn flush(&mut self) -> io
::Result
<()> {
30 self.0.lock().unwrap().flush()
35 let out
= process
::Command
::new("rustc")
36 .arg("--print=sysroot")
40 let sysroot
= str::from_utf8(&out
.stdout
).unwrap().trim();
41 let buffer
= sync
::Arc
::new(sync
::Mutex
::new(Vec
::new()));
42 let config
= rustc_interface
::Config
{
43 opts
: config
::Options
{
44 maybe_sysroot
: Some(path
::PathBuf
::from(sysroot
)),
45 // Configure the compiler to emit diagnostics in compact JSON format.
46 error_format
: config
::ErrorOutputType
::Json
{
48 json_rendered
: rustc_errors
::emitter
::HumanReadableErrorType
::Default(
49 rustc_errors
::emitter
::ColorConfig
::Never
,
52 ..config
::Options
::default()
54 // This program contains a type error.
55 input
: config
::Input
::Str
{
56 name
: source_map
::FileName
::Custom("main.rs".into()),
64 crate_cfg
: rustc_hash
::FxHashSet
::default(),
65 crate_check_cfg
: CheckCfg
::default(),
69 locale_resources
: rustc_driver
::DEFAULT_LOCALE_RESOURCES
,
70 lint_caps
: rustc_hash
::FxHashMap
::default(),
71 parse_sess_created
: None
,
73 override_queries
: None
,
74 registry
: registry
::Registry
::new(&rustc_error_codes
::DIAGNOSTICS
),
75 make_codegen_backend
: None
,
77 rustc_interface
::run_compiler(config
, |compiler
| {
78 compiler
.enter(|queries
| {
79 queries
.global_ctxt().unwrap().enter(|tcx
| {
80 // Run the analysis phase on the local crate to trigger the type error.
81 let _
= tcx
.analysis(());
85 // Read buffered diagnostics.
86 let diagnostics
= String
::from_utf8(buffer
.lock().unwrap().clone()).unwrap();
87 println
!("{diagnostics}");