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_parse::new_parser_from_source_str;
15 use std::path::PathBuf;
17 use std::sync::{Arc, Mutex};
18 use syntax::ast::{self, MetaItemKind};
20 use syntax::source_map::{FileName, FileLoader, SourceMap};
21 use syntax::sess::ParseSess;
22 use syntax_expand::config::process_configure_mod;
23 use syntax_pos::edition;
25 pub type Result<T> = result::Result<T, ErrorReported>;
27 /// Represents a compiler session.
28 /// Can be used 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) queries: Queries,
39 pub(crate) crate_name: Option<String>,
40 pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
44 pub fn session(&self) -> &Lrc<Session> {
47 pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
50 pub fn source_map(&self) -> &Lrc<SourceMap> {
53 pub fn input(&self) -> &Input {
56 pub fn output_dir(&self) -> &Option<PathBuf> {
59 pub fn output_file(&self) -> &Option<PathBuf> {
64 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
65 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
66 syntax::with_default_globals(move || {
67 let cfg = cfgspecs.into_iter().map(|s| {
68 let sess = ParseSess::with_silent_emitter(process_configure_mod);
69 let filename = FileName::cfg_spec_source_code(&s);
70 let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());
72 macro_rules! error {($reason: expr) => {
73 early_error(ErrorOutputType::default(),
74 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
77 match &mut parser.parse_meta_item() {
78 Ok(meta_item) if parser.token == token::Eof => {
79 if meta_item.path.segments.len() != 1 {
80 error!("argument key must be an identifier");
82 match &meta_item.kind {
83 MetaItemKind::List(..) => {
84 error!(r#"expected `key` or `key="value"`"#);
86 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
87 error!("argument value must be a string");
89 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
90 let ident = meta_item.ident().expect("multi-segment cfg key");
91 return (ident.name, meta_item.value_str());
96 Err(err) => err.cancel(),
99 error!(r#"expected `key` or `key="value"`"#);
100 }).collect::<ast::CrateConfig>();
101 cfg.into_iter().map(|(a, b)| {
102 (a.to_string(), b.map(|b| b.to_string()))
107 /// The compiler configuration
109 /// Command line options
110 pub opts: config::Options,
112 /// cfg! configuration in addition to the default ones
113 pub crate_cfg: FxHashSet<(String, Option<String>)>,
116 pub input_path: Option<PathBuf>,
117 pub output_dir: Option<PathBuf>,
118 pub output_file: Option<PathBuf>,
119 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
120 pub diagnostic_output: DiagnosticOutput,
122 /// Set to capture stderr output during compiler execution
123 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
125 pub crate_name: Option<String>,
126 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
128 /// This is a callback from the driver that is called when we're registering lints;
129 /// it is called during plugin registration when we have the LintStore in a non-shared state.
131 /// Note that if you find a Some here you probably want to call that function in the new
132 /// function being registered.
133 pub register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
136 pub fn run_compiler_in_existing_thread_pool<F, R>(config: Config, f: F) -> R
138 F: FnOnce(&Compiler) -> R,
140 let (sess, codegen_backend, source_map) = util::create_session(
143 config.diagnostic_output,
145 config.input_path.clone(),
149 let compiler = Compiler {
154 input_path: config.input_path,
155 output_dir: config.output_dir,
156 output_file: config.output_file,
157 queries: Default::default(),
158 crate_name: config.crate_name,
159 register_lints: config.register_lints,
162 let _sess_abort_error = OnDrop(|| {
163 compiler.sess.diagnostic().print_error_count(&util::diagnostics_registry());
169 pub fn run_compiler<F, R>(mut config: Config, f: F) -> R
171 F: FnOnce(&Compiler) -> R + Send,
174 let stderr = config.stderr.take();
175 util::spawn_thread_pool(
177 config.opts.debugging_opts.threads,
179 || run_compiler_in_existing_thread_pool(config, f),
183 pub fn default_thread_pool<F, R>(edition: edition::Edition, f: F) -> R
185 F: FnOnce() -> R + Send,
188 // the 1 here is duplicating code in config.opts.debugging_opts.threads
189 // which also defaults to 1; it ultimately doesn't matter as the default
190 // isn't threaded, and just ignores this parameter
191 util::spawn_thread_pool(edition, 1, &None, f)