1 use crate::queries::Queries;
3 pub use crate::passes::BoxedResolver;
6 use rustc::session::early_error;
7 use rustc::session::config::{self, Input, ErrorOutputType};
8 use rustc::session::{DiagnosticOutput, Session};
9 use rustc::util::common::ErrorReported;
10 use rustc_codegen_utils::codegen_backend::CodegenBackend;
11 use rustc_data_structures::OnDrop;
12 use rustc_data_structures::sync::Lrc;
13 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
14 use rustc_errors::registry::Registry;
15 use rustc_parse::new_parser_from_source_str;
17 use std::path::PathBuf;
19 use std::sync::{Arc, Mutex};
20 use syntax::ast::{self, MetaItemKind};
22 use syntax::source_map::{FileName, FileLoader, SourceMap};
23 use syntax::sess::ParseSess;
24 use syntax_expand::config::process_configure_mod;
25 use syntax_pos::edition;
27 pub type Result<T> = result::Result<T, ErrorReported>;
29 /// Represents a compiler session.
30 /// Can be used 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 source_map: Lrc<SourceMap>,
36 pub(crate) input: Input,
37 pub(crate) input_path: Option<PathBuf>,
38 pub(crate) output_dir: Option<PathBuf>,
39 pub(crate) output_file: Option<PathBuf>,
40 pub(crate) queries: Queries,
41 pub(crate) crate_name: Option<String>,
42 pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
43 pub(crate) override_queries:
44 Option<fn(&Session, &mut ty::query::Providers<'_>, &mut ty::query::Providers<'_>)>,
48 pub fn session(&self) -> &Lrc<Session> {
51 pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
54 pub fn source_map(&self) -> &Lrc<SourceMap> {
57 pub fn input(&self) -> &Input {
60 pub fn output_dir(&self) -> &Option<PathBuf> {
63 pub fn output_file(&self) -> &Option<PathBuf> {
68 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
69 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
70 syntax::with_default_globals(move || {
71 let cfg = cfgspecs.into_iter().map(|s| {
72 let sess = ParseSess::with_silent_emitter(process_configure_mod);
73 let filename = FileName::cfg_spec_source_code(&s);
74 let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());
76 macro_rules! error {($reason: expr) => {
77 early_error(ErrorOutputType::default(),
78 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
81 match &mut parser.parse_meta_item() {
82 Ok(meta_item) if parser.token == token::Eof => {
83 if meta_item.path.segments.len() != 1 {
84 error!("argument key must be an identifier");
86 match &meta_item.kind {
87 MetaItemKind::List(..) => {
88 error!(r#"expected `key` or `key="value"`"#);
90 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
91 error!("argument value must be a string");
93 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
94 let ident = meta_item.ident().expect("multi-segment cfg key");
95 return (ident.name, meta_item.value_str());
100 Err(err) => err.cancel(),
103 error!(r#"expected `key` or `key="value"`"#);
104 }).collect::<ast::CrateConfig>();
105 cfg.into_iter().map(|(a, b)| {
106 (a.to_string(), b.map(|b| b.to_string()))
111 /// The compiler configuration
113 /// Command line options
114 pub opts: config::Options,
116 /// cfg! configuration in addition to the default ones
117 pub crate_cfg: FxHashSet<(String, Option<String>)>,
120 pub input_path: Option<PathBuf>,
121 pub output_dir: Option<PathBuf>,
122 pub output_file: Option<PathBuf>,
123 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
124 pub diagnostic_output: DiagnosticOutput,
126 /// Set to capture stderr output during compiler execution
127 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
129 pub crate_name: Option<String>,
130 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
132 /// This is a callback from the driver that is called when we're registering lints;
133 /// it is called during plugin registration when we have the LintStore in a non-shared state.
135 /// Note that if you find a Some here you probably want to call that function in the new
136 /// function being registered.
137 pub register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
139 /// This is a callback from the driver that is called just after we have populated
140 /// the list of queries.
142 /// The second parameter is local providers and the third parameter is external providers.
143 pub override_queries:
144 Option<fn(&Session, &mut ty::query::Providers<'_>, &mut ty::query::Providers<'_>)>,
146 /// Registry of diagnostics codes.
147 pub registry: Registry,
150 pub fn run_compiler_in_existing_thread_pool<R>(
152 f: impl FnOnce(&Compiler) -> R,
154 let registry = &config.registry;
155 let (sess, codegen_backend, source_map) = util::create_session(
158 config.diagnostic_output,
160 config.input_path.clone(),
165 let compiler = Compiler {
170 input_path: config.input_path,
171 output_dir: config.output_dir,
172 output_file: config.output_file,
173 queries: Default::default(),
174 crate_name: config.crate_name,
175 register_lints: config.register_lints,
176 override_queries: config.override_queries,
179 let _sess_abort_error = OnDrop(|| {
180 compiler.sess.diagnostic().print_error_count(registry);
186 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
187 let stderr = config.stderr.take();
188 util::spawn_thread_pool(
190 config.opts.debugging_opts.threads,
192 || run_compiler_in_existing_thread_pool(config, f),
196 pub fn default_thread_pool<R: Send>(edition: edition::Edition, f: impl FnOnce() -> R + Send) -> R {
197 // the 1 here is duplicating code in config.opts.debugging_opts.threads
198 // which also defaults to 1; it ultimately doesn't matter as the default
199 // isn't threaded, and just ignores this parameter
200 util::spawn_thread_pool(edition, 1, &None, f)