1use std::path::PathBuf;
2use std::result;
3use std::sync::Arc;
45use rustc_ast::{LitKind, MetaItemKind, token};
6use rustc_codegen_ssa::traits::CodegenBackend;
7use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8use rustc_data_structures::jobserver;
9use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
10use rustc_lint::LintStore;
11use rustc_middle::ty;
12use rustc_middle::ty::CurrentGcx;
13use rustc_middle::util::Providers;
14use rustc_parse::lexer::StripTokens;
15use rustc_parse::new_parser_from_source_str;
16use rustc_parse::parser::Recovery;
17use rustc_query_impl::print_query_stack;
18use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, OutFileName};
19use rustc_session::parse::ParseSess;
20use rustc_session::{CompilerIO, EarlyDiagCtxt, Session, lint};
21use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs};
22use rustc_span::{FileName, sym};
23use tracing::trace;
2425use crate::util;
2627pub type Result<T> = result::Result<T, ErrorGuaranteed>;
2829/// Represents a compiler session. Note that every `Compiler` contains a
30/// `Session`, but `Compiler` also contains some things that cannot be in
31/// `Session`, due to `Session` being in a crate that has many fewer
32/// dependencies than this crate.
33///
34/// Can be used to run `rustc_interface` queries.
35/// Created by passing [`Config`] to [`run_compiler`].
36pub struct Compiler {
37pub sess: Session,
38pub codegen_backend: Box<dyn CodegenBackend>,
39pub(crate) override_queries: Option<fn(&Session, &mut Providers)>,
4041/// A reference to the current `GlobalCtxt` which we pass on to `GlobalCtxt`.
42pub(crate) current_gcx: CurrentGcx,
43}
4445/// Converts strings provided as `--cfg [cfgspec]` into a `Cfg`.
46pub(crate) fn parse_cfg(dcx: DiagCtxtHandle<'_>, cfgs: Vec<String>) -> Cfg {
47cfgs.into_iter()
48 .map(|s| {
49let psess = ParseSess::emitter_with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this occurred on the command line: `--cfg={0}`",
s))
})format!(
50"this occurred on the command line: `--cfg={s}`"
51));
52let filename = FileName::cfg_spec_source_code(&s);
5354macro_rules! error {
55 ($reason: expr) => {
56 dcx.fatal(format!("invalid `--cfg` argument: `{s}` ({})", $reason));
57 };
58 }
5960match new_parser_from_source_str(&psess, filename, s.to_string(), StripTokens::Nothing)
61 {
62Ok(mut parser) => {
63parser = parser.recovery(Recovery::Forbidden);
64match parser.parse_meta_item() {
65Ok(meta_item)
66if parser.token == token::Eof67 && parser.dcx().has_errors().is_none() =>
68 {
69if meta_item.path.segments.len() != 1 {
70dcx.fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
"argument key must be an identifier", s))
}));error!("argument key must be an identifier");
71 }
72match &meta_item.kind {
73 MetaItemKind::List(..) => {}
74 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
75dcx.fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
"argument value must be a string", s))
}));error!("argument value must be a string");
76 }
77 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
78let ident = meta_item.ident().expect("multi-segment cfg key");
7980if ident.is_path_segment_keyword() {
81dcx.fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
"malformed `cfg` input, expected a valid identifier", s))
}));error!(
82"malformed `cfg` input, expected a valid identifier"
83);
84 }
8586return (ident.name, meta_item.value_str());
87 }
88 }
89 }
90Ok(..) => {}
91Err(err) => err.cancel(),
92 }
93 }
94Err(errs) => errs.into_iter().for_each(|err| err.cancel()),
95 };
9697// If the user tried to use a key="value" flag, but is missing the quotes, provide
98 // a hint about how to resolve this.
99if s.contains('=') && !s.contains("=\"") && !s.ends_with('"') {
100dcx.fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
"expected `key` or `key=\"value\"`, ensure escaping is appropriate for your shell, try \'key=\"value\"\' or key=\\\"value\\\"",
s))
}));error!(concat!(
101r#"expected `key` or `key="value"`, ensure escaping is appropriate"#,
102r#" for your shell, try 'key="value"' or key=\"value\""#
103));
104 } else {
105dcx.fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
r#"expected `key` or `key="value"`"#, s))
}));error!(r#"expected `key` or `key="value"`"#);
106 }
107 })
108 .collect::<Cfg>()
109}
110111/// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
112pub(crate) fn parse_check_cfg(dcx: DiagCtxtHandle<'_>, specs: Vec<String>) -> CheckCfg {
113// If any --check-cfg is passed then exhaustive_values and exhaustive_names
114 // are enabled by default.
115let exhaustive_names = !specs.is_empty();
116let exhaustive_values = !specs.is_empty();
117let mut check_cfg = CheckCfg { exhaustive_names, exhaustive_values, ..CheckCfg::default() };
118119for s in specs {
120let psess = ParseSess::emitter_with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this occurred on the command line: `--check-cfg={0}`",
s))
})format!(
121"this occurred on the command line: `--check-cfg={s}`"
122));
123let filename = FileName::cfg_spec_source_code(&s);
124125const VISIT: &str =
126"visit <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more details";
127128macro_rules! error {
129 ($reason:expr) => {{
130let mut diag = dcx.struct_fatal(format!("invalid `--check-cfg` argument: `{s}`"));
131 diag.note($reason);
132 diag.note(VISIT);
133 diag.emit()
134 }};
135 (in $arg:expr, $reason:expr) => {{
136let mut diag = dcx.struct_fatal(format!("invalid `--check-cfg` argument: `{s}`"));
137138let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string($arg);
139if let Some(lit) = $arg.lit() {
140let (lit_kind_article, lit_kind_descr) = {
141let lit_kind = lit.as_token_lit().kind;
142 (lit_kind.article(), lit_kind.descr())
143 };
144 diag.note(format!("`{pparg}` is {lit_kind_article} {lit_kind_descr} literal"));
145 } else {
146 diag.note(format!("`{pparg}` is invalid"));
147 }
148149 diag.note($reason);
150 diag.note(VISIT);
151 diag.emit()
152 }};
153 }
154155let expected_error = || -> ! {
156{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
diag.note("expected `cfg(name, values(\"value1\", \"value2\", ... \"valueN\"))`");
diag.note(VISIT);
diag.emit()
}error!("expected `cfg(name, values(\"value1\", \"value2\", ... \"valueN\"))`")157 };
158159let mut parser =
160match new_parser_from_source_str(&psess, filename, s.to_string(), StripTokens::Nothing)
161 {
162Ok(parser) => parser.recovery(Recovery::Forbidden),
163Err(errs) => {
164 errs.into_iter().for_each(|err| err.cancel());
165 expected_error();
166 }
167 };
168169let meta_item = match parser.parse_meta_item() {
170Ok(meta_item) if parser.token == token::Eof && parser.dcx().has_errors().is_none() => {
171 meta_item
172 }
173Ok(..) => expected_error(),
174Err(err) => {
175 err.cancel();
176 expected_error();
177 }
178 };
179180let Some(args) = meta_item.meta_item_list() else {
181 expected_error();
182 };
183184if !meta_item.has_name(sym::cfg) {
185 expected_error();
186 }
187188let mut names = Vec::new();
189let mut values: FxHashSet<_> = Default::default();
190191let mut any_specified = false;
192let mut values_specified = false;
193let mut values_any_specified = false;
194195for arg in args {
196if arg.is_word()
197 && let Some(ident) = arg.ident()
198 {
199if values_specified {
200{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
diag.note("`cfg()` names cannot be after values");
diag.note(VISIT);
diag.emit()
};error!("`cfg()` names cannot be after values");
201 }
202203if ident.is_path_segment_keyword() {
204{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
diag.note("malformed `cfg` input, expected a valid identifier");
diag.note(VISIT);
diag.emit()
};error!("malformed `cfg` input, expected a valid identifier");
205 }
206207 names.push(ident);
208 } else if let Some(boolean) = arg.boolean_literal() {
209if values_specified {
210{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
diag.note("`cfg()` names cannot be after values");
diag.note(VISIT);
diag.emit()
};error!("`cfg()` names cannot be after values");
211 }
212 names.push(rustc_span::Ident::new(
213if boolean { rustc_span::kw::True } else { rustc_span::kw::False },
214 arg.span(),
215 ));
216 } else if arg.has_name(sym::any)
217 && let Some(args) = arg.meta_item_list()
218 {
219if any_specified {
220{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
diag.note("`any()` cannot be specified multiple times");
diag.note(VISIT);
diag.emit()
};error!("`any()` cannot be specified multiple times");
221 }
222 any_specified = true;
223if !args.is_empty() {
224{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
if let Some(lit) = arg.lit() {
let (lit_kind_article, lit_kind_descr) =
{
let lit_kind = lit.as_token_lit().kind;
(lit_kind.article(), lit_kind.descr())
};
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
pparg, lit_kind_article, lit_kind_descr))
}));
} else {
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is invalid",
pparg))
}));
}
diag.note("`any()` takes no argument");
diag.note(VISIT);
diag.emit()
};error!(in arg, "`any()` takes no argument");
225 }
226 } else if arg.has_name(sym::values)
227 && let Some(args) = arg.meta_item_list()
228 {
229if names.is_empty() {
230{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
diag.note("`values()` cannot be specified before the names");
diag.note(VISIT);
diag.emit()
};error!("`values()` cannot be specified before the names");
231 } else if values_specified {
232{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
diag.note("`values()` cannot be specified multiple times");
diag.note(VISIT);
diag.emit()
};error!("`values()` cannot be specified multiple times");
233 }
234 values_specified = true;
235236for arg in args {
237if let Some(LitKind::Str(s, _)) = arg.lit().map(|lit| &lit.kind) {
238 values.insert(Some(*s));
239 } else if arg.has_name(sym::any)
240 && let Some(args) = arg.meta_item_list()
241 {
242if values_any_specified {
243{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
if let Some(lit) = arg.lit() {
let (lit_kind_article, lit_kind_descr) =
{
let lit_kind = lit.as_token_lit().kind;
(lit_kind.article(), lit_kind.descr())
};
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
pparg, lit_kind_article, lit_kind_descr))
}));
} else {
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is invalid",
pparg))
}));
}
diag.note("`any()` in `values()` cannot be specified multiple times");
diag.note(VISIT);
diag.emit()
};error!(in arg, "`any()` in `values()` cannot be specified multiple times");
244 }
245 values_any_specified = true;
246if !args.is_empty() {
247{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
if let Some(lit) = arg.lit() {
let (lit_kind_article, lit_kind_descr) =
{
let lit_kind = lit.as_token_lit().kind;
(lit_kind.article(), lit_kind.descr())
};
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
pparg, lit_kind_article, lit_kind_descr))
}));
} else {
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is invalid",
pparg))
}));
}
diag.note("`any()` in `values()` takes no argument");
diag.note(VISIT);
diag.emit()
};error!(in arg, "`any()` in `values()` takes no argument");
248 }
249 } else if arg.has_name(sym::none)
250 && let Some(args) = arg.meta_item_list()
251 {
252 values.insert(None);
253if !args.is_empty() {
254{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
if let Some(lit) = arg.lit() {
let (lit_kind_article, lit_kind_descr) =
{
let lit_kind = lit.as_token_lit().kind;
(lit_kind.article(), lit_kind.descr())
};
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
pparg, lit_kind_article, lit_kind_descr))
}));
} else {
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is invalid",
pparg))
}));
}
diag.note("`none()` in `values()` takes no argument");
diag.note(VISIT);
diag.emit()
};error!(in arg, "`none()` in `values()` takes no argument");
255 }
256 } else {
257{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
if let Some(lit) = arg.lit() {
let (lit_kind_article, lit_kind_descr) =
{
let lit_kind = lit.as_token_lit().kind;
(lit_kind.article(), lit_kind.descr())
};
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
pparg, lit_kind_article, lit_kind_descr))
}));
} else {
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is invalid",
pparg))
}));
}
diag.note("`values()` arguments must be string literals, `none()` or `any()`");
diag.note(VISIT);
diag.emit()
};error!(in arg, "`values()` arguments must be string literals, `none()` or `any()`");
258 }
259 }
260 } else {
261{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string(arg);
if let Some(lit) = arg.lit() {
let (lit_kind_article, lit_kind_descr) =
{
let lit_kind = lit.as_token_lit().kind;
(lit_kind.article(), lit_kind.descr())
};
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is {1} {2} literal",
pparg, lit_kind_article, lit_kind_descr))
}));
} else {
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is invalid",
pparg))
}));
}
diag.note("`cfg()` arguments must be simple identifiers, `any()` or `values(...)`");
diag.note(VISIT);
diag.emit()
};error!(in arg, "`cfg()` arguments must be simple identifiers, `any()` or `values(...)`");
262 }
263 }
264265if !values_specified && !any_specified {
266// `cfg(name)` is equivalent to `cfg(name, values(none()))` so add
267 // an implicit `none()`
268values.insert(None);
269 } else if !values.is_empty() && values_any_specified {
270{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
diag.note("`values()` arguments cannot specify string literals and `any()` at the same time");
diag.note(VISIT);
diag.emit()
};error!(
271"`values()` arguments cannot specify string literals and `any()` at the same time"
272);
273 }
274275if any_specified {
276if names.is_empty() && values.is_empty() && !values_specified && !values_any_specified {
277 check_cfg.exhaustive_names = false;
278 } else {
279{
let mut diag =
dcx.struct_fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--check-cfg` argument: `{0}`",
s))
}));
diag.note("`cfg(any())` can only be provided in isolation");
diag.note(VISIT);
diag.emit()
};error!("`cfg(any())` can only be provided in isolation");
280 }
281 } else {
282for name in names {
283 check_cfg
284 .expecteds
285 .entry(name.name)
286 .and_modify(|v| match v {
287 ExpectedValues::Some(v) if !values_any_specified =>
288 {
289#[allow(rustc::potential_query_instability)]
290v.extend(values.clone())
291 }
292 ExpectedValues::Some(_) => *v = ExpectedValues::Any,
293 ExpectedValues::Any => {}
294 })
295 .or_insert_with(|| {
296if values_any_specified {
297 ExpectedValues::Any
298 } else {
299 ExpectedValues::Some(values.clone())
300 }
301 });
302 }
303 }
304 }
305306check_cfg307}
308309/// The compiler configuration
310pub struct Config {
311/// Command line options
312pub opts: config::Options,
313314/// Unparsed cfg! configuration in addition to the default ones.
315pub crate_cfg: Vec<String>,
316pub crate_check_cfg: Vec<String>,
317318pub input: Input,
319pub output_dir: Option<PathBuf>,
320pub output_file: Option<OutFileName>,
321pub ice_file: Option<PathBuf>,
322/// Load files from sources other than the file system.
323 ///
324 /// Has no uses within this repository, but may be used in the future by
325 /// bjorn3 for "hooking rust-analyzer's VFS into rustc at some point for
326 /// running rustc without having to save". (See #102759.)
327pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
328329pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
330331/// This is a callback from the driver that is called when [`ParseSess`] is created.
332pub psess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
333334/// This is a callback to track otherwise untracked state used by the caller.
335 ///
336 /// You can write to `sess.env_depinfo` and `sess.file_depinfo` to track env vars and files.
337pub track_state: Option<Box<dyn FnOnce(&Session) + Send>>,
338339/// This is a callback from the driver that is called when we're registering lints;
340 /// it is called during lint loading when we have the LintStore in a non-shared state.
341 ///
342 /// Note that if you find a Some here you probably want to call that function in the new
343 /// function being registered.
344pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
345346/// This is a callback from the driver that is called just after we have populated
347 /// the list of queries.
348pub override_queries: Option<fn(&Session, &mut Providers)>,
349350/// An extra set of symbols to add to the symbol interner, the symbol indices
351 /// will start at [`PREDEFINED_SYMBOLS_COUNT`](rustc_span::symbol::PREDEFINED_SYMBOLS_COUNT)
352pub extra_symbols: Vec<&'static str>,
353354/// This is a callback from the driver that is called to create a codegen backend.
355 ///
356 /// Has no uses within this repository, but is used by bjorn3 for "the
357 /// hotswapping branch of cg_clif" for "setting the codegen backend from a
358 /// custom driver where the custom codegen backend has arbitrary data."
359 /// (See #102759.)
360pub make_codegen_backend: Option<Box<dyn FnOnce(&Session) -> Box<dyn CodegenBackend> + Send>>,
361362/// The inner atomic value is set to true when a feature marked as `internal` is
363 /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
364 /// internal features are wontfix, and they are usually the cause of the ICEs.
365pub using_internal_features: &'static std::sync::atomic::AtomicBool,
366}
367368// JUSTIFICATION: before session exists, only config
369#[allow(rustc::bad_opt_access)]
370pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
371{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_interface/src/interface.rs:371",
"rustc_interface::interface", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/interface.rs"),
::tracing_core::__macro_support::Option::Some(371u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::interface"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("run_compiler")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("run_compiler");
372373// Set parallel mode before thread pool creation, which will create `Lock`s.
374rustc_data_structures::sync::set_dyn_thread_safe_mode(config.opts.jobs.frontend.is_some());
375376// Initialize jobserver as early as possible.
377let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
378let jobs = config.opts.jobs;
379if let Some(limit) = jobs.frontend.max(jobs.backend).max(jobs.linker.limit()) {
380 jobserver::initialize(limit.get(), |err| {
381let note = "the build environment is likely misconfigured";
382early_dcx.early_struct_warn(err).with_note(note).emit()
383 });
384 }
385386crate::callbacks::setup_callbacks();
387388let target = config::build_target_config(
389&early_dcx,
390&config.opts.target_triple,
391config.opts.sysroot.path(),
392config.opts.unstable_opts.unstable_options,
393 );
394let file_loader = config.file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
395let path_mapping = config.opts.file_path_mapping();
396let hash_kind = config.opts.unstable_opts.src_hash_algorithm(&target);
397let checksum_hash_kind = config.opts.unstable_opts.checksum_hash_algorithm();
398399 util::run_in_thread_pool_with_globals(
400&early_dcx,
401config.opts.edition,
402jobs,
403&config.extra_symbols,
404SourceMapInputs { file_loader, path_mapping, hash_kind, checksum_hash_kind },
405 |current_gcx| {
406// The previous `early_dcx` can't be reused here because it doesn't
407 // impl `Send`. Creating a new one is fine.
408let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
409410let temps_dir = config.opts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
411412let mut sess = rustc_session::build_session(
413config.opts,
414CompilerIO {
415 input: config.input,
416 output_dir: config.output_dir,
417 output_file: config.output_file,
418temps_dir,
419 },
420config.lint_caps,
421target,
422 util::rustc_version_str().unwrap_or("unknown"),
423config.ice_file,
424config.using_internal_features,
425 );
426427let codegen_backend = match config.make_codegen_backend {
428None => util::get_codegen_backend(
429&early_dcx,
430&sess.opts.sysroot,
431sess.opts.unstable_opts.codegen_backend.as_deref(),
432&sess.target,
433 ),
434Some(make_codegen_backend) => {
435// N.B. `make_codegen_backend` takes precedence over
436 // `target.default_codegen_backend`, which is ignored in this case.
437make_codegen_backend(&sess)
438 }
439 };
440codegen_backend.init(&sess);
441sess.replaced_intrinsics = FxHashSet::from_iter(codegen_backend.replaced_intrinsics());
442sess.fallback_intrinsics = FxHashSet::from_iter(codegen_backend.fallback_intrinsics());
443sess.thin_lto_supported = codegen_backend.thin_lto_supported();
444445let cfg = parse_cfg(sess.dcx(), config.crate_cfg);
446let mut cfg = config::build_configuration(&sess, cfg);
447 util::add_configuration(&mut cfg, &mut sess, &*codegen_backend);
448sess.config = cfg;
449450let mut check_cfg = parse_check_cfg(sess.dcx(), config.crate_check_cfg);
451check_cfg.fill_well_known(&sess.target);
452sess.check_config = check_cfg;
453454if let Some(psess_created) = config.psess_created {
455psess_created(&mut sess.psess);
456 }
457458if let Some(track_state) = config.track_state {
459track_state(&sess);
460 }
461462// Even though the session holds the lint store, we can't build the
463 // lint store until after the session exists. And we wait until now
464 // so that `register_lints` sees the fully initialized session.
465let mut lint_store = rustc_lint::new_lint_store(sess.enable_internal_lints());
466if let Some(register_lints) = config.register_lints.as_deref() {
467register_lints(&sess, &mut lint_store);
468 }
469sess.lint_store = Some(Arc::new(lint_store));
470471 util::check_abi_required_features(&sess);
472473let compiler = Compiler {
474sess,
475codegen_backend,
476 override_queries: config.override_queries,
477current_gcx,
478 };
479480// There are two paths out of `f`.
481 // - Normal exit.
482 // - Panic, e.g. triggered by `abort_if_errors` or a fatal error.
483 //
484 // We must run `finish_diagnostics` in both cases.
485let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&compiler)));
486487compiler.sess.finish_diagnostics();
488489// If error diagnostics have been emitted, we can't return an
490 // error directly, because the return type of this function
491 // is `R`, not `Result<R, E>`. But we need to communicate the
492 // errors' existence to the caller, otherwise the caller might
493 // mistakenly think that no errors occurred and return a zero
494 // exit code. So we abort (panic) instead, similar to if `f`
495 // had panicked.
496if res.is_ok() {
497compiler.sess.dcx().abort_if_errors();
498 }
499500// Also make sure to flush delayed bugs as if we panicked, the
501 // bugs would be flushed by the Drop impl of DiagCtxt while
502 // unwinding, which would result in an abort with
503 // "panic in a destructor during cleanup".
504compiler.sess.dcx().flush_delayed();
505506let res = match res {
507Ok(res) => res,
508// Resume unwinding if a panic happened.
509Err(err) => std::panic::resume_unwind(err),
510 };
511512let prof = compiler.sess.prof.clone();
513prof.generic_activity("drop_compiler").run(move || drop(compiler));
514515res516 },
517 )
518}
519520pub fn try_print_query_stack(
521 dcx: DiagCtxtHandle<'_>,
522 limit_frames: Option<usize>,
523 file: Option<std::fs::File>,
524) {
525{ ::std::io::_eprint(format_args!("query stack during panic:\n")); };eprintln!("query stack during panic:");
526527// Be careful relying on global state here: this code is called from
528 // a panic hook, which means that the global `DiagCtxt` may be in a weird
529 // state if it was responsible for triggering the panic.
530let all_frames = ty::tls::with_context_opt(|icx| {
531if let Some(icx) = icx {
532{
{
let _guard = ReducedQueriesGuard::new();
{
let _guard = ForcedImplGuard::new();
{
let _guard = NoTrimmedGuard::new();
{
let _guard = NoVisibleGuard::new();
print_query_stack(icx.tcx, icx.query, dcx, limit_frames,
file)
}
}
}
}
}ty::print::with_no_queries!(print_query_stack(
533 icx.tcx,
534 icx.query,
535 dcx,
536 limit_frames,
537 file,
538 ))539 } else {
5400
541}
542 });
543544if let Some(limit_frames) = limit_frames545 && all_frames > limit_frames546 {
547{
::std::io::_eprint(format_args!("... and {0} other queries... use `env RUST_BACKTRACE=1` to see the full query stack\n",
all_frames - limit_frames));
};eprintln!(
548"... and {} other queries... use `env RUST_BACKTRACE=1` to see the full query stack",
549 all_frames - limit_frames
550 );
551 } else {
552{ ::std::io::_eprint(format_args!("end of query stack\n")); };eprintln!("end of query stack");
553 }
554}