1 pub use crate::passes::BoxedResolver;
5 use rustc::session::config::{self, ErrorOutputType, Input};
6 use rustc::session::early_error;
7 use rustc::session::{DiagnosticOutput, Session};
9 use rustc::util::common::ErrorReported;
10 use rustc_codegen_utils::codegen_backend::CodegenBackend;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_data_structures::sync::Lrc;
13 use rustc_data_structures::OnDrop;
14 use rustc_errors::registry::Registry;
15 use rustc_parse::new_parser_from_source_str;
16 use rustc_span::edition;
17 use rustc_span::source_map::{FileLoader, FileName, SourceMap};
18 use std::path::PathBuf;
20 use std::sync::{Arc, Mutex};
21 use syntax::ast::{self, MetaItemKind};
22 use syntax::sess::ParseSess;
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 source_map: Lrc<SourceMap>,
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) crate_name: Option<String>,
39 pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut lint::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 source_map(&self) -> &Lrc<SourceMap> {
54 pub fn input(&self) -> &Input {
57 pub fn output_dir(&self) -> &Option<PathBuf> {
60 pub fn output_file(&self) -> &Option<PathBuf> {
65 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
66 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
67 syntax::with_default_globals(move || {
71 let sess = ParseSess::with_silent_emitter();
72 let filename = FileName::cfg_spec_source_code(&s);
73 let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());
78 ErrorOutputType::default(),
79 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
84 match &mut parser.parse_meta_item() {
85 Ok(meta_item) if parser.token == token::Eof => {
86 if meta_item.path.segments.len() != 1 {
87 error!("argument key must be an identifier");
89 match &meta_item.kind {
90 MetaItemKind::List(..) => {
91 error!(r#"expected `key` or `key="value"`"#);
93 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
94 error!("argument value must be a string");
96 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
97 let ident = meta_item.ident().expect("multi-segment cfg key");
98 return (ident.name, meta_item.value_str());
103 Err(err) => err.cancel(),
106 error!(r#"expected `key` or `key="value"`"#);
108 .collect::<ast::CrateConfig>();
109 cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
113 /// The compiler configuration
115 /// Command line options
116 pub opts: config::Options,
118 /// cfg! configuration in addition to the default ones
119 pub crate_cfg: FxHashSet<(String, Option<String>)>,
122 pub input_path: Option<PathBuf>,
123 pub output_dir: Option<PathBuf>,
124 pub output_file: Option<PathBuf>,
125 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
126 pub diagnostic_output: DiagnosticOutput,
128 /// Set to capture stderr output during compiler execution
129 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
131 pub crate_name: Option<String>,
132 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
134 /// This is a callback from the driver that is called when we're registering lints;
135 /// it is called during plugin registration when we have the LintStore in a non-shared state.
137 /// Note that if you find a Some here you probably want to call that function in the new
138 /// function being registered.
139 pub register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
141 /// This is a callback from the driver that is called just after we have populated
142 /// the list of queries.
144 /// The second parameter is local providers and the third parameter is external providers.
145 pub override_queries:
146 Option<fn(&Session, &mut ty::query::Providers<'_>, &mut ty::query::Providers<'_>)>,
148 /// Registry of diagnostics codes.
149 pub registry: Registry,
152 pub fn run_compiler_in_existing_thread_pool<R>(
154 f: impl FnOnce(&Compiler) -> R,
156 let registry = &config.registry;
157 let (sess, codegen_backend, source_map) = util::create_session(
160 config.diagnostic_output,
162 config.input_path.clone(),
167 let compiler = Compiler {
172 input_path: config.input_path,
173 output_dir: config.output_dir,
174 output_file: config.output_file,
175 crate_name: config.crate_name,
176 register_lints: config.register_lints,
177 override_queries: config.override_queries,
181 let _sess_abort_error = OnDrop(|| {
182 compiler.sess.diagnostic().print_error_count(registry);
188 let prof = compiler.sess.prof.clone();
189 prof.generic_activity("drop_compiler").run(move || drop(compiler));
193 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
194 let stderr = config.stderr.take();
195 util::spawn_thread_pool(
197 config.opts.debugging_opts.threads,
199 || run_compiler_in_existing_thread_pool(config, f),
203 pub fn default_thread_pool<R: Send>(edition: edition::Edition, f: impl FnOnce() -> R + Send) -> R {
204 // the 1 here is duplicating code in config.opts.debugging_opts.threads
205 // which also defaults to 1; it ultimately doesn't matter as the default
206 // isn't threaded, and just ignores this parameter
207 util::spawn_thread_pool(edition, 1, &None, f)