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};
19 use syntax::parse::token;
20 use syntax::source_map::{FileName, FilePathMapping, FileLoader, SourceMap};
21 use syntax::sess::ParseSess;
22 use syntax_pos::edition;
23 use rustc_errors::{Diagnostic, emitter::Emitter, Handler, SourceMapperDyn};
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>)> {
67 impl Emitter for NullEmitter {
68 fn emit_diagnostic(&mut self, _: &Diagnostic) {}
69 fn source_map(&self) -> Option<&Lrc<SourceMapperDyn>> { None }
72 syntax::with_default_globals(move || {
73 let cfg = cfgspecs.into_iter().map(|s| {
75 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
76 let handler = Handler::with_emitter(false, None, Box::new(NullEmitter));
77 let sess = ParseSess::with_span_handler(handler, cm);
78 let filename = FileName::cfg_spec_source_code(&s);
79 let mut parser = parse::new_parser_from_source_str(&sess, filename, s.to_string());
81 macro_rules! error {($reason: expr) => {
82 early_error(ErrorOutputType::default(),
83 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
86 match &mut parser.parse_meta_item() {
87 Ok(meta_item) if parser.token == token::Eof => {
88 if meta_item.path.segments.len() != 1 {
89 error!("argument key must be an identifier");
91 match &meta_item.kind {
92 MetaItemKind::List(..) => {
93 error!(r#"expected `key` or `key="value"`"#);
95 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
96 error!("argument value must be a string");
98 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
99 let ident = meta_item.ident().expect("multi-segment cfg key");
100 return (ident.name, meta_item.value_str());
105 Err(err) => err.cancel(),
108 error!(r#"expected `key` or `key="value"`"#);
109 }).collect::<ast::CrateConfig>();
110 cfg.into_iter().map(|(a, b)| {
111 (a.to_string(), b.map(|b| b.to_string()))
116 /// The compiler configuration
118 /// Command line options
119 pub opts: config::Options,
121 /// cfg! configuration in addition to the default ones
122 pub crate_cfg: FxHashSet<(String, Option<String>)>,
125 pub input_path: Option<PathBuf>,
126 pub output_dir: Option<PathBuf>,
127 pub output_file: Option<PathBuf>,
128 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
129 pub diagnostic_output: DiagnosticOutput,
131 /// Set to capture stderr output during compiler execution
132 pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
134 pub crate_name: Option<String>,
135 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
137 /// This is a callback from the driver that is called when we're registering lints;
138 /// it is called during plugin registration when we have the LintStore in a non-shared state.
140 /// Note that if you find a Some here you probably want to call that function in the new
141 /// function being registered.
142 pub register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
145 pub fn run_compiler_in_existing_thread_pool<F, R>(config: Config, f: F) -> R
147 F: FnOnce(&Compiler) -> R,
149 let (sess, codegen_backend, source_map) = util::create_session(
152 config.diagnostic_output,
154 config.input_path.clone(),
158 let compiler = Compiler {
163 input_path: config.input_path,
164 output_dir: config.output_dir,
165 output_file: config.output_file,
166 queries: Default::default(),
167 crate_name: config.crate_name,
168 register_lints: config.register_lints,
171 let _sess_abort_error = OnDrop(|| {
172 compiler.sess.diagnostic().print_error_count(&util::diagnostics_registry());
178 pub fn run_compiler<F, R>(mut config: Config, f: F) -> R
180 F: FnOnce(&Compiler) -> R + Send,
183 let stderr = config.stderr.take();
184 util::spawn_thread_pool(
186 config.opts.debugging_opts.threads,
188 || run_compiler_in_existing_thread_pool(config, f),
192 pub fn default_thread_pool<F, R>(edition: edition::Edition, f: F) -> R
194 F: FnOnce() -> R + Send,
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)