1use std::any::Any;
2use std::ffi::{OsStr, OsString};
3use std::io::{self, BufWriter, Write};
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, LazyLock, OnceLock};
6use std::{env, fs, iter};
7
8use rustc_ast as ast;
9use rustc_attr_ir::{Attribute, AttributeKind, find_attr};
10use rustc_attr_parsing::{AttributeParser, ShouldEmit};
11use rustc_codegen_ssa::traits::CodegenBackend;
12use rustc_codegen_ssa::{CompiledModules, CrateInfo};
13use rustc_crate_store::Untracked;
14use rustc_data_structures::indexmap::IndexMap;
15use rustc_data_structures::steal::Steal;
16use rustc_data_structures::sync::{
17 AppendOnlyIndexVec, DynSend, DynSync, FreezeLock, WorkerLocal, par_fns,
18};
19use rustc_data_structures::thousands;
20use rustc_errors::timings::TimingSection;
21use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level};
22use rustc_expand::base::{ExtCtxt, LintStoreExpand};
23use rustc_feature::Features;
24use rustc_fs_util::try_canonicalize;
25use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap};
26use rustc_hir::definitions::Definitions;
27use rustc_incremental::setup_dep_graph;
28use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore, unerased_lint_store};
29use rustc_metadata::EncodedMetadata;
30use rustc_metadata::creader::CStore;
31use rustc_middle::arena::Arena;
32use rustc_middle::dep_graph::IncrCompSession;
33use rustc_middle::middle::resolve::{ResolverAstLowering, ResolverGlobalCtxt};
34use rustc_middle::ty::{self, RegisteredTools, TyCtxt};
35use rustc_middle::util::Providers;
36use rustc_parse::lexer::StripTokens;
37use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
38use rustc_passes::{abi_test, input_stats, layout_test};
39use rustc_resolve::{Resolver, ResolverOutputs};
40use rustc_session::Session;
41use rustc_session::config::{Input, Offload, OutFileName, OutputFilenames};
42use rustc_session::diagnostics::feature_err;
43use rustc_session::output::{OutputType, filename_for_input, invalid_output_for_target};
44use rustc_session::search_paths::PathKind;
45use rustc_span::{
46 DUMMY_SP, ErrorGuaranteed, ExpnKind, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, sym,
47};
48use rustc_structures::CrateType;
49use rustc_trait_selection::{solve, traits};
50use tracing::{info, instrument};
51
52use crate::interface::Compiler;
53use crate::{diagnostics, limits, util};
54
55pub fn parse<'a>(sess: &'a Session) -> ast::Crate {
56 let mut krate = sess
57 .time("parse_crate", || {
58 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
59 Input::File(file) => new_parser_from_file(
60 &sess.psess,
61 file,
62 StripTokens::ShebangAndFrontmatter,
63 None,
64 ),
65 instr @ (Input::Str { input, .. } | Input::DocTestStr { input, .. }) => {
66 new_parser_from_source_str(
67 &sess.psess,
68 instr.file_name(sess),
69 input.clone(),
70 StripTokens::ShebangAndFrontmatter,
71 )
72 }
73 });
74 parser.parse_crate_mod()
75 })
76 .unwrap_or_else(|parse_error| {
77 let guar: ErrorGuaranteed = parse_error.emit_err();
78 guar.raise_fatal();
79 });
80
81 rustc_builtin_macros::cmdline_attrs::inject(
82 &mut krate,
83 &sess.psess,
84 &sess.opts.unstable_opts.crate_attr,
85 );
86
87 krate
88}
89
90fn pre_expansion_lint<'a>(
91 sess: &Session,
92 features: &Features,
93 lint_store: &LintStore,
94 registered_lint_tools: &RegisteredTools,
95 check_node: EarlyCheckNode<'a>,
96 node_name: Symbol,
97) {
98 sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
99 || {
100 rustc_lint::check_ast_node(
101 sess,
102 features,
103 true,
104 lint_store,
105 registered_lint_tools,
106 None,
107 check_node,
108 );
109 },
110 );
111}
112
113struct LintStoreExpandImpl<'a>(&'a LintStore);
115
116impl LintStoreExpand for LintStoreExpandImpl<'_> {
117 fn pre_expansion_lint(
118 &self,
119 sess: &Session,
120 features: &Features,
121 registered_lint_tools: &RegisteredTools,
122 node_id: ast::NodeId,
123 attrs: &[ast::Attribute],
124 items: &[Box<ast::Item>],
125 name: Symbol,
126 ) {
127 let check_node = EarlyCheckNode::LoadedMod(node_id, attrs, items);
128 pre_expansion_lint(sess, features, self.0, registered_lint_tools, check_node, name);
129 }
130}
131
132{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("configure_and_expand",
"rustc_interface::passes", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(136u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pre_configured_attrs")
}> =
::tracing::__macro_support::FieldName::new("pre_configured_attrs");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pre_configured_attrs)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ast::Crate = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = resolver.tcx();
let sess = tcx.sess;
let features = tcx.features();
let lint_store = unerased_lint_store(sess);
let crate_name = tcx.crate_name(LOCAL_CRATE);
pre_expansion_lint(sess, features, lint_store,
tcx.registered_lint_tools(()),
EarlyCheckNode::CrateRoot(&krate, pre_configured_attrs),
crate_name);
rustc_builtin_macros::register_builtin_macros(resolver);
let num_standard_library_imports =
sess.time("crate_injection",
||
{
rustc_builtin_macros::standard_library_imports::inject(&mut krate,
pre_configured_attrs, resolver, sess, features)
});
krate =
sess.time("macro_expand_crate",
||
{
let mut old_path = OsString::new();
if false {
old_path = env::var_os("PATH").unwrap_or(old_path);
let mut new_path =
Vec::from_iter(sess.host_filesearch().search_paths(PathKind::Native).map(|p|
p.dir.to_path_buf()));
for path in env::split_paths(&old_path) {
if !new_path.contains(&path) { new_path.push(path); }
}
unsafe {
env::set_var("PATH",
env::join_paths(new_path.iter().filter(|p|
env::join_paths(iter::once(p)).is_ok())).unwrap());
}
}
let recursion_limit = tcx.recursion_limit();
let cfg =
rustc_expand::expand::ExpansionConfig {
crate_name,
features,
recursion_limit,
trace_mac: sess.opts.unstable_opts.trace_macros,
should_test: sess.is_test_crate(),
span_debug: sess.opts.unstable_opts.span_debug,
proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
};
let lint_store = LintStoreExpandImpl(lint_store);
let mut ecx =
ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
ecx.num_standard_library_imports =
num_standard_library_imports;
let krate =
sess.time("expand_crate",
|| ecx.monotonic_expander().expand_crate(krate));
if ecx.nb_macro_errors > 0 { sess.dcx().abort_if_errors(); }
sess.psess.buffered_lints.with_lock(|buffered_lints:
&mut Option<Vec<BufferedEarlyLint>>|
{
buffered_lints.as_mut().expect("Buffered lints are not stolen yet").append(&mut ecx.buffered_early_lint);
});
sess.time("check_unused_macros",
|| { ecx.check_unused_macros(); });
if ecx.reduced_recursion_limit.is_some() {
sess.dcx().abort_if_errors();
::core::panicking::unreachable_default_msg();
}
if false { unsafe { env::set_var("PATH", &old_path); } }
if ecx.sess.opts.unstable_opts.macro_stats {
print_macro_stats(&ecx);
}
krate
});
sess.time("maybe_building_test_harness",
||
{
rustc_builtin_macros::test_harness::inject(&mut krate, sess,
features, resolver)
});
let has_proc_macro_decls =
sess.time("AST_validation",
||
{
rustc_ast_passes::ast_validation::check_crate(sess,
features, &krate, tcx.is_sdylib_interface_build(),
resolver.lint_buffer())
});
if features.rustc_attrs() {
rustc_ast_passes::show_spans::check_crate(sess, &krate);
}
let crate_types = tcx.crate_types();
let is_executable_crate =
crate_types.contains(&CrateType::Executable);
let is_proc_macro_crate =
crate_types.contains(&CrateType::ProcMacro);
if crate_types.len() > 1 {
if is_executable_crate {
sess.dcx().emit_err(diagnostics::MixedBinCrate);
}
if is_proc_macro_crate {
sess.dcx().emit_err(diagnostics::MixedProcMacroCrate);
}
}
if is_proc_macro_crate && sess.target.is_like_wasm &&
!sess.opts.unstable_opts.wasm_proc_macros {
sess.dcx().emit_err(diagnostics::UnstableWasmProcMacro);
}
if crate_types.contains(&CrateType::Sdylib) &&
!tcx.features().export_stable() {
feature_err(sess, sym::export_stable, DUMMY_SP,
"`sdylib` crate type is unstable").emit();
}
if is_proc_macro_crate && !sess.sanitizers().is_empty() {
sess.dcx().emit_err(diagnostics::CannotSanitizeProcMacro);
}
if is_proc_macro_crate && !sess.panic_strategy().unwinds() {
sess.dcx().emit_warn(diagnostics::ProcMacroCratePanicAbort);
}
sess.time("maybe_create_a_macro_crate",
||
{
let is_test_crate = sess.is_test_crate();
rustc_builtin_macros::proc_macro_harness::inject(&mut krate,
sess, features, resolver, is_proc_macro_crate,
has_proc_macro_decls, is_test_crate, sess.dcx())
});
resolver.resolve_crate(&krate);
CStore::from_tcx(tcx).report_session_incompatibilities(tcx,
&krate);
krate
}
}
}#[instrument(level = "trace", skip(krate, resolver))]
137fn configure_and_expand(
138 mut krate: ast::Crate,
139 pre_configured_attrs: &[ast::Attribute],
140 resolver: &mut Resolver<'_, '_>,
141) -> ast::Crate {
142 let tcx = resolver.tcx();
143 let sess = tcx.sess;
144 let features = tcx.features();
145 let lint_store = unerased_lint_store(sess);
146 let crate_name = tcx.crate_name(LOCAL_CRATE);
147 pre_expansion_lint(
148 sess,
149 features,
150 lint_store,
151 tcx.registered_lint_tools(()),
152 EarlyCheckNode::CrateRoot(&krate, pre_configured_attrs),
153 crate_name,
154 );
155 rustc_builtin_macros::register_builtin_macros(resolver);
156
157 let num_standard_library_imports = sess.time("crate_injection", || {
158 rustc_builtin_macros::standard_library_imports::inject(
159 &mut krate,
160 pre_configured_attrs,
161 resolver,
162 sess,
163 features,
164 )
165 });
166
167 krate = sess.time("macro_expand_crate", || {
169 let mut old_path = OsString::new();
183 if cfg!(windows) {
184 old_path = env::var_os("PATH").unwrap_or(old_path);
185 let mut new_path = Vec::from_iter(
186 sess.host_filesearch().search_paths(PathKind::Native).map(|p| p.dir.to_path_buf()),
187 );
188 for path in env::split_paths(&old_path) {
189 if !new_path.contains(&path) {
190 new_path.push(path);
191 }
192 }
193 unsafe {
194 env::set_var(
195 "PATH",
196 env::join_paths(
197 new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
198 )
199 .unwrap(),
200 );
201 }
202 }
203
204 let recursion_limit = tcx.recursion_limit();
206 let cfg = rustc_expand::expand::ExpansionConfig {
207 crate_name,
208 features,
209 recursion_limit,
210 trace_mac: sess.opts.unstable_opts.trace_macros,
211 should_test: sess.is_test_crate(),
212 span_debug: sess.opts.unstable_opts.span_debug,
213 proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
214 };
215
216 let lint_store = LintStoreExpandImpl(lint_store);
217 let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
218 ecx.num_standard_library_imports = num_standard_library_imports;
219 let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
221
222 if ecx.nb_macro_errors > 0 {
223 sess.dcx().abort_if_errors();
224 }
225
226 sess.psess.buffered_lints.with_lock(
229 |buffered_lints: &mut Option<Vec<BufferedEarlyLint>>| {
230 buffered_lints
231 .as_mut()
232 .expect("Buffered lints are not stolen yet")
233 .append(&mut ecx.buffered_early_lint);
234 },
235 );
236
237 sess.time("check_unused_macros", || {
238 ecx.check_unused_macros();
239 });
240
241 if ecx.reduced_recursion_limit.is_some() {
244 sess.dcx().abort_if_errors();
245 unreachable!();
246 }
247
248 if cfg!(windows) {
249 unsafe {
250 env::set_var("PATH", &old_path);
251 }
252 }
253
254 if ecx.sess.opts.unstable_opts.macro_stats {
255 print_macro_stats(&ecx);
256 }
257
258 krate
259 });
260
261 sess.time("maybe_building_test_harness", || {
262 rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
263 });
264
265 let has_proc_macro_decls = sess.time("AST_validation", || {
266 rustc_ast_passes::ast_validation::check_crate(
267 sess,
268 features,
269 &krate,
270 tcx.is_sdylib_interface_build(),
271 resolver.lint_buffer(),
272 )
273 });
274
275 if features.rustc_attrs() {
276 rustc_ast_passes::show_spans::check_crate(sess, &krate);
277 }
278
279 let crate_types = tcx.crate_types();
280 let is_executable_crate = crate_types.contains(&CrateType::Executable);
281 let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
282
283 if crate_types.len() > 1 {
284 if is_executable_crate {
285 sess.dcx().emit_err(diagnostics::MixedBinCrate);
286 }
287 if is_proc_macro_crate {
288 sess.dcx().emit_err(diagnostics::MixedProcMacroCrate);
289 }
290 }
291
292 if is_proc_macro_crate && sess.target.is_like_wasm && !sess.opts.unstable_opts.wasm_proc_macros
293 {
294 sess.dcx().emit_err(diagnostics::UnstableWasmProcMacro);
295 }
296
297 if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() {
298 feature_err(sess, sym::export_stable, DUMMY_SP, "`sdylib` crate type is unstable").emit();
299 }
300
301 if is_proc_macro_crate && !sess.sanitizers().is_empty() {
302 sess.dcx().emit_err(diagnostics::CannotSanitizeProcMacro);
303 }
304
305 if is_proc_macro_crate && !sess.panic_strategy().unwinds() {
306 sess.dcx().emit_warn(diagnostics::ProcMacroCratePanicAbort);
307 }
308
309 sess.time("maybe_create_a_macro_crate", || {
310 let is_test_crate = sess.is_test_crate();
311 rustc_builtin_macros::proc_macro_harness::inject(
312 &mut krate,
313 sess,
314 features,
315 resolver,
316 is_proc_macro_crate,
317 has_proc_macro_decls,
318 is_test_crate,
319 sess.dcx(),
320 )
321 });
322
323 resolver.resolve_crate(&krate);
326
327 CStore::from_tcx(tcx).report_session_incompatibilities(tcx, &krate);
328 krate
329}
330
331fn print_macro_stats(ecx: &ExtCtxt<'_>) {
332 use std::fmt::Write;
333
334 let crate_name = ecx.ecfg.crate_name.as_str();
335 let crate_name = if crate_name == "build_script_build" {
336 let pkg_name =
338 std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "<unknown crate>".to_string());
339 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} build script", pkg_name))
})format!("{pkg_name} build script")
340 } else {
341 crate_name.to_string()
342 };
343
344 #[allow(rustc::potential_query_instability)]
346 let mut macro_stats: Vec<_> = ecx
347 .macro_stats
348 .iter()
349 .map(|((name, kind), stat)| {
350 (stat.bytes, stat.lines, stat.uses, name, *kind)
352 })
353 .collect();
354 macro_stats.sort_unstable();
355 macro_stats.reverse(); let prefix = "macro-stats";
358 let name_w = 32;
359 let uses_w = 7;
360 let lines_w = 11;
361 let avg_lines_w = 11;
362 let bytes_w = 11;
363 let avg_bytes_w = 11;
364 let banner_w = name_w + uses_w + lines_w + avg_lines_w + bytes_w + avg_bytes_w;
365
366 let mut s = String::new();
372 _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
373 _ = s.write_fmt(format_args!("{1} MACRO EXPANSION STATS: {0}\n", crate_name,
prefix))writeln!(s, "{prefix} MACRO EXPANSION STATS: {}", crate_name);
374 _ = s.write_fmt(format_args!("{6} {0:<7$}{1:>8$}{2:>9$}{3:>10$}{4:>11$}{5:>12$}\n",
"Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
prefix, name_w, uses_w, lines_w, avg_lines_w, bytes_w, avg_bytes_w))writeln!(
375 s,
376 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
377 "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
378 );
379 _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
380 if macro_stats.is_empty() {
383 _ = s.write_fmt(format_args!("{0} (none)\n", prefix))writeln!(s, "{prefix} (none)");
384 }
385 for (bytes, lines, uses, name, kind) in macro_stats {
386 let mut name = ExpnKind::Macro(kind, *name).descr();
387 let uses_with_underscores = thousands::usize_with_underscores(uses);
388 let avg_lines = lines as f64 / uses as f64;
389 let avg_bytes = bytes as f64 / uses as f64;
390
391 let mut uses_w = uses_w;
393 if name.len() + uses_with_underscores.len() >= name_w + uses_w {
394 _ = s.write_fmt(format_args!("{1} {0:<2$}\n", name, prefix, name_w))writeln!(s, "{prefix} {:<name_w$}", name);
398 name = String::new();
399 } else if name.len() >= name_w {
400 uses_w -= name.len() - name_w;
404 };
405
406 _ = s.write_fmt(format_args!("{6} {0:<7$}{1:>8$}{2:>9$}{3:>10$}{4:>11$}{5:>12$}\n",
name, uses_with_underscores, thousands::usize_with_underscores(lines),
thousands::f64p1_with_underscores(avg_lines),
thousands::usize_with_underscores(bytes),
thousands::f64p1_with_underscores(avg_bytes), prefix, name_w, uses_w,
lines_w, avg_lines_w, bytes_w, avg_bytes_w))writeln!(
407 s,
408 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
409 name,
410 uses_with_underscores,
411 thousands::usize_with_underscores(lines),
412 thousands::f64p1_with_underscores(avg_lines),
413 thousands::usize_with_underscores(bytes),
414 thousands::f64p1_with_underscores(avg_bytes),
415 );
416 }
417 _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
418 { ::std::io::_eprint(format_args!("{0}", s)); };eprint!("{s}");
419}
420
421fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
422 let sess = tcx.sess;
423 let (resolver, krate) = tcx.resolver_for_lowering();
424 let resolver = &*resolver.borrow();
425 let krate = &*krate.borrow();
426 let mut lint_buffer = resolver.lint_buffer.steal();
427
428 if sess.opts.unstable_opts.input_stats {
429 input_stats::print_ast_stats(tcx, krate);
430 }
431
432 sess.time("complete_gated_feature_checking", || {
434 rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
435 });
436
437 sess.psess.buffered_lints.with_lock(|buffered_lints| {
439 let buffered_lints = buffered_lints.take().expect("Buffered lints are not stolen yet");
440 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/passes.rs:440",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(440u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::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!("{0} parse sess buffered_lints",
buffered_lints.len()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("{} parse sess buffered_lints", buffered_lints.len());
441 for early_lint in buffered_lints {
442 lint_buffer.add_early_lint(early_lint);
443 }
444 });
445
446 sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
448 for (ident, mut spans) in identifiers.drain(..) {
449 spans.sort_by_key(|span| span.lo_hi());
450 if ident == sym::ferris {
451 enum FerrisFix {
452 SnakeCase,
453 ScreamingSnakeCase,
454 PascalCase,
455 }
456
457 impl FerrisFix {
458 const fn as_str(self) -> &'static str {
459 match self {
460 FerrisFix::SnakeCase => "ferris",
461 FerrisFix::ScreamingSnakeCase => "FERRIS",
462 FerrisFix::PascalCase => "Ferris",
463 }
464 }
465 }
466
467 let first_span = spans[0];
468 let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
469 let ferris_fix = prev_source
470 .map_or(FerrisFix::SnakeCase, |source| {
471 let mut source_before_ferris = source.split_whitespace().rev();
472 match source_before_ferris.next() {
473 Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
474 FerrisFix::PascalCase
475 }
476 Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
477 Some("mut") if source_before_ferris.next() == Some("static") => {
478 FerrisFix::ScreamingSnakeCase
479 }
480 _ => FerrisFix::SnakeCase,
481 }
482 })
483 .as_str();
484
485 sess.dcx().emit_err(diagnostics::FerrisIdentifier {
486 spans,
487 first_span,
488 ferris_fix,
489 });
490 } else {
491 sess.dcx().emit_err(diagnostics::EmojiIdentifier { spans, ident });
492 }
493 }
494 });
495
496 let lint_store = unerased_lint_store(tcx.sess);
497 rustc_lint::check_ast_node(
498 sess,
499 tcx.features(),
500 false,
501 lint_store,
502 tcx.registered_lint_tools(()),
503 Some(lint_buffer),
504 EarlyCheckNode::CrateRoot(&*krate, &*krate.attrs),
505 )
506}
507
508fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
509 let value = env::var_os(key);
510
511 let value_tcx = value.as_ref().map(|value| tcx.arena.alloc_os_str(value));
512
513 tcx.sess.env_depinfo.borrow_mut().insert((
519 Symbol::intern(&key.to_string_lossy()),
520 value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(value)),
521 ));
522
523 value_tcx
524}
525
526fn generated_output_paths(
528 tcx: TyCtxt<'_>,
529 outputs: &OutputFilenames,
530 exact_name: bool,
531 crate_name: Symbol,
532) -> Vec<PathBuf> {
533 let sess = tcx.sess;
534 let mut out_filenames = Vec::new();
535 for output_type in sess.opts.output_types.keys() {
536 let out_filename = outputs.path(*output_type);
537 let file = out_filename.as_path().to_path_buf();
538 match *output_type {
539 OutputType::Exe if !exact_name => {
542 for crate_type in tcx.crate_types().iter() {
543 let p = filename_for_input(sess, *crate_type, crate_name, outputs);
544 out_filenames.push(p.as_path().to_path_buf());
545 }
546 }
547 OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
548 }
550 OutputType::DepInfo if out_filename.is_stdout() => {
551 }
553 _ => {
554 out_filenames.push(file);
555 }
556 }
557 }
558 out_filenames
559}
560
561fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
562 let input_path = try_canonicalize(input_path).ok();
563 if input_path.is_none() {
564 return false;
565 }
566 output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
567}
568
569fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
570 output_paths.iter().find(|output_path| output_path.is_dir())
571}
572
573fn escape_dep_filename(filename: &str) -> String {
574 filename.replace(' ', "\\ ")
577}
578
579fn escape_dep_env(symbol: Symbol) -> String {
582 let s = symbol.as_str();
583 let mut escaped = String::with_capacity(s.len());
584 for c in s.chars() {
585 match c {
586 '\n' => escaped.push_str(r"\n"),
587 '\r' => escaped.push_str(r"\r"),
588 '\\' => escaped.push_str(r"\\"),
589 _ => escaped.push(c),
590 }
591 }
592 escaped
593}
594
595fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
596 let sess = tcx.sess;
598 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
599 return;
600 }
601 let deps_output = outputs.path(OutputType::DepInfo);
602 let deps_filename = deps_output.as_path();
603
604 let result = try {
605 let mut files: IndexMap<String, (u64, Option<SourceFileHash>)> = sess
608 .source_map()
609 .files()
610 .iter()
611 .filter(|fmap| fmap.is_real_file())
612 .filter(|fmap| !fmap.is_imported())
613 .map(|fmap| {
614 (
615 escape_dep_filename(&fmap.name.prefer_local_unconditionally().to_string()),
616 (
617 fmap.unnormalized_source_len as u64,
620 fmap.checksum_hash,
621 ),
622 )
623 })
624 .collect();
625
626 let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
627
628 let file_depinfo = sess.file_depinfo.borrow();
631
632 let normalize_path = |path: PathBuf| escape_dep_filename(&path.to_string_lossy());
633
634 fn hash_iter_files<P: AsRef<Path>>(
637 it: impl Iterator<Item = P>,
638 checksum_hash_algo: Option<SourceFileHashAlgorithm>,
639 ) -> impl Iterator<Item = (P, (u64, Option<SourceFileHash>))> {
640 it.map(move |path| {
641 match checksum_hash_algo.and_then(|algo| {
642 fs::File::open(path.as_ref())
643 .and_then(|mut file| {
644 SourceFileHash::new(algo, &mut file).map(|h| (file, h))
645 })
646 .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
647 .map_err(|e| {
648 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/passes.rs:648",
"rustc_interface::passes", ::tracing::Level::ERROR,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(648u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::ERROR <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::ERROR <=
::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!("failed to compute checksum, omitting it from dep-info {0} {1}",
path.as_ref().display(), e) as
&dyn ::tracing::field::Value))])
});
} else { ; }
}tracing::error!(
649 "failed to compute checksum, omitting it from dep-info {} {e}",
650 path.as_ref().display()
651 )
652 })
653 .ok()
654 }) {
655 Some((file_len, checksum)) => (path, (file_len, Some(checksum))),
656 None => (path, (0, None)),
657 }
658 })
659 }
660
661 let extra_tracked_files = hash_iter_files(
662 file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
663 checksum_hash_algo,
664 );
665 files.extend(extra_tracked_files);
666
667 if let Some(ref profile_instr) = sess.opts.cg.profile_use {
669 files.extend(hash_iter_files(
670 iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
671 checksum_hash_algo,
672 ));
673 }
674 if let Some(ref profile_sample) = sess.opts.cg.profile_sample_use {
675 files.extend(hash_iter_files(
676 iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
677 checksum_hash_algo,
678 ));
679 }
680
681 for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
683 files.extend(hash_iter_files(
684 iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
685 checksum_hash_algo,
686 ));
687 }
688
689 if sess.binary_dep_depinfo() {
690 if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
691 if backend.contains('.') {
692 files.extend(hash_iter_files(
695 iter::once(backend.to_string()),
696 checksum_hash_algo,
697 ));
698 }
699 }
700
701 for &cnum in tcx.crates(()) {
702 let source = tcx.used_crate_source(cnum);
703 if let Some(path) = &source.dylib {
704 files.extend(hash_iter_files(
705 iter::once(escape_dep_filename(&path.display().to_string())),
706 checksum_hash_algo,
707 ));
708 }
709 if let Some(path) = &source.rlib {
710 files.extend(hash_iter_files(
711 iter::once(escape_dep_filename(&path.display().to_string())),
712 checksum_hash_algo,
713 ));
714 }
715 if let Some(path) = &source.rmeta {
716 files.extend(hash_iter_files(
717 iter::once(escape_dep_filename(&path.display().to_string())),
718 checksum_hash_algo,
719 ));
720 }
721 }
722 }
723
724 let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
725 for path in out_filenames {
726 file.write_fmt(format_args!("{0}: {1}\n\n", path.display(),
files.keys().map(String::as_str).intersperse(" ").collect::<String>()))writeln!(
727 file,
728 "{}: {}\n",
729 path.display(),
730 files.keys().map(String::as_str).intersperse(" ").collect::<String>()
731 )?;
732 }
733
734 for path in files.keys() {
738 file.write_fmt(format_args!("{0}:\n", path))writeln!(file, "{path}:")?;
739 }
740
741 let env_depinfo = sess.env_depinfo.borrow();
743 if !env_depinfo.is_empty() {
744 #[allow(rustc::potential_query_instability)]
746 let mut envs: Vec<_> = env_depinfo
747 .iter()
748 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
749 .collect();
750 envs.sort_unstable();
751 file.write_fmt(format_args!("\n"))writeln!(file)?;
752 for (k, v) in envs {
753 file.write_fmt(format_args!("# env-dep:{0}", k))write!(file, "# env-dep:{k}")?;
754 if let Some(v) = v {
755 file.write_fmt(format_args!("={0}", v))write!(file, "={v}")?;
756 }
757 file.write_fmt(format_args!("\n"))writeln!(file)?;
758 }
759 }
760
761 if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
764 files
765 .iter()
766 .filter_map(|(path, (file_len, hash_algo))| {
767 hash_algo.map(|hash_algo| (path, file_len, hash_algo))
768 })
769 .try_for_each(|(path, file_len, checksum_hash)| {
770 file.write_fmt(format_args!("# checksum:{0} file_len:{1} {2}\n",
checksum_hash, file_len, path))writeln!(file, "# checksum:{checksum_hash} file_len:{file_len} {path}")
771 })?;
772 }
773
774 Ok(())
775 };
776
777 match deps_output {
778 OutFileName::Stdout => {
779 let mut file = BufWriter::new(io::stdout());
780 write_deps_to_file(&mut file)?;
781 }
782 OutFileName::Real(ref path) => {
783 let mut file = fs::File::create_buffered(path)?;
784 write_deps_to_file(&mut file)?;
785 }
786 }
787 };
788
789 match result {
790 Ok(_) => {
791 if sess.opts.json_artifact_notifications {
792 sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
793 }
794 }
795 Err(error) => {
796 sess.dcx()
797 .emit_fatal(diagnostics::ErrorWritingDependencies { path: deps_filename, error });
798 }
799 }
800}
801
802fn resolver_for_lowering_raw<'tcx>(
803 tcx: TyCtxt<'tcx>,
804 (): (),
805) -> (&'tcx Steal<ResolverAstLowering<'tcx>>, &'tcx Steal<ast::Crate>, &'tcx ResolverGlobalCtxt) {
806 let arenas = WorkerLocal::new(|_| Resolver::arenas());
807 let _ = tcx.registered_attr_tools(()); let _ = tcx.registered_lint_tools(()); let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
810 let mut resolver = Resolver::new(
811 tcx,
812 &pre_configured_attrs,
813 krate.spans.inner_span,
814 krate.spans.inject_use_span,
815 &arenas,
816 );
817 let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
818
819 tcx.untracked().freeze_cstore();
821
822 let ResolverOutputs {
823 global_ctxt: untracked_resolutions,
824 ast_lowering: untracked_resolver_for_lowering,
825 } = resolver.into_outputs();
826
827 (
828 tcx.arena.alloc(Steal::new(untracked_resolver_for_lowering)),
829 tcx.arena.alloc(Steal::new(krate)),
830 tcx.arena.alloc(untracked_resolutions),
831 )
832}
833
834pub fn write_dep_info(tcx: TyCtxt<'_>) {
835 let _ = tcx.resolver_for_lowering();
839
840 let sess = tcx.sess;
841 let _timer = sess.timer("write_dep_info");
842 let crate_name = tcx.crate_name(LOCAL_CRATE);
843
844 let outputs = tcx.output_filenames(());
845 let output_paths =
846 generated_output_paths(tcx, outputs, sess.io.output_file.is_some(), crate_name);
847
848 if let Some(input_path) = sess.io.input.opt_path() {
850 if sess.opts.will_create_output_file() {
851 if output_contains_path(&output_paths, input_path) {
852 sess.dcx()
853 .emit_fatal(diagnostics::InputFileWouldBeOverWritten { path: input_path });
854 }
855 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
856 sess.dcx().emit_fatal(diagnostics::GeneratedFileConflictsWithDirectory {
857 input_path,
858 dir_path,
859 });
860 }
861 }
862 }
863
864 if let Some(ref dir) = sess.io.temps_dir {
865 if fs::create_dir_all(dir).is_err() {
866 sess.dcx().emit_fatal(diagnostics::TempsDirError);
867 }
868 }
869
870 write_out_deps(tcx, outputs, &output_paths);
871
872 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
873 && sess.opts.output_types.len() == 1;
874
875 if !only_dep_info {
876 if let Some(ref dir) = sess.io.output_dir {
877 if fs::create_dir_all(dir).is_err() {
878 sess.dcx().emit_fatal(diagnostics::OutDirError);
879 }
880 }
881 }
882}
883
884pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
885 if !tcx.crate_types().contains(&rustc_structures::CrateType::Sdylib) {
886 return;
887 }
888 let _timer = tcx.sess.timer("write_interface");
889 let (_, krate) = tcx.resolver_for_lowering();
890
891 let krate = rustc_ast_pretty::pprust::print_crate_as_interface(
892 &*krate.borrow(),
893 tcx.sess.psess.edition,
894 &tcx.sess.psess.attr_id_generator,
895 );
896 let export_output = tcx.output_filenames(()).interface_path();
897 let mut file = fs::File::create_buffered(&export_output).unwrap_or_else(|error| {
898 tcx.dcx().emit_fatal(diagnostics::FailedWritingFile { path: &export_output, error })
899 });
900 if let Err(error) = file.write_fmt(format_args!("{0}", krate))write!(file, "{}", krate) {
901 tcx.dcx().emit_fatal(diagnostics::FailedWritingFile { path: &export_output, error });
902 }
903}
904
905pub fn finish_and_emit_metadata<'tcx>(tcx: TyCtxt<'tcx>) -> EncodedMetadata {
906 if let Some((def_id, _)) = tcx.entry_fn(())
908 && {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcDelayedBugFromInsideQuery)
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, RustcDelayedBugFromInsideQuery)
909 {
910 tcx.ensure_ok().trigger_delayed_bug(def_id);
911 }
912
913 if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
917 guar.raise_fatal();
918 }
919
920 let metadata = match rustc_metadata::fs::encode_and_write_metadata(tcx) {
921 Ok(metadata) => metadata,
922 Err(guar) => guar.raise_fatal(),
923 };
924
925 metadata
926}
927
928pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
929 let providers = &mut Providers::default();
930 providers.queries.required_analysis = run_required_analyses;
931 providers.queries.resolver_for_lowering_raw = resolver_for_lowering_raw;
932 providers.queries.stripped_cfg_items = |tcx, _| &tcx.resolutions(()).stripped_cfg_items[..];
933 providers.queries.get_lang_items = |tcx, ()| &tcx.resolutions(()).lang_items;
934 providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).2;
935 providers.queries.early_lint_checks = early_lint_checks;
936 providers.queries.env_var_os = env_var_os;
937 providers.queries.proc_macro_decls_static = |tcx, _| tcx.hir_crate_items(()).proc_macro_decls();
938 rustc_ast_lowering::provide(&mut providers.queries);
939 rustc_expand_queries::provide(&mut providers.queries);
940 rustc_const_eval::provide(providers);
941 rustc_middle::hir::provide(&mut providers.queries);
942 rustc_borrowck::provide(&mut providers.queries);
943 rustc_incremental::provide(providers);
944 rustc_mir_build::provide(providers);
945 rustc_mir_dataflow::provide(providers);
946 rustc_mir_transform::provide(providers);
947 rustc_monomorphize::provide(providers);
948 rustc_privacy::provide(&mut providers.queries);
949 rustc_query_impl::provide(providers);
950 rustc_resolve::provide(&mut providers.queries);
951 rustc_hir_analysis::provide(&mut providers.queries);
952 rustc_hir_typeck::provide(&mut providers.queries);
953 ty::provide(&mut providers.queries);
954 traits::provide(&mut providers.queries);
955 solve::provide(&mut providers.queries);
956 rustc_passes::provide(&mut providers.queries);
957 rustc_traits::provide(&mut providers.queries);
958 rustc_ty_utils::provide(&mut providers.queries);
959 rustc_metadata::provide(providers);
960 rustc_lint::provide(&mut providers.queries);
961 rustc_symbol_mangling::provide(&mut providers.queries);
962 rustc_codegen_ssa::provide(providers);
963 *providers
964});
965
966pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
967 compiler: &Compiler,
968 krate: rustc_ast::Crate,
969 f: F,
970) -> (T, Option<IncrCompSession>) {
971 let sess = &compiler.sess;
972
973 let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
974
975 let crate_name = get_crate_name(sess, &pre_configured_attrs);
976 let crate_types = collect_crate_types(
977 sess,
978 &compiler.codegen_backend.supported_crate_types(sess),
979 compiler.codegen_backend.name(),
980 &pre_configured_attrs,
981 krate.spans.inner_span,
982 );
983 let stable_crate_id = StableCrateId::new(
984 crate_name,
985 crate_types.contains(&CrateType::Executable),
986 sess.opts.cg.metadata.clone(),
987 sess.cfg_version,
988 );
989
990 let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
991
992 let (dep_graph, incr_comp_session) = setup_dep_graph(sess, crate_name, stable_crate_id);
993
994 let cstore =
995 FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
996 let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
997
998 let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
999 let untracked = Untracked {
1000 cstore,
1001 source_span: AppendOnlyIndexVec::new(),
1002 definitions,
1003 stable_crate_ids,
1004 local_crate_hash: OnceLock::new(),
1005 };
1006
1007 dep_graph.assert_ignored();
1011
1012 let query_result_on_disk_cache = incr_comp_session.as_ref().map(|incr_comp_session| {
1013 rustc_incremental::load_query_result_cache(sess, incr_comp_session)
1014 });
1015
1016 let codegen_backend = &compiler.codegen_backend;
1017 let mut providers = *DEFAULT_QUERY_PROVIDERS;
1018 codegen_backend.provide(&mut providers);
1019
1020 if let Some(callback) = compiler.override_queries {
1021 callback(sess, &mut providers);
1022 }
1023
1024 let incremental = dep_graph.is_fully_enabled();
1025 let track_present = incremental
1026 || sess.opts.unstable_opts.incremental_verify_ich
1027 || sess.prof.enabled()
1028 || truecfg!(debug_assertions);
1029
1030 let gcx_cell = OnceLock::new();
1042 let arena = WorkerLocal::new(|_| Arena::default());
1043 let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
1044
1045 let res = TyCtxt::create_global_ctxt(
1046 &gcx_cell,
1047 &compiler.sess,
1048 crate_types,
1049 stable_crate_id,
1050 &arena,
1051 &hir_arena,
1052 untracked,
1053 incr_comp_session.as_ref(),
1054 dep_graph,
1055 rustc_query_impl::query_system(
1056 &arena,
1057 providers.queries,
1058 providers.extern_queries,
1059 query_result_on_disk_cache,
1060 incremental,
1061 track_present,
1062 ),
1063 providers.hooks,
1064 compiler.current_gcx.clone(),
1065 |tcx| {
1066 let feed = tcx.create_crate_num(stable_crate_id).unwrap();
1067 {
match (&feed.key(), &LOCAL_CRATE) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(feed.key(), LOCAL_CRATE);
1068 feed.crate_name(crate_name);
1069
1070 let feed = tcx.feed_unit_query();
1071 let features = tcx.arena.alloc(rustc_expand::config::features(
1072 tcx.sess,
1073 &pre_configured_attrs,
1074 crate_name,
1075 ));
1076 feed.features_query(features);
1077 feed.limits(limits::get_limits(&pre_configured_attrs, tcx.sess, features));
1078 feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
1079 feed.output_filenames(Arc::new(outputs));
1080
1081 let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(tcx)));
1089 let res = match res {
1090 Ok(res) => res,
1091 Err(err) => {
1092 tcx.alloc_self_profile_query_strings();
1093
1094 std::panic::resume_unwind(err);
1096 }
1097 };
1098
1099 tcx.finish();
1100 res
1101 },
1102 );
1103
1104 (res, incr_comp_session)
1105}
1106
1107struct DiagCallback<'tcx> {
1108 callback: Box<
1109 dyn for<'b> FnOnce(DiagCtxtHandle<'b>, Level, &dyn Any) -> Diag<'b> + DynSend + DynSync,
1110 >,
1111 tcx: TyCtxt<'tcx>,
1112}
1113
1114impl<'a, 'tcx> Diagnostic<'a> for DiagCallback<'tcx> {
1115 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
1116 (self.callback)(dcx, level, self.tcx.sess)
1117 }
1118}
1119
1120pub fn emit_delayed_lints(tcx: TyCtxt<'_>) {
1121 for owner_id in tcx.hir_crate_items(()).owners() {
1122 if let Some(delayed_lints) = tcx.opt_ast_lowering_delayed_lints(owner_id) {
1123 for lint in delayed_lints.steal() {
1124 tcx.emit_node_span_lint(
1125 lint.lint_id.lint,
1126 lint.id,
1127 lint.span.clone(),
1128 DiagCallback { callback: lint.callback, tcx },
1129 );
1130 }
1131 }
1132 }
1133}
1134
1135fn run_required_analyses(tcx: TyCtxt<'_>, (): ()) {
1138 if tcx.sess.opts.unstable_opts.input_stats {
1139 rustc_passes::input_stats::print_hir_stats(tcx);
1140 }
1141 #[cfg(all(not(doc), debug_assertions))]
1144 rustc_passes::hir_id_validator::check_crate(tcx);
1145
1146 tcx.ensure_done().hir_crate_items(());
1150
1151 tcx.untracked().definitions.write().commit_end_of_determinism();
1152
1153 rustc_passes::delegation::check_glob_and_list_delegations_target_expr(tcx);
1154
1155 let sess = tcx.sess;
1156 sess.time("misc_checking_1", || {
1157 par_fns(&mut [
1158 &mut || {
1159 sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
1160 sess.time("check_externally_implementable_items", || {
1161 tcx.ensure_ok().check_externally_implementable_items(())
1162 });
1163
1164 sess.time("looking_for_derive_registrar", || {
1165 tcx.ensure_ok().proc_macro_decls_static(())
1166 });
1167
1168 CStore::from_tcx(tcx).report_unused_deps(tcx);
1169 },
1170 &mut || {
1171 tcx.ensure_ok().exportable_items(LOCAL_CRATE);
1172 tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
1173 tcx.par_hir_for_each_module(|module| {
1174 tcx.ensure_ok().check_mod_attrs(module);
1175 tcx.ensure_ok().check_mod_unstable_api_usage(module);
1176 });
1177 },
1178 ]);
1179 });
1180
1181 sess.time("emit_ast_lowering_delayed_lints", || {
1182 emit_delayed_lints(tcx);
1183 });
1184
1185 rustc_hir_analysis::check_crate(tcx);
1186 tcx.untracked().definitions.freeze();
1192
1193 sess.time("MIR_checking", || {
1194 tcx.par_hir_body_owners(|def_id| {
1195 if tcx.is_intrinsic_that_must_be_overridden(def_id) {
1196 return; }
1198 let not_typeck_child = !tcx.is_typeck_child(def_id.to_def_id());
1199 if not_typeck_child {
1200 tcx.ensure_ok().check_unsafety(def_id);
1202 }
1203 if tcx.is_trivial_const(def_id) {
1204 return; }
1206 if not_typeck_child {
1207 tcx.ensure_ok().mir_borrowck(def_id);
1208 tcx.ensure_ok().check_transmutes(def_id);
1209 if !tcx.sess.opts.unstable_opts.offload.is_empty() {
1210 tcx.ensure_ok().check_offloads(def_id);
1211 }
1212 }
1213 tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1214 tcx.ensure_ok().check_liveness(def_id);
1215
1216 if tcx.sess.opts.output_types.should_codegen()
1220 || tcx.hir_body_const_context(def_id).is_some()
1221 {
1222 tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1223 }
1224 if tcx.is_coroutine(def_id.to_def_id())
1225 && (!tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()))
1226 {
1227 tcx.ensure_ok()
1229 .layout_of(ty::TypingEnv::codegen(tcx, def_id.to_def_id()).as_query_input(
1230 tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
1231 ));
1232 }
1233 });
1234 });
1235
1236 sess.time("layout_testing", || layout_test::test_layout(tcx));
1237 sess.time("abi_testing", || abi_test::test_abi(tcx));
1238}
1239
1240pub fn full_analysis(tcx: TyCtxt<'_>) {
1243 tcx.ensure_ok().required_analysis(());
1244
1245 let sess = tcx.sess;
1246
1247 if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1256 guar.raise_fatal();
1257 }
1258
1259 sess.time("misc_checking_3", || {
1260 par_fns(&mut [
1261 &mut || {
1262 tcx.ensure_ok().effective_visibilities(());
1263
1264 par_fns(&mut [
1265 &mut || {
1266 tcx.par_hir_for_each_module(|module| {
1267 tcx.ensure_ok().check_private_in_public(module)
1268 })
1269 },
1270 &mut || {
1271 tcx.par_hir_for_each_module(|module| {
1272 tcx.ensure_ok().check_mod_deathness(module)
1273 });
1274 },
1275 &mut || {
1276 sess.time("lint_checking", || {
1277 rustc_lint::check_crate(tcx);
1278 });
1279 },
1280 &mut || {
1281 tcx.ensure_ok().clashing_extern_declarations(());
1282 },
1283 ]);
1284 },
1285 &mut || {
1286 sess.time("privacy_checking_modules", || {
1287 tcx.par_hir_for_each_module(|module| {
1288 tcx.ensure_ok().check_mod_privacy(module);
1289 });
1290 });
1291 },
1292 ]);
1293
1294 sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1297
1298 let _ = tcx.all_diagnostic_items(());
1302
1303 let _ = tcx.all_canonical_symbols(());
1307 });
1308
1309 if tcx.sess.opts.unstable_opts.validate_mir {
1316 sess.time("ensuring_final_MIR_is_computable", || {
1317 tcx.par_hir_body_owners(|def_id| {
1318 if !tcx.is_trivial_const(def_id)
1319 && !tcx.is_intrinsic_that_must_be_overridden(def_id)
1320 {
1321 tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1322 }
1323 });
1324 });
1325 }
1326}
1327
1328pub(crate) fn start_codegen<'tcx>(
1331 codegen_backend: &dyn CodegenBackend,
1332 tcx: TyCtxt<'tcx>,
1333) -> (Box<dyn Any>, CrateInfo) {
1334 tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen);
1335 if tcx.sess.opts.output_types.should_codegen() {
1338 rustc_symbol_mangling::test::dump_symbol_names_and_def_paths(tcx);
1339 }
1340
1341 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/passes.rs:1341",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(1341u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::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!("Pre-codegen\n{0:?}",
tcx.debug_stats()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("Pre-codegen\n{:?}", tcx.debug_stats());
1342
1343 let is_host_metadata = tcx
1344 .sess
1345 .opts
1346 .unstable_opts
1347 .offload
1348 .iter()
1349 .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
rustc_session::config::Offload::HostMetadata(_) => true,
_ => false,
}matches!(o, rustc_session::config::Offload::HostMetadata(_)));
1350
1351 let codegen = tcx.sess.time("codegen_crate", || {
1352 if tcx.sess.opts.unstable_opts.no_codegen
1353 || !tcx.sess.opts.output_types.should_codegen()
1354 || is_host_metadata
1355 {
1356 tcx.sess.dcx().abort_if_errors();
1357
1358 if is_host_metadata {
1359 rustc_monomorphize::write_host_metadata_offload_manifest(tcx);
1360 }
1361
1362 Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
1364 } else {
1365 codegen_backend.codegen_crate(tcx)
1366 }
1367 });
1368
1369 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/passes.rs:1369",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(1369u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::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!("Post-codegen\n{0:?}",
tcx.debug_stats()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("Post-codegen\n{:?}", tcx.debug_stats());
1370
1371 if tcx.sess.opts.unstable_opts.print_type_sizes {
1374 tcx.sess.code_stats.print_type_sizes();
1375 }
1376
1377 let crate_info = CrateInfo::new(tcx, codegen_backend.target_cpu(tcx.sess));
1378
1379 (codegen, crate_info)
1380}
1381
1382pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1384 let attr_crate_name =
1392 parse_crate_name(sess, krate_attrs, ShouldEmit::EarlyFatal { also_emit_lints: true });
1393
1394 let validate = |name, span| {
1395 rustc_session::output::validate_crate_name(sess, name, span);
1396 name
1397 };
1398
1399 if let Some(crate_name) = &sess.opts.crate_name {
1400 let crate_name = Symbol::intern(crate_name);
1401 if let Some((attr_crate_name, span)) = attr_crate_name
1402 && attr_crate_name != crate_name
1403 {
1404 sess.dcx().emit_err(diagnostics::CrateNameDoesNotMatch {
1405 span,
1406 crate_name,
1407 attr_crate_name,
1408 });
1409 }
1410 return validate(crate_name, None);
1411 }
1412
1413 if let Some((crate_name, span)) = attr_crate_name {
1414 return validate(crate_name, Some(span));
1415 }
1416
1417 if let Input::File(ref path) = sess.io.input
1418 && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1419 {
1420 if file_stem.starts_with('-') {
1421 sess.dcx().emit_err(diagnostics::CrateNameInvalid { crate_name: file_stem });
1422 } else {
1423 return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1424 }
1425 }
1426
1427 sym::rust_out
1428}
1429
1430pub(crate) fn parse_crate_name(
1431 sess: &Session,
1432 attrs: &[ast::Attribute],
1433 emit_errors: ShouldEmit,
1434) -> Option<(Symbol, Span)> {
1435 let Attribute::Parsed(AttributeKind::CrateName { name, name_span, .. }) =
1436 AttributeParser::parse_limited_sym_should_emit(
1437 sess,
1438 attrs,
1439 &[sym::crate_name],
1440 DUMMY_SP,
1441 None,
1442 emit_errors,
1443 )?
1444 else {
1445 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("crate_name is the only attr we could\'ve parsed here")));
};unreachable!("crate_name is the only attr we could've parsed here");
1446 };
1447
1448 Some((name, name_span))
1449}
1450
1451pub fn collect_crate_types(
1452 session: &Session,
1453 backend_crate_types: &[CrateType],
1454 codegen_backend_name: &'static str,
1455 attrs: &[ast::Attribute],
1456 crate_span: Span,
1457) -> Vec<CrateType> {
1458 if session.opts.test {
1461 if !session.target.executables {
1462 session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForTarget {
1463 crate_type: CrateType::Executable,
1464 target_triple: &session.opts.target_triple,
1465 });
1466 return Vec::new();
1467 }
1468 return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[CrateType::Executable]))vec![CrateType::Executable];
1469 }
1470
1471 if session.opts.unstable_opts.build_sdylib_interface {
1473 return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[CrateType::Rlib]))vec![CrateType::Rlib];
1474 }
1475
1476 #[allow(rustc::bad_opt_access)]
1481 let mut base = session.opts.crate_types.clone();
1482 if base.is_empty() {
1483 if let Some(Attribute::Parsed(AttributeKind::CrateType(crate_type))) =
1484 AttributeParser::parse_limited_sym_should_emit(
1485 session,
1486 attrs,
1487 &[sym::crate_type],
1488 crate_span,
1489 None,
1490 ShouldEmit::EarlyFatal { also_emit_lints: false },
1491 )
1492 {
1493 base.extend(crate_type);
1494 }
1495
1496 if base.is_empty() {
1497 base.push(default_output_for_target(session));
1498 } else {
1499 base.sort();
1500 base.dedup();
1501 }
1502 }
1503
1504 if session.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
Offload::Device(_) => true,
_ => false,
}matches!(o, Offload::Device(_))) {
1507 for crate_type in &mut base {
1508 if *crate_type == CrateType::Executable {
1509 *crate_type = CrateType::Cdylib;
1510 }
1511 }
1512 }
1513
1514 base.retain(|crate_type| {
1515 if invalid_output_for_target(session, *crate_type) {
1516 session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForTarget {
1517 crate_type: *crate_type,
1518 target_triple: &session.opts.target_triple,
1519 });
1520 false
1521 } else if !backend_crate_types.contains(crate_type) {
1522 session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForCodegenBackend {
1523 crate_type: *crate_type,
1524 codegen_backend: codegen_backend_name,
1525 });
1526 false
1527 } else {
1528 true
1529 }
1530 });
1531
1532 base
1533}
1534
1535fn default_output_for_target(sess: &Session) -> CrateType {
1545 if !sess.target.executables { CrateType::StaticLib } else { CrateType::Executable }
1546}