1 pub use crate::passes::BoxedResolver;
5 use rustc::session::config::{self, ErrorOutputType, Input, OutputFilenames};
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_lint::LintStore;
16 use rustc_parse::new_parser_from_source_str;
17 use rustc_session::parse::{CrateConfig, ParseSess};
18 use rustc_span::edition;
19 use rustc_span::source_map::{FileLoader, FileName, SourceMap};
20 use std::path::PathBuf;
22 use std::sync::{Arc, Mutex};
23 use syntax::ast::{self, MetaItemKind};
26 pub type Result<T> = result::Result<T, ErrorReported>;
28 /// 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 source_map: Lrc<SourceMap>,
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) crate_name: Option<String>,
40 pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
41 pub(crate) override_queries:
42 Option<fn(&Session, &mut ty::query::Providers<'_>, &mut ty::query::Providers<'_>)>,
46 pub fn session(&self) -> &Lrc<Session> {
49 pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
52 pub fn source_map(&self) -> &Lrc<SourceMap> {
55 pub fn input(&self) -> &Input {
58 pub fn output_dir(&self) -> &Option<PathBuf> {
61 pub fn output_file(&self) -> &Option<PathBuf> {
64 pub fn build_output_filenames(
67 attrs: &[ast::Attribute],
68 ) -> OutputFilenames {
69 util::build_output_filenames(
79 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
80 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
81 syntax::with_default_globals(move || {
85 let sess = ParseSess::with_silent_emitter();
86 let filename = FileName::cfg_spec_source_code(&s);
87 let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());
92 ErrorOutputType::default(),
93 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
98 match &mut parser.parse_meta_item() {
99 Ok(meta_item) if parser.token == token::Eof => {
100 if meta_item.path.segments.len() != 1 {
101 error!("argument key must be an identifier");
103 match &meta_item.kind {
104 MetaItemKind::List(..) => {
105 error!(r#"expected `key` or `key="value"`"#);
107 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
108 error!("argument value must be a string");
110 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
111 let ident = meta_item.ident().expect("multi-segment cfg key");
112 return (ident.name, meta_item.value_str());
117 Err(err) => err.cancel(),
120 error!(r#"expected `key` or `key="value"`"#);
122 .collect::<CrateConfig>();
123 cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
127 /// The compiler configuration
129 /// Command line options
130 pub opts: config::Options,
132 /// cfg! configuration in addition to the default ones
133 pub crate_cfg: FxHashSet<(String, Option<String>)>,
136 pub input_path: Option<PathBuf>,
137 pub output_dir: Option<PathBuf>,
138 pub output_file: Option<PathBuf>,
139 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
140 pub diagnostic_output: DiagnosticOutput,
142 /// Set to capture stderr output during compiler execution
143 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
145 pub crate_name: Option<String>,
146 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
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.
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>>,
155 /// This is a callback from the driver that is called just after we have populated
156 /// the list of queries.
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<'_>)>,
162 /// Registry of diagnostics codes.
163 pub registry: Registry,
166 pub fn run_compiler_in_existing_thread_pool<R>(
168 f: impl FnOnce(&Compiler) -> R,
170 let registry = &config.registry;
171 let (sess, codegen_backend, source_map) = util::create_session(
174 config.diagnostic_output,
176 config.input_path.clone(),
181 let compiler = Compiler {
186 input_path: config.input_path,
187 output_dir: config.output_dir,
188 output_file: config.output_file,
189 crate_name: config.crate_name,
190 register_lints: config.register_lints,
191 override_queries: config.override_queries,
195 let _sess_abort_error = OnDrop(|| {
196 compiler.sess.diagnostic().print_error_count(registry);
202 let prof = compiler.sess.prof.clone();
203 prof.generic_activity("drop_compiler").run(move || drop(compiler));
207 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
208 let stderr = config.stderr.take();
209 util::spawn_thread_pool(
211 config.opts.debugging_opts.threads,
213 || run_compiler_in_existing_thread_pool(config, f),
217 pub fn default_thread_pool<R: Send>(edition: edition::Edition, f: impl FnOnce() -> R + Send) -> R {
218 // the 1 here is duplicating code in config.opts.debugging_opts.threads
219 // which also defaults to 1; it ultimately doesn't matter as the default
220 // isn't threaded, and just ignores this parameter
221 util::spawn_thread_pool(edition, 1, &None, f)