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::{self as ast, CRATE_NODE_ID};
9use rustc_attr_parsing::{AttributeParser, Early, ShouldEmit};
10use rustc_codegen_ssa::traits::CodegenBackend;
11use rustc_codegen_ssa::{CompiledModules, CrateInfo};
12use rustc_data_structures::indexmap::IndexMap;
13use rustc_data_structures::steal::Steal;
14use rustc_data_structures::sync::{AppendOnlyIndexVec, FreezeLock, WorkerLocal, par_fns};
15use rustc_data_structures::thousands;
16use rustc_errors::DiagCallback;
17use rustc_errors::timings::TimingSection;
18use rustc_expand::base::{ExtCtxt, LintStoreExpand};
19use rustc_feature::Features;
20use rustc_fs_util::try_canonicalize;
21use rustc_hir::attrs::AttributeKind;
22use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap};
23use rustc_hir::definitions::Definitions;
24use rustc_hir::limit::Limit;
25use rustc_hir::lints::DelayedLint;
26use rustc_hir::{Attribute, MaybeOwner, Target, find_attr};
27use rustc_incremental::setup_dep_graph;
28use rustc_lint::{
29 BufferedEarlyLint, DecorateAttrLint, EarlyCheckNode, LintStore, unerased_lint_store,
30};
31use rustc_metadata::EncodedMetadata;
32use rustc_metadata::creader::CStore;
33use rustc_middle::arena::Arena;
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::{CrateType, Input, OutFileName, OutputFilenames, OutputType};
42use rustc_session::cstore::Untracked;
43use rustc_session::output::{filename_for_input, invalid_output_for_target};
44use rustc_session::parse::feature_err;
45use rustc_session::search_paths::PathKind;
46use rustc_span::{
47 DUMMY_SP, ErrorGuaranteed, ExpnKind, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, sym,
48};
49use rustc_trait_selection::{solve, traits};
50use tracing::{info, instrument};
51
52use crate::interface::Compiler;
53use crate::{errors, limits, proc_macro_decls, 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 Input::Str { input, name } => new_parser_from_source_str(
66 &sess.psess,
67 name.clone(),
68 input.clone(),
69 StripTokens::ShebangAndFrontmatter,
70 ),
71 });
72 parser.parse_crate_mod()
73 })
74 .unwrap_or_else(|parse_error| {
75 let guar: ErrorGuaranteed = parse_error.emit();
76 guar.raise_fatal();
77 });
78
79 rustc_builtin_macros::cmdline_attrs::inject(
80 &mut krate,
81 &sess.psess,
82 &sess.opts.unstable_opts.crate_attr,
83 );
84
85 krate
86}
87
88fn pre_expansion_lint<'a>(
89 sess: &Session,
90 features: &Features,
91 lint_store: &LintStore,
92 registered_tools: &RegisteredTools,
93 check_node: impl EarlyCheckNode<'a>,
94 node_name: Symbol,
95) {
96 sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
97 || {
98 rustc_lint::check_ast_node(
99 sess,
100 None,
101 features,
102 true,
103 lint_store,
104 registered_tools,
105 None,
106 rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
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_tools: &RegisteredTools,
122 node_id: ast::NodeId,
123 attrs: &[ast::Attribute],
124 items: &[Box<ast::Item>],
125 name: Symbol,
126 ) {
127 pre_expansion_lint(sess, features, self.0, registered_tools, (node_id, attrs, items), name);
128 }
129}
130
131#[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(135u32),
::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)
});
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_session_incompatibilities(tcx,
&krate);
krate
}
}
}#[instrument(level = "trace", skip(krate, resolver))]
136fn configure_and_expand(
137 mut krate: ast::Crate,
138 pre_configured_attrs: &[ast::Attribute],
139 resolver: &mut Resolver<'_, '_>,
140) -> ast::Crate {
141 let tcx = resolver.tcx();
142 let sess = tcx.sess;
143 let features = tcx.features();
144 let lint_store = unerased_lint_store(tcx.sess);
145 let crate_name = tcx.crate_name(LOCAL_CRATE);
146 let lint_check_node = (&krate, pre_configured_attrs);
147 pre_expansion_lint(
148 sess,
149 features,
150 lint_store,
151 tcx.registered_tools(()),
152 lint_check_node,
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::All).map(|p| p.dir.clone()),
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 = get_recursion_limit(pre_configured_attrs, sess);
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(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
229 buffered_lints.append(&mut ecx.buffered_early_lint);
230 });
231
232 sess.time("check_unused_macros", || {
233 ecx.check_unused_macros();
234 });
235
236 if ecx.reduced_recursion_limit.is_some() {
239 sess.dcx().abort_if_errors();
240 unreachable!();
241 }
242
243 if cfg!(windows) {
244 unsafe {
245 env::set_var("PATH", &old_path);
246 }
247 }
248
249 if ecx.sess.opts.unstable_opts.macro_stats {
250 print_macro_stats(&ecx);
251 }
252
253 krate
254 });
255
256 sess.time("maybe_building_test_harness", || {
257 rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
258 });
259
260 let has_proc_macro_decls = sess.time("AST_validation", || {
261 rustc_ast_passes::ast_validation::check_crate(
262 sess,
263 features,
264 &krate,
265 tcx.is_sdylib_interface_build(),
266 resolver.lint_buffer(),
267 )
268 });
269
270 let crate_types = tcx.crate_types();
271 let is_executable_crate = crate_types.contains(&CrateType::Executable);
272 let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
273
274 if crate_types.len() > 1 {
275 if is_executable_crate {
276 sess.dcx().emit_err(errors::MixedBinCrate);
277 }
278 if is_proc_macro_crate {
279 sess.dcx().emit_err(errors::MixedProcMacroCrate);
280 }
281 }
282 if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() {
283 feature_err(sess, sym::export_stable, DUMMY_SP, "`sdylib` crate type is unstable").emit();
284 }
285
286 if is_proc_macro_crate && !sess.panic_strategy().unwinds() {
287 sess.dcx().emit_warn(errors::ProcMacroCratePanicAbort);
288 }
289
290 sess.time("maybe_create_a_macro_crate", || {
291 let is_test_crate = sess.is_test_crate();
292 rustc_builtin_macros::proc_macro_harness::inject(
293 &mut krate,
294 sess,
295 features,
296 resolver,
297 is_proc_macro_crate,
298 has_proc_macro_decls,
299 is_test_crate,
300 sess.dcx(),
301 )
302 });
303
304 resolver.resolve_crate(&krate);
307
308 CStore::from_tcx(tcx).report_session_incompatibilities(tcx, &krate);
309 krate
310}
311
312fn print_macro_stats(ecx: &ExtCtxt<'_>) {
313 use std::fmt::Write;
314
315 let crate_name = ecx.ecfg.crate_name.as_str();
316 let crate_name = if crate_name == "build_script_build" {
317 let pkg_name =
319 std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "<unknown crate>".to_string());
320 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} build script", pkg_name))
})format!("{pkg_name} build script")
321 } else {
322 crate_name.to_string()
323 };
324
325 #[allow(rustc::potential_query_instability)]
327 let mut macro_stats: Vec<_> = ecx
328 .macro_stats
329 .iter()
330 .map(|((name, kind), stat)| {
331 (stat.bytes, stat.lines, stat.uses, name, *kind)
333 })
334 .collect();
335 macro_stats.sort_unstable();
336 macro_stats.reverse(); let prefix = "macro-stats";
339 let name_w = 32;
340 let uses_w = 7;
341 let lines_w = 11;
342 let avg_lines_w = 11;
343 let bytes_w = 11;
344 let avg_bytes_w = 11;
345 let banner_w = name_w + uses_w + lines_w + avg_lines_w + bytes_w + avg_bytes_w;
346
347 let mut s = String::new();
353 _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
354 _ = s.write_fmt(format_args!("{1} MACRO EXPANSION STATS: {0}\n", crate_name,
prefix))writeln!(s, "{prefix} MACRO EXPANSION STATS: {}", crate_name);
355 _ = 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!(
356 s,
357 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
358 "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
359 );
360 _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
361 if macro_stats.is_empty() {
364 _ = s.write_fmt(format_args!("{0} (none)\n", prefix))writeln!(s, "{prefix} (none)");
365 }
366 for (bytes, lines, uses, name, kind) in macro_stats {
367 let mut name = ExpnKind::Macro(kind, *name).descr();
368 let uses_with_underscores = thousands::usize_with_underscores(uses);
369 let avg_lines = lines as f64 / uses as f64;
370 let avg_bytes = bytes as f64 / uses as f64;
371
372 let mut uses_w = uses_w;
374 if name.len() + uses_with_underscores.len() >= name_w + uses_w {
375 _ = s.write_fmt(format_args!("{1} {0:<2$}\n", name, prefix, name_w))writeln!(s, "{prefix} {:<name_w$}", name);
379 name = String::new();
380 } else if name.len() >= name_w {
381 uses_w -= name.len() - name_w;
385 };
386
387 _ = 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!(
388 s,
389 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
390 name,
391 uses_with_underscores,
392 thousands::usize_with_underscores(lines),
393 thousands::f64p1_with_underscores(avg_lines),
394 thousands::usize_with_underscores(bytes),
395 thousands::f64p1_with_underscores(avg_bytes),
396 );
397 }
398 _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
399 { ::std::io::_eprint(format_args!("{0}", s)); };eprint!("{s}");
400}
401
402fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
403 let sess = tcx.sess;
404 let (resolver, krate) = &*tcx.resolver_for_lowering().borrow();
405 let mut lint_buffer = resolver.lint_buffer.steal();
406
407 if sess.opts.unstable_opts.input_stats {
408 input_stats::print_ast_stats(tcx, krate);
409 }
410
411 sess.time("complete_gated_feature_checking", || {
413 rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
414 });
415
416 sess.psess.buffered_lints.with_lock(|buffered_lints| {
418 {
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:418",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(418u32),
::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());
419 for early_lint in buffered_lints.drain(..) {
420 lint_buffer.add_early_lint(early_lint);
421 }
422 });
423
424 sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
426 for (ident, mut spans) in identifiers.drain(..) {
427 spans.sort();
428 if ident == sym::ferris {
429 enum FerrisFix {
430 SnakeCase,
431 ScreamingSnakeCase,
432 PascalCase,
433 }
434
435 impl FerrisFix {
436 const fn as_str(self) -> &'static str {
437 match self {
438 FerrisFix::SnakeCase => "ferris",
439 FerrisFix::ScreamingSnakeCase => "FERRIS",
440 FerrisFix::PascalCase => "Ferris",
441 }
442 }
443 }
444
445 let first_span = spans[0];
446 let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
447 let ferris_fix = prev_source
448 .map_or(FerrisFix::SnakeCase, |source| {
449 let mut source_before_ferris = source.split_whitespace().rev();
450 match source_before_ferris.next() {
451 Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
452 FerrisFix::PascalCase
453 }
454 Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
455 Some("mut") if source_before_ferris.next() == Some("static") => {
456 FerrisFix::ScreamingSnakeCase
457 }
458 _ => FerrisFix::SnakeCase,
459 }
460 })
461 .as_str();
462
463 sess.dcx().emit_err(errors::FerrisIdentifier { spans, first_span, ferris_fix });
464 } else {
465 sess.dcx().emit_err(errors::EmojiIdentifier { spans, ident });
466 }
467 }
468 });
469
470 let lint_store = unerased_lint_store(tcx.sess);
471 rustc_lint::check_ast_node(
472 sess,
473 Some(tcx),
474 tcx.features(),
475 false,
476 lint_store,
477 tcx.registered_tools(()),
478 Some(lint_buffer),
479 rustc_lint::BuiltinCombinedEarlyLintPass::new(),
480 (&**krate, &*krate.attrs),
481 )
482}
483
484fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
485 let value = env::var_os(key);
486
487 let value_tcx = value.as_ref().map(|value| {
488 let encoded_bytes = tcx.arena.alloc_slice(value.as_encoded_bytes());
489 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);
490 unsafe { OsStr::from_encoded_bytes_unchecked(encoded_bytes) }
494 });
495
496 tcx.sess.env_depinfo.borrow_mut().insert((
502 Symbol::intern(&key.to_string_lossy()),
503 value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(value)),
504 ));
505
506 value_tcx
507}
508
509fn generated_output_paths(
511 tcx: TyCtxt<'_>,
512 outputs: &OutputFilenames,
513 exact_name: bool,
514 crate_name: Symbol,
515) -> Vec<PathBuf> {
516 let sess = tcx.sess;
517 let mut out_filenames = Vec::new();
518 for output_type in sess.opts.output_types.keys() {
519 let out_filename = outputs.path(*output_type);
520 let file = out_filename.as_path().to_path_buf();
521 match *output_type {
522 OutputType::Exe if !exact_name => {
525 for crate_type in tcx.crate_types().iter() {
526 let p = filename_for_input(sess, *crate_type, crate_name, outputs);
527 out_filenames.push(p.as_path().to_path_buf());
528 }
529 }
530 OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
531 }
533 OutputType::DepInfo if out_filename.is_stdout() => {
534 }
536 _ => {
537 out_filenames.push(file);
538 }
539 }
540 }
541 out_filenames
542}
543
544fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
545 let input_path = try_canonicalize(input_path).ok();
546 if input_path.is_none() {
547 return false;
548 }
549 output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
550}
551
552fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
553 output_paths.iter().find(|output_path| output_path.is_dir())
554}
555
556fn escape_dep_filename(filename: &str) -> String {
557 filename.replace(' ', "\\ ")
560}
561
562fn escape_dep_env(symbol: Symbol) -> String {
565 let s = symbol.as_str();
566 let mut escaped = String::with_capacity(s.len());
567 for c in s.chars() {
568 match c {
569 '\n' => escaped.push_str(r"\n"),
570 '\r' => escaped.push_str(r"\r"),
571 '\\' => escaped.push_str(r"\\"),
572 _ => escaped.push(c),
573 }
574 }
575 escaped
576}
577
578fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
579 let sess = tcx.sess;
581 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
582 return;
583 }
584 let deps_output = outputs.path(OutputType::DepInfo);
585 let deps_filename = deps_output.as_path();
586
587 let result = try {
588 let mut files: IndexMap<String, (u64, Option<SourceFileHash>)> = sess
591 .source_map()
592 .files()
593 .iter()
594 .filter(|fmap| fmap.is_real_file())
595 .filter(|fmap| !fmap.is_imported())
596 .map(|fmap| {
597 (
598 escape_dep_filename(&fmap.name.prefer_local_unconditionally().to_string()),
599 (
600 fmap.unnormalized_source_len as u64,
603 fmap.checksum_hash,
604 ),
605 )
606 })
607 .collect();
608
609 let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
610
611 let file_depinfo = sess.file_depinfo.borrow();
614
615 let normalize_path = |path: PathBuf| escape_dep_filename(&path.to_string_lossy());
616
617 fn hash_iter_files<P: AsRef<Path>>(
620 it: impl Iterator<Item = P>,
621 checksum_hash_algo: Option<SourceFileHashAlgorithm>,
622 ) -> impl Iterator<Item = (P, (u64, Option<SourceFileHash>))> {
623 it.map(move |path| {
624 match checksum_hash_algo.and_then(|algo| {
625 fs::File::open(path.as_ref())
626 .and_then(|mut file| {
627 SourceFileHash::new(algo, &mut file).map(|h| (file, h))
628 })
629 .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
630 .map_err(|e| {
631 {
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:631",
"rustc_interface::passes", ::tracing::Level::ERROR,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(631u32),
::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!(
632 "failed to compute checksum, omitting it from dep-info {} {e}",
633 path.as_ref().display()
634 )
635 })
636 .ok()
637 }) {
638 Some((file_len, checksum)) => (path, (file_len, Some(checksum))),
639 None => (path, (0, None)),
640 }
641 })
642 }
643
644 let extra_tracked_files = hash_iter_files(
645 file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
646 checksum_hash_algo,
647 );
648 files.extend(extra_tracked_files);
649
650 if let Some(ref profile_instr) = sess.opts.cg.profile_use {
652 files.extend(hash_iter_files(
653 iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
654 checksum_hash_algo,
655 ));
656 }
657 if let Some(ref profile_sample) = sess.opts.unstable_opts.profile_sample_use {
658 files.extend(hash_iter_files(
659 iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
660 checksum_hash_algo,
661 ));
662 }
663
664 for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
666 files.extend(hash_iter_files(
667 iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
668 checksum_hash_algo,
669 ));
670 }
671
672 if sess.binary_dep_depinfo() {
673 if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
674 if backend.contains('.') {
675 files.extend(hash_iter_files(
678 iter::once(backend.to_string()),
679 checksum_hash_algo,
680 ));
681 }
682 }
683
684 for &cnum in tcx.crates(()) {
685 let source = tcx.used_crate_source(cnum);
686 if let Some(path) = &source.dylib {
687 files.extend(hash_iter_files(
688 iter::once(escape_dep_filename(&path.display().to_string())),
689 checksum_hash_algo,
690 ));
691 }
692 if let Some(path) = &source.rlib {
693 files.extend(hash_iter_files(
694 iter::once(escape_dep_filename(&path.display().to_string())),
695 checksum_hash_algo,
696 ));
697 }
698 if let Some(path) = &source.rmeta {
699 files.extend(hash_iter_files(
700 iter::once(escape_dep_filename(&path.display().to_string())),
701 checksum_hash_algo,
702 ));
703 }
704 }
705 }
706
707 let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
708 for path in out_filenames {
709 file.write_fmt(format_args!("{0}: {1}\n\n", path.display(),
files.keys().map(String::as_str).intersperse(" ").collect::<String>()))writeln!(
710 file,
711 "{}: {}\n",
712 path.display(),
713 files.keys().map(String::as_str).intersperse(" ").collect::<String>()
714 )?;
715 }
716
717 for path in files.keys() {
721 file.write_fmt(format_args!("{0}:\n", path))writeln!(file, "{path}:")?;
722 }
723
724 let env_depinfo = sess.env_depinfo.borrow();
726 if !env_depinfo.is_empty() {
727 #[allow(rustc::potential_query_instability)]
729 let mut envs: Vec<_> = env_depinfo
730 .iter()
731 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
732 .collect();
733 envs.sort_unstable();
734 file.write_fmt(format_args!("\n"))writeln!(file)?;
735 for (k, v) in envs {
736 file.write_fmt(format_args!("# env-dep:{0}", k))write!(file, "# env-dep:{k}")?;
737 if let Some(v) = v {
738 file.write_fmt(format_args!("={0}", v))write!(file, "={v}")?;
739 }
740 file.write_fmt(format_args!("\n"))writeln!(file)?;
741 }
742 }
743
744 if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
747 files
748 .iter()
749 .filter_map(|(path, (file_len, hash_algo))| {
750 hash_algo.map(|hash_algo| (path, file_len, hash_algo))
751 })
752 .try_for_each(|(path, file_len, checksum_hash)| {
753 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}")
754 })?;
755 }
756
757 Ok(())
758 };
759
760 match deps_output {
761 OutFileName::Stdout => {
762 let mut file = BufWriter::new(io::stdout());
763 write_deps_to_file(&mut file)?;
764 }
765 OutFileName::Real(ref path) => {
766 let mut file = fs::File::create_buffered(path)?;
767 write_deps_to_file(&mut file)?;
768 }
769 }
770 };
771
772 match result {
773 Ok(_) => {
774 if sess.opts.json_artifact_notifications {
775 sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
776 }
777 }
778 Err(error) => {
779 sess.dcx().emit_fatal(errors::ErrorWritingDependencies { path: deps_filename, error });
780 }
781 }
782}
783
784fn resolver_for_lowering_raw<'tcx>(
785 tcx: TyCtxt<'tcx>,
786 (): (),
787) -> (&'tcx Steal<(ty::ResolverAstLowering<'tcx>, Arc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
788 let arenas = Resolver::arenas();
789 let _ = tcx.registered_tools(()); let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
791 let mut resolver = Resolver::new(
792 tcx,
793 &pre_configured_attrs,
794 krate.spans.inner_span,
795 krate.spans.inject_use_span,
796 &arenas,
797 );
798 let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
799
800 tcx.untracked().cstore.freeze();
802
803 let ResolverOutputs {
804 global_ctxt: untracked_resolutions,
805 ast_lowering: untracked_resolver_for_lowering,
806 } = resolver.into_outputs();
807
808 let resolutions = tcx.arena.alloc(untracked_resolutions);
809 (tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Arc::new(krate)))), resolutions)
810}
811
812pub fn write_dep_info(tcx: TyCtxt<'_>) {
813 let _ = tcx.resolver_for_lowering();
817
818 let sess = tcx.sess;
819 let _timer = sess.timer("write_dep_info");
820 let crate_name = tcx.crate_name(LOCAL_CRATE);
821
822 let outputs = tcx.output_filenames(());
823 let output_paths =
824 generated_output_paths(tcx, outputs, sess.io.output_file.is_some(), crate_name);
825
826 if let Some(input_path) = sess.io.input.opt_path() {
828 if sess.opts.will_create_output_file() {
829 if output_contains_path(&output_paths, input_path) {
830 sess.dcx().emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path });
831 }
832 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
833 sess.dcx().emit_fatal(errors::GeneratedFileConflictsWithDirectory {
834 input_path,
835 dir_path,
836 });
837 }
838 }
839 }
840
841 if let Some(ref dir) = sess.io.temps_dir {
842 if fs::create_dir_all(dir).is_err() {
843 sess.dcx().emit_fatal(errors::TempsDirError);
844 }
845 }
846
847 write_out_deps(tcx, outputs, &output_paths);
848
849 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
850 && sess.opts.output_types.len() == 1;
851
852 if !only_dep_info {
853 if let Some(ref dir) = sess.io.output_dir {
854 if fs::create_dir_all(dir).is_err() {
855 sess.dcx().emit_fatal(errors::OutDirError);
856 }
857 }
858 }
859}
860
861pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
862 if !tcx.crate_types().contains(&rustc_session::config::CrateType::Sdylib) {
863 return;
864 }
865 let _timer = tcx.sess.timer("write_interface");
866 let (_, krate) = &*tcx.resolver_for_lowering().borrow();
867
868 let krate = rustc_ast_pretty::pprust::print_crate_as_interface(
869 krate,
870 tcx.sess.psess.edition,
871 &tcx.sess.psess.attr_id_generator,
872 );
873 let export_output = tcx.output_filenames(()).interface_path();
874 let mut file = fs::File::create_buffered(export_output).unwrap();
875 if let Err(err) = file.write_fmt(format_args!("{0}", krate))write!(file, "{}", krate) {
876 tcx.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("error writing interface file: {0}",
err))
})format!("error writing interface file: {}", err));
877 }
878}
879
880pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
881 let providers = &mut Providers::default();
882 providers.queries.analysis = analysis;
883 providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
884 providers.queries.lower_delayed_owner = rustc_ast_lowering::lower_delayed_owner;
885 providers.queries.delayed_owner = |_, _| MaybeOwner::Phantom;
888 providers.queries.resolver_for_lowering_raw = resolver_for_lowering_raw;
889 providers.queries.stripped_cfg_items = |tcx, _| &tcx.resolutions(()).stripped_cfg_items[..];
890 providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
891 providers.queries.early_lint_checks = early_lint_checks;
892 providers.queries.env_var_os = env_var_os;
893 limits::provide(&mut providers.queries);
894 proc_macro_decls::provide(&mut providers.queries);
895 rustc_expand::provide(&mut providers.queries);
896 rustc_const_eval::provide(providers);
897 rustc_middle::hir::provide(&mut providers.queries);
898 rustc_borrowck::provide(&mut providers.queries);
899 rustc_incremental::provide(providers);
900 rustc_mir_build::provide(providers);
901 rustc_mir_transform::provide(providers);
902 rustc_monomorphize::provide(providers);
903 rustc_privacy::provide(&mut providers.queries);
904 rustc_query_impl::provide(providers);
905 rustc_resolve::provide(&mut providers.queries);
906 rustc_hir_analysis::provide(&mut providers.queries);
907 rustc_hir_typeck::provide(&mut providers.queries);
908 ty::provide(&mut providers.queries);
909 traits::provide(&mut providers.queries);
910 solve::provide(&mut providers.queries);
911 rustc_passes::provide(&mut providers.queries);
912 rustc_traits::provide(&mut providers.queries);
913 rustc_ty_utils::provide(&mut providers.queries);
914 rustc_metadata::provide(providers);
915 rustc_lint::provide(&mut providers.queries);
916 rustc_symbol_mangling::provide(&mut providers.queries);
917 rustc_codegen_ssa::provide(providers);
918 *providers
919});
920
921pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
922 compiler: &Compiler,
923 krate: rustc_ast::Crate,
924 f: F,
925) -> T {
926 let sess = &compiler.sess;
927
928 let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
929
930 let crate_name = get_crate_name(sess, &pre_configured_attrs);
931 let crate_types = collect_crate_types(
932 sess,
933 &compiler.codegen_backend.supported_crate_types(sess),
934 compiler.codegen_backend.name(),
935 &pre_configured_attrs,
936 krate.spans.inner_span,
937 );
938 let stable_crate_id = StableCrateId::new(
939 crate_name,
940 crate_types.contains(&CrateType::Executable),
941 sess.opts.cg.metadata.clone(),
942 sess.cfg_version,
943 );
944
945 let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
946
947 let dep_graph = setup_dep_graph(sess, crate_name, stable_crate_id);
948
949 let cstore =
950 FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
951 let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
952
953 let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
954 let untracked =
955 Untracked { cstore, source_span: AppendOnlyIndexVec::new(), definitions, stable_crate_ids };
956
957 dep_graph.assert_ignored();
961
962 let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess);
963
964 let codegen_backend = &compiler.codegen_backend;
965 let mut providers = *DEFAULT_QUERY_PROVIDERS;
966 codegen_backend.provide(&mut providers);
967
968 if let Some(callback) = compiler.override_queries {
969 callback(sess, &mut providers);
970 }
971
972 let incremental = dep_graph.is_fully_enabled();
973
974 let gcx_cell = OnceLock::new();
986 let arena = WorkerLocal::new(|_| Arena::default());
987 let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
988
989 TyCtxt::create_global_ctxt(
990 &gcx_cell,
991 &compiler.sess,
992 crate_types,
993 stable_crate_id,
994 &arena,
995 &hir_arena,
996 untracked,
997 dep_graph,
998 rustc_query_impl::make_dep_kind_vtables(&arena),
999 rustc_query_impl::query_system(
1000 providers.queries,
1001 providers.extern_queries,
1002 query_result_on_disk_cache,
1003 incremental,
1004 ),
1005 providers.hooks,
1006 compiler.current_gcx.clone(),
1007 Arc::clone(&compiler.jobserver_proxy),
1008 |tcx| {
1009 let feed = tcx.create_crate_num(stable_crate_id).unwrap();
1010 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);
1011 feed.crate_name(crate_name);
1012
1013 let feed = tcx.feed_unit_query();
1014 feed.features_query(tcx.arena.alloc(rustc_expand::config::features(
1015 tcx.sess,
1016 &pre_configured_attrs,
1017 crate_name,
1018 )));
1019 feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
1020 feed.output_filenames(Arc::new(outputs));
1021
1022 let res = f(tcx);
1023 tcx.finish();
1026 res
1027 },
1028 )
1029}
1030
1031pub fn emit_delayed_lints(tcx: TyCtxt<'_>) {
1032 for owner_id in tcx.hir_crate_items(()).delayed_lint_items() {
1033 if let Some(delayed_lints) = tcx.opt_ast_lowering_delayed_lints(owner_id) {
1034 for lint in delayed_lints {
1035 match lint {
1036 DelayedLint::AttributeParsing(attribute_lint) => {
1037 tcx.emit_node_span_lint(
1038 attribute_lint.lint_id.lint,
1039 attribute_lint.id,
1040 attribute_lint.span.clone(),
1041 DecorateAttrLint {
1042 sess: tcx.sess,
1043 tcx: Some(tcx),
1044 diagnostic: &attribute_lint.kind,
1045 },
1046 );
1047 }
1048 DelayedLint::Dynamic(attribute_lint) => tcx.emit_node_span_lint(
1049 attribute_lint.lint_id.lint,
1050 attribute_lint.id,
1051 attribute_lint.span.clone(),
1052 DiagCallback(&attribute_lint.callback),
1053 ),
1054 }
1055 }
1056 }
1057 }
1058}
1059
1060fn run_required_analyses(tcx: TyCtxt<'_>) {
1063 if tcx.sess.opts.unstable_opts.input_stats {
1064 rustc_passes::input_stats::print_hir_stats(tcx);
1065 }
1066 #[cfg(all(not(doc), debug_assertions))]
1069 rustc_passes::hir_id_validator::check_crate(tcx);
1070
1071 tcx.ensure_done().hir_crate_items(());
1075
1076 let sess = tcx.sess;
1077 sess.time("misc_checking_1", || {
1078 par_fns(&mut [
1079 &mut || {
1080 sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
1081 sess.time("check_externally_implementable_items", || {
1082 tcx.ensure_ok().check_externally_implementable_items(())
1083 });
1084
1085 sess.time("looking_for_derive_registrar", || {
1086 tcx.ensure_ok().proc_macro_decls_static(())
1087 });
1088
1089 CStore::from_tcx(tcx).report_unused_deps(tcx);
1090 },
1091 &mut || {
1092 tcx.ensure_ok().exportable_items(LOCAL_CRATE);
1093 tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
1094 tcx.par_hir_for_each_module(|module| {
1095 tcx.ensure_ok().check_mod_attrs(module);
1096 tcx.ensure_ok().check_mod_unstable_api_usage(module);
1097 });
1098 },
1099 &mut || {
1100 tcx.ensure_ok().limits(());
1105 },
1106 ]);
1107 });
1108
1109 sess.time("emit_ast_lowering_delayed_lints", || {
1110 #[cfg(debug_assertions)]
1120 {
1121 let hir_items = tcx.hir_crate_items(());
1122 for owner_id in hir_items.owners() {
1123 if let Some(delayed_lints) = tcx.opt_ast_lowering_delayed_lints(owner_id)
1124 && !delayed_lints.is_empty()
1125 {
1126 if !hir_items.delayed_lint_items().any(|i| i == owner_id) {
::core::panicking::panic("assertion failed: hir_items.delayed_lint_items().any(|i| i == owner_id)")
};assert!(hir_items.delayed_lint_items().any(|i| i == owner_id));
1128 }
1129 }
1130 }
1131
1132 emit_delayed_lints(tcx);
1133 });
1134
1135 rustc_hir_analysis::check_crate(tcx);
1136 tcx.untracked().definitions.freeze();
1142
1143 sess.time("MIR_borrow_checking", || {
1144 tcx.par_hir_body_owners(|def_id| {
1145 let not_typeck_child = !tcx.is_typeck_child(def_id.to_def_id());
1146 if not_typeck_child {
1147 tcx.ensure_ok().check_unsafety(def_id);
1149 }
1150 if tcx.is_trivial_const(def_id) {
1151 return;
1152 }
1153 if not_typeck_child {
1154 tcx.ensure_ok().mir_borrowck(def_id);
1155 tcx.ensure_ok().check_transmutes(def_id);
1156 }
1157 tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1158 tcx.ensure_ok().check_liveness(def_id);
1159
1160 if tcx.sess.opts.output_types.should_codegen()
1164 || tcx.hir_body_const_context(def_id).is_some()
1165 {
1166 tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1167 }
1168 if tcx.is_coroutine(def_id.to_def_id())
1169 && (!tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()))
1170 {
1171 tcx.ensure_ok().layout_of(
1173 ty::TypingEnv::post_analysis(tcx, def_id.to_def_id())
1174 .as_query_input(tcx.type_of(def_id).instantiate_identity()),
1175 );
1176 }
1177 });
1178 });
1179
1180 sess.time("layout_testing", || layout_test::test_layout(tcx));
1181 sess.time("abi_testing", || abi_test::test_abi(tcx));
1182}
1183
1184fn analysis(tcx: TyCtxt<'_>, (): ()) {
1187 run_required_analyses(tcx);
1188
1189 let sess = tcx.sess;
1190
1191 if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1200 guar.raise_fatal();
1201 }
1202
1203 sess.time("misc_checking_3", || {
1204 par_fns(&mut [
1205 &mut || {
1206 tcx.ensure_ok().effective_visibilities(());
1207
1208 par_fns(&mut [
1209 &mut || {
1210 tcx.par_hir_for_each_module(|module| {
1211 tcx.ensure_ok().check_private_in_public(module)
1212 })
1213 },
1214 &mut || {
1215 tcx.par_hir_for_each_module(|module| {
1216 tcx.ensure_ok().check_mod_deathness(module)
1217 });
1218 },
1219 &mut || {
1220 sess.time("lint_checking", || {
1221 rustc_lint::check_crate(tcx);
1222 });
1223 },
1224 &mut || {
1225 tcx.ensure_ok().clashing_extern_declarations(());
1226 },
1227 ]);
1228 },
1229 &mut || {
1230 sess.time("privacy_checking_modules", || {
1231 tcx.par_hir_for_each_module(|module| {
1232 tcx.ensure_ok().check_mod_privacy(module);
1233 });
1234 });
1235 },
1236 ]);
1237
1238 sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1241
1242 let _ = tcx.all_diagnostic_items(());
1246 });
1247
1248 if tcx.sess.opts.unstable_opts.validate_mir {
1255 sess.time("ensuring_final_MIR_is_computable", || {
1256 tcx.par_hir_body_owners(|def_id| {
1257 if !tcx.is_trivial_const(def_id) {
1258 tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1259 }
1260 });
1261 });
1262 }
1263}
1264
1265pub(crate) fn start_codegen<'tcx>(
1268 codegen_backend: &dyn CodegenBackend,
1269 tcx: TyCtxt<'tcx>,
1270) -> (Box<dyn Any>, CrateInfo, EncodedMetadata) {
1271 tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen);
1272
1273 if let Some((def_id, _)) = tcx.entry_fn(())
1275 && {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx)
{
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcDelayedBugFromInsideQuery)
=> {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, RustcDelayedBugFromInsideQuery)
1276 {
1277 tcx.ensure_ok().trigger_delayed_bug(def_id);
1278 }
1279
1280 if tcx.sess.opts.output_types.should_codegen() {
1283 rustc_symbol_mangling::test::dump_symbol_names_and_def_paths(tcx);
1284 }
1285
1286 if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
1290 guar.raise_fatal();
1291 }
1292
1293 {
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:1293",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(1293u32),
::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());
1294
1295 let metadata = rustc_metadata::fs::encode_and_write_metadata(tcx);
1296
1297 let crate_info = CrateInfo::new(tcx, codegen_backend.target_cpu(tcx.sess));
1298
1299 let codegen = tcx.sess.time("codegen_crate", || {
1300 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1301 tcx.sess.dcx().abort_if_errors();
1303
1304 Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
1306 } else {
1307 codegen_backend.codegen_crate(tcx, &crate_info)
1308 }
1309 });
1310
1311 {
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:1311",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(1311u32),
::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());
1312
1313 if tcx.sess.opts.unstable_opts.print_type_sizes {
1316 tcx.sess.code_stats.print_type_sizes();
1317 }
1318
1319 (codegen, crate_info, metadata)
1320}
1321
1322pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1324 let attr_crate_name =
1332 parse_crate_name(sess, krate_attrs, ShouldEmit::EarlyFatal { also_emit_lints: true });
1333
1334 let validate = |name, span| {
1335 rustc_session::output::validate_crate_name(sess, name, span);
1336 name
1337 };
1338
1339 if let Some(crate_name) = &sess.opts.crate_name {
1340 let crate_name = Symbol::intern(crate_name);
1341 if let Some((attr_crate_name, span)) = attr_crate_name
1342 && attr_crate_name != crate_name
1343 {
1344 sess.dcx().emit_err(errors::CrateNameDoesNotMatch {
1345 span,
1346 crate_name,
1347 attr_crate_name,
1348 });
1349 }
1350 return validate(crate_name, None);
1351 }
1352
1353 if let Some((crate_name, span)) = attr_crate_name {
1354 return validate(crate_name, Some(span));
1355 }
1356
1357 if let Input::File(ref path) = sess.io.input
1358 && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1359 {
1360 if file_stem.starts_with('-') {
1361 sess.dcx().emit_err(errors::CrateNameInvalid { crate_name: file_stem });
1362 } else {
1363 return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1364 }
1365 }
1366
1367 sym::rust_out
1368}
1369
1370pub(crate) fn parse_crate_name(
1371 sess: &Session,
1372 attrs: &[ast::Attribute],
1373 emit_errors: ShouldEmit,
1374) -> Option<(Symbol, Span)> {
1375 let rustc_hir::Attribute::Parsed(AttributeKind::CrateName { name, name_span, .. }) =
1376 AttributeParser::parse_limited_should_emit(
1377 sess,
1378 attrs,
1379 &[sym::crate_name],
1380 DUMMY_SP,
1381 rustc_ast::node_id::CRATE_NODE_ID,
1382 Target::Crate,
1383 None,
1384 emit_errors,
1385 )?
1386 else {
1387 {
::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");
1388 };
1389
1390 Some((name, name_span))
1391}
1392
1393pub fn collect_crate_types(
1394 session: &Session,
1395 backend_crate_types: &[CrateType],
1396 codegen_backend_name: &'static str,
1397 attrs: &[ast::Attribute],
1398 crate_span: Span,
1399) -> Vec<CrateType> {
1400 if session.opts.test {
1403 if !session.target.executables {
1404 session.dcx().emit_warn(errors::UnsupportedCrateTypeForTarget {
1405 crate_type: CrateType::Executable,
1406 target_triple: &session.opts.target_triple,
1407 });
1408 return Vec::new();
1409 }
1410 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];
1411 }
1412
1413 if session.opts.unstable_opts.build_sdylib_interface {
1415 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];
1416 }
1417
1418 #[allow(rustc::bad_opt_access)]
1423 let mut base = session.opts.crate_types.clone();
1424 if base.is_empty() {
1425 if let Some(Attribute::Parsed(AttributeKind::CrateType(crate_type))) =
1426 AttributeParser::<Early>::parse_limited_should_emit(
1427 session,
1428 attrs,
1429 &[sym::crate_type],
1430 crate_span,
1431 CRATE_NODE_ID,
1432 Target::Crate,
1433 None,
1434 ShouldEmit::EarlyFatal { also_emit_lints: false },
1435 )
1436 {
1437 base.extend(crate_type);
1438 }
1439
1440 if base.is_empty() {
1441 base.push(default_output_for_target(session));
1442 } else {
1443 base.sort();
1444 base.dedup();
1445 }
1446 }
1447
1448 base.retain(|crate_type| {
1449 if invalid_output_for_target(session, *crate_type) {
1450 session.dcx().emit_warn(errors::UnsupportedCrateTypeForTarget {
1451 crate_type: *crate_type,
1452 target_triple: &session.opts.target_triple,
1453 });
1454 false
1455 } else if !backend_crate_types.contains(crate_type) {
1456 session.dcx().emit_warn(errors::UnsupportedCrateTypeForCodegenBackend {
1457 crate_type: *crate_type,
1458 codegen_backend: codegen_backend_name,
1459 });
1460 false
1461 } else {
1462 true
1463 }
1464 });
1465
1466 base
1467}
1468
1469fn default_output_for_target(sess: &Session) -> CrateType {
1479 if !sess.target.executables { CrateType::StaticLib } else { CrateType::Executable }
1480}
1481
1482fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1483 let attr = AttributeParser::parse_limited_should_emit(
1484 sess,
1485 &krate_attrs,
1486 &[sym::recursion_limit],
1487 DUMMY_SP,
1488 rustc_ast::node_id::CRATE_NODE_ID,
1489 Target::Crate,
1490 None,
1491 ShouldEmit::EarlyFatal { also_emit_lints: false },
1496 );
1497 crate::limits::get_recursion_limit(attr.as_slice(), sess)
1498}