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