]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/interface.rs
Sync rust-lang/portable-simd@5f49d4c8435a25d804b2f375e949cb25479f5be9
[rust.git] / compiler / rustc_interface / src / interface.rs
1 pub use crate::passes::BoxedResolver;
2 use crate::util;
3
4 use rustc_ast::token;
5 use rustc_ast::{self as ast, LitKind, MetaItemKind};
6 use rustc_codegen_ssa::traits::CodegenBackend;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_data_structures::sync::Lrc;
9 use rustc_data_structures::OnDrop;
10 use rustc_errors::registry::Registry;
11 use rustc_errors::{ErrorReported, Handler};
12 use rustc_lint::LintStore;
13 use rustc_middle::ty;
14 use rustc_parse::maybe_new_parser_from_source_str;
15 use rustc_query_impl::QueryCtxt;
16 use rustc_session::config::{self, CheckCfg, ErrorOutputType, Input, OutputFilenames};
17 use rustc_session::early_error;
18 use rustc_session::lint;
19 use rustc_session::parse::{CrateConfig, ParseSess};
20 use rustc_session::{DiagnosticOutput, Session};
21 use rustc_span::source_map::{FileLoader, FileName};
22 use rustc_span::symbol::sym;
23 use std::path::PathBuf;
24 use std::result;
25
26 pub type Result<T> = result::Result<T, ErrorReported>;
27
28 /// Represents a compiler session.
29 ///
30 /// Can be used to 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     pub(crate) input: Input,
36     pub(crate) input_path: Option<PathBuf>,
37     pub(crate) output_dir: Option<PathBuf>,
38     pub(crate) output_file: Option<PathBuf>,
39     pub(crate) temps_dir: Option<PathBuf>,
40     pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
41     pub(crate) override_queries:
42         Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::ExternProviders)>,
43 }
44
45 impl Compiler {
46     pub fn session(&self) -> &Lrc<Session> {
47         &self.sess
48     }
49     pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
50         &self.codegen_backend
51     }
52     pub fn input(&self) -> &Input {
53         &self.input
54     }
55     pub fn output_dir(&self) -> &Option<PathBuf> {
56         &self.output_dir
57     }
58     pub fn output_file(&self) -> &Option<PathBuf> {
59         &self.output_file
60     }
61     pub fn temps_dir(&self) -> &Option<PathBuf> {
62         &self.temps_dir
63     }
64     pub fn register_lints(&self) -> &Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>> {
65         &self.register_lints
66     }
67     pub fn build_output_filenames(
68         &self,
69         sess: &Session,
70         attrs: &[ast::Attribute],
71     ) -> OutputFilenames {
72         util::build_output_filenames(
73             &self.input,
74             &self.output_dir,
75             &self.output_file,
76             &self.temps_dir,
77             attrs,
78             sess,
79         )
80     }
81 }
82
83 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
84 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
85     rustc_span::create_default_session_if_not_set_then(move |_| {
86         let cfg = cfgspecs
87             .into_iter()
88             .map(|s| {
89                 let sess = ParseSess::with_silent_emitter(Some(format!(
90                     "this error occurred on the command line: `--cfg={}`",
91                     s
92                 )));
93                 let filename = FileName::cfg_spec_source_code(&s);
94
95                 macro_rules! error {
96                     ($reason: expr) => {
97                         early_error(
98                             ErrorOutputType::default(),
99                             &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
100                         );
101                     };
102                 }
103
104                 match maybe_new_parser_from_source_str(&sess, filename, s.to_string()) {
105                     Ok(mut parser) => match &mut parser.parse_meta_item() {
106                         Ok(meta_item) if parser.token == token::Eof => {
107                             if meta_item.path.segments.len() != 1 {
108                                 error!("argument key must be an identifier");
109                             }
110                             match &meta_item.kind {
111                                 MetaItemKind::List(..) => {}
112                                 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
113                                     error!("argument value must be a string");
114                                 }
115                                 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
116                                     let ident = meta_item.ident().expect("multi-segment cfg key");
117                                     return (ident.name, meta_item.value_str());
118                                 }
119                             }
120                         }
121                         Ok(..) => {}
122                         Err(err) => err.cancel(),
123                     },
124                     Err(errs) => errs.into_iter().for_each(|mut err| err.cancel()),
125                 }
126
127                 // If the user tried to use a key="value" flag, but is missing the quotes, provide
128                 // a hint about how to resolve this.
129                 if s.contains('=') && !s.contains("=\"") && !s.ends_with('"') {
130                     error!(concat!(
131                         r#"expected `key` or `key="value"`, ensure escaping is appropriate"#,
132                         r#" for your shell, try 'key="value"' or key=\"value\""#
133                     ));
134                 } else {
135                     error!(r#"expected `key` or `key="value"`"#);
136                 }
137             })
138             .collect::<CrateConfig>();
139         cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
140     })
141 }
142
143 /// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
144 pub fn parse_check_cfg(specs: Vec<String>) -> CheckCfg {
145     rustc_span::create_default_session_if_not_set_then(move |_| {
146         let mut cfg = CheckCfg::default();
147
148         'specs: for s in specs {
149             let sess = ParseSess::with_silent_emitter(Some(format!(
150                 "this error occurred on the command line: `--check-cfg={}`",
151                 s
152             )));
153             let filename = FileName::cfg_spec_source_code(&s);
154
155             macro_rules! error {
156                 ($reason: expr) => {
157                     early_error(
158                         ErrorOutputType::default(),
159                         &format!(
160                             concat!("invalid `--check-cfg` argument: `{}` (", $reason, ")"),
161                             s
162                         ),
163                     );
164                 };
165             }
166
167             match maybe_new_parser_from_source_str(&sess, filename, s.to_string()) {
168                 Ok(mut parser) => match &mut parser.parse_meta_item() {
169                     Ok(meta_item) if parser.token == token::Eof => {
170                         if let Some(args) = meta_item.meta_item_list() {
171                             if meta_item.has_name(sym::names) {
172                                 cfg.names_checked = true;
173                                 for arg in args {
174                                     if arg.is_word() && arg.ident().is_some() {
175                                         let ident = arg.ident().expect("multi-segment cfg key");
176                                         cfg.names_valid.insert(ident.name.to_string());
177                                     } else {
178                                         error!("`names()` arguments must be simple identifers");
179                                     }
180                                 }
181                                 continue 'specs;
182                             } else if meta_item.has_name(sym::values) {
183                                 if let Some((name, values)) = args.split_first() {
184                                     if name.is_word() && name.ident().is_some() {
185                                         let ident = name.ident().expect("multi-segment cfg key");
186                                         cfg.values_checked.insert(ident.to_string());
187                                         for val in values {
188                                             if let Some(LitKind::Str(s, _)) =
189                                                 val.literal().map(|lit| &lit.kind)
190                                             {
191                                                 cfg.values_valid
192                                                     .insert((ident.to_string(), s.to_string()));
193                                             } else {
194                                                 error!(
195                                                     "`values()` arguments must be string literals"
196                                                 );
197                                             }
198                                         }
199
200                                         continue 'specs;
201                                     } else {
202                                         error!(
203                                             "`values()` first argument must be a simple identifer"
204                                         );
205                                     }
206                                 }
207                             }
208                         }
209                     }
210                     Ok(..) => {}
211                     Err(err) => err.cancel(),
212                 },
213                 Err(errs) => errs.into_iter().for_each(|mut err| err.cancel()),
214             }
215
216             error!(
217                 "expected `names(name1, name2, ... nameN)` or \
218                 `values(name, \"value1\", \"value2\", ... \"valueN\")`"
219             );
220         }
221
222         cfg.names_valid.extend(cfg.values_checked.iter().cloned());
223         cfg
224     })
225 }
226
227 /// The compiler configuration
228 pub struct Config {
229     /// Command line options
230     pub opts: config::Options,
231
232     /// cfg! configuration in addition to the default ones
233     pub crate_cfg: FxHashSet<(String, Option<String>)>,
234     pub crate_check_cfg: CheckCfg,
235
236     pub input: Input,
237     pub input_path: Option<PathBuf>,
238     pub output_dir: Option<PathBuf>,
239     pub output_file: Option<PathBuf>,
240     pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
241     pub diagnostic_output: DiagnosticOutput,
242
243     pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
244
245     /// This is a callback from the driver that is called when [`ParseSess`] is created.
246     pub parse_sess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
247
248     /// This is a callback from the driver that is called when we're registering lints;
249     /// it is called during plugin registration when we have the LintStore in a non-shared state.
250     ///
251     /// Note that if you find a Some here you probably want to call that function in the new
252     /// function being registered.
253     pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
254
255     /// This is a callback from the driver that is called just after we have populated
256     /// the list of queries.
257     ///
258     /// The second parameter is local providers and the third parameter is external providers.
259     pub override_queries:
260         Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::ExternProviders)>,
261
262     /// This is a callback from the driver that is called to create a codegen backend.
263     pub make_codegen_backend:
264         Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
265
266     /// Registry of diagnostics codes.
267     pub registry: Registry,
268 }
269
270 pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R) -> R {
271     crate::callbacks::setup_callbacks();
272
273     let registry = &config.registry;
274     let (mut sess, codegen_backend) = util::create_session(
275         config.opts,
276         config.crate_cfg,
277         config.crate_check_cfg,
278         config.diagnostic_output,
279         config.file_loader,
280         config.input_path.clone(),
281         config.lint_caps,
282         config.make_codegen_backend,
283         registry.clone(),
284     );
285
286     if let Some(parse_sess_created) = config.parse_sess_created {
287         parse_sess_created(
288             &mut Lrc::get_mut(&mut sess)
289                 .expect("create_session() should never share the returned session")
290                 .parse_sess,
291         );
292     }
293
294     let temps_dir = sess.opts.debugging_opts.temps_dir.as_ref().map(|o| PathBuf::from(&o));
295
296     let compiler = Compiler {
297         sess,
298         codegen_backend,
299         input: config.input,
300         input_path: config.input_path,
301         output_dir: config.output_dir,
302         output_file: config.output_file,
303         temps_dir,
304         register_lints: config.register_lints,
305         override_queries: config.override_queries,
306     };
307
308     rustc_span::with_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
309         let r = {
310             let _sess_abort_error = OnDrop(|| {
311                 compiler.sess.finish_diagnostics(registry);
312             });
313
314             f(&compiler)
315         };
316
317         let prof = compiler.sess.prof.clone();
318         prof.generic_activity("drop_compiler").run(move || drop(compiler));
319         r
320     })
321 }
322
323 pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
324     tracing::trace!("run_compiler");
325     util::run_in_thread_pool_with_globals(
326         config.opts.edition,
327         config.opts.debugging_opts.threads,
328         || create_compiler_and_run(config, f),
329     )
330 }
331
332 pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
333     eprintln!("query stack during panic:");
334
335     // Be careful relying on global state here: this code is called from
336     // a panic hook, which means that the global `Handler` may be in a weird
337     // state if it was responsible for triggering the panic.
338     let i = ty::tls::with_context_opt(|icx| {
339         if let Some(icx) = icx {
340             QueryCtxt::from_tcx(icx.tcx).try_print_query_stack(icx.query, handler, num_frames)
341         } else {
342             0
343         }
344     });
345
346     if num_frames == None || num_frames >= Some(i) {
347         eprintln!("end of query stack");
348     } else {
349         eprintln!("we're just showing a limited slice of the query stack");
350     }
351 }