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::{self, Proxy};
9use rustc_data_structures::stable_hasher::StableHasher;
10use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
11use rustc_lint::LintStore;
12use rustc_middle::ty;
13use rustc_middle::ty::CurrentGcx;
14use rustc_middle::util::Providers;
15use rustc_parse::lexer::StripTokens;
16use rustc_parse::new_parser_from_source_str;
17use rustc_parse::parser::Recovery;
18use rustc_parse::parser::attr::AllowLeadingUnsafe;
19use rustc_query_impl::print_query_stack;
20use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, OutFileName};
21use rustc_session::parse::ParseSess;
22use rustc_session::{CompilerIO, EarlyDiagCtxt, Session, lint};
23use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs};
24use rustc_span::{FileName, sym};
25use tracing::trace;
2627use crate::util;
2829pub type Result<T> = result::Result<T, ErrorGuaranteed>;
3031/// Represents a compiler session. Note that every `Compiler` contains a
32/// `Session`, but `Compiler` also contains some things that cannot be in
33/// `Session`, due to `Session` being in a crate that has many fewer
34/// dependencies than this crate.
35///
36/// Can be used to run `rustc_interface` queries.
37/// Created by passing [`Config`] to [`run_compiler`].
38pub struct Compiler {
39pub sess: Session,
40pub codegen_backend: Box<dyn CodegenBackend>,
41pub(crate) override_queries: Option<fn(&Session, &mut Providers)>,
4243/// A reference to the current `GlobalCtxt` which we pass on to `GlobalCtxt`.
44pub(crate) current_gcx: CurrentGcx,
4546/// A jobserver reference which we pass on to `GlobalCtxt`.
47pub(crate) jobserver_proxy: Arc<Proxy>,
48}
4950/// Converts strings provided as `--cfg [cfgspec]` into a `Cfg`.
51pub(crate) fn parse_cfg(dcx: DiagCtxtHandle<'_>, cfgs: Vec<String>) -> Cfg {
52cfgs.into_iter()
53 .map(|s| {
54let psess = ParseSess::emitter_with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this occurred on the command line: `--cfg={0}`",
s))
})format!(
55"this occurred on the command line: `--cfg={s}`"
56));
57let filename = FileName::cfg_spec_source_code(&s);
5859macro_rules! error {
60 ($reason: expr) => {
61 dcx.fatal(format!("invalid `--cfg` argument: `{s}` ({})", $reason));
62 };
63 }
6465match new_parser_from_source_str(&psess, filename, s.to_string(), StripTokens::Nothing)
66 {
67Ok(mut parser) => {
68parser = parser.recovery(Recovery::Forbidden);
69match parser.parse_meta_item(AllowLeadingUnsafe::No) {
70Ok(meta_item)
71if parser.token == token::Eof72 && parser.dcx().has_errors().is_none() =>
73 {
74if meta_item.path.segments.len() != 1 {
75dcx.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");
76 }
77match &meta_item.kind {
78 MetaItemKind::List(..) => {}
79 MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
80dcx.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");
81 }
82 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
83let ident = meta_item.ident().expect("multi-segment cfg key");
8485if ident.is_path_segment_keyword() {
86dcx.fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid `--cfg` argument: `{1}` ({0})",
"malformed `cfg` input, expected a valid identifier", s))
}));error!(
87"malformed `cfg` input, expected a valid identifier"
88);
89 }
9091return (ident.name, meta_item.value_str());
92 }
93 }
94 }
95Ok(..) => {}
96Err(err) => err.cancel(),
97 }
98 }
99Err(errs) => errs.into_iter().for_each(|err| err.cancel()),
100 };
101102// If the user tried to use a key="value" flag, but is missing the quotes, provide
103 // a hint about how to resolve this.
104if s.contains('=') && !s.contains("=\"") && !s.ends_with('"') {
105dcx.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!(
106r#"expected `key` or `key="value"`, ensure escaping is appropriate"#,
107r#" for your shell, try 'key="value"' or key=\"value\""#
108));
109 } else {
110dcx.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"`"#);
111 }
112 })
113 .collect::<Cfg>()
114}
115116/// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
117pub(crate) fn parse_check_cfg(dcx: DiagCtxtHandle<'_>, specs: Vec<String>) -> CheckCfg {
118// If any --check-cfg is passed then exhaustive_values and exhaustive_names
119 // are enabled by default.
120let exhaustive_names = !specs.is_empty();
121let exhaustive_values = !specs.is_empty();
122let mut check_cfg = CheckCfg { exhaustive_names, exhaustive_values, ..CheckCfg::default() };
123124for s in specs {
125let 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!(
126"this occurred on the command line: `--check-cfg={s}`"
127));
128let filename = FileName::cfg_spec_source_code(&s);
129130const VISIT: &str =
131"visit <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more details";
132133macro_rules! error {
134 ($reason:expr) => {{
135let mut diag = dcx.struct_fatal(format!("invalid `--check-cfg` argument: `{s}`"));
136 diag.note($reason);
137 diag.note(VISIT);
138 diag.emit()
139 }};
140 (in $arg:expr, $reason:expr) => {{
141let mut diag = dcx.struct_fatal(format!("invalid `--check-cfg` argument: `{s}`"));
142143let pparg = rustc_ast_pretty::pprust::meta_list_item_to_string($arg);
144if let Some(lit) = $arg.lit() {
145let (lit_kind_article, lit_kind_descr) = {
146let lit_kind = lit.as_token_lit().kind;
147 (lit_kind.article(), lit_kind.descr())
148 };
149 diag.note(format!("`{pparg}` is {lit_kind_article} {lit_kind_descr} literal"));
150 } else {
151 diag.note(format!("`{pparg}` is invalid"));
152 }
153154 diag.note($reason);
155 diag.note(VISIT);
156 diag.emit()
157 }};
158 }
159160let expected_error = || -> ! {
161{
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\"))`")162 };
163164let mut parser =
165match new_parser_from_source_str(&psess, filename, s.to_string(), StripTokens::Nothing)
166 {
167Ok(parser) => parser.recovery(Recovery::Forbidden),
168Err(errs) => {
169 errs.into_iter().for_each(|err| err.cancel());
170 expected_error();
171 }
172 };
173174let meta_item = match parser.parse_meta_item(AllowLeadingUnsafe::No) {
175Ok(meta_item) if parser.token == token::Eof && parser.dcx().has_errors().is_none() => {
176 meta_item
177 }
178Ok(..) => expected_error(),
179Err(err) => {
180 err.cancel();
181 expected_error();
182 }
183 };
184185let Some(args) = meta_item.meta_item_list() else {
186 expected_error();
187 };
188189if !meta_item.has_name(sym::cfg) {
190 expected_error();
191 }
192193let mut names = Vec::new();
194let mut values: FxHashSet<_> = Default::default();
195196let mut any_specified = false;
197let mut values_specified = false;
198let mut values_any_specified = false;
199200for arg in args {
201if arg.is_word()
202 && let Some(ident) = arg.ident()
203 {
204if values_specified {
205{
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");
206 }
207208if ident.is_path_segment_keyword() {
209{
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");
210 }
211212 names.push(ident);
213 } else if let Some(boolean) = arg.boolean_literal() {
214if values_specified {
215{
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");
216 }
217 names.push(rustc_span::Ident::new(
218if boolean { rustc_span::kw::True } else { rustc_span::kw::False },
219 arg.span(),
220 ));
221 } else if arg.has_name(sym::any)
222 && let Some(args) = arg.meta_item_list()
223 {
224if any_specified {
225{
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");
226 }
227 any_specified = true;
228if !args.is_empty() {
229{
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");
230 }
231 } else if arg.has_name(sym::values)
232 && let Some(args) = arg.meta_item_list()
233 {
234if names.is_empty() {
235{
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");
236 } else if values_specified {
237{
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");
238 }
239 values_specified = true;
240241for arg in args {
242if let Some(LitKind::Str(s, _)) = arg.lit().map(|lit| &lit.kind) {
243 values.insert(Some(*s));
244 } else if arg.has_name(sym::any)
245 && let Some(args) = arg.meta_item_list()
246 {
247if values_any_specified {
248{
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");
249 }
250 values_any_specified = true;
251if !args.is_empty() {
252{
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");
253 }
254 } else if arg.has_name(sym::none)
255 && let Some(args) = arg.meta_item_list()
256 {
257 values.insert(None);
258if !args.is_empty() {
259{
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");
260 }
261 } else {
262{
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()`");
263 }
264 }
265 } else {
266{
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(...)`");
267 }
268 }
269270if !values_specified && !any_specified {
271// `cfg(name)` is equivalent to `cfg(name, values(none()))` so add
272 // an implicit `none()`
273values.insert(None);
274 } else if !values.is_empty() && values_any_specified {
275{
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!(
276"`values()` arguments cannot specify string literals and `any()` at the same time"
277);
278 }
279280if any_specified {
281if names.is_empty() && values.is_empty() && !values_specified && !values_any_specified {
282 check_cfg.exhaustive_names = false;
283 } else {
284{
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");
285 }
286 } else {
287for name in names {
288 check_cfg
289 .expecteds
290 .entry(name.name)
291 .and_modify(|v| match v {
292 ExpectedValues::Some(v) if !values_any_specified =>
293 {
294#[allow(rustc::potential_query_instability)]
295v.extend(values.clone())
296 }
297 ExpectedValues::Some(_) => *v = ExpectedValues::Any,
298 ExpectedValues::Any => {}
299 })
300 .or_insert_with(|| {
301if values_any_specified {
302 ExpectedValues::Any
303 } else {
304 ExpectedValues::Some(values.clone())
305 }
306 });
307 }
308 }
309 }
310311check_cfg312}
313314/// The compiler configuration
315pub struct Config {
316/// Command line options
317pub opts: config::Options,
318319/// Unparsed cfg! configuration in addition to the default ones.
320pub crate_cfg: Vec<String>,
321pub crate_check_cfg: Vec<String>,
322323pub input: Input,
324pub output_dir: Option<PathBuf>,
325pub output_file: Option<OutFileName>,
326pub ice_file: Option<PathBuf>,
327/// Load files from sources other than the file system.
328 ///
329 /// Has no uses within this repository, but may be used in the future by
330 /// bjorn3 for "hooking rust-analyzer's VFS into rustc at some point for
331 /// running rustc without having to save". (See #102759.)
332pub file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
333334pub lint_caps: FxHashMap<lint::LintId, lint::Level>,
335336/// This is a callback from the driver that is called when [`ParseSess`] is created.
337pub psess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
338339/// This is a callback to track otherwise untracked state used by the caller.
340 ///
341 /// You can write to `sess.env_depinfo` and `sess.file_depinfo` to track env vars and files.
342 /// To track any other state you can write to the given hasher. If the hash changes between
343 /// runs the incremental cache will be cleared.
344 ///
345 /// The hashing functionality has no known user. FIXME should this be removed?
346pub track_state: Option<Box<dyn FnOnce(&Session, &mut StableHasher) + Send>>,
347348/// This is a callback from the driver that is called when we're registering lints;
349 /// it is called during lint loading when we have the LintStore in a non-shared state.
350 ///
351 /// Note that if you find a Some here you probably want to call that function in the new
352 /// function being registered.
353pub register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
354355/// This is a callback from the driver that is called just after we have populated
356 /// the list of queries.
357pub override_queries: Option<fn(&Session, &mut Providers)>,
358359/// An extra set of symbols to add to the symbol interner, the symbol indices
360 /// will start at [`PREDEFINED_SYMBOLS_COUNT`](rustc_span::symbol::PREDEFINED_SYMBOLS_COUNT)
361pub extra_symbols: Vec<&'static str>,
362363/// This is a callback from the driver that is called to create a codegen backend.
364 ///
365 /// Has no uses within this repository, but is used by bjorn3 for "the
366 /// hotswapping branch of cg_clif" for "setting the codegen backend from a
367 /// custom driver where the custom codegen backend has arbitrary data."
368 /// (See #102759.)
369pub make_codegen_backend: Option<Box<dyn FnOnce(&Session) -> Box<dyn CodegenBackend> + Send>>,
370371/// The inner atomic value is set to true when a feature marked as `internal` is
372 /// enabled. Makes it so that "please report a bug" is hidden, as ICEs with
373 /// internal features are wontfix, and they are usually the cause of the ICEs.
374pub using_internal_features: &'static std::sync::atomic::AtomicBool,
375}
376377/// Initialize jobserver before getting `jobserver::client` and `build_session`.
378pub(crate) fn initialize_checked_jobserver(early_dcx: &EarlyDiagCtxt) {
379 jobserver::initialize_checked(|err| {
380early_dcx381 .early_struct_warn(err)
382 .with_note("the build environment is likely misconfigured")
383 .emit()
384 });
385}
386387// JUSTIFICATION: before session exists, only config
388#[allow(rustc::bad_opt_access)]
389pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
390{
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:390",
"rustc_interface::interface", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/interface.rs"),
::tracing_core::__macro_support::Option::Some(390u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("run_compiler")
as &dyn Value))])
});
} else { ; }
};trace!("run_compiler");
391392// Set parallel mode before thread pool creation, which will create `Lock`s.
393rustc_data_structures::sync::set_dyn_thread_safe_mode(config.opts.unstable_opts.threads > 1);
394395// Check jobserver before run_in_thread_pool_with_globals, which call jobserver::acquire_thread
396let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
397initialize_checked_jobserver(&early_dcx);
398399crate::callbacks::setup_callbacks();
400401let target = config::build_target_config(
402&early_dcx,
403&config.opts.target_triple,
404config.opts.sysroot.path(),
405config.opts.unstable_opts.unstable_options,
406 );
407let file_loader = config.file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
408let path_mapping = config.opts.file_path_mapping();
409let hash_kind = config.opts.unstable_opts.src_hash_algorithm(&target);
410let checksum_hash_kind = config.opts.unstable_opts.checksum_hash_algorithm();
411412 util::run_in_thread_pool_with_globals(
413&early_dcx,
414config.opts.edition,
415config.opts.unstable_opts.threads,
416&config.extra_symbols,
417SourceMapInputs { file_loader, path_mapping, hash_kind, checksum_hash_kind },
418 |current_gcx, jobserver_proxy| {
419// The previous `early_dcx` can't be reused here because it doesn't
420 // impl `Send`. Creating a new one is fine.
421let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
422423let temps_dir = config.opts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
424425let mut sess = rustc_session::build_session(
426config.opts,
427CompilerIO {
428 input: config.input,
429 output_dir: config.output_dir,
430 output_file: config.output_file,
431temps_dir,
432 },
433config.lint_caps,
434target,
435 util::rustc_version_str().unwrap_or("unknown"),
436config.ice_file,
437config.using_internal_features,
438 );
439440let codegen_backend = match config.make_codegen_backend {
441None => util::get_codegen_backend(
442&early_dcx,
443&sess.opts.sysroot,
444sess.opts.unstable_opts.codegen_backend.as_deref(),
445&sess.target,
446 ),
447Some(make_codegen_backend) => {
448// N.B. `make_codegen_backend` takes precedence over
449 // `target.default_codegen_backend`, which is ignored in this case.
450make_codegen_backend(&sess)
451 }
452 };
453codegen_backend.init(&sess);
454sess.replaced_intrinsics = FxHashSet::from_iter(codegen_backend.replaced_intrinsics());
455sess.thin_lto_supported = codegen_backend.thin_lto_supported();
456457let cfg = parse_cfg(sess.dcx(), config.crate_cfg);
458let mut cfg = config::build_configuration(&sess, cfg);
459 util::add_configuration(&mut cfg, &mut sess, &*codegen_backend);
460sess.psess.config = cfg;
461462let mut check_cfg = parse_check_cfg(sess.dcx(), config.crate_check_cfg);
463check_cfg.fill_well_known(&sess.target);
464sess.psess.check_config = check_cfg;
465466if let Some(psess_created) = config.psess_created {
467psess_created(&mut sess.psess);
468 }
469470if let Some(track_state) = config.track_state {
471let mut hasher = StableHasher::new();
472track_state(&sess, &mut hasher);
473sess.opts.untracked_state_hash = hasher.finish()
474 }
475476// Even though the session holds the lint store, we can't build the
477 // lint store until after the session exists. And we wait until now
478 // so that `register_lints` sees the fully initialized session.
479let mut lint_store = rustc_lint::new_lint_store(sess.enable_internal_lints());
480if let Some(register_lints) = config.register_lints.as_deref() {
481register_lints(&sess, &mut lint_store);
482 }
483sess.lint_store = Some(Arc::new(lint_store));
484485 util::check_abi_required_features(&sess);
486487let compiler = Compiler {
488sess,
489codegen_backend,
490 override_queries: config.override_queries,
491current_gcx,
492jobserver_proxy,
493 };
494495// There are two paths out of `f`.
496 // - Normal exit.
497 // - Panic, e.g. triggered by `abort_if_errors` or a fatal error.
498 //
499 // We must run `finish_diagnostics` in both cases.
500let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&compiler)));
501502compiler.sess.finish_diagnostics();
503504// If error diagnostics have been emitted, we can't return an
505 // error directly, because the return type of this function
506 // is `R`, not `Result<R, E>`. But we need to communicate the
507 // errors' existence to the caller, otherwise the caller might
508 // mistakenly think that no errors occurred and return a zero
509 // exit code. So we abort (panic) instead, similar to if `f`
510 // had panicked.
511if res.is_ok() {
512compiler.sess.dcx().abort_if_errors();
513 }
514515// Also make sure to flush delayed bugs as if we panicked, the
516 // bugs would be flushed by the Drop impl of DiagCtxt while
517 // unwinding, which would result in an abort with
518 // "panic in a destructor during cleanup".
519compiler.sess.dcx().flush_delayed();
520521let res = match res {
522Ok(res) => res,
523// Resume unwinding if a panic happened.
524Err(err) => std::panic::resume_unwind(err),
525 };
526527let prof = compiler.sess.prof.clone();
528prof.generic_activity("drop_compiler").run(move || drop(compiler));
529530res531 },
532 )
533}
534535pub fn try_print_query_stack(
536 dcx: DiagCtxtHandle<'_>,
537 limit_frames: Option<usize>,
538 file: Option<std::fs::File>,
539) {
540{ ::std::io::_eprint(format_args!("query stack during panic:\n")); };eprintln!("query stack during panic:");
541542// Be careful relying on global state here: this code is called from
543 // a panic hook, which means that the global `DiagCtxt` may be in a weird
544 // state if it was responsible for triggering the panic.
545let all_frames = ty::tls::with_context_opt(|icx| {
546if let Some(icx) = icx {
547{
{
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(
548 icx.tcx,
549 icx.query,
550 dcx,
551 limit_frames,
552 file,
553 ))554 } else {
5550
556}
557 });
558559if let Some(limit_frames) = limit_frames560 && all_frames > limit_frames561 {
562{
::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!(
563"... and {} other queries... use `env RUST_BACKTRACE=1` to see the full query stack",
564 all_frames - limit_frames
565 );
566 } else {
567{ ::std::io::_eprint(format_args!("end of query stack\n")); };eprintln!("end of query stack");
568 }
569}