]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/interface.rs
Auto merge of #93645 - matthiaskrgr:rollup-eua2621, r=matthiaskrgr
[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, 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, 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 std::path::PathBuf;
23 use std::result;
24 use std::sync::{Arc, Mutex};
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 /// The compiler configuration
144 pub struct Config {
145     /// Command line options
146     pub opts: config::Options,
147
148     /// cfg! configuration in addition to the default ones
149     pub crate_cfg: FxHashSet<(String, Option<String>)>,
150
151     pub input: Input,
152     pub input_path: Option<PathBuf>,
153     pub output_dir: Option<PathBuf>,
154     pub output_file: Option<PathBuf>,
155     pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
156     pub diagnostic_output: DiagnosticOutput,
157
158     /// Set to capture stderr output during compiler execution
159     pub stderr: Option<Arc<Mutex<Vec<u8>>>>,
160
161     pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
162
163     /// This is a callback from the driver that is called when [`ParseSess`] is created.
164     pub parse_sess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
165
166     /// This is a callback from the driver that is called when we're registering lints;
167     /// it is called during plugin registration when we have the LintStore in a non-shared state.
168     ///
169     /// Note that if you find a Some here you probably want to call that function in the new
170     /// function being registered.
171     pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
172
173     /// This is a callback from the driver that is called just after we have populated
174     /// the list of queries.
175     ///
176     /// The second parameter is local providers and the third parameter is external providers.
177     pub override_queries:
178         Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::ExternProviders)>,
179
180     /// This is a callback from the driver that is called to create a codegen backend.
181     pub make_codegen_backend:
182         Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
183
184     /// Registry of diagnostics codes.
185     pub registry: Registry,
186 }
187
188 pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R) -> R {
189     let registry = &config.registry;
190     let (mut sess, codegen_backend) = util::create_session(
191         config.opts,
192         config.crate_cfg,
193         config.diagnostic_output,
194         config.file_loader,
195         config.input_path.clone(),
196         config.lint_caps,
197         config.make_codegen_backend,
198         registry.clone(),
199     );
200
201     if let Some(parse_sess_created) = config.parse_sess_created {
202         parse_sess_created(
203             &mut Lrc::get_mut(&mut sess)
204                 .expect("create_session() should never share the returned session")
205                 .parse_sess,
206         );
207     }
208
209     let temps_dir = sess.opts.debugging_opts.temps_dir.as_ref().map(|o| PathBuf::from(&o));
210
211     let compiler = Compiler {
212         sess,
213         codegen_backend,
214         input: config.input,
215         input_path: config.input_path,
216         output_dir: config.output_dir,
217         output_file: config.output_file,
218         temps_dir,
219         register_lints: config.register_lints,
220         override_queries: config.override_queries,
221     };
222
223     rustc_span::with_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
224         let r = {
225             let _sess_abort_error = OnDrop(|| {
226                 compiler.sess.finish_diagnostics(registry);
227             });
228
229             f(&compiler)
230         };
231
232         let prof = compiler.sess.prof.clone();
233         prof.generic_activity("drop_compiler").run(move || drop(compiler));
234         r
235     })
236 }
237
238 pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
239     tracing::trace!("run_compiler");
240     let stderr = config.stderr.take();
241     util::setup_callbacks_and_run_in_thread_pool_with_globals(
242         config.opts.edition,
243         config.opts.debugging_opts.threads,
244         &stderr,
245         || create_compiler_and_run(config, f),
246     )
247 }
248
249 pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
250     eprintln!("query stack during panic:");
251
252     // Be careful relying on global state here: this code is called from
253     // a panic hook, which means that the global `Handler` may be in a weird
254     // state if it was responsible for triggering the panic.
255     let i = ty::tls::with_context_opt(|icx| {
256         if let Some(icx) = icx {
257             QueryCtxt::from_tcx(icx.tcx).try_print_query_stack(icx.query, handler, num_frames)
258         } else {
259             0
260         }
261     });
262
263     if num_frames == None || num_frames >= Some(i) {
264         eprintln!("end of query stack");
265     } else {
266         eprintln!("we're just showing a limited slice of the query stack");
267     }
268 }