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_parsing::{AttributeParser, ShouldEmit};
10use rustc_codegen_ssa::traits::CodegenBackend;
11use rustc_codegen_ssa::{CodegenResults, CrateInfo};
12use rustc_data_structures::jobserver::Proxy;
13use rustc_data_structures::steal::Steal;
14use rustc_data_structures::sync::{AppendOnlyIndexVec, FreezeLock, WorkerLocal};
15use rustc_data_structures::{parallel, thousands};
16use rustc_errors::timings::TimingSection;
17use rustc_expand::base::{ExtCtxt, LintStoreExpand};
18use rustc_feature::Features;
19use rustc_fs_util::try_canonicalize;
20use rustc_hir::attrs::AttributeKind;
21use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap};
22use rustc_hir::definitions::Definitions;
23use rustc_hir::limit::Limit;
24use rustc_incremental::setup_dep_graph;
25use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore, unerased_lint_store};
26use rustc_metadata::EncodedMetadata;
27use rustc_metadata::creader::CStore;
28use rustc_middle::arena::Arena;
29use rustc_middle::dep_graph::DepsType;
30use rustc_middle::ty::{self, CurrentGcx, GlobalCtxt, RegisteredTools, TyCtxt};
31use rustc_middle::util::Providers;
32use rustc_parse::lexer::StripTokens;
33use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
34use rustc_passes::{abi_test, input_stats, layout_test};
35use rustc_resolve::{Resolver, ResolverOutputs};
36use rustc_session::Session;
37use rustc_session::config::{CrateType, Input, OutFileName, OutputFilenames, OutputType};
38use rustc_session::cstore::Untracked;
39use rustc_session::output::{collect_crate_types, filename_for_input};
40use rustc_session::parse::feature_err;
41use rustc_session::search_paths::PathKind;
42use rustc_span::{
43 DUMMY_SP, ErrorGuaranteed, ExpnKind, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, sym,
44};
45use rustc_trait_selection::{solve, traits};
46use tracing::{info, instrument};
47
48use crate::interface::Compiler;
49use crate::{errors, limits, proc_macro_decls, util};
50
51pub fn parse<'a>(sess: &'a Session) -> ast::Crate {
52 let mut krate = sess
53 .time("parse_crate", || {
54 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
55 Input::File(file) => new_parser_from_file(
56 &sess.psess,
57 file,
58 StripTokens::ShebangAndFrontmatter,
59 None,
60 ),
61 Input::Str { input, name } => new_parser_from_source_str(
62 &sess.psess,
63 name.clone(),
64 input.clone(),
65 StripTokens::ShebangAndFrontmatter,
66 ),
67 });
68 parser.parse_crate_mod()
69 })
70 .unwrap_or_else(|parse_error| {
71 let guar: ErrorGuaranteed = parse_error.emit();
72 guar.raise_fatal();
73 });
74
75 rustc_builtin_macros::cmdline_attrs::inject(
76 &mut krate,
77 &sess.psess,
78 &sess.opts.unstable_opts.crate_attr,
79 );
80
81 krate
82}
83
84fn pre_expansion_lint<'a>(
85 sess: &Session,
86 features: &Features,
87 lint_store: &LintStore,
88 registered_tools: &RegisteredTools,
89 check_node: impl EarlyCheckNode<'a>,
90 node_name: Symbol,
91) {
92 sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
93 || {
94 rustc_lint::check_ast_node(
95 sess,
96 None,
97 features,
98 true,
99 lint_store,
100 registered_tools,
101 None,
102 rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
103 check_node,
104 );
105 },
106 );
107}
108
109struct LintStoreExpandImpl<'a>(&'a LintStore);
111
112impl LintStoreExpand for LintStoreExpandImpl<'_> {
113 fn pre_expansion_lint(
114 &self,
115 sess: &Session,
116 features: &Features,
117 registered_tools: &RegisteredTools,
118 node_id: ast::NodeId,
119 attrs: &[ast::Attribute],
120 items: &[Box<ast::Item>],
121 name: Symbol,
122 ) {
123 pre_expansion_lint(sess, features, self.0, registered_tools, (node_id, attrs, items), name);
124 }
125}
126
127#[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("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(131u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
::tracing_core::field::FieldSet::new(&["pre_configured_attrs"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pre_configured_attrs)
as &dyn 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(tcx.sess);
let crate_name = tcx.crate_name(LOCAL_CRATE);
let lint_check_node = (&krate, pre_configured_attrs);
pre_expansion_lint(sess, features, lint_store,
tcx.registered_tools(()), lint_check_node, 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)
});
util::check_attr_crate_type(sess, pre_configured_attrs,
resolver.lint_buffer());
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::All).map(|p|
p.dir.clone()));
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 =
get_recursion_limit(pre_configured_attrs, sess);
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 Vec<BufferedEarlyLint>|
{ buffered_lints.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::panic("internal error: entered unreachable code");
}
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())
});
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(errors::MixedBinCrate);
}
if is_proc_macro_crate {
sess.dcx().emit_err(errors::MixedProcMacroCrate);
}
}
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.panic_strategy().unwinds() {
sess.dcx().emit_warn(errors::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_incompatible_target_modifiers(tcx,
&krate);
CStore::from_tcx(tcx).report_incompatible_async_drop_feature(tcx,
&krate);
krate
}
}
}#[instrument(level = "trace", skip(krate, resolver))]
132fn configure_and_expand(
133 mut krate: ast::Crate,
134 pre_configured_attrs: &[ast::Attribute],
135 resolver: &mut Resolver<'_, '_>,
136) -> ast::Crate {
137 let tcx = resolver.tcx();
138 let sess = tcx.sess;
139 let features = tcx.features();
140 let lint_store = unerased_lint_store(tcx.sess);
141 let crate_name = tcx.crate_name(LOCAL_CRATE);
142 let lint_check_node = (&krate, pre_configured_attrs);
143 pre_expansion_lint(
144 sess,
145 features,
146 lint_store,
147 tcx.registered_tools(()),
148 lint_check_node,
149 crate_name,
150 );
151 rustc_builtin_macros::register_builtin_macros(resolver);
152
153 let num_standard_library_imports = sess.time("crate_injection", || {
154 rustc_builtin_macros::standard_library_imports::inject(
155 &mut krate,
156 pre_configured_attrs,
157 resolver,
158 sess,
159 features,
160 )
161 });
162
163 util::check_attr_crate_type(sess, pre_configured_attrs, resolver.lint_buffer());
164
165 krate = sess.time("macro_expand_crate", || {
167 let mut old_path = OsString::new();
181 if cfg!(windows) {
182 old_path = env::var_os("PATH").unwrap_or(old_path);
183 let mut new_path = Vec::from_iter(
184 sess.host_filesearch().search_paths(PathKind::All).map(|p| p.dir.clone()),
185 );
186 for path in env::split_paths(&old_path) {
187 if !new_path.contains(&path) {
188 new_path.push(path);
189 }
190 }
191 unsafe {
192 env::set_var(
193 "PATH",
194 env::join_paths(
195 new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
196 )
197 .unwrap(),
198 );
199 }
200 }
201
202 let recursion_limit = get_recursion_limit(pre_configured_attrs, sess);
204 let cfg = rustc_expand::expand::ExpansionConfig {
205 crate_name,
206 features,
207 recursion_limit,
208 trace_mac: sess.opts.unstable_opts.trace_macros,
209 should_test: sess.is_test_crate(),
210 span_debug: sess.opts.unstable_opts.span_debug,
211 proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
212 };
213
214 let lint_store = LintStoreExpandImpl(lint_store);
215 let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
216 ecx.num_standard_library_imports = num_standard_library_imports;
217 let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
219
220 if ecx.nb_macro_errors > 0 {
221 sess.dcx().abort_if_errors();
222 }
223
224 sess.psess.buffered_lints.with_lock(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
227 buffered_lints.append(&mut ecx.buffered_early_lint);
228 });
229
230 sess.time("check_unused_macros", || {
231 ecx.check_unused_macros();
232 });
233
234 if ecx.reduced_recursion_limit.is_some() {
237 sess.dcx().abort_if_errors();
238 unreachable!();
239 }
240
241 if cfg!(windows) {
242 unsafe {
243 env::set_var("PATH", &old_path);
244 }
245 }
246
247 if ecx.sess.opts.unstable_opts.macro_stats {
248 print_macro_stats(&ecx);
249 }
250
251 krate
252 });
253
254 sess.time("maybe_building_test_harness", || {
255 rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
256 });
257
258 let has_proc_macro_decls = sess.time("AST_validation", || {
259 rustc_ast_passes::ast_validation::check_crate(
260 sess,
261 features,
262 &krate,
263 tcx.is_sdylib_interface_build(),
264 resolver.lint_buffer(),
265 )
266 });
267
268 let crate_types = tcx.crate_types();
269 let is_executable_crate = crate_types.contains(&CrateType::Executable);
270 let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
271
272 if crate_types.len() > 1 {
273 if is_executable_crate {
274 sess.dcx().emit_err(errors::MixedBinCrate);
275 }
276 if is_proc_macro_crate {
277 sess.dcx().emit_err(errors::MixedProcMacroCrate);
278 }
279 }
280 if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() {
281 feature_err(sess, sym::export_stable, DUMMY_SP, "`sdylib` crate type is unstable").emit();
282 }
283
284 if is_proc_macro_crate && !sess.panic_strategy().unwinds() {
285 sess.dcx().emit_warn(errors::ProcMacroCratePanicAbort);
286 }
287
288 sess.time("maybe_create_a_macro_crate", || {
289 let is_test_crate = sess.is_test_crate();
290 rustc_builtin_macros::proc_macro_harness::inject(
291 &mut krate,
292 sess,
293 features,
294 resolver,
295 is_proc_macro_crate,
296 has_proc_macro_decls,
297 is_test_crate,
298 sess.dcx(),
299 )
300 });
301
302 resolver.resolve_crate(&krate);
305
306 CStore::from_tcx(tcx).report_incompatible_target_modifiers(tcx, &krate);
307 CStore::from_tcx(tcx).report_incompatible_async_drop_feature(tcx, &krate);
308 krate
309}
310
311fn print_macro_stats(ecx: &ExtCtxt<'_>) {
312 use std::fmt::Write;
313
314 let crate_name = ecx.ecfg.crate_name.as_str();
315 let crate_name = if crate_name == "build_script_build" {
316 let pkg_name =
318 std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "<unknown crate>".to_string());
319 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} build script", pkg_name))
})format!("{pkg_name} build script")
320 } else {
321 crate_name.to_string()
322 };
323
324 #[allow(rustc::potential_query_instability)]
326 let mut macro_stats: Vec<_> = ecx
327 .macro_stats
328 .iter()
329 .map(|((name, kind), stat)| {
330 (stat.bytes, stat.lines, stat.uses, name, *kind)
332 })
333 .collect();
334 macro_stats.sort_unstable();
335 macro_stats.reverse(); let prefix = "macro-stats";
338 let name_w = 32;
339 let uses_w = 7;
340 let lines_w = 11;
341 let avg_lines_w = 11;
342 let bytes_w = 11;
343 let avg_bytes_w = 11;
344 let banner_w = name_w + uses_w + lines_w + avg_lines_w + bytes_w + avg_bytes_w;
345
346 let mut s = String::new();
352 _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
353 _ = s.write_fmt(format_args!("{1} MACRO EXPANSION STATS: {0}\n", crate_name,
prefix))writeln!(s, "{prefix} MACRO EXPANSION STATS: {}", crate_name);
354 _ = 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!(
355 s,
356 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
357 "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
358 );
359 _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
360 if macro_stats.is_empty() {
363 _ = s.write_fmt(format_args!("{0} (none)\n", prefix))writeln!(s, "{prefix} (none)");
364 }
365 for (bytes, lines, uses, name, kind) in macro_stats {
366 let mut name = ExpnKind::Macro(kind, *name).descr();
367 let uses_with_underscores = thousands::usize_with_underscores(uses);
368 let avg_lines = lines as f64 / uses as f64;
369 let avg_bytes = bytes as f64 / uses as f64;
370
371 let mut uses_w = uses_w;
373 if name.len() + uses_with_underscores.len() >= name_w + uses_w {
374 _ = s.write_fmt(format_args!("{1} {0:<2$}\n", name, prefix, name_w))writeln!(s, "{prefix} {:<name_w$}", name);
378 name = String::new();
379 } else if name.len() >= name_w {
380 uses_w -= name.len() - name_w;
384 };
385
386 _ = 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!(
387 s,
388 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
389 name,
390 uses_with_underscores,
391 thousands::usize_with_underscores(lines),
392 thousands::f64p1_with_underscores(avg_lines),
393 thousands::usize_with_underscores(bytes),
394 thousands::f64p1_with_underscores(avg_bytes),
395 );
396 }
397 _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
398 { ::std::io::_eprint(format_args!("{0}", s)); };eprint!("{s}");
399}
400
401fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
402 let sess = tcx.sess;
403 let (resolver, krate) = &*tcx.resolver_for_lowering().borrow();
404 let mut lint_buffer = resolver.lint_buffer.steal();
405
406 if sess.opts.unstable_opts.input_stats {
407 input_stats::print_ast_stats(tcx, krate);
408 }
409
410 sess.time("complete_gated_feature_checking", || {
412 rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
413 });
414
415 sess.psess.buffered_lints.with_lock(|buffered_lints| {
417 {
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/passes.rs:417",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(417u32),
::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};
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!("{0} parse sess buffered_lints",
buffered_lints.len()) as &dyn Value))])
});
} else { ; }
};info!("{} parse sess buffered_lints", buffered_lints.len());
418 for early_lint in buffered_lints.drain(..) {
419 lint_buffer.add_early_lint(early_lint);
420 }
421 });
422
423 sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
425 for (ident, mut spans) in identifiers.drain(..) {
426 spans.sort();
427 if ident == sym::ferris {
428 enum FerrisFix {
429 SnakeCase,
430 ScreamingSnakeCase,
431 PascalCase,
432 }
433
434 impl FerrisFix {
435 const fn as_str(self) -> &'static str {
436 match self {
437 FerrisFix::SnakeCase => "ferris",
438 FerrisFix::ScreamingSnakeCase => "FERRIS",
439 FerrisFix::PascalCase => "Ferris",
440 }
441 }
442 }
443
444 let first_span = spans[0];
445 let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
446 let ferris_fix = prev_source
447 .map_or(FerrisFix::SnakeCase, |source| {
448 let mut source_before_ferris = source.split_whitespace().rev();
449 match source_before_ferris.next() {
450 Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
451 FerrisFix::PascalCase
452 }
453 Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
454 Some("mut") if source_before_ferris.next() == Some("static") => {
455 FerrisFix::ScreamingSnakeCase
456 }
457 _ => FerrisFix::SnakeCase,
458 }
459 })
460 .as_str();
461
462 sess.dcx().emit_err(errors::FerrisIdentifier { spans, first_span, ferris_fix });
463 } else {
464 sess.dcx().emit_err(errors::EmojiIdentifier { spans, ident });
465 }
466 }
467 });
468
469 let lint_store = unerased_lint_store(tcx.sess);
470 rustc_lint::check_ast_node(
471 sess,
472 Some(tcx),
473 tcx.features(),
474 false,
475 lint_store,
476 tcx.registered_tools(()),
477 Some(lint_buffer),
478 rustc_lint::BuiltinCombinedEarlyLintPass::new(),
479 (&**krate, &*krate.attrs),
480 )
481}
482
483fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
484 let value = env::var_os(key);
485
486 let value_tcx = value.as_ref().map(|value| {
487 let encoded_bytes = tcx.arena.alloc_slice(value.as_encoded_bytes());
488 if true {
match (&value.as_encoded_bytes(), &encoded_bytes) {
(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);
}
}
};
};debug_assert_eq!(value.as_encoded_bytes(), encoded_bytes);
489 unsafe { OsStr::from_encoded_bytes_unchecked(encoded_bytes) }
493 });
494
495 tcx.sess.psess.env_depinfo.borrow_mut().insert((
501 Symbol::intern(&key.to_string_lossy()),
502 value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(value)),
503 ));
504
505 value_tcx
506}
507
508fn generated_output_paths(
510 tcx: TyCtxt<'_>,
511 outputs: &OutputFilenames,
512 exact_name: bool,
513 crate_name: Symbol,
514) -> Vec<PathBuf> {
515 let sess = tcx.sess;
516 let mut out_filenames = Vec::new();
517 for output_type in sess.opts.output_types.keys() {
518 let out_filename = outputs.path(*output_type);
519 let file = out_filename.as_path().to_path_buf();
520 match *output_type {
521 OutputType::Exe if !exact_name => {
524 for crate_type in tcx.crate_types().iter() {
525 let p = filename_for_input(sess, *crate_type, crate_name, outputs);
526 out_filenames.push(p.as_path().to_path_buf());
527 }
528 }
529 OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
530 }
532 OutputType::DepInfo if out_filename.is_stdout() => {
533 }
535 _ => {
536 out_filenames.push(file);
537 }
538 }
539 }
540 out_filenames
541}
542
543fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
544 let input_path = try_canonicalize(input_path).ok();
545 if input_path.is_none() {
546 return false;
547 }
548 output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
549}
550
551fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
552 output_paths.iter().find(|output_path| output_path.is_dir())
553}
554
555fn escape_dep_filename(filename: &str) -> String {
556 filename.replace(' ', "\\ ")
559}
560
561fn escape_dep_env(symbol: Symbol) -> String {
564 let s = symbol.as_str();
565 let mut escaped = String::with_capacity(s.len());
566 for c in s.chars() {
567 match c {
568 '\n' => escaped.push_str(r"\n"),
569 '\r' => escaped.push_str(r"\r"),
570 '\\' => escaped.push_str(r"\\"),
571 _ => escaped.push(c),
572 }
573 }
574 escaped
575}
576
577fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
578 let sess = tcx.sess;
580 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
581 return;
582 }
583 let deps_output = outputs.path(OutputType::DepInfo);
584 let deps_filename = deps_output.as_path();
585
586 let result: io::Result<()> = try {
587 let mut files: Vec<(String, u64, Option<SourceFileHash>)> = sess
590 .source_map()
591 .files()
592 .iter()
593 .filter(|fmap| fmap.is_real_file())
594 .filter(|fmap| !fmap.is_imported())
595 .map(|fmap| {
596 (
597 escape_dep_filename(&fmap.name.prefer_local_unconditionally().to_string()),
598 fmap.unnormalized_source_len as u64,
601 fmap.checksum_hash,
602 )
603 })
604 .collect();
605
606 let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
607
608 let file_depinfo = sess.psess.file_depinfo.borrow();
611
612 let normalize_path = |path: PathBuf| escape_dep_filename(&path.to_string_lossy());
613
614 fn hash_iter_files<P: AsRef<Path>>(
617 it: impl Iterator<Item = P>,
618 checksum_hash_algo: Option<SourceFileHashAlgorithm>,
619 ) -> impl Iterator<Item = (P, u64, Option<SourceFileHash>)> {
620 it.map(move |path| {
621 match checksum_hash_algo.and_then(|algo| {
622 fs::File::open(path.as_ref())
623 .and_then(|mut file| {
624 SourceFileHash::new(algo, &mut file).map(|h| (file, h))
625 })
626 .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
627 .map_err(|e| {
628 {
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/passes.rs:628",
"rustc_interface::passes", ::tracing::Level::ERROR,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(628u32),
::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};
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!("failed to compute checksum, omitting it from dep-info {0} {1}",
path.as_ref().display(), e) as &dyn Value))])
});
} else { ; }
}tracing::error!(
629 "failed to compute checksum, omitting it from dep-info {} {e}",
630 path.as_ref().display()
631 )
632 })
633 .ok()
634 }) {
635 Some((file_len, checksum)) => (path, file_len, Some(checksum)),
636 None => (path, 0, None),
637 }
638 })
639 }
640
641 let extra_tracked_files = hash_iter_files(
642 file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
643 checksum_hash_algo,
644 );
645 files.extend(extra_tracked_files);
646
647 if let Some(ref profile_instr) = sess.opts.cg.profile_use {
649 files.extend(hash_iter_files(
650 iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
651 checksum_hash_algo,
652 ));
653 }
654 if let Some(ref profile_sample) = sess.opts.unstable_opts.profile_sample_use {
655 files.extend(hash_iter_files(
656 iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
657 checksum_hash_algo,
658 ));
659 }
660
661 for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
663 files.extend(hash_iter_files(
664 iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
665 checksum_hash_algo,
666 ));
667 }
668
669 if sess.binary_dep_depinfo() {
670 if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
671 if backend.contains('.') {
672 files.extend(hash_iter_files(
675 iter::once(backend.to_string()),
676 checksum_hash_algo,
677 ));
678 }
679 }
680
681 for &cnum in tcx.crates(()) {
682 let source = tcx.used_crate_source(cnum);
683 if let Some(path) = &source.dylib {
684 files.extend(hash_iter_files(
685 iter::once(escape_dep_filename(&path.display().to_string())),
686 checksum_hash_algo,
687 ));
688 }
689 if let Some(path) = &source.rlib {
690 files.extend(hash_iter_files(
691 iter::once(escape_dep_filename(&path.display().to_string())),
692 checksum_hash_algo,
693 ));
694 }
695 if let Some(path) = &source.rmeta {
696 files.extend(hash_iter_files(
697 iter::once(escape_dep_filename(&path.display().to_string())),
698 checksum_hash_algo,
699 ));
700 }
701 }
702 }
703
704 let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
705 for path in out_filenames {
706 file.write_fmt(format_args!("{0}: {1}\n\n", path.display(),
files.iter().map(|(path, _file_len, _checksum_hash_algo)|
path.as_str()).intersperse(" ").collect::<String>()))writeln!(
707 file,
708 "{}: {}\n",
709 path.display(),
710 files
711 .iter()
712 .map(|(path, _file_len, _checksum_hash_algo)| path.as_str())
713 .intersperse(" ")
714 .collect::<String>()
715 )?;
716 }
717
718 for (path, _file_len, _checksum_hash_algo) in &files {
722 file.write_fmt(format_args!("{0}:\n", path))writeln!(file, "{path}:")?;
723 }
724
725 let env_depinfo = sess.psess.env_depinfo.borrow();
727 if !env_depinfo.is_empty() {
728 #[allow(rustc::potential_query_instability)]
730 let mut envs: Vec<_> = env_depinfo
731 .iter()
732 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
733 .collect();
734 envs.sort_unstable();
735 file.write_fmt(format_args!("\n"))writeln!(file)?;
736 for (k, v) in envs {
737 file.write_fmt(format_args!("# env-dep:{0}", k))write!(file, "# env-dep:{k}")?;
738 if let Some(v) = v {
739 file.write_fmt(format_args!("={0}", v))write!(file, "={v}")?;
740 }
741 file.write_fmt(format_args!("\n"))writeln!(file)?;
742 }
743 }
744
745 if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
748 files
749 .iter()
750 .filter_map(|(path, file_len, hash_algo)| {
751 hash_algo.map(|hash_algo| (path, file_len, hash_algo))
752 })
753 .try_for_each(|(path, file_len, checksum_hash)| {
754 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}")
755 })?;
756 }
757
758 Ok(())
759 };
760
761 match deps_output {
762 OutFileName::Stdout => {
763 let mut file = BufWriter::new(io::stdout());
764 write_deps_to_file(&mut file)?;
765 }
766 OutFileName::Real(ref path) => {
767 let mut file = fs::File::create_buffered(path)?;
768 write_deps_to_file(&mut file)?;
769 }
770 }
771 };
772
773 match result {
774 Ok(_) => {
775 if sess.opts.json_artifact_notifications {
776 sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
777 }
778 }
779 Err(error) => {
780 sess.dcx().emit_fatal(errors::ErrorWritingDependencies { path: deps_filename, error });
781 }
782 }
783}
784
785fn resolver_for_lowering_raw<'tcx>(
786 tcx: TyCtxt<'tcx>,
787 (): (),
788) -> (&'tcx Steal<(ty::ResolverAstLowering, Arc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
789 let arenas = Resolver::arenas();
790 let _ = tcx.registered_tools(()); let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
792 let mut resolver = Resolver::new(
793 tcx,
794 &pre_configured_attrs,
795 krate.spans.inner_span,
796 krate.spans.inject_use_span,
797 &arenas,
798 );
799 let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
800
801 tcx.untracked().cstore.freeze();
803
804 let ResolverOutputs {
805 global_ctxt: untracked_resolutions,
806 ast_lowering: untracked_resolver_for_lowering,
807 } = resolver.into_outputs();
808
809 let resolutions = tcx.arena.alloc(untracked_resolutions);
810 (tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Arc::new(krate)))), resolutions)
811}
812
813pub fn write_dep_info(tcx: TyCtxt<'_>) {
814 let _ = tcx.resolver_for_lowering();
818
819 let sess = tcx.sess;
820 let _timer = sess.timer("write_dep_info");
821 let crate_name = tcx.crate_name(LOCAL_CRATE);
822
823 let outputs = tcx.output_filenames(());
824 let output_paths =
825 generated_output_paths(tcx, outputs, sess.io.output_file.is_some(), crate_name);
826
827 if let Some(input_path) = sess.io.input.opt_path() {
829 if sess.opts.will_create_output_file() {
830 if output_contains_path(&output_paths, input_path) {
831 sess.dcx().emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path });
832 }
833 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
834 sess.dcx().emit_fatal(errors::GeneratedFileConflictsWithDirectory {
835 input_path,
836 dir_path,
837 });
838 }
839 }
840 }
841
842 if let Some(ref dir) = sess.io.temps_dir {
843 if fs::create_dir_all(dir).is_err() {
844 sess.dcx().emit_fatal(errors::TempsDirError);
845 }
846 }
847
848 write_out_deps(tcx, outputs, &output_paths);
849
850 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
851 && sess.opts.output_types.len() == 1;
852
853 if !only_dep_info {
854 if let Some(ref dir) = sess.io.output_dir {
855 if fs::create_dir_all(dir).is_err() {
856 sess.dcx().emit_fatal(errors::OutDirError);
857 }
858 }
859 }
860}
861
862pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
863 if !tcx.crate_types().contains(&rustc_session::config::CrateType::Sdylib) {
864 return;
865 }
866 let _timer = tcx.sess.timer("write_interface");
867 let (_, krate) = &*tcx.resolver_for_lowering().borrow();
868
869 let krate = rustc_ast_pretty::pprust::print_crate_as_interface(
870 krate,
871 tcx.sess.psess.edition,
872 &tcx.sess.psess.attr_id_generator,
873 );
874 let export_output = tcx.output_filenames(()).interface_path();
875 let mut file = fs::File::create_buffered(export_output).unwrap();
876 if let Err(err) = file.write_fmt(format_args!("{0}", krate))write!(file, "{}", krate) {
877 tcx.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("error writing interface file: {0}",
err))
})format!("error writing interface file: {}", err));
878 }
879}
880
881pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
882 let providers = &mut Providers::default();
883 providers.queries.analysis = analysis;
884 providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
885 providers.queries.resolver_for_lowering_raw = resolver_for_lowering_raw;
886 providers.queries.stripped_cfg_items = |tcx, _| &tcx.resolutions(()).stripped_cfg_items[..];
887 providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
888 providers.queries.early_lint_checks = early_lint_checks;
889 providers.queries.env_var_os = env_var_os;
890 limits::provide(&mut providers.queries);
891 proc_macro_decls::provide(&mut providers.queries);
892 rustc_expand::provide(&mut providers.queries);
893 rustc_const_eval::provide(providers);
894 rustc_middle::hir::provide(&mut providers.queries);
895 rustc_borrowck::provide(&mut providers.queries);
896 rustc_incremental::provide(providers);
897 rustc_mir_build::provide(providers);
898 rustc_mir_transform::provide(providers);
899 rustc_monomorphize::provide(providers);
900 rustc_privacy::provide(&mut providers.queries);
901 rustc_query_impl::provide(providers);
902 rustc_resolve::provide(&mut providers.queries);
903 rustc_hir_analysis::provide(&mut providers.queries);
904 rustc_hir_typeck::provide(&mut providers.queries);
905 ty::provide(&mut providers.queries);
906 traits::provide(&mut providers.queries);
907 solve::provide(&mut providers.queries);
908 rustc_passes::provide(&mut providers.queries);
909 rustc_traits::provide(&mut providers.queries);
910 rustc_ty_utils::provide(&mut providers.queries);
911 rustc_metadata::provide(providers);
912 rustc_lint::provide(&mut providers.queries);
913 rustc_symbol_mangling::provide(&mut providers.queries);
914 rustc_codegen_ssa::provide(providers);
915 *providers
916});
917
918pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
919 compiler: &Compiler,
920 krate: rustc_ast::Crate,
921 f: F,
922) -> T {
923 let sess = &compiler.sess;
924
925 let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
926
927 let crate_name = get_crate_name(sess, &pre_configured_attrs);
928 let crate_types = collect_crate_types(
929 sess,
930 &compiler.codegen_backend.supported_crate_types(sess),
931 compiler.codegen_backend.name(),
932 &pre_configured_attrs,
933 );
934 let stable_crate_id = StableCrateId::new(
935 crate_name,
936 crate_types.contains(&CrateType::Executable),
937 sess.opts.cg.metadata.clone(),
938 sess.cfg_version,
939 );
940
941 let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
942
943 let dep_type = DepsType { dep_names: rustc_query_impl::dep_kind_names() };
944 let dep_graph = setup_dep_graph(sess, crate_name, stable_crate_id, &dep_type);
945
946 let cstore =
947 FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
948 let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
949
950 let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
951 let untracked =
952 Untracked { cstore, source_span: AppendOnlyIndexVec::new(), definitions, stable_crate_ids };
953
954 dep_graph.assert_ignored();
958
959 let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess);
960
961 let codegen_backend = &compiler.codegen_backend;
962 let mut providers = *DEFAULT_QUERY_PROVIDERS;
963 codegen_backend.provide(&mut providers);
964
965 if let Some(callback) = compiler.override_queries {
966 callback(sess, &mut providers);
967 }
968
969 let incremental = dep_graph.is_fully_enabled();
970
971 let gcx_cell = OnceLock::new();
972 let arena = WorkerLocal::new(|_| Arena::default());
973 let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
974
975 let inner: Box<
978 dyn for<'tcx> FnOnce(
979 &'tcx Session,
980 CurrentGcx,
981 Arc<Proxy>,
982 &'tcx OnceLock<GlobalCtxt<'tcx>>,
983 &'tcx WorkerLocal<Arena<'tcx>>,
984 &'tcx WorkerLocal<rustc_hir::Arena<'tcx>>,
985 F,
986 ) -> T,
987 > = Box::new(move |sess, current_gcx, jobserver_proxy, gcx_cell, arena, hir_arena, f| {
988 TyCtxt::create_global_ctxt(
989 gcx_cell,
990 sess,
991 crate_types,
992 stable_crate_id,
993 arena,
994 hir_arena,
995 untracked,
996 dep_graph,
997 rustc_query_impl::query_callbacks(arena),
998 rustc_query_impl::query_system(
999 providers.queries,
1000 providers.extern_queries,
1001 query_result_on_disk_cache,
1002 incremental,
1003 ),
1004 providers.hooks,
1005 current_gcx,
1006 jobserver_proxy,
1007 |tcx| {
1008 let feed = tcx.create_crate_num(stable_crate_id).unwrap();
1009 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);
1010 feed.crate_name(crate_name);
1011
1012 let feed = tcx.feed_unit_query();
1013 feed.features_query(tcx.arena.alloc(rustc_expand::config::features(
1014 tcx.sess,
1015 &pre_configured_attrs,
1016 crate_name,
1017 )));
1018 feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
1019 feed.output_filenames(Arc::new(outputs));
1020
1021 let res = f(tcx);
1022 tcx.finish();
1024 res
1025 },
1026 )
1027 });
1028
1029 inner(
1030 &compiler.sess,
1031 compiler.current_gcx.clone(),
1032 Arc::clone(&compiler.jobserver_proxy),
1033 &gcx_cell,
1034 &arena,
1035 &hir_arena,
1036 f,
1037 )
1038}
1039
1040fn run_required_analyses(tcx: TyCtxt<'_>) {
1043 if tcx.sess.opts.unstable_opts.input_stats {
1044 rustc_passes::input_stats::print_hir_stats(tcx);
1045 }
1046 #[cfg(all(not(doc), debug_assertions))]
1049 rustc_passes::hir_id_validator::check_crate(tcx);
1050
1051 tcx.ensure_done().hir_crate_items(());
1055
1056 let sess = tcx.sess;
1057 sess.time("misc_checking_1", || {
1058 if ::rustc_data_structures::sync::is_dyn_thread_safe() {
::rustc_data_structures::sync::parallel_guard(|guard|
{
::rustc_data_structures::sync::scope(|s|
{
let block =
::rustc_data_structures::sync::FromDyn::from(||
{ tcx.ensure_ok().limits(()); });
s.spawn(move |_|
{ guard.run(move || block.into_inner()()); });
let block =
::rustc_data_structures::sync::FromDyn::from(||
{
tcx.ensure_ok().exportable_items(LOCAL_CRATE);
tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
tcx.par_hir_for_each_module(|module|
{
tcx.ensure_ok().check_mod_attrs(module);
tcx.ensure_ok().check_mod_unstable_api_usage(module);
});
});
s.spawn(move |_|
{ guard.run(move || block.into_inner()()); });
guard.run(||
{
sess.time("looking_for_entry_point",
|| tcx.ensure_ok().entry_fn(()));
sess.time("check_externally_implementable_items",
||
{
tcx.ensure_ok().check_externally_implementable_items(())
});
sess.time("looking_for_derive_registrar",
|| { tcx.ensure_ok().proc_macro_decls_static(()) });
CStore::from_tcx(tcx).report_unused_deps(tcx);
});
});
});
;
} else {
::rustc_data_structures::sync::parallel_guard(|guard|
{
guard.run(||
{
sess.time("looking_for_entry_point",
|| tcx.ensure_ok().entry_fn(()));
sess.time("check_externally_implementable_items",
||
{
tcx.ensure_ok().check_externally_implementable_items(())
});
sess.time("looking_for_derive_registrar",
|| { tcx.ensure_ok().proc_macro_decls_static(()) });
CStore::from_tcx(tcx).report_unused_deps(tcx);
});
guard.run(||
{
tcx.ensure_ok().exportable_items(LOCAL_CRATE);
tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
tcx.par_hir_for_each_module(|module|
{
tcx.ensure_ok().check_mod_attrs(module);
tcx.ensure_ok().check_mod_unstable_api_usage(module);
});
});
guard.run(|| { tcx.ensure_ok().limits(()); });
});
};parallel!(
1059 {
1060 sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
1061 sess.time("check_externally_implementable_items", || {
1062 tcx.ensure_ok().check_externally_implementable_items(())
1063 });
1064
1065 sess.time("looking_for_derive_registrar", || {
1066 tcx.ensure_ok().proc_macro_decls_static(())
1067 });
1068
1069 CStore::from_tcx(tcx).report_unused_deps(tcx);
1070 },
1071 {
1072 tcx.ensure_ok().exportable_items(LOCAL_CRATE);
1073 tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
1074 tcx.par_hir_for_each_module(|module| {
1075 tcx.ensure_ok().check_mod_attrs(module);
1076 tcx.ensure_ok().check_mod_unstable_api_usage(module);
1077 });
1078 },
1079 {
1080 tcx.ensure_ok().limits(());
1085 }
1086 );
1087 });
1088
1089 rustc_hir_analysis::check_crate(tcx);
1090 tcx.untracked().definitions.freeze();
1096
1097 sess.time("MIR_borrow_checking", || {
1098 tcx.par_hir_body_owners(|def_id| {
1099 let not_typeck_child = !tcx.is_typeck_child(def_id.to_def_id());
1100 if not_typeck_child {
1101 tcx.ensure_ok().check_unsafety(def_id);
1103 }
1104 if tcx.is_trivial_const(def_id) {
1105 return;
1106 }
1107 if not_typeck_child {
1108 tcx.ensure_ok().mir_borrowck(def_id);
1109 tcx.ensure_ok().check_transmutes(def_id);
1110 }
1111 tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1112 tcx.ensure_ok().check_liveness(def_id);
1113
1114 if tcx.sess.opts.output_types.should_codegen()
1118 || tcx.hir_body_const_context(def_id).is_some()
1119 {
1120 tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1121 }
1122 if tcx.is_coroutine(def_id.to_def_id()) {
1123 tcx.ensure_ok().mir_coroutine_witnesses(def_id);
1124 let _ = tcx.ensure_ok().check_coroutine_obligations(
1125 tcx.typeck_root_def_id(def_id.to_def_id()).expect_local(),
1126 );
1127 if !tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()) {
1128 tcx.ensure_ok().layout_of(
1130 ty::TypingEnv::post_analysis(tcx, def_id.to_def_id())
1131 .as_query_input(tcx.type_of(def_id).instantiate_identity()),
1132 );
1133 }
1134 }
1135 });
1136 });
1137
1138 sess.time("layout_testing", || layout_test::test_layout(tcx));
1139 sess.time("abi_testing", || abi_test::test_abi(tcx));
1140}
1141
1142fn analysis(tcx: TyCtxt<'_>, (): ()) {
1145 run_required_analyses(tcx);
1146
1147 let sess = tcx.sess;
1148
1149 if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1158 guar.raise_fatal();
1159 }
1160
1161 sess.time("misc_checking_3", || {
1162 if ::rustc_data_structures::sync::is_dyn_thread_safe() {
::rustc_data_structures::sync::parallel_guard(|guard|
{
::rustc_data_structures::sync::scope(|s|
{
let block =
::rustc_data_structures::sync::FromDyn::from(||
{
sess.time("privacy_checking_modules",
||
{
tcx.par_hir_for_each_module(|module|
{ tcx.ensure_ok().check_mod_privacy(module); });
});
});
s.spawn(move |_|
{ guard.run(move || block.into_inner()()); });
guard.run(||
{
tcx.ensure_ok().effective_visibilities(());
if ::rustc_data_structures::sync::is_dyn_thread_safe() {
::rustc_data_structures::sync::parallel_guard(|guard|
{
::rustc_data_structures::sync::scope(|s|
{
let block =
::rustc_data_structures::sync::FromDyn::from(||
{ tcx.ensure_ok().clashing_extern_declarations(()); });
s.spawn(move |_|
{ guard.run(move || block.into_inner()()); });
let block =
::rustc_data_structures::sync::FromDyn::from(||
{
sess.time("lint_checking",
|| { rustc_lint::check_crate(tcx); });
});
s.spawn(move |_|
{ guard.run(move || block.into_inner()()); });
let block =
::rustc_data_structures::sync::FromDyn::from(||
{
tcx.par_hir_for_each_module(|module|
{ tcx.ensure_ok().check_mod_deathness(module) });
});
s.spawn(move |_|
{ guard.run(move || block.into_inner()()); });
guard.run(||
{
tcx.par_hir_for_each_module(|module|
{ tcx.ensure_ok().check_private_in_public(module) })
});
});
});
;
} else {
::rustc_data_structures::sync::parallel_guard(|guard|
{
guard.run(||
{
tcx.par_hir_for_each_module(|module|
{ tcx.ensure_ok().check_private_in_public(module) })
});
guard.run(||
{
tcx.par_hir_for_each_module(|module|
{ tcx.ensure_ok().check_mod_deathness(module) });
});
guard.run(||
{
sess.time("lint_checking",
|| { rustc_lint::check_crate(tcx); });
});
guard.run(||
{ tcx.ensure_ok().clashing_extern_declarations(()); });
});
};
});
});
});
;
} else {
::rustc_data_structures::sync::parallel_guard(|guard|
{
guard.run(||
{
tcx.ensure_ok().effective_visibilities(());
if ::rustc_data_structures::sync::is_dyn_thread_safe() {
::rustc_data_structures::sync::parallel_guard(|guard|
{
::rustc_data_structures::sync::scope(|s|
{
let block =
::rustc_data_structures::sync::FromDyn::from(||
{ tcx.ensure_ok().clashing_extern_declarations(()); });
s.spawn(move |_|
{ guard.run(move || block.into_inner()()); });
let block =
::rustc_data_structures::sync::FromDyn::from(||
{
sess.time("lint_checking",
|| { rustc_lint::check_crate(tcx); });
});
s.spawn(move |_|
{ guard.run(move || block.into_inner()()); });
let block =
::rustc_data_structures::sync::FromDyn::from(||
{
tcx.par_hir_for_each_module(|module|
{ tcx.ensure_ok().check_mod_deathness(module) });
});
s.spawn(move |_|
{ guard.run(move || block.into_inner()()); });
guard.run(||
{
tcx.par_hir_for_each_module(|module|
{ tcx.ensure_ok().check_private_in_public(module) })
});
});
});
;
} else {
::rustc_data_structures::sync::parallel_guard(|guard|
{
guard.run(||
{
tcx.par_hir_for_each_module(|module|
{ tcx.ensure_ok().check_private_in_public(module) })
});
guard.run(||
{
tcx.par_hir_for_each_module(|module|
{ tcx.ensure_ok().check_mod_deathness(module) });
});
guard.run(||
{
sess.time("lint_checking",
|| { rustc_lint::check_crate(tcx); });
});
guard.run(||
{ tcx.ensure_ok().clashing_extern_declarations(()); });
});
};
});
guard.run(||
{
sess.time("privacy_checking_modules",
||
{
tcx.par_hir_for_each_module(|module|
{ tcx.ensure_ok().check_mod_privacy(module); });
});
});
});
};parallel!(
1163 {
1164 tcx.ensure_ok().effective_visibilities(());
1165
1166 parallel!(
1167 {
1168 tcx.par_hir_for_each_module(|module| {
1169 tcx.ensure_ok().check_private_in_public(module)
1170 })
1171 },
1172 {
1173 tcx.par_hir_for_each_module(|module| {
1174 tcx.ensure_ok().check_mod_deathness(module)
1175 });
1176 },
1177 {
1178 sess.time("lint_checking", || {
1179 rustc_lint::check_crate(tcx);
1180 });
1181 },
1182 {
1183 tcx.ensure_ok().clashing_extern_declarations(());
1184 }
1185 );
1186 },
1187 {
1188 sess.time("privacy_checking_modules", || {
1189 tcx.par_hir_for_each_module(|module| {
1190 tcx.ensure_ok().check_mod_privacy(module);
1191 });
1192 });
1193 }
1194 );
1195
1196 sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1199
1200 let _ = tcx.all_diagnostic_items(());
1204 });
1205
1206 if tcx.sess.opts.unstable_opts.validate_mir {
1213 sess.time("ensuring_final_MIR_is_computable", || {
1214 tcx.par_hir_body_owners(|def_id| {
1215 if !tcx.is_trivial_const(def_id) {
1216 tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1217 }
1218 });
1219 });
1220 }
1221}
1222
1223pub(crate) fn start_codegen<'tcx>(
1226 codegen_backend: &dyn CodegenBackend,
1227 tcx: TyCtxt<'tcx>,
1228) -> (Box<dyn Any>, EncodedMetadata) {
1229 tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen);
1230
1231 if let Some((def_id, _)) = tcx.entry_fn(())
1233 && tcx.has_attr(def_id, sym::rustc_delayed_bug_from_inside_query)
1234 {
1235 tcx.ensure_ok().trigger_delayed_bug(def_id);
1236 }
1237
1238 if tcx.sess.opts.output_types.should_codegen() {
1241 rustc_symbol_mangling::test::report_symbol_names(tcx);
1242 }
1243
1244 if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
1248 guar.raise_fatal();
1249 }
1250
1251 {
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/passes.rs:1251",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(1251u32),
::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};
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!("Pre-codegen\n{0:?}",
tcx.debug_stats()) as &dyn Value))])
});
} else { ; }
};info!("Pre-codegen\n{:?}", tcx.debug_stats());
1252
1253 let metadata = rustc_metadata::fs::encode_and_write_metadata(tcx);
1254
1255 let codegen = tcx.sess.time("codegen_crate", move || {
1256 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1257 tcx.sess.dcx().abort_if_errors();
1259
1260 Box::new(CodegenResults {
1262 modules: ::alloc::vec::Vec::new()vec![],
1263 allocator_module: None,
1264 crate_info: CrateInfo::new(tcx, "<dummy cpu>".to_owned()),
1265 })
1266 } else {
1267 codegen_backend.codegen_crate(tcx)
1268 }
1269 });
1270
1271 {
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/passes.rs:1271",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(1271u32),
::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};
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!("Post-codegen\n{0:?}",
tcx.debug_stats()) as &dyn Value))])
});
} else { ; }
};info!("Post-codegen\n{:?}", tcx.debug_stats());
1272
1273 if tcx.sess.opts.unstable_opts.print_type_sizes {
1276 tcx.sess.code_stats.print_type_sizes();
1277 }
1278
1279 (codegen, metadata)
1280}
1281
1282pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1284 let attr_crate_name =
1292 parse_crate_name(sess, krate_attrs, ShouldEmit::EarlyFatal { also_emit_lints: true });
1293
1294 let validate = |name, span| {
1295 rustc_session::output::validate_crate_name(sess, name, span);
1296 name
1297 };
1298
1299 if let Some(crate_name) = &sess.opts.crate_name {
1300 let crate_name = Symbol::intern(crate_name);
1301 if let Some((attr_crate_name, span)) = attr_crate_name
1302 && attr_crate_name != crate_name
1303 {
1304 sess.dcx().emit_err(errors::CrateNameDoesNotMatch {
1305 span,
1306 crate_name,
1307 attr_crate_name,
1308 });
1309 }
1310 return validate(crate_name, None);
1311 }
1312
1313 if let Some((crate_name, span)) = attr_crate_name {
1314 return validate(crate_name, Some(span));
1315 }
1316
1317 if let Input::File(ref path) = sess.io.input
1318 && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1319 {
1320 if file_stem.starts_with('-') {
1321 sess.dcx().emit_err(errors::CrateNameInvalid { crate_name: file_stem });
1322 } else {
1323 return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1324 }
1325 }
1326
1327 sym::rust_out
1328}
1329
1330pub(crate) fn parse_crate_name(
1331 sess: &Session,
1332 attrs: &[ast::Attribute],
1333 emit_errors: ShouldEmit,
1334) -> Option<(Symbol, Span)> {
1335 let rustc_hir::Attribute::Parsed(AttributeKind::CrateName { name, name_span, .. }) =
1336 AttributeParser::parse_limited_should_emit(
1337 sess,
1338 attrs,
1339 sym::crate_name,
1340 DUMMY_SP,
1341 rustc_ast::node_id::CRATE_NODE_ID,
1342 None,
1343 emit_errors,
1344 )?
1345 else {
1346 {
::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");
1347 };
1348
1349 Some((name, name_span))
1350}
1351
1352fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1353 let attr = AttributeParser::parse_limited_should_emit(
1354 sess,
1355 &krate_attrs,
1356 sym::recursion_limit,
1357 DUMMY_SP,
1358 rustc_ast::node_id::CRATE_NODE_ID,
1359 None,
1360 ShouldEmit::EarlyFatal { also_emit_lints: false },
1365 );
1366 crate::limits::get_recursion_limit(attr.as_slice())
1367}