1 pub use crate::passes::BoxedResolver;
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::{ErrorGuaranteed, Handler};
12 use rustc_lint::LintStore;
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::Session;
21 use rustc_span::source_map::{FileLoader, FileName};
22 use rustc_span::symbol::sym;
23 use std::path::PathBuf;
26 pub type Result<T> = result::Result<T, ErrorGuaranteed>;
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.
33 /// Can be used to run `rustc_interface` queries.
34 /// Created by passing [`Config`] to [`run_compiler`].
36 pub(crate) sess: Lrc<Session>,
37 codegen_backend: Lrc<Box<dyn CodegenBackend>>,
38 pub(crate) input: Input,
39 pub(crate) input_path: Option<PathBuf>,
40 pub(crate) output_dir: Option<PathBuf>,
41 pub(crate) output_file: Option<PathBuf>,
42 pub(crate) temps_dir: Option<PathBuf>,
43 pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
44 pub(crate) override_queries:
45 Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::ExternProviders)>,
49 pub fn session(&self) -> &Lrc<Session> {
52 pub fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
55 pub fn input(&self) -> &Input {
58 pub fn output_dir(&self) -> &Option<PathBuf> {
61 pub fn output_file(&self) -> &Option<PathBuf> {
64 pub fn temps_dir(&self) -> &Option<PathBuf> {
67 pub fn register_lints(&self) -> &Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>> {
70 pub fn build_output_filenames(
73 attrs: &[ast::Attribute],
74 ) -> OutputFilenames {
75 util::build_output_filenames(
86 /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
87 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
88 rustc_span::create_default_session_if_not_set_then(move |_| {
92 let sess = ParseSess::with_silent_emitter(Some(format!(
93 "this error occurred on the command line: `--cfg={s}`"
95 let filename = FileName::cfg_spec_source_code(&s);
100 ErrorOutputType::default(),
101 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s),
106 match maybe_new_parser_from_source_str(&sess, filename, s.to_string()) {
107 Ok(mut parser) => match parser.parse_meta_item() {
108 Ok(meta_item) if parser.token == token::Eof => {
109 if meta_item.path.segments.len() != 1 {
110 error!("argument key must be an identifier");
112 match &meta_item.kind {
113 MetaItemKind::List(..) => {}
114 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
115 error!("argument value must be a string");
117 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
118 let ident = meta_item.ident().expect("multi-segment cfg key");
119 return (ident.name, meta_item.value_str());
124 Err(err) => err.cancel(),
126 Err(errs) => drop(errs),
129 // If the user tried to use a key="value" flag, but is missing the quotes, provide
130 // a hint about how to resolve this.
131 if s.contains('=') && !s.contains("=\"") && !s.ends_with('"') {
133 r#"expected `key` or `key="value"`, ensure escaping is appropriate"#,
134 r#" for your shell, try 'key="value"' or key=\"value\""#
137 error!(r#"expected `key` or `key="value"`"#);
140 .collect::<CrateConfig>();
141 cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
145 /// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
146 pub fn parse_check_cfg(specs: Vec<String>) -> CheckCfg {
147 rustc_span::create_default_session_if_not_set_then(move |_| {
148 let mut cfg = CheckCfg::default();
150 'specs: for s in specs {
151 let sess = ParseSess::with_silent_emitter(Some(format!(
152 "this error occurred on the command line: `--check-cfg={s}`"
154 let filename = FileName::cfg_spec_source_code(&s);
159 ErrorOutputType::default(),
161 concat!("invalid `--check-cfg` argument: `{}` (", $reason, ")"),
168 match maybe_new_parser_from_source_str(&sess, filename, s.to_string()) {
169 Ok(mut parser) => match parser.parse_meta_item() {
170 Ok(meta_item) if parser.token == token::Eof => {
171 if let Some(args) = meta_item.meta_item_list() {
172 if meta_item.has_name(sym::names) {
174 cfg.names_valid.get_or_insert_with(|| FxHashSet::default());
176 if arg.is_word() && arg.ident().is_some() {
177 let ident = arg.ident().expect("multi-segment cfg key");
178 names_valid.insert(ident.name.to_string());
180 error!("`names()` arguments must be simple identifiers");
184 } else if meta_item.has_name(sym::values) {
185 if let Some((name, values)) = args.split_first() {
186 if name.is_word() && name.ident().is_some() {
187 let ident = name.ident().expect("multi-segment cfg key");
188 let ident_values = cfg
190 .entry(ident.name.to_string())
191 .or_insert_with(|| FxHashSet::default());
194 if let Some(LitKind::Str(s, _)) =
195 val.lit().map(|lit| &lit.kind)
197 ident_values.insert(s.to_string());
200 "`values()` arguments must be string literals"
208 "`values()` first argument must be a simple identifier"
211 } else if args.is_empty() {
212 cfg.well_known_values = true;
219 Err(err) => err.cancel(),
221 Err(errs) => drop(errs),
225 "expected `names(name1, name2, ... nameN)` or \
226 `values(name, \"value1\", \"value2\", ... \"valueN\")`"
230 if let Some(names_valid) = &mut cfg.names_valid {
231 names_valid.extend(cfg.values_valid.keys().cloned());
237 /// The compiler configuration
239 /// Command line options
240 pub opts: config::Options,
242 /// cfg! configuration in addition to the default ones
243 pub crate_cfg: FxHashSet<(String, Option<String>)>,
244 pub crate_check_cfg: CheckCfg,
247 pub input_path: Option<PathBuf>,
248 pub output_dir: Option<PathBuf>,
249 pub output_file: Option<PathBuf>,
250 pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
252 pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
254 /// This is a callback from the driver that is called when [`ParseSess`] is created.
255 pub parse_sess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
257 /// This is a callback from the driver that is called when we're registering lints;
258 /// it is called during plugin registration when we have the LintStore in a non-shared state.
260 /// Note that if you find a Some here you probably want to call that function in the new
261 /// function being registered.
262 pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
264 /// This is a callback from the driver that is called just after we have populated
265 /// the list of queries.
267 /// The second parameter is local providers and the third parameter is external providers.
268 pub override_queries:
269 Option<fn(&Session, &mut ty::query::Providers, &mut ty::query::ExternProviders)>,
271 /// This is a callback from the driver that is called to create a codegen backend.
272 pub make_codegen_backend:
273 Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
275 /// Registry of diagnostics codes.
276 pub registry: Registry,
279 // JUSTIFICATION: before session exists, only config
280 #[allow(rustc::bad_opt_access)]
281 pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
282 trace!("run_compiler");
283 util::run_in_thread_pool_with_globals(
285 config.opts.unstable_opts.threads,
287 crate::callbacks::setup_callbacks();
289 let registry = &config.registry;
290 let (mut sess, codegen_backend) = util::create_session(
293 config.crate_check_cfg,
295 config.input_path.clone(),
297 config.make_codegen_backend,
301 if let Some(parse_sess_created) = config.parse_sess_created {
302 parse_sess_created(&mut sess.parse_sess);
305 let temps_dir = sess.opts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
307 let compiler = Compiler {
308 sess: Lrc::new(sess),
309 codegen_backend: Lrc::new(codegen_backend),
311 input_path: config.input_path,
312 output_dir: config.output_dir,
313 output_file: config.output_file,
315 register_lints: config.register_lints,
316 override_queries: config.override_queries,
319 rustc_span::with_source_map(compiler.sess.parse_sess.clone_source_map(), move || {
321 let _sess_abort_error = OnDrop(|| {
322 compiler.sess.finish_diagnostics(registry);
328 let prof = compiler.sess.prof.clone();
329 prof.generic_activity("drop_compiler").run(move || drop(compiler));
336 pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
337 eprintln!("query stack during panic:");
339 // Be careful relying on global state here: this code is called from
340 // a panic hook, which means that the global `Handler` may be in a weird
341 // state if it was responsible for triggering the panic.
342 let i = ty::tls::with_context_opt(|icx| {
343 if let Some(icx) = icx {
344 QueryCtxt::from_tcx(icx.tcx).try_print_query_stack(icx.query, handler, num_frames)
350 if num_frames == None || num_frames >= Some(i) {
351 eprintln!("end of query stack");
353 eprintln!("we're just showing a limited slice of the query stack");