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