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::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_hir::lints::DelayedLint;
25use rustc_hir::{Attribute, MaybeOwner, Target, find_attr};
26use rustc_incremental::setup_dep_graph;
27use rustc_lint::{
28 BufferedEarlyLint, DecorateAttrLint, EarlyCheckNode, LintStore, unerased_lint_store,
29};
30use rustc_metadata::EncodedMetadata;
31use rustc_metadata::creader::CStore;
32use rustc_middle::arena::Arena;
33use rustc_middle::ty::{self, RegisteredTools, TyCtxt};
34use rustc_middle::util::Providers;
35use rustc_parse::lexer::StripTokens;
36use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
37use rustc_passes::{abi_test, input_stats, layout_test};
38use rustc_resolve::{Resolver, ResolverOutputs};
39use rustc_session::Session;
40use rustc_session::config::{CrateType, Input, OutFileName, OutputFilenames, OutputType};
41use rustc_session::cstore::Untracked;
42use rustc_session::output::{filename_for_input, invalid_output_for_target};
43use rustc_session::parse::feature_err;
44use rustc_session::search_paths::PathKind;
45use rustc_span::{
46 DUMMY_SP, ErrorGuaranteed, ExpnKind, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, sym,
47};
48use rustc_trait_selection::{solve, traits};
49use tracing::{info, instrument};
50
51use crate::interface::Compiler;
52use crate::{errors, limits, proc_macro_decls, util};
53
54pub fn parse<'a>(sess: &'a Session) -> ast::Crate {
55 let mut krate = sess
56 .time("parse_crate", || {
57 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
58 Input::File(file) => new_parser_from_file(
59 &sess.psess,
60 file,
61 StripTokens::ShebangAndFrontmatter,
62 None,
63 ),
64 Input::Str { input, name } => new_parser_from_source_str(
65 &sess.psess,
66 name.clone(),
67 input.clone(),
68 StripTokens::ShebangAndFrontmatter,
69 ),
70 });
71 parser.parse_crate_mod()
72 })
73 .unwrap_or_else(|parse_error| {
74 let guar: ErrorGuaranteed = parse_error.emit();
75 guar.raise_fatal();
76 });
77
78 rustc_builtin_macros::cmdline_attrs::inject(
79 &mut krate,
80 &sess.psess,
81 &sess.opts.unstable_opts.crate_attr,
82 );
83
84 krate
85}
86
87fn pre_expansion_lint<'a>(
88 sess: &Session,
89 features: &Features,
90 lint_store: &LintStore,
91 registered_tools: &RegisteredTools,
92 check_node: impl EarlyCheckNode<'a>,
93 node_name: Symbol,
94) {
95 sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
96 || {
97 rustc_lint::check_ast_node(
98 sess,
99 None,
100 features,
101 true,
102 lint_store,
103 registered_tools,
104 None,
105 rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
106 check_node,
107 );
108 },
109 );
110}
111
112struct LintStoreExpandImpl<'a>(&'a LintStore);
114
115impl LintStoreExpand for LintStoreExpandImpl<'_> {
116 fn pre_expansion_lint(
117 &self,
118 sess: &Session,
119 features: &Features,
120 registered_tools: &RegisteredTools,
121 node_id: ast::NodeId,
122 attrs: &[ast::Attribute],
123 items: &[Box<ast::Item>],
124 name: Symbol,
125 ) {
126 pre_expansion_lint(sess, features, self.0, registered_tools, (node_id, attrs, items), name);
127 }
128}
129
130#[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(134u32),
::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))]
135fn configure_and_expand(
136 mut krate: ast::Crate,
137 pre_configured_attrs: &[ast::Attribute],
138 resolver: &mut Resolver<'_, '_>,
139) -> ast::Crate {
140 let tcx = resolver.tcx();
141 let sess = tcx.sess;
142 let features = tcx.features();
143 let lint_store = unerased_lint_store(tcx.sess);
144 let crate_name = tcx.crate_name(LOCAL_CRATE);
145 let lint_check_node = (&krate, pre_configured_attrs);
146 pre_expansion_lint(
147 sess,
148 features,
149 lint_store,
150 tcx.registered_tools(()),
151 lint_check_node,
152 crate_name,
153 );
154 rustc_builtin_macros::register_builtin_macros(resolver);
155
156 let num_standard_library_imports = sess.time("crate_injection", || {
157 rustc_builtin_macros::standard_library_imports::inject(
158 &mut krate,
159 pre_configured_attrs,
160 resolver,
161 sess,
162 features,
163 )
164 });
165
166 krate = sess.time("macro_expand_crate", || {
168 let mut old_path = OsString::new();
182 if cfg!(windows) {
183 old_path = env::var_os("PATH").unwrap_or(old_path);
184 let mut new_path = Vec::from_iter(
185 sess.host_filesearch().search_paths(PathKind::All).map(|p| p.dir.clone()),
186 );
187 for path in env::split_paths(&old_path) {
188 if !new_path.contains(&path) {
189 new_path.push(path);
190 }
191 }
192 unsafe {
193 env::set_var(
194 "PATH",
195 env::join_paths(
196 new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
197 )
198 .unwrap(),
199 );
200 }
201 }
202
203 let recursion_limit = get_recursion_limit(pre_configured_attrs, sess);
205 let cfg = rustc_expand::expand::ExpansionConfig {
206 crate_name,
207 features,
208 recursion_limit,
209 trace_mac: sess.opts.unstable_opts.trace_macros,
210 should_test: sess.is_test_crate(),
211 span_debug: sess.opts.unstable_opts.span_debug,
212 proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
213 };
214
215 let lint_store = LintStoreExpandImpl(lint_store);
216 let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
217 ecx.num_standard_library_imports = num_standard_library_imports;
218 let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
220
221 if ecx.nb_macro_errors > 0 {
222 sess.dcx().abort_if_errors();
223 }
224
225 sess.psess.buffered_lints.with_lock(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
228 buffered_lints.append(&mut ecx.buffered_early_lint);
229 });
230
231 sess.time("check_unused_macros", || {
232 ecx.check_unused_macros();
233 });
234
235 if ecx.reduced_recursion_limit.is_some() {
238 sess.dcx().abort_if_errors();
239 unreachable!();
240 }
241
242 if cfg!(windows) {
243 unsafe {
244 env::set_var("PATH", &old_path);
245 }
246 }
247
248 if ecx.sess.opts.unstable_opts.macro_stats {
249 print_macro_stats(&ecx);
250 }
251
252 krate
253 });
254
255 sess.time("maybe_building_test_harness", || {
256 rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
257 });
258
259 let has_proc_macro_decls = sess.time("AST_validation", || {
260 rustc_ast_passes::ast_validation::check_crate(
261 sess,
262 features,
263 &krate,
264 tcx.is_sdylib_interface_build(),
265 resolver.lint_buffer(),
266 )
267 });
268
269 let crate_types = tcx.crate_types();
270 let is_executable_crate = crate_types.contains(&CrateType::Executable);
271 let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
272
273 if crate_types.len() > 1 {
274 if is_executable_crate {
275 sess.dcx().emit_err(errors::MixedBinCrate);
276 }
277 if is_proc_macro_crate {
278 sess.dcx().emit_err(errors::MixedProcMacroCrate);
279 }
280 }
281 if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() {
282 feature_err(sess, sym::export_stable, DUMMY_SP, "`sdylib` crate type is unstable").emit();
283 }
284
285 if is_proc_macro_crate && !sess.panic_strategy().unwinds() {
286 sess.dcx().emit_warn(errors::ProcMacroCratePanicAbort);
287 }
288
289 sess.time("maybe_create_a_macro_crate", || {
290 let is_test_crate = sess.is_test_crate();
291 rustc_builtin_macros::proc_macro_harness::inject(
292 &mut krate,
293 sess,
294 features,
295 resolver,
296 is_proc_macro_crate,
297 has_proc_macro_decls,
298 is_test_crate,
299 sess.dcx(),
300 )
301 });
302
303 resolver.resolve_crate(&krate);
306
307 CStore::from_tcx(tcx).report_session_incompatibilities(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.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 = try {
587 let mut files: IndexMap<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 (
599 fmap.unnormalized_source_len as u64,
602 fmap.checksum_hash,
603 ),
604 )
605 })
606 .collect();
607
608 let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
609
610 let file_depinfo = sess.file_depinfo.borrow();
613
614 let normalize_path = |path: PathBuf| escape_dep_filename(&path.to_string_lossy());
615
616 fn hash_iter_files<P: AsRef<Path>>(
619 it: impl Iterator<Item = P>,
620 checksum_hash_algo: Option<SourceFileHashAlgorithm>,
621 ) -> impl Iterator<Item = (P, (u64, Option<SourceFileHash>))> {
622 it.map(move |path| {
623 match checksum_hash_algo.and_then(|algo| {
624 fs::File::open(path.as_ref())
625 .and_then(|mut file| {
626 SourceFileHash::new(algo, &mut file).map(|h| (file, h))
627 })
628 .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
629 .map_err(|e| {
630 {
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:630",
"rustc_interface::passes", ::tracing::Level::ERROR,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(630u32),
::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!(
631 "failed to compute checksum, omitting it from dep-info {} {e}",
632 path.as_ref().display()
633 )
634 })
635 .ok()
636 }) {
637 Some((file_len, checksum)) => (path, (file_len, Some(checksum))),
638 None => (path, (0, None)),
639 }
640 })
641 }
642
643 let extra_tracked_files = hash_iter_files(
644 file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
645 checksum_hash_algo,
646 );
647 files.extend(extra_tracked_files);
648
649 if let Some(ref profile_instr) = sess.opts.cg.profile_use {
651 files.extend(hash_iter_files(
652 iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
653 checksum_hash_algo,
654 ));
655 }
656 if let Some(ref profile_sample) = sess.opts.unstable_opts.profile_sample_use {
657 files.extend(hash_iter_files(
658 iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
659 checksum_hash_algo,
660 ));
661 }
662
663 for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
665 files.extend(hash_iter_files(
666 iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
667 checksum_hash_algo,
668 ));
669 }
670
671 if sess.binary_dep_depinfo() {
672 if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
673 if backend.contains('.') {
674 files.extend(hash_iter_files(
677 iter::once(backend.to_string()),
678 checksum_hash_algo,
679 ));
680 }
681 }
682
683 for &cnum in tcx.crates(()) {
684 let source = tcx.used_crate_source(cnum);
685 if let Some(path) = &source.dylib {
686 files.extend(hash_iter_files(
687 iter::once(escape_dep_filename(&path.display().to_string())),
688 checksum_hash_algo,
689 ));
690 }
691 if let Some(path) = &source.rlib {
692 files.extend(hash_iter_files(
693 iter::once(escape_dep_filename(&path.display().to_string())),
694 checksum_hash_algo,
695 ));
696 }
697 if let Some(path) = &source.rmeta {
698 files.extend(hash_iter_files(
699 iter::once(escape_dep_filename(&path.display().to_string())),
700 checksum_hash_algo,
701 ));
702 }
703 }
704 }
705
706 let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
707 for path in out_filenames {
708 file.write_fmt(format_args!("{0}: {1}\n\n", path.display(),
files.keys().map(String::as_str).intersperse(" ").collect::<String>()))writeln!(
709 file,
710 "{}: {}\n",
711 path.display(),
712 files.keys().map(String::as_str).intersperse(" ").collect::<String>()
713 )?;
714 }
715
716 for path in files.keys() {
720 file.write_fmt(format_args!("{0}:\n", path))writeln!(file, "{path}:")?;
721 }
722
723 let env_depinfo = sess.env_depinfo.borrow();
725 if !env_depinfo.is_empty() {
726 #[allow(rustc::potential_query_instability)]
728 let mut envs: Vec<_> = env_depinfo
729 .iter()
730 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
731 .collect();
732 envs.sort_unstable();
733 file.write_fmt(format_args!("\n"))writeln!(file)?;
734 for (k, v) in envs {
735 file.write_fmt(format_args!("# env-dep:{0}", k))write!(file, "# env-dep:{k}")?;
736 if let Some(v) = v {
737 file.write_fmt(format_args!("={0}", v))write!(file, "={v}")?;
738 }
739 file.write_fmt(format_args!("\n"))writeln!(file)?;
740 }
741 }
742
743 if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
746 files
747 .iter()
748 .filter_map(|(path, (file_len, hash_algo))| {
749 hash_algo.map(|hash_algo| (path, file_len, hash_algo))
750 })
751 .try_for_each(|(path, file_len, checksum_hash)| {
752 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}")
753 })?;
754 }
755
756 Ok(())
757 };
758
759 match deps_output {
760 OutFileName::Stdout => {
761 let mut file = BufWriter::new(io::stdout());
762 write_deps_to_file(&mut file)?;
763 }
764 OutFileName::Real(ref path) => {
765 let mut file = fs::File::create_buffered(path)?;
766 write_deps_to_file(&mut file)?;
767 }
768 }
769 };
770
771 match result {
772 Ok(_) => {
773 if sess.opts.json_artifact_notifications {
774 sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
775 }
776 }
777 Err(error) => {
778 sess.dcx().emit_fatal(errors::ErrorWritingDependencies { path: deps_filename, error });
779 }
780 }
781}
782
783fn resolver_for_lowering_raw<'tcx>(
784 tcx: TyCtxt<'tcx>,
785 (): (),
786) -> (&'tcx Steal<(ty::ResolverAstLowering<'tcx>, Arc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
787 let arenas = Resolver::arenas();
788 let _ = tcx.registered_tools(()); let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
790 let mut resolver = Resolver::new(
791 tcx,
792 &pre_configured_attrs,
793 krate.spans.inner_span,
794 krate.spans.inject_use_span,
795 &arenas,
796 );
797 let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
798
799 tcx.untracked().cstore.freeze();
801
802 let ResolverOutputs {
803 global_ctxt: untracked_resolutions,
804 ast_lowering: untracked_resolver_for_lowering,
805 } = resolver.into_outputs();
806
807 let resolutions = tcx.arena.alloc(untracked_resolutions);
808 (tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Arc::new(krate)))), resolutions)
809}
810
811pub fn write_dep_info(tcx: TyCtxt<'_>) {
812 let _ = tcx.resolver_for_lowering();
816
817 let sess = tcx.sess;
818 let _timer = sess.timer("write_dep_info");
819 let crate_name = tcx.crate_name(LOCAL_CRATE);
820
821 let outputs = tcx.output_filenames(());
822 let output_paths =
823 generated_output_paths(tcx, outputs, sess.io.output_file.is_some(), crate_name);
824
825 if let Some(input_path) = sess.io.input.opt_path() {
827 if sess.opts.will_create_output_file() {
828 if output_contains_path(&output_paths, input_path) {
829 sess.dcx().emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path });
830 }
831 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
832 sess.dcx().emit_fatal(errors::GeneratedFileConflictsWithDirectory {
833 input_path,
834 dir_path,
835 });
836 }
837 }
838 }
839
840 if let Some(ref dir) = sess.io.temps_dir {
841 if fs::create_dir_all(dir).is_err() {
842 sess.dcx().emit_fatal(errors::TempsDirError);
843 }
844 }
845
846 write_out_deps(tcx, outputs, &output_paths);
847
848 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
849 && sess.opts.output_types.len() == 1;
850
851 if !only_dep_info {
852 if let Some(ref dir) = sess.io.output_dir {
853 if fs::create_dir_all(dir).is_err() {
854 sess.dcx().emit_fatal(errors::OutDirError);
855 }
856 }
857 }
858}
859
860pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
861 if !tcx.crate_types().contains(&rustc_session::config::CrateType::Sdylib) {
862 return;
863 }
864 let _timer = tcx.sess.timer("write_interface");
865 let (_, krate) = &*tcx.resolver_for_lowering().borrow();
866
867 let krate = rustc_ast_pretty::pprust::print_crate_as_interface(
868 krate,
869 tcx.sess.psess.edition,
870 &tcx.sess.psess.attr_id_generator,
871 );
872 let export_output = tcx.output_filenames(()).interface_path();
873 let mut file = fs::File::create_buffered(export_output).unwrap();
874 if let Err(err) = file.write_fmt(format_args!("{0}", krate))write!(file, "{}", krate) {
875 tcx.dcx().fatal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("error writing interface file: {0}",
err))
})format!("error writing interface file: {}", err));
876 }
877}
878
879pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
880 let providers = &mut Providers::default();
881 providers.queries.analysis = analysis;
882 providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
883 providers.queries.lower_delayed_owner = rustc_ast_lowering::lower_delayed_owner;
884 providers.queries.delayed_owner = |_, _| MaybeOwner::Phantom;
887 providers.queries.resolver_for_lowering_raw = resolver_for_lowering_raw;
888 providers.queries.stripped_cfg_items = |tcx, _| &tcx.resolutions(()).stripped_cfg_items[..];
889 providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
890 providers.queries.early_lint_checks = early_lint_checks;
891 providers.queries.env_var_os = env_var_os;
892 limits::provide(&mut providers.queries);
893 proc_macro_decls::provide(&mut providers.queries);
894 rustc_expand::provide(&mut providers.queries);
895 rustc_const_eval::provide(providers);
896 rustc_middle::hir::provide(&mut providers.queries);
897 rustc_borrowck::provide(&mut providers.queries);
898 rustc_incremental::provide(providers);
899 rustc_mir_build::provide(providers);
900 rustc_mir_transform::provide(providers);
901 rustc_monomorphize::provide(providers);
902 rustc_privacy::provide(&mut providers.queries);
903 rustc_query_impl::provide(providers);
904 rustc_resolve::provide(&mut providers.queries);
905 rustc_hir_analysis::provide(&mut providers.queries);
906 rustc_hir_typeck::provide(&mut providers.queries);
907 ty::provide(&mut providers.queries);
908 traits::provide(&mut providers.queries);
909 solve::provide(&mut providers.queries);
910 rustc_passes::provide(&mut providers.queries);
911 rustc_traits::provide(&mut providers.queries);
912 rustc_ty_utils::provide(&mut providers.queries);
913 rustc_metadata::provide(providers);
914 rustc_lint::provide(&mut providers.queries);
915 rustc_symbol_mangling::provide(&mut providers.queries);
916 rustc_codegen_ssa::provide(providers);
917 *providers
918});
919
920pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
921 compiler: &Compiler,
922 krate: rustc_ast::Crate,
923 f: F,
924) -> T {
925 let sess = &compiler.sess;
926
927 let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
928
929 let crate_name = get_crate_name(sess, &pre_configured_attrs);
930 let crate_types = collect_crate_types(
931 sess,
932 &compiler.codegen_backend.supported_crate_types(sess),
933 compiler.codegen_backend.name(),
934 &pre_configured_attrs,
935 krate.spans.inner_span,
936 );
937 let stable_crate_id = StableCrateId::new(
938 crate_name,
939 crate_types.contains(&CrateType::Executable),
940 sess.opts.cg.metadata.clone(),
941 sess.cfg_version,
942 );
943
944 let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
945
946 let dep_graph = setup_dep_graph(sess, crate_name, stable_crate_id);
947
948 let cstore =
949 FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
950 let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
951
952 let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
953 let untracked =
954 Untracked { cstore, source_span: AppendOnlyIndexVec::new(), definitions, stable_crate_ids };
955
956 dep_graph.assert_ignored();
960
961 let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess);
962
963 let codegen_backend = &compiler.codegen_backend;
964 let mut providers = *DEFAULT_QUERY_PROVIDERS;
965 codegen_backend.provide(&mut providers);
966
967 if let Some(callback) = compiler.override_queries {
968 callback(sess, &mut providers);
969 }
970
971 let incremental = dep_graph.is_fully_enabled();
972
973 let gcx_cell = OnceLock::new();
985 let arena = WorkerLocal::new(|_| Arena::default());
986 let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
987
988 TyCtxt::create_global_ctxt(
989 &gcx_cell,
990 &compiler.sess,
991 crate_types,
992 stable_crate_id,
993 &arena,
994 &hir_arena,
995 untracked,
996 dep_graph,
997 rustc_query_impl::make_dep_kind_vtables(&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 compiler.current_gcx.clone(),
1006 Arc::clone(&compiler.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();
1025 res
1026 },
1027 )
1028}
1029
1030pub fn emit_delayed_lints(tcx: TyCtxt<'_>) {
1031 for owner_id in tcx.hir_crate_items(()).delayed_lint_items() {
1032 if let Some(delayed_lints) = tcx.opt_ast_lowering_delayed_lints(owner_id) {
1033 for lint in &delayed_lints.lints {
1034 match lint {
1035 DelayedLint::AttributeParsing(attribute_lint) => {
1036 tcx.emit_node_span_lint(
1037 attribute_lint.lint_id.lint,
1038 attribute_lint.id,
1039 attribute_lint.span.clone(),
1040 DecorateAttrLint {
1041 sess: tcx.sess,
1042 tcx: Some(tcx),
1043 diagnostic: &attribute_lint.kind,
1044 },
1045 );
1046 }
1047 }
1048 }
1049 }
1050 }
1051}
1052
1053fn run_required_analyses(tcx: TyCtxt<'_>) {
1056 if tcx.sess.opts.unstable_opts.input_stats {
1057 rustc_passes::input_stats::print_hir_stats(tcx);
1058 }
1059 #[cfg(all(not(doc), debug_assertions))]
1062 rustc_passes::hir_id_validator::check_crate(tcx);
1063
1064 tcx.ensure_done().hir_crate_items(());
1068
1069 let sess = tcx.sess;
1070 sess.time("misc_checking_1", || {
1071 par_fns(&mut [
1072 &mut || {
1073 sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
1074 sess.time("check_externally_implementable_items", || {
1075 tcx.ensure_ok().check_externally_implementable_items(())
1076 });
1077
1078 sess.time("looking_for_derive_registrar", || {
1079 tcx.ensure_ok().proc_macro_decls_static(())
1080 });
1081
1082 CStore::from_tcx(tcx).report_unused_deps(tcx);
1083 },
1084 &mut || {
1085 tcx.ensure_ok().exportable_items(LOCAL_CRATE);
1086 tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
1087 tcx.par_hir_for_each_module(|module| {
1088 tcx.ensure_ok().check_mod_attrs(module);
1089 tcx.ensure_ok().check_mod_unstable_api_usage(module);
1090 });
1091 },
1092 &mut || {
1093 tcx.ensure_ok().limits(());
1098 },
1099 ]);
1100 });
1101
1102 sess.time("emit_ast_lowering_delayed_lints", || {
1103 #[cfg(debug_assertions)]
1113 {
1114 let hir_items = tcx.hir_crate_items(());
1115 for owner_id in hir_items.owners() {
1116 if let Some(delayed_lints) = tcx.opt_ast_lowering_delayed_lints(owner_id) {
1117 if !delayed_lints.lints.is_empty() {
1118 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));
1120 }
1121 }
1122 }
1123 }
1124
1125 emit_delayed_lints(tcx);
1126 });
1127
1128 rustc_hir_analysis::check_crate(tcx);
1129 tcx.untracked().definitions.freeze();
1135
1136 sess.time("MIR_borrow_checking", || {
1137 tcx.par_hir_body_owners(|def_id| {
1138 let not_typeck_child = !tcx.is_typeck_child(def_id.to_def_id());
1139 if not_typeck_child {
1140 tcx.ensure_ok().check_unsafety(def_id);
1142 }
1143 if tcx.is_trivial_const(def_id) {
1144 return;
1145 }
1146 if not_typeck_child {
1147 tcx.ensure_ok().mir_borrowck(def_id);
1148 tcx.ensure_ok().check_transmutes(def_id);
1149 }
1150 tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1151 tcx.ensure_ok().check_liveness(def_id);
1152
1153 if tcx.sess.opts.output_types.should_codegen()
1157 || tcx.hir_body_const_context(def_id).is_some()
1158 {
1159 tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1160 }
1161 if tcx.is_coroutine(def_id.to_def_id())
1162 && (!tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()))
1163 {
1164 tcx.ensure_ok().layout_of(
1166 ty::TypingEnv::post_analysis(tcx, def_id.to_def_id())
1167 .as_query_input(tcx.type_of(def_id).instantiate_identity()),
1168 );
1169 }
1170 });
1171 });
1172
1173 sess.time("layout_testing", || layout_test::test_layout(tcx));
1174 sess.time("abi_testing", || abi_test::test_abi(tcx));
1175}
1176
1177fn analysis(tcx: TyCtxt<'_>, (): ()) {
1180 run_required_analyses(tcx);
1181
1182 let sess = tcx.sess;
1183
1184 if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1193 guar.raise_fatal();
1194 }
1195
1196 sess.time("misc_checking_3", || {
1197 par_fns(&mut [
1198 &mut || {
1199 tcx.ensure_ok().effective_visibilities(());
1200
1201 par_fns(&mut [
1202 &mut || {
1203 tcx.par_hir_for_each_module(|module| {
1204 tcx.ensure_ok().check_private_in_public(module)
1205 })
1206 },
1207 &mut || {
1208 tcx.par_hir_for_each_module(|module| {
1209 tcx.ensure_ok().check_mod_deathness(module)
1210 });
1211 },
1212 &mut || {
1213 sess.time("lint_checking", || {
1214 rustc_lint::check_crate(tcx);
1215 });
1216 },
1217 &mut || {
1218 tcx.ensure_ok().clashing_extern_declarations(());
1219 },
1220 ]);
1221 },
1222 &mut || {
1223 sess.time("privacy_checking_modules", || {
1224 tcx.par_hir_for_each_module(|module| {
1225 tcx.ensure_ok().check_mod_privacy(module);
1226 });
1227 });
1228 },
1229 ]);
1230
1231 sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1234
1235 let _ = tcx.all_diagnostic_items(());
1239 });
1240
1241 if tcx.sess.opts.unstable_opts.validate_mir {
1248 sess.time("ensuring_final_MIR_is_computable", || {
1249 tcx.par_hir_body_owners(|def_id| {
1250 if !tcx.is_trivial_const(def_id) {
1251 tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1252 }
1253 });
1254 });
1255 }
1256}
1257
1258pub(crate) fn start_codegen<'tcx>(
1261 codegen_backend: &dyn CodegenBackend,
1262 tcx: TyCtxt<'tcx>,
1263) -> (Box<dyn Any>, CrateInfo, EncodedMetadata) {
1264 tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen);
1265
1266 if let Some((def_id, _)) = tcx.entry_fn(())
1268 && {
{
'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)
1269 {
1270 tcx.ensure_ok().trigger_delayed_bug(def_id);
1271 }
1272
1273 if tcx.sess.opts.output_types.should_codegen() {
1276 rustc_symbol_mangling::test::dump_symbol_names_and_def_paths(tcx);
1277 }
1278
1279 if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
1283 guar.raise_fatal();
1284 }
1285
1286 {
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:1286",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(1286u32),
::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());
1287
1288 let metadata = rustc_metadata::fs::encode_and_write_metadata(tcx);
1289
1290 let crate_info = CrateInfo::new(tcx, codegen_backend.target_cpu(tcx.sess));
1291
1292 let codegen = tcx.sess.time("codegen_crate", || {
1293 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1294 tcx.sess.dcx().abort_if_errors();
1296
1297 Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
1299 } else {
1300 codegen_backend.codegen_crate(tcx, &crate_info)
1301 }
1302 });
1303
1304 {
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:1304",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(1304u32),
::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());
1305
1306 if tcx.sess.opts.unstable_opts.print_type_sizes {
1309 tcx.sess.code_stats.print_type_sizes();
1310 }
1311
1312 (codegen, crate_info, metadata)
1313}
1314
1315pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1317 let attr_crate_name =
1325 parse_crate_name(sess, krate_attrs, ShouldEmit::EarlyFatal { also_emit_lints: true });
1326
1327 let validate = |name, span| {
1328 rustc_session::output::validate_crate_name(sess, name, span);
1329 name
1330 };
1331
1332 if let Some(crate_name) = &sess.opts.crate_name {
1333 let crate_name = Symbol::intern(crate_name);
1334 if let Some((attr_crate_name, span)) = attr_crate_name
1335 && attr_crate_name != crate_name
1336 {
1337 sess.dcx().emit_err(errors::CrateNameDoesNotMatch {
1338 span,
1339 crate_name,
1340 attr_crate_name,
1341 });
1342 }
1343 return validate(crate_name, None);
1344 }
1345
1346 if let Some((crate_name, span)) = attr_crate_name {
1347 return validate(crate_name, Some(span));
1348 }
1349
1350 if let Input::File(ref path) = sess.io.input
1351 && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1352 {
1353 if file_stem.starts_with('-') {
1354 sess.dcx().emit_err(errors::CrateNameInvalid { crate_name: file_stem });
1355 } else {
1356 return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1357 }
1358 }
1359
1360 sym::rust_out
1361}
1362
1363pub(crate) fn parse_crate_name(
1364 sess: &Session,
1365 attrs: &[ast::Attribute],
1366 emit_errors: ShouldEmit,
1367) -> Option<(Symbol, Span)> {
1368 let rustc_hir::Attribute::Parsed(AttributeKind::CrateName { name, name_span, .. }) =
1369 AttributeParser::parse_limited_should_emit(
1370 sess,
1371 attrs,
1372 &[sym::crate_name],
1373 DUMMY_SP,
1374 rustc_ast::node_id::CRATE_NODE_ID,
1375 Target::Crate,
1376 None,
1377 emit_errors,
1378 )?
1379 else {
1380 {
::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");
1381 };
1382
1383 Some((name, name_span))
1384}
1385
1386pub fn collect_crate_types(
1387 session: &Session,
1388 backend_crate_types: &[CrateType],
1389 codegen_backend_name: &'static str,
1390 attrs: &[ast::Attribute],
1391 crate_span: Span,
1392) -> Vec<CrateType> {
1393 if session.opts.test {
1396 if !session.target.executables {
1397 session.dcx().emit_warn(errors::UnsupportedCrateTypeForTarget {
1398 crate_type: CrateType::Executable,
1399 target_triple: &session.opts.target_triple,
1400 });
1401 return Vec::new();
1402 }
1403 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];
1404 }
1405
1406 if session.opts.unstable_opts.build_sdylib_interface {
1408 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];
1409 }
1410
1411 #[allow(rustc::bad_opt_access)]
1416 let mut base = session.opts.crate_types.clone();
1417 if base.is_empty() {
1418 if let Some(Attribute::Parsed(AttributeKind::CrateType(crate_type))) =
1419 AttributeParser::<Early>::parse_limited_should_emit(
1420 session,
1421 attrs,
1422 &[sym::crate_type],
1423 crate_span,
1424 CRATE_NODE_ID,
1425 Target::Crate,
1426 None,
1427 ShouldEmit::EarlyFatal { also_emit_lints: false },
1428 )
1429 {
1430 base.extend(crate_type);
1431 }
1432
1433 if base.is_empty() {
1434 base.push(default_output_for_target(session));
1435 } else {
1436 base.sort();
1437 base.dedup();
1438 }
1439 }
1440
1441 base.retain(|crate_type| {
1442 if invalid_output_for_target(session, *crate_type) {
1443 session.dcx().emit_warn(errors::UnsupportedCrateTypeForTarget {
1444 crate_type: *crate_type,
1445 target_triple: &session.opts.target_triple,
1446 });
1447 false
1448 } else if !backend_crate_types.contains(crate_type) {
1449 session.dcx().emit_warn(errors::UnsupportedCrateTypeForCodegenBackend {
1450 crate_type: *crate_type,
1451 codegen_backend: codegen_backend_name,
1452 });
1453 false
1454 } else {
1455 true
1456 }
1457 });
1458
1459 base
1460}
1461
1462fn default_output_for_target(sess: &Session) -> CrateType {
1472 if !sess.target.executables { CrateType::StaticLib } else { CrateType::Executable }
1473}
1474
1475fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1476 let attr = AttributeParser::parse_limited_should_emit(
1477 sess,
1478 &krate_attrs,
1479 &[sym::recursion_limit],
1480 DUMMY_SP,
1481 rustc_ast::node_id::CRATE_NODE_ID,
1482 Target::Crate,
1483 None,
1484 ShouldEmit::EarlyFatal { also_emit_lints: false },
1489 );
1490 crate::limits::get_recursion_limit(attr.as_slice(), sess)
1491}