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