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