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_pos::edition;
26 pub type Result<T> = result::Result<T, ErrorReported>;
28 /// Represents a compiler session.
29 /// Can be used 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) queries: Queries,
40 pub(crate) crate_name: Option<String>,
41 pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
42 pub(crate) override_queries:
43 Option<fn(&Session, &mut ty::query::Providers<'_>, &mut ty::query::Providers<'_>)>,
47 pub fn session(&self) -> &Lrc<Session> {
50 pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
53 pub fn source_map(&self) -> &Lrc<SourceMap> {
56 pub fn input(&self) -> &Input {
59 pub fn output_dir(&self) -> &Option<PathBuf> {
62 pub fn output_file(&self) -> &Option<PathBuf> {
67 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
68 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
69 syntax::with_default_globals(move || {
70 let cfg = cfgspecs.into_iter().map(|s| {
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());
75 macro_rules! error {($reason: expr) => {
76 early_error(ErrorOutputType::default(),
77 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
80 match &mut parser.parse_meta_item() {
81 Ok(meta_item) if parser.token == token::Eof => {
82 if meta_item.path.segments.len() != 1 {
83 error!("argument key must be an identifier");
85 match &meta_item.kind {
86 MetaItemKind::List(..) => {
87 error!(r#"expected `key` or `key="value"`"#);
89 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
90 error!("argument value must be a string");
92 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
93 let ident = meta_item.ident().expect("multi-segment cfg key");
94 return (ident.name, meta_item.value_str());
99 Err(err) => err.cancel(),
102 error!(r#"expected `key` or `key="value"`"#);
103 }).collect::<ast::CrateConfig>();
104 cfg.into_iter().map(|(a, b)| {
105 (a.to_string(), b.map(|b| b.to_string()))
110 /// The compiler configuration
112 /// Command line options
113 pub opts: config::Options,
115 /// cfg! configuration in addition to the default ones
116 pub crate_cfg: FxHashSet<(String, Option<String>)>,
119 pub input_path: Option<PathBuf>,
120 pub output_dir: Option<PathBuf>,
121 pub output_file: Option<PathBuf>,
122 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
123 pub diagnostic_output: DiagnosticOutput,
125 /// Set to capture stderr output during compiler execution
126 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
128 pub crate_name: Option<String>,
129 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
131 /// This is a callback from the driver that is called when we're registering lints;
132 /// it is called during plugin registration when we have the LintStore in a non-shared state.
134 /// Note that if you find a Some here you probably want to call that function in the new
135 /// function being registered.
136 pub register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
138 /// This is a callback from the driver that is called just after we have populated
139 /// the list of queries.
141 /// The second parameter is local providers and the third parameter is external providers.
142 pub override_queries:
143 Option<fn(&Session, &mut ty::query::Providers<'_>, &mut ty::query::Providers<'_>)>,
145 /// Registry of diagnostics codes.
146 pub registry: Registry,
149 pub fn run_compiler_in_existing_thread_pool<R>(
151 f: impl FnOnce(&Compiler) -> R,
153 let registry = &config.registry;
154 let (sess, codegen_backend, source_map) = util::create_session(
157 config.diagnostic_output,
159 config.input_path.clone(),
164 let compiler = Compiler {
169 input_path: config.input_path,
170 output_dir: config.output_dir,
171 output_file: config.output_file,
172 queries: Default::default(),
173 crate_name: config.crate_name,
174 register_lints: config.register_lints,
175 override_queries: config.override_queries,
178 let _sess_abort_error = OnDrop(|| {
179 compiler.sess.diagnostic().print_error_count(registry);
185 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
186 let stderr = config.stderr.take();
187 util::spawn_thread_pool(
189 config.opts.debugging_opts.threads,
191 || run_compiler_in_existing_thread_pool(config, f),
195 pub fn default_thread_pool<R: Send>(edition: edition::Edition, f: impl FnOnce() -> R + Send) -> R {
196 // the 1 here is duplicating code in config.opts.debugging_opts.threads
197 // which also defaults to 1; it ultimately doesn't matter as the default
198 // isn't threaded, and just ignores this parameter
199 util::spawn_thread_pool(edition, 1, &None, f)