]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/interface.rs
Auto merge of #82864 - jyn514:short-circuit, r=GuillaumeGomez
[rust.git] / compiler / rustc_interface / src / interface.rs
1 pub use crate::passes::BoxedResolver;
2 use crate::util;
3
4 use rustc_ast::token;
5 use rustc_ast::{self as ast, MetaItemKind};
6 use rustc_codegen_ssa::traits::CodegenBackend;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_data_structures::sync::Lrc;
9 use rustc_data_structures::OnDrop;
10 use rustc_errors::registry::Registry;
11 use rustc_errors::{ErrorReported, Handler};
12 use rustc_lint::LintStore;
13 use rustc_middle::ty;
14 use rustc_parse::new_parser_from_source_str;
15 use rustc_session::config::{self, ErrorOutputType, Input, OutputFilenames};
16 use rustc_session::early_error;
17 use rustc_session::lint;
18 use rustc_session::parse::{CrateConfig, ParseSess};
19 use rustc_session::{DiagnosticOutput, Session};
20 use rustc_span::source_map::{FileLoader, FileName};
21 use std::path::PathBuf;
22 use std::result;
23 use std::sync::{Arc, Mutex};
24
25 pub type Result<T> = result::Result<T, ErrorReported>;
26
27 /// Represents a compiler session.
28 ///
29 /// Can be used to run `rustc_interface` queries.
30 /// Created by passing [`Config`] to [`run_compiler`].
31 pub struct Compiler {
32     pub(crate) sess: Lrc<Session>,
33     codegen_backend: Lrc<Box<dyn CodegenBackend>>,
34     pub(crate) input: Input,
35     pub(crate) input_path: Option<PathBuf>,
36     pub(crate) output_dir: Option<PathBuf>,
37     pub(crate) output_file: Option<PathBuf>,
38     pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
39     pub(crate) override_queries:
40         Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
41 }
42
43 impl Compiler {
44     pub fn session(&self) -> &Lrc<Session> {
45         &self.sess
46     }
47     pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
48         &self.codegen_backend
49     }
50     pub fn input(&self) -> &Input {
51         &self.input
52     }
53     pub fn output_dir(&self) -> &Option<PathBuf> {
54         &self.output_dir
55     }
56     pub fn output_file(&self) -> &Option<PathBuf> {
57         &self.output_file
58     }
59     pub fn register_lints(&self) -> &Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>> {
60         &self.register_lints
61     }
62     pub fn build_output_filenames(
63         &self,
64         sess: &Session,
65         attrs: &[ast::Attribute],
66     ) -> OutputFilenames {
67         util::build_output_filenames(
68             &self.input,
69             &self.output_dir,
70             &self.output_file,
71             &attrs,
72             &sess,
73         )
74     }
75 }
76
77 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
78 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
79     rustc_span::with_default_session_globals(move || {
80         let cfg = cfgspecs
81             .into_iter()
82             .map(|s| {
83                 let sess = ParseSess::with_silent_emitter();
84                 let filename = FileName::cfg_spec_source_code(&s);
85                 let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());
86
87                 macro_rules! error {
88                     ($reason: expr) => {
89                         early_error(
90                             ErrorOutputType::default(),
91                             &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
92                         );
93                     };
94                 }
95
96                 match &mut parser.parse_meta_item() {
97                     Ok(meta_item) if parser.token == token::Eof => {
98                         if meta_item.path.segments.len() != 1 {
99                             error!("argument key must be an identifier");
100                         }
101                         match &meta_item.kind {
102                             MetaItemKind::List(..) => {
103                                 error!(r#"expected `key` or `key="value"`"#);
104                             }
105                             MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
106                                 error!("argument value must be a string");
107                             }
108                             MetaItemKind::NameValue(..) | MetaItemKind::Word => {
109                                 let ident = meta_item.ident().expect("multi-segment cfg key");
110                                 return (ident.name, meta_item.value_str());
111                             }
112                         }
113                     }
114                     Ok(..) => {}
115                     Err(err) => err.cancel(),
116                 }
117
118                 error!(r#"expected `key` or `key="value"`"#);
119             })
120             .collect::<CrateConfig>();
121         cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
122     })
123 }
124
125 /// The compiler configuration
126 pub struct Config {
127     /// Command line options
128     pub opts: config::Options,
129
130     /// cfg! configuration in addition to the default ones
131     pub crate_cfg: FxHashSet<(String, Option<String>)>,
132
133     pub input: Input,
134     pub input_path: Option<PathBuf>,
135     pub output_dir: Option<PathBuf>,
136     pub output_file: Option<PathBuf>,
137     pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
138     pub diagnostic_output: DiagnosticOutput,
139
140     /// Set to capture stderr output during compiler execution
141     pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
142
143     pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
144
145     /// This is a callback from the driver that is called when [`ParseSess`] is created.
146     pub parse_sess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
147
148     /// This is a callback from the driver that is called when we're registering lints;
149     /// it is called during plugin registration when we have the LintStore in a non-shared state.
150     ///
151     /// Note that if you find a Some here you probably want to call that function in the new
152     /// function being registered.
153     pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
154
155     /// This is a callback from the driver that is called just after we have populated
156     /// the list of queries.
157     ///
158     /// The second parameter is local providers and the third parameter is external providers.
159     pub override_queries:
160         Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
161
162     /// This is a callback from the driver that is called to create a codegen backend.
163     pub make_codegen_backend:
164         Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
165
166     /// Registry of diagnostics codes.
167     pub registry: Registry,
168 }
169
170 pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R) -> R {
171     let registry = &config.registry;
172     let (mut sess, codegen_backend) = util::create_session(
173         config.opts,
174         config.crate_cfg,
175         config.diagnostic_output,
176         config.file_loader,
177         config.input_path.clone(),
178         config.lint_caps,
179         config.make_codegen_backend,
180         registry.clone(),
181     );
182
183     if let Some(parse_sess_created) = config.parse_sess_created {
184         parse_sess_created(
185             &mut Lrc::get_mut(&mut sess)
186                 .expect("create_session() should never share the returned session")
187                 .parse_sess,
188         );
189     }
190
191     let compiler = Compiler {
192         sess,
193         codegen_backend,
194         input: config.input,
195         input_path: config.input_path,
196         output_dir: config.output_dir,
197         output_file: config.output_file,
198         register_lints: config.register_lints,
199         override_queries: config.override_queries,
200     };
201
202     rustc_span::with_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
203         let r = {
204             let _sess_abort_error = OnDrop(|| {
205                 compiler.sess.finish_diagnostics(registry);
206             });
207
208             f(&compiler)
209         };
210
211         let prof = compiler.sess.prof.clone();
212         prof.generic_activity("drop_compiler").run(move || drop(compiler));
213         r
214     })
215 }
216
217 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
218     tracing::trace!("run_compiler");
219     let stderr = config.stderr.take();
220     util::setup_callbacks_and_run_in_thread_pool_with_globals(
221         config.opts.edition,
222         config.opts.debugging_opts.threads,
223         &stderr,
224         || create_compiler_and_run(config, f),
225     )
226 }
227
228 pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
229     eprintln!("query stack during panic:");
230
231     // Be careful relying on global state here: this code is called from
232     // a panic hook, which means that the global `Handler` may be in a weird
233     // state if it was responsible for triggering the panic.
234     let i = ty::tls::with_context_opt(|icx| {
235         if let Some(icx) = icx {
236             icx.tcx.queries.try_print_query_stack(icx.tcx, icx.query, handler, num_frames)
237         } else {
238             0
239         }
240     });
241
242     if num_frames == None || num_frames >= Some(i) {
243         eprintln!("end of query stack");
244     } else {
245         eprintln!("we're just showing a limited slice of the query stack");
246     }
247 }