]>
Commit | Line | Data |
---|---|---|
6a06907d XL |
1 | # Example: Getting diagnostic through `rustc_interface` |
2 | ||
3 | `rustc_interface` allows you to intercept diagnostics that would otherwise be printed to stderr. | |
4 | ||
5 | ## Getting diagnostics | |
6 | ||
cdc7bbd5 XL |
7 | To get diagnostics from the compiler, |
8 | configure `rustc_interface::Config` to output diagnostic to a buffer, | |
923072b8 FG |
9 | and run `TyCtxt.analysis`. The following was tested |
10 | with <!-- date: 2022-06 --> `nightly-2022-06-05` (See [here][example] | |
cdc7bbd5 XL |
11 | for the complete example): |
12 | ||
13 | [example]: https://github.com/rust-lang/rustc-dev-guide/blob/master/examples/rustc-driver-getting-diagnostics.rs | |
6a06907d XL |
14 | |
15 | ```rust | |
6a06907d XL |
16 | let buffer = sync::Arc::new(sync::Mutex::new(Vec::new())); |
17 | let config = rustc_interface::Config { | |
18 | opts: config::Options { | |
19 | // Configure the compiler to emit diagnostics in compact JSON format. | |
20 | error_format: config::ErrorOutputType::Json { | |
21 | pretty: false, | |
22 | json_rendered: rustc_errors::emitter::HumanReadableErrorType::Default( | |
23 | rustc_errors::emitter::ColorConfig::Never, | |
24 | ), | |
25 | }, | |
26 | /* other config */ | |
27 | }, | |
28 | // Redirect the diagnostic output of the compiler to a buffer. | |
29 | diagnostic_output: rustc_session::DiagnosticOutput::Raw(Box::from(DiagnosticSink( | |
30 | buffer.clone(), | |
31 | ))), | |
32 | /* other config */ | |
33 | }; | |
34 | rustc_interface::run_compiler(config, |compiler| { | |
35 | compiler.enter(|queries| { | |
36 | queries.global_ctxt().unwrap().take().enter(|tcx| { | |
37 | // Run the analysis phase on the local crate to trigger the type error. | |
923072b8 | 38 | let _ = tcx.analysis(()); |
6a06907d XL |
39 | }); |
40 | }); | |
41 | }); | |
42 | // Read buffered diagnostics. | |
43 | let diagnostics = String::from_utf8(buffer.lock().unwrap().clone()).unwrap(); | |
44 | ``` |