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_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;
23 use std::sync::{Arc, Mutex};
25 pub type Result<T> = result::Result<T, ErrorReported>;
27 /// Represents a compiler session.
29 /// Can be used to run `rustc_interface` queries.
30 /// Created by passing [`Config`] to [`run_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)>,
44 pub fn session(&self) -> &Lrc<Session> {
47 pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
50 pub fn input(&self) -> &Input {
53 pub fn output_dir(&self) -> &Option<PathBuf> {
56 pub fn output_file(&self) -> &Option<PathBuf> {
59 pub fn register_lints(&self) -> &Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>> {
62 pub fn build_output_filenames(
65 attrs: &[ast::Attribute],
66 ) -> OutputFilenames {
67 util::build_output_filenames(
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 || {
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());
90 ErrorOutputType::default(),
91 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
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");
101 match &meta_item.kind {
102 MetaItemKind::List(..) => {
103 error!(r#"expected `key` or `key="value"`"#);
105 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
106 error!("argument value must be a string");
108 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
109 let ident = meta_item.ident().expect("multi-segment cfg key");
110 return (ident.name, meta_item.value_str());
115 Err(err) => err.cancel(),
118 error!(r#"expected `key` or `key="value"`"#);
120 .collect::<CrateConfig>();
121 cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
125 /// The compiler configuration
127 /// Command line options
128 pub opts: config::Options,
130 /// cfg! configuration in addition to the default ones
131 pub crate_cfg: FxHashSet<(String, Option<String>)>,
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,
140 /// Set to capture stderr output during compiler execution
141 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
143 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
145 /// This is a callback from the driver that is called when we're registering lints;
146 /// it is called during plugin registration when we have the LintStore in a non-shared state.
148 /// Note that if you find a Some here you probably want to call that function in the new
149 /// function being registered.
150 pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
152 /// This is a callback from the driver that is called just after we have populated
153 /// the list of queries.
155 /// The second parameter is local providers and the third parameter is external providers.
156 pub override_queries:
157 Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
159 /// This is a callback from the driver that is called to create a codegen backend.
160 pub make_codegen_backend:
161 Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
163 /// Registry of diagnostics codes.
164 pub registry: Registry,
167 pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R) -> R {
168 let registry = &config.registry;
169 let (sess, codegen_backend) = util::create_session(
172 config.diagnostic_output,
174 config.input_path.clone(),
176 config.make_codegen_backend,
180 let compiler = Compiler {
184 input_path: config.input_path,
185 output_dir: config.output_dir,
186 output_file: config.output_file,
187 register_lints: config.register_lints,
188 override_queries: config.override_queries,
191 rustc_span::with_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
193 let _sess_abort_error = OnDrop(|| {
194 compiler.sess.finish_diagnostics(registry);
200 let prof = compiler.sess.prof.clone();
201 prof.generic_activity("drop_compiler").run(move || drop(compiler));
206 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
207 tracing::trace!("run_compiler");
208 let stderr = config.stderr.take();
209 util::setup_callbacks_and_run_in_thread_pool_with_globals(
211 config.opts.debugging_opts.threads,
213 || create_compiler_and_run(config, f),
217 pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
218 eprintln!("query stack during panic:");
220 // Be careful relying on global state here: this code is called from
221 // a panic hook, which means that the global `Handler` may be in a weird
222 // state if it was responsible for triggering the panic.
223 let i = ty::tls::with_context_opt(|icx| {
224 if let Some(icx) = icx {
225 icx.tcx.queries.try_print_query_stack(icx.tcx, icx.query, handler, num_frames)
231 if num_frames == None || num_frames >= Some(i) {
232 eprintln!("end of query stack");
234 eprintln!("we're just showing a limited slice of the query stack");