1 pub use crate::passes::BoxedResolver;
4 use rustc_ast::ast::{self, 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;
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.
28 /// Can be used to run `rustc_interface` queries.
29 /// Created by passing `Config` to `run_compiler`.
31 pub(crate) sess: Lrc<Session>,
32 codegen_backend: Lrc<Box<dyn CodegenBackend>>,
33 pub(crate) input: Input,
34 pub(crate) input_path: Option<PathBuf>,
35 pub(crate) output_dir: Option<PathBuf>,
36 pub(crate) output_file: Option<PathBuf>,
37 pub(crate) crate_name: Option<String>,
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 build_output_filenames(
62 attrs: &[ast::Attribute],
63 ) -> OutputFilenames {
64 util::build_output_filenames(
74 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
75 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
76 rustc_span::with_default_session_globals(move || {
80 let sess = ParseSess::with_silent_emitter();
81 let filename = FileName::cfg_spec_source_code(&s);
82 let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());
87 ErrorOutputType::default(),
88 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
93 match &mut parser.parse_meta_item() {
94 Ok(meta_item) if parser.token == token::Eof => {
95 if meta_item.path.segments.len() != 1 {
96 error!("argument key must be an identifier");
98 match &meta_item.kind {
99 MetaItemKind::List(..) => {
100 error!(r#"expected `key` or `key="value"`"#);
102 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
103 error!("argument value must be a string");
105 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
106 let ident = meta_item.ident().expect("multi-segment cfg key");
107 return (ident.name, meta_item.value_str());
112 Err(err) => err.cancel(),
115 error!(r#"expected `key` or `key="value"`"#);
117 .collect::<CrateConfig>();
118 cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
122 /// The compiler configuration
124 /// Command line options
125 pub opts: config::Options,
127 /// cfg! configuration in addition to the default ones
128 pub crate_cfg: FxHashSet<(String, Option<String>)>,
131 pub input_path: Option<PathBuf>,
132 pub output_dir: Option<PathBuf>,
133 pub output_file: Option<PathBuf>,
134 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
135 pub diagnostic_output: DiagnosticOutput,
137 /// Set to capture stderr output during compiler execution
138 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
140 pub crate_name: Option<String>,
141 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
143 /// This is a callback from the driver that is called when we're registering lints;
144 /// it is called during plugin registration when we have the LintStore in a non-shared state.
146 /// Note that if you find a Some here you probably want to call that function in the new
147 /// function being registered.
148 pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
150 /// This is a callback from the driver that is called just after we have populated
151 /// the list of queries.
153 /// The second parameter is local providers and the third parameter is external providers.
154 pub override_queries:
155 Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::Providers)>,
157 /// Registry of diagnostics codes.
158 pub registry: Registry,
161 pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R) -> R {
162 let registry = &config.registry;
163 let (sess, codegen_backend) = util::create_session(
166 config.diagnostic_output,
168 config.input_path.clone(),
173 let compiler = Compiler {
177 input_path: config.input_path,
178 output_dir: config.output_dir,
179 output_file: config.output_file,
180 crate_name: config.crate_name,
181 register_lints: config.register_lints,
182 override_queries: config.override_queries,
185 rustc_span::with_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
187 let _sess_abort_error = OnDrop(|| {
188 compiler.sess.finish_diagnostics(registry);
194 let prof = compiler.sess.prof.clone();
195 prof.generic_activity("drop_compiler").run(move || drop(compiler));
200 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
201 tracing::trace!("run_compiler");
202 let stderr = config.stderr.take();
203 util::setup_callbacks_and_run_in_thread_pool_with_globals(
205 config.opts.debugging_opts.threads,
207 || create_compiler_and_run(config, f),