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