]> git.lizzy.rs Git - rust.git/blob - src/librustc_interface/interface.rs
Rollup merge of #68084 - estebank:ice-68000, r=varkor
[rust.git] / src / librustc_interface / interface.rs
1 pub use crate::passes::BoxedResolver;
2 use crate::util;
3
4 use rustc::lint;
5 use rustc::session::config::{self, ErrorOutputType, Input};
6 use rustc::session::early_error;
7 use rustc::session::{DiagnosticOutput, Session};
8 use rustc::ty;
9 use rustc::util::common::ErrorReported;
10 use rustc_codegen_utils::codegen_backend::CodegenBackend;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_data_structures::sync::Lrc;
13 use rustc_data_structures::OnDrop;
14 use rustc_errors::registry::Registry;
15 use rustc_parse::new_parser_from_source_str;
16 use rustc_span::edition;
17 use rustc_span::source_map::{FileLoader, FileName, SourceMap};
18 use std::path::PathBuf;
19 use std::result;
20 use std::sync::{Arc, Mutex};
21 use syntax::ast::{self, MetaItemKind};
22 use syntax::sess::ParseSess;
23 use syntax::token;
24
25 pub type Result<T> = result::Result<T, ErrorReported>;
26
27 /// Represents a compiler session.
28 /// Can be used to run `rustc_interface` queries.
29 /// Created by passing `Config` to `run_compiler`.
30 pub struct 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) crate_name: Option<String>,
39     pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
40     pub(crate) override_queries:
41         Option<fn(&Session, &mut ty::query::Providers<'_>, &mut ty::query::Providers<'_>)>,
42 }
43
44 impl Compiler {
45     pub fn session(&self) -> &Lrc<Session> {
46         &self.sess
47     }
48     pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
49         &self.codegen_backend
50     }
51     pub fn source_map(&self) -> &Lrc<SourceMap> {
52         &self.source_map
53     }
54     pub fn input(&self) -> &Input {
55         &self.input
56     }
57     pub fn output_dir(&self) -> &Option<PathBuf> {
58         &self.output_dir
59     }
60     pub fn output_file(&self) -> &Option<PathBuf> {
61         &self.output_file
62     }
63 }
64
65 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
66 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
67     syntax::with_default_globals(move || {
68         let cfg = cfgspecs
69             .into_iter()
70             .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());
74
75                 macro_rules! error {
76                     ($reason: expr) => {
77                         early_error(
78                             ErrorOutputType::default(),
79                             &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
80                         );
81                     };
82                 }
83
84                 match &mut parser.parse_meta_item() {
85                     Ok(meta_item) if parser.token == token::Eof => {
86                         if meta_item.path.segments.len() != 1 {
87                             error!("argument key must be an identifier");
88                         }
89                         match &meta_item.kind {
90                             MetaItemKind::List(..) => {
91                                 error!(r#"expected `key` or `key="value"`"#);
92                             }
93                             MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
94                                 error!("argument value must be a string");
95                             }
96                             MetaItemKind::NameValue(..) | MetaItemKind::Word => {
97                                 let ident = meta_item.ident().expect("multi-segment cfg key");
98                                 return (ident.name, meta_item.value_str());
99                             }
100                         }
101                     }
102                     Ok(..) => {}
103                     Err(err) => err.cancel(),
104                 }
105
106                 error!(r#"expected `key` or `key="value"`"#);
107             })
108             .collect::<ast::CrateConfig>();
109         cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
110     })
111 }
112
113 /// The compiler configuration
114 pub struct Config {
115     /// Command line options
116     pub opts: config::Options,
117
118     /// cfg! configuration in addition to the default ones
119     pub crate_cfg: FxHashSet<(String, Option<String>)>,
120
121     pub input: Input,
122     pub input_path: Option<PathBuf>,
123     pub output_dir: Option<PathBuf>,
124     pub output_file: Option<PathBuf>,
125     pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
126     pub diagnostic_output: DiagnosticOutput,
127
128     /// Set to capture stderr output during compiler execution
129     pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
130
131     pub crate_name: Option<String>,
132     pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
133
134     /// This is a callback from the driver that is called when we're registering lints;
135     /// it is called during plugin registration when we have the LintStore in a non-shared state.
136     ///
137     /// Note that if you find a Some here you probably want to call that function in the new
138     /// function being registered.
139     pub register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
140
141     /// This is a callback from the driver that is called just after we have populated
142     /// the list of queries.
143     ///
144     /// The second parameter is local providers and the third parameter is external providers.
145     pub override_queries:
146         Option<fn(&Session, &mut ty::query::Providers<'_>, &mut ty::query::Providers<'_>)>,
147
148     /// Registry of diagnostics codes.
149     pub registry: Registry,
150 }
151
152 pub fn run_compiler_in_existing_thread_pool<R>(
153     config: Config,
154     f: impl FnOnce(&Compiler) -> R,
155 ) -> R {
156     let registry = &config.registry;
157     let (sess, codegen_backend, source_map) = util::create_session(
158         config.opts,
159         config.crate_cfg,
160         config.diagnostic_output,
161         config.file_loader,
162         config.input_path.clone(),
163         config.lint_caps,
164         registry.clone(),
165     );
166
167     let compiler = Compiler {
168         sess,
169         codegen_backend,
170         source_map,
171         input: config.input,
172         input_path: config.input_path,
173         output_dir: config.output_dir,
174         output_file: config.output_file,
175         crate_name: config.crate_name,
176         register_lints: config.register_lints,
177         override_queries: config.override_queries,
178     };
179
180     let r = {
181         let _sess_abort_error = OnDrop(|| {
182             compiler.sess.diagnostic().print_error_count(registry);
183         });
184
185         f(&compiler)
186     };
187
188     let prof = compiler.sess.prof.clone();
189     prof.generic_activity("drop_compiler").run(move || drop(compiler));
190     r
191 }
192
193 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
194     let stderr = config.stderr.take();
195     util::spawn_thread_pool(
196         config.opts.edition,
197         config.opts.debugging_opts.threads,
198         &stderr,
199         || run_compiler_in_existing_thread_pool(config, f),
200     )
201 }
202
203 pub fn default_thread_pool<R: Send>(edition: edition::Edition, f: impl FnOnce() -> R + Send) -> R {
204     // the 1 here is duplicating code in config.opts.debugging_opts.threads
205     // which also defaults to 1; it ultimately doesn't matter as the default
206     // isn't threaded, and just ignores this parameter
207     util::spawn_thread_pool(edition, 1, &None, f)
208 }