1 pub use crate::passes::BoxedResolver;
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;
14 use rustc_parse::new_parser_from_source_str;
15 use rustc_query_impl::QueryCtxt;
16 use rustc_session::config::{self, ErrorOutputType, Input, OutputFilenames};
17 use rustc_session::early_error;
18 use rustc_session::lint;
19 use rustc_session::parse::{CrateConfig, ParseSess};
20 use rustc_session::{DiagnosticOutput, Session};
21 use rustc_span::source_map::{FileLoader, FileName};
22 use std::path::PathBuf;
24 use std::sync::{Arc, Mutex};
26 pub type Result<T> = result::Result<T, ErrorReported>;
28 /// Represents a compiler session.
30 /// Can be used to run `rustc_interface` queries.
31 /// Created by passing [`Config`] to [`run_compiler`].
33 pub(crate) sess: Lrc<Session>,
34 codegen_backend: Lrc<Box<dyn CodegenBackend>>,
35 pub(crate) input: Input,
36 pub(crate) input_path: Option<PathBuf>,
37 pub(crate) output_dir: Option<PathBuf>,
38 pub(crate) output_file: Option<PathBuf>,
39 pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
40 pub(crate) override_queries:
41 Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
45 pub fn session(&self) -> &Lrc<Session> {
48 pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
51 pub fn input(&self) -> &Input {
54 pub fn output_dir(&self) -> &Option<PathBuf> {
57 pub fn output_file(&self) -> &Option<PathBuf> {
60 pub fn register_lints(&self) -> &Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>> {
63 pub fn build_output_filenames(
66 attrs: &[ast::Attribute],
67 ) -> OutputFilenames {
68 util::build_output_filenames(&self.input, &self.output_dir, &self.output_file, attrs, sess)
72 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
73 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
74 rustc_span::create_default_session_if_not_set_then(move |_| {
78 let sess = ParseSess::with_silent_emitter(Some(format!(
79 "this error occurred on the command line: `--cfg={}`",
82 let filename = FileName::cfg_spec_source_code(&s);
83 let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());
88 ErrorOutputType::default(),
89 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
94 match &mut parser.parse_meta_item() {
95 Ok(meta_item) if parser.token == token::Eof => {
96 if meta_item.path.segments.len() != 1 {
97 error!("argument key must be an identifier");
99 match &meta_item.kind {
100 MetaItemKind::List(..) => {
101 error!(r#"expected `key` or `key="value"`"#);
103 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
104 error!("argument value must be a string");
106 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
107 let ident = meta_item.ident().expect("multi-segment cfg key");
108 return (ident.name, meta_item.value_str());
113 Err(err) => err.cancel(),
116 error!(r#"expected `key` or `key="value"`"#);
118 .collect::<CrateConfig>();
119 cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
123 /// The compiler configuration
125 /// Command line options
126 pub opts: config::Options,
128 /// cfg! configuration in addition to the default ones
129 pub crate_cfg: FxHashSet<(String, Option<String>)>,
132 pub input_path: Option<PathBuf>,
133 pub output_dir: Option<PathBuf>,
134 pub output_file: Option<PathBuf>,
135 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
136 pub diagnostic_output: DiagnosticOutput,
138 /// Set to capture stderr output during compiler execution
139 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
141 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
143 /// This is a callback from the driver that is called when [`ParseSess`] is created.
144 pub parse_sess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
146 /// This is a callback from the driver that is called when we're registering lints;
147 /// it is called during plugin registration when we have the LintStore in a non-shared state.
149 /// Note that if you find a Some here you probably want to call that function in the new
150 /// function being registered.
151 pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
153 /// This is a callback from the driver that is called just after we have populated
154 /// the list of queries.
156 /// The second parameter is local providers and the third parameter is external providers.
157 pub override_queries:
158 Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
160 /// This is a callback from the driver that is called to create a codegen backend.
161 pub make_codegen_backend:
162 Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
164 /// Registry of diagnostics codes.
165 pub registry: Registry,
168 pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R) -> R {
169 let registry = &config.registry;
170 let (mut sess, codegen_backend) = util::create_session(
173 config.diagnostic_output,
175 config.input_path.clone(),
177 config.make_codegen_backend,
181 if let Some(parse_sess_created) = config.parse_sess_created {
183 &mut Lrc::get_mut(&mut sess)
184 .expect("create_session() should never share the returned session")
189 let compiler = Compiler {
193 input_path: config.input_path,
194 output_dir: config.output_dir,
195 output_file: config.output_file,
196 register_lints: config.register_lints,
197 override_queries: config.override_queries,
200 rustc_span::with_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
202 let _sess_abort_error = OnDrop(|| {
203 compiler.sess.finish_diagnostics(registry);
209 let prof = compiler.sess.prof.clone();
210 prof.generic_activity("drop_compiler").run(move || drop(compiler));
215 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
216 tracing::trace!("run_compiler");
217 let stderr = config.stderr.take();
218 util::setup_callbacks_and_run_in_thread_pool_with_globals(
220 config.opts.debugging_opts.threads,
222 || create_compiler_and_run(config, f),
226 pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
227 eprintln!("query stack during panic:");
229 // Be careful relying on global state here: this code is called from
230 // a panic hook, which means that the global `Handler` may be in a weird
231 // state if it was responsible for triggering the panic.
232 let i = ty::tls::with_context_opt(|icx| {
233 if let Some(icx) = icx {
234 QueryCtxt::from_tcx(icx.tcx).try_print_query_stack(icx.query, handler, num_frames)
240 if num_frames == None || num_frames >= Some(i) {
241 eprintln!("end of query stack");
243 eprintln!("we're just showing a limited slice of the query stack");