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 std::path::PathBuf;
16 use std::sync::{Arc, Mutex};
17 use syntax::{self, parse};
18 use syntax::ast::{self, MetaItemKind};
20 use syntax::source_map::{FileName, FileLoader, SourceMap};
21 use syntax::sess::ParseSess;
22 use syntax_pos::edition;
24 pub type Result<T> = result::Result<T, ErrorReported>;
26 /// Represents a compiler session.
27 /// Can be used run `rustc_interface` queries.
28 /// Created by passing `Config` to `run_compiler`.
30 pub(crate) sess: Lrc<Session>,
31 codegen_backend: Lrc<Box<dyn CodegenBackend>>,
32 source_map: Lrc<SourceMap>,
33 pub(crate) input: Input,
34 pub(crate) input_path: Option<PathBuf>,
35 pub(crate) output_dir: Option<PathBuf>,
36 pub(crate) output_file: Option<PathBuf>,
37 pub(crate) queries: Queries,
38 pub(crate) crate_name: Option<String>,
39 pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
43 pub fn session(&self) -> &Lrc<Session> {
46 pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
49 pub fn source_map(&self) -> &Lrc<SourceMap> {
52 pub fn input(&self) -> &Input {
55 pub fn output_dir(&self) -> &Option<PathBuf> {
58 pub fn output_file(&self) -> &Option<PathBuf> {
63 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
64 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
65 syntax::with_default_globals(move || {
66 let cfg = cfgspecs.into_iter().map(|s| {
67 let sess = ParseSess::with_silent_emitter();
68 let filename = FileName::cfg_spec_source_code(&s);
69 let mut parser = parse::new_parser_from_source_str(&sess, filename, s.to_string());
71 macro_rules! error {($reason: expr) => {
72 early_error(ErrorOutputType::default(),
73 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
76 match &mut parser.parse_meta_item() {
77 Ok(meta_item) if parser.token == token::Eof => {
78 if meta_item.path.segments.len() != 1 {
79 error!("argument key must be an identifier");
81 match &meta_item.kind {
82 MetaItemKind::List(..) => {
83 error!(r#"expected `key` or `key="value"`"#);
85 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
86 error!("argument value must be a string");
88 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
89 let ident = meta_item.ident().expect("multi-segment cfg key");
90 return (ident.name, meta_item.value_str());
95 Err(err) => err.cancel(),
98 error!(r#"expected `key` or `key="value"`"#);
99 }).collect::<ast::CrateConfig>();
100 cfg.into_iter().map(|(a, b)| {
101 (a.to_string(), b.map(|b| b.to_string()))
106 /// The compiler configuration
108 /// Command line options
109 pub opts: config::Options,
111 /// cfg! configuration in addition to the default ones
112 pub crate_cfg: FxHashSet<(String, Option<String>)>,
115 pub input_path: Option<PathBuf>,
116 pub output_dir: Option<PathBuf>,
117 pub output_file: Option<PathBuf>,
118 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
119 pub diagnostic_output: DiagnosticOutput,
121 /// Set to capture stderr output during compiler execution
122 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
124 pub crate_name: Option<String>,
125 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
127 /// This is a callback from the driver that is called when we're registering lints;
128 /// it is called during plugin registration when we have the LintStore in a non-shared state.
130 /// Note that if you find a Some here you probably want to call that function in the new
131 /// function being registered.
132 pub register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
135 pub fn run_compiler_in_existing_thread_pool<F, R>(config: Config, f: F) -> R
137 F: FnOnce(&Compiler) -> R,
139 let (sess, codegen_backend, source_map) = util::create_session(
142 config.diagnostic_output,
144 config.input_path.clone(),
148 let compiler = Compiler {
153 input_path: config.input_path,
154 output_dir: config.output_dir,
155 output_file: config.output_file,
156 queries: Default::default(),
157 crate_name: config.crate_name,
158 register_lints: config.register_lints,
161 let _sess_abort_error = OnDrop(|| {
162 compiler.sess.diagnostic().print_error_count(&util::diagnostics_registry());
168 pub fn run_compiler<F, R>(mut config: Config, f: F) -> R
170 F: FnOnce(&Compiler) -> R + Send,
173 let stderr = config.stderr.take();
174 util::spawn_thread_pool(
176 config.opts.debugging_opts.threads,
178 || run_compiler_in_existing_thread_pool(config, f),
182 pub fn default_thread_pool<F, R>(edition: edition::Edition, f: F) -> R
184 F: FnOnce() -> R + Send,
187 // the 1 here is duplicating code in config.opts.debugging_opts.threads
188 // which also defaults to 1; it ultimately doesn't matter as the default
189 // isn't threaded, and just ignores this parameter
190 util::spawn_thread_pool(edition, 1, &None, f)