]> git.proxmox.com Git - rustc.git/blob - src/doc/rustc-dev-guide/examples/rustc-driver-getting-diagnostics.rs
New upstream version 1.70.0+dfsg1
[rustc.git] / src / doc / rustc-dev-guide / examples / rustc-driver-getting-diagnostics.rs
1 #![feature(rustc_private)]
2
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;
11
12 use rustc_errors::registry;
13 use rustc_session::config::{self, CheckCfg};
14 use rustc_span::source_map;
15 use std::io;
16 use std::path;
17 use std::process;
18 use std::str;
19 use std::sync;
20
21 // Buffer diagnostics in a Vec<u8>.
22 #[derive(Clone)]
23 pub struct DiagnosticSink(sync::Arc<sync::Mutex<Vec<u8>>>);
24
25 impl io::Write for DiagnosticSink {
26 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
27 self.0.lock().unwrap().write(buf)
28 }
29 fn flush(&mut self) -> io::Result<()> {
30 self.0.lock().unwrap().flush()
31 }
32 }
33
34 fn main() {
35 let out = process::Command::new("rustc")
36 .arg("--print=sysroot")
37 .current_dir(".")
38 .output()
39 .unwrap();
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 {
47 pretty: false,
48 json_rendered: rustc_errors::emitter::HumanReadableErrorType::Default(
49 rustc_errors::emitter::ColorConfig::Never,
50 ),
51 },
52 ..config::Options::default()
53 },
54 // This program contains a type error.
55 input: config::Input::Str {
56 name: source_map::FileName::Custom("main.rs".into()),
57 input: "
58 fn main() {
59 let x: &str = 1;
60 }
61 "
62 .into(),
63 },
64 crate_cfg: rustc_hash::FxHashSet::default(),
65 crate_check_cfg: CheckCfg::default(),
66 output_dir: None,
67 output_file: None,
68 file_loader: None,
69 locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES,
70 lint_caps: rustc_hash::FxHashMap::default(),
71 parse_sess_created: None,
72 register_lints: None,
73 override_queries: None,
74 registry: registry::Registry::new(&rustc_error_codes::DIAGNOSTICS),
75 make_codegen_backend: None,
76 };
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(());
82 });
83 });
84 });
85 // Read buffered diagnostics.
86 let diagnostics = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
87 println!("{diagnostics}");
88 }