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_ir::{Attribute, AttributeKind, find_attr};
10use rustc_attr_parsing::{AttributeParser, ShouldEmit};
11use rustc_codegen_ssa::traits::CodegenBackend;
12use rustc_codegen_ssa::{CompiledModules, CrateInfo};
13use rustc_crate_store::Untracked;
14use rustc_data_structures::indexmap::IndexMap;
15use rustc_data_structures::steal::Steal;
16use rustc_data_structures::sync::{
17 AppendOnlyIndexVec, DynSend, DynSync, FreezeLock, WorkerLocal, par_fns,
18};
19use rustc_data_structures::thousands;
20use rustc_errors::timings::TimingSection;
21use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level};
22use rustc_expand::base::{ExtCtxt, LintStoreExpand};
23use rustc_feature::Features;
24use rustc_fs_util::try_canonicalize;
25use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap};
26use rustc_hir::definitions::Definitions;
27use rustc_incremental::setup_dep_graph;
28use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore, unerased_lint_store};
29use rustc_metadata::EncodedMetadata;
30use rustc_metadata::creader::CStore;
31use rustc_middle::arena::Arena;
32use rustc_middle::middle::resolve::{ResolverAstLowering, ResolverGlobalCtxt};
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::{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_structures::CrateType;
48use rustc_trait_selection::{solve, traits};
49use tracing::{info, instrument};
50
51use crate::interface::Compiler;
52use crate::{diagnostics, limits, util};
53
54pub fn parse<'a>(sess: &'a Session) -> ast::Crate {
55 let mut krate = sess
56 .time("parse_crate", || {
57 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
58 Input::File(file) => new_parser_from_file(
59 &sess.psess,
60 file,
61 StripTokens::ShebangAndFrontmatter,
62 None,
63 ),
64 instr @ (Input::Str { input, .. } | Input::DocTestStr { input, .. }) => {
65 new_parser_from_source_str(
66 &sess.psess,
67 instr.file_name(sess),
68 input.clone(),
69 StripTokens::ShebangAndFrontmatter,
70 )
71 }
72 });
73 parser.parse_crate_mod()
74 })
75 .unwrap_or_else(|parse_error| {
76 let guar: ErrorGuaranteed = parse_error.emit_err();
77 guar.raise_fatal();
78 });
79
80 rustc_builtin_macros::cmdline_attrs::inject(
81 &mut krate,
82 &sess.psess,
83 &sess.opts.unstable_opts.crate_attr,
84 );
85
86 krate
87}
88
89fn pre_expansion_lint<'a>(
90 sess: &Session,
91 features: &Features,
92 lint_store: &LintStore,
93 registered_lint_tools: &RegisteredTools,
94 check_node: EarlyCheckNode<'a>,
95 node_name: Symbol,
96) {
97 sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
98 || {
99 rustc_lint::check_ast_node(
100 sess,
101 features,
102 true,
103 lint_store,
104 registered_lint_tools,
105 None,
106 check_node,
107 );
108 },
109 );
110}
111
112struct LintStoreExpandImpl<'a>(&'a LintStore);
114
115impl LintStoreExpand for LintStoreExpandImpl<'_> {
116 fn pre_expansion_lint(
117 &self,
118 sess: &Session,
119 features: &Features,
120 registered_lint_tools: &RegisteredTools,
121 node_id: ast::NodeId,
122 attrs: &[ast::Attribute],
123 items: &[Box<ast::Item>],
124 name: Symbol,
125 ) {
126 let check_node = EarlyCheckNode::LoadedMod(node_id, attrs, items);
127 pre_expansion_lint(sess, features, self.0, registered_lint_tools, check_node, name);
128 }
129}
130
131{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("configure_and_expand",
"rustc_interface::passes", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(135u32),
::tracing_core::__macro_support::Option::Some("rustc_interface::passes"),
::tracing_core::field::FieldSet::new(&[{
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 = tcx.recursion_limit();
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())
});
if features.rustc_attrs() {
rustc_ast_passes::show_spans::check_crate(sess, &krate);
}
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))]
136fn configure_and_expand(
137 mut krate: ast::Crate,
138 pre_configured_attrs: &[ast::Attribute],
139 resolver: &mut Resolver<'_, '_>,
140) -> ast::Crate {
141 let tcx = resolver.tcx();
142 let sess = tcx.sess;
143 let features = tcx.features();
144 let lint_store = unerased_lint_store(sess);
145 let crate_name = tcx.crate_name(LOCAL_CRATE);
146 pre_expansion_lint(
147 sess,
148 features,
149 lint_store,
150 tcx.registered_lint_tools(()),
151 EarlyCheckNode::CrateRoot(&krate, pre_configured_attrs),
152 crate_name,
153 );
154 rustc_builtin_macros::register_builtin_macros(resolver);
155
156 let num_standard_library_imports = sess.time("crate_injection", || {
157 rustc_builtin_macros::standard_library_imports::inject(
158 &mut krate,
159 pre_configured_attrs,
160 resolver,
161 sess,
162 features,
163 )
164 });
165
166 krate = sess.time("macro_expand_crate", || {
168 let mut old_path = OsString::new();
182 if cfg!(windows) {
183 old_path = env::var_os("PATH").unwrap_or(old_path);
184 let mut new_path = Vec::from_iter(
185 sess.host_filesearch().search_paths(PathKind::Native).map(|p| p.dir.to_path_buf()),
186 );
187 for path in env::split_paths(&old_path) {
188 if !new_path.contains(&path) {
189 new_path.push(path);
190 }
191 }
192 unsafe {
193 env::set_var(
194 "PATH",
195 env::join_paths(
196 new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
197 )
198 .unwrap(),
199 );
200 }
201 }
202
203 let recursion_limit = tcx.recursion_limit();
205 let cfg = rustc_expand::expand::ExpansionConfig {
206 crate_name,
207 features,
208 recursion_limit,
209 trace_mac: sess.opts.unstable_opts.trace_macros,
210 should_test: sess.is_test_crate(),
211 span_debug: sess.opts.unstable_opts.span_debug,
212 proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
213 };
214
215 let lint_store = LintStoreExpandImpl(lint_store);
216 let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
217 ecx.num_standard_library_imports = num_standard_library_imports;
218 let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
220
221 if ecx.nb_macro_errors > 0 {
222 sess.dcx().abort_if_errors();
223 }
224
225 sess.psess.buffered_lints.with_lock(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
228 buffered_lints.append(&mut ecx.buffered_early_lint);
229 });
230
231 sess.time("check_unused_macros", || {
232 ecx.check_unused_macros();
233 });
234
235 if ecx.reduced_recursion_limit.is_some() {
238 sess.dcx().abort_if_errors();
239 unreachable!();
240 }
241
242 if cfg!(windows) {
243 unsafe {
244 env::set_var("PATH", &old_path);
245 }
246 }
247
248 if ecx.sess.opts.unstable_opts.macro_stats {
249 print_macro_stats(&ecx);
250 }
251
252 krate
253 });
254
255 sess.time("maybe_building_test_harness", || {
256 rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
257 });
258
259 let has_proc_macro_decls = sess.time("AST_validation", || {
260 rustc_ast_passes::ast_validation::check_crate(
261 sess,
262 features,
263 &krate,
264 tcx.is_sdylib_interface_build(),
265 resolver.lint_buffer(),
266 )
267 });
268
269 if features.rustc_attrs() {
270 rustc_ast_passes::show_spans::check_crate(sess, &krate);
271 }
272
273 let crate_types = tcx.crate_types();
274 let is_executable_crate = crate_types.contains(&CrateType::Executable);
275 let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
276
277 if crate_types.len() > 1 {
278 if is_executable_crate {
279 sess.dcx().emit_err(diagnostics::MixedBinCrate);
280 }
281 if is_proc_macro_crate {
282 sess.dcx().emit_err(diagnostics::MixedProcMacroCrate);
283 }
284 }
285
286 if is_proc_macro_crate && sess.target.is_like_wasm && !sess.opts.unstable_opts.wasm_proc_macros
287 {
288 sess.dcx().emit_err(diagnostics::UnstableWasmProcMacro);
289 }
290
291 if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() {
292 feature_err(sess, sym::export_stable, DUMMY_SP, "`sdylib` crate type is unstable").emit();
293 }
294
295 if is_proc_macro_crate && !sess.sanitizers().is_empty() {
296 sess.dcx().emit_err(diagnostics::CannotSanitizeProcMacro);
297 }
298
299 if is_proc_macro_crate && !sess.panic_strategy().unwinds() {
300 sess.dcx().emit_warn(diagnostics::ProcMacroCratePanicAbort);
301 }
302
303 sess.time("maybe_create_a_macro_crate", || {
304 let is_test_crate = sess.is_test_crate();
305 rustc_builtin_macros::proc_macro_harness::inject(
306 &mut krate,
307 sess,
308 features,
309 resolver,
310 is_proc_macro_crate,
311 has_proc_macro_decls,
312 is_test_crate,
313 sess.dcx(),
314 )
315 });
316
317 resolver.resolve_crate(&krate);
320
321 CStore::from_tcx(tcx).report_session_incompatibilities(tcx, &krate);
322 krate
323}
324
325fn print_macro_stats(ecx: &ExtCtxt<'_>) {
326 use std::fmt::Write;
327
328 let crate_name = ecx.ecfg.crate_name.as_str();
329 let crate_name = if crate_name == "build_script_build" {
330 let pkg_name =
332 std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "<unknown crate>".to_string());
333 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} build script", pkg_name))
})format!("{pkg_name} build script")
334 } else {
335 crate_name.to_string()
336 };
337
338 #[allow(rustc::potential_query_instability)]
340 let mut macro_stats: Vec<_> = ecx
341 .macro_stats
342 .iter()
343 .map(|((name, kind), stat)| {
344 (stat.bytes, stat.lines, stat.uses, name, *kind)
346 })
347 .collect();
348 macro_stats.sort_unstable();
349 macro_stats.reverse(); let prefix = "macro-stats";
352 let name_w = 32;
353 let uses_w = 7;
354 let lines_w = 11;
355 let avg_lines_w = 11;
356 let bytes_w = 11;
357 let avg_bytes_w = 11;
358 let banner_w = name_w + uses_w + lines_w + avg_lines_w + bytes_w + avg_bytes_w;
359
360 let mut s = String::new();
366 _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
367 _ = s.write_fmt(format_args!("{1} MACRO EXPANSION STATS: {0}\n", crate_name,
prefix))writeln!(s, "{prefix} MACRO EXPANSION STATS: {}", crate_name);
368 _ = 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!(
369 s,
370 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
371 "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
372 );
373 _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
374 if macro_stats.is_empty() {
377 _ = s.write_fmt(format_args!("{0} (none)\n", prefix))writeln!(s, "{prefix} (none)");
378 }
379 for (bytes, lines, uses, name, kind) in macro_stats {
380 let mut name = ExpnKind::Macro(kind, *name).descr();
381 let uses_with_underscores = thousands::usize_with_underscores(uses);
382 let avg_lines = lines as f64 / uses as f64;
383 let avg_bytes = bytes as f64 / uses as f64;
384
385 let mut uses_w = uses_w;
387 if name.len() + uses_with_underscores.len() >= name_w + uses_w {
388 _ = s.write_fmt(format_args!("{1} {0:<2$}\n", name, prefix, name_w))writeln!(s, "{prefix} {:<name_w$}", name);
392 name = String::new();
393 } else if name.len() >= name_w {
394 uses_w -= name.len() - name_w;
398 };
399
400 _ = 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!(
401 s,
402 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
403 name,
404 uses_with_underscores,
405 thousands::usize_with_underscores(lines),
406 thousands::f64p1_with_underscores(avg_lines),
407 thousands::usize_with_underscores(bytes),
408 thousands::f64p1_with_underscores(avg_bytes),
409 );
410 }
411 _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
412 { ::std::io::_eprint(format_args!("{0}", s)); };eprint!("{s}");
413}
414
415fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
416 let sess = tcx.sess;
417 let (resolver, krate) = tcx.resolver_for_lowering();
418 let resolver = &*resolver.borrow();
419 let krate = &*krate.borrow();
420 let mut lint_buffer = resolver.lint_buffer.steal();
421
422 if sess.opts.unstable_opts.input_stats {
423 input_stats::print_ast_stats(tcx, krate);
424 }
425
426 sess.time("complete_gated_feature_checking", || {
428 rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
429 });
430
431 sess.psess.buffered_lints.with_lock(|buffered_lints| {
433 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_interface/src/passes.rs:433",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(433u32),
::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());
434 for early_lint in buffered_lints.drain(..) {
435 lint_buffer.add_early_lint(early_lint);
436 }
437 });
438
439 sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
441 for (ident, mut spans) in identifiers.drain(..) {
442 spans.sort_by_key(|span| span.lo_hi());
443 if ident == sym::ferris {
444 enum FerrisFix {
445 SnakeCase,
446 ScreamingSnakeCase,
447 PascalCase,
448 }
449
450 impl FerrisFix {
451 const fn as_str(self) -> &'static str {
452 match self {
453 FerrisFix::SnakeCase => "ferris",
454 FerrisFix::ScreamingSnakeCase => "FERRIS",
455 FerrisFix::PascalCase => "Ferris",
456 }
457 }
458 }
459
460 let first_span = spans[0];
461 let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
462 let ferris_fix = prev_source
463 .map_or(FerrisFix::SnakeCase, |source| {
464 let mut source_before_ferris = source.split_whitespace().rev();
465 match source_before_ferris.next() {
466 Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
467 FerrisFix::PascalCase
468 }
469 Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
470 Some("mut") if source_before_ferris.next() == Some("static") => {
471 FerrisFix::ScreamingSnakeCase
472 }
473 _ => FerrisFix::SnakeCase,
474 }
475 })
476 .as_str();
477
478 sess.dcx().emit_err(diagnostics::FerrisIdentifier {
479 spans,
480 first_span,
481 ferris_fix,
482 });
483 } else {
484 sess.dcx().emit_err(diagnostics::EmojiIdentifier { spans, ident });
485 }
486 }
487 });
488
489 let lint_store = unerased_lint_store(tcx.sess);
490 rustc_lint::check_ast_node(
491 sess,
492 tcx.features(),
493 false,
494 lint_store,
495 tcx.registered_lint_tools(()),
496 Some(lint_buffer),
497 EarlyCheckNode::CrateRoot(&*krate, &*krate.attrs),
498 )
499}
500
501fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
502 let value = env::var_os(key);
503
504 let value_tcx = value.as_ref().map(|value| tcx.arena.alloc_os_str(value));
505
506 tcx.sess.env_depinfo.borrow_mut().insert((
512 Symbol::intern(&key.to_string_lossy()),
513 value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(value)),
514 ));
515
516 value_tcx
517}
518
519fn generated_output_paths(
521 tcx: TyCtxt<'_>,
522 outputs: &OutputFilenames,
523 exact_name: bool,
524 crate_name: Symbol,
525) -> Vec<PathBuf> {
526 let sess = tcx.sess;
527 let mut out_filenames = Vec::new();
528 for output_type in sess.opts.output_types.keys() {
529 let out_filename = outputs.path(*output_type);
530 let file = out_filename.as_path().to_path_buf();
531 match *output_type {
532 OutputType::Exe if !exact_name => {
535 for crate_type in tcx.crate_types().iter() {
536 let p = filename_for_input(sess, *crate_type, crate_name, outputs);
537 out_filenames.push(p.as_path().to_path_buf());
538 }
539 }
540 OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
541 }
543 OutputType::DepInfo if out_filename.is_stdout() => {
544 }
546 _ => {
547 out_filenames.push(file);
548 }
549 }
550 }
551 out_filenames
552}
553
554fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
555 let input_path = try_canonicalize(input_path).ok();
556 if input_path.is_none() {
557 return false;
558 }
559 output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
560}
561
562fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
563 output_paths.iter().find(|output_path| output_path.is_dir())
564}
565
566fn escape_dep_filename(filename: &str) -> String {
567 filename.replace(' ', "\\ ")
570}
571
572fn escape_dep_env(symbol: Symbol) -> String {
575 let s = symbol.as_str();
576 let mut escaped = String::with_capacity(s.len());
577 for c in s.chars() {
578 match c {
579 '\n' => escaped.push_str(r"\n"),
580 '\r' => escaped.push_str(r"\r"),
581 '\\' => escaped.push_str(r"\\"),
582 _ => escaped.push(c),
583 }
584 }
585 escaped
586}
587
588fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
589 let sess = tcx.sess;
591 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
592 return;
593 }
594 let deps_output = outputs.path(OutputType::DepInfo);
595 let deps_filename = deps_output.as_path();
596
597 let result = try {
598 let mut files: IndexMap<String, (u64, Option<SourceFileHash>)> = sess
601 .source_map()
602 .files()
603 .iter()
604 .filter(|fmap| fmap.is_real_file())
605 .filter(|fmap| !fmap.is_imported())
606 .map(|fmap| {
607 (
608 escape_dep_filename(&fmap.name.prefer_local_unconditionally().to_string()),
609 (
610 fmap.unnormalized_source_len as u64,
613 fmap.checksum_hash,
614 ),
615 )
616 })
617 .collect();
618
619 let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
620
621 let file_depinfo = sess.file_depinfo.borrow();
624
625 let normalize_path = |path: PathBuf| escape_dep_filename(&path.to_string_lossy());
626
627 fn hash_iter_files<P: AsRef<Path>>(
630 it: impl Iterator<Item = P>,
631 checksum_hash_algo: Option<SourceFileHashAlgorithm>,
632 ) -> impl Iterator<Item = (P, (u64, Option<SourceFileHash>))> {
633 it.map(move |path| {
634 match checksum_hash_algo.and_then(|algo| {
635 fs::File::open(path.as_ref())
636 .and_then(|mut file| {
637 SourceFileHash::new(algo, &mut file).map(|h| (file, h))
638 })
639 .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
640 .map_err(|e| {
641 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_interface/src/passes.rs:641",
"rustc_interface::passes", ::tracing::Level::ERROR,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(641u32),
::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!(
642 "failed to compute checksum, omitting it from dep-info {} {e}",
643 path.as_ref().display()
644 )
645 })
646 .ok()
647 }) {
648 Some((file_len, checksum)) => (path, (file_len, Some(checksum))),
649 None => (path, (0, None)),
650 }
651 })
652 }
653
654 let extra_tracked_files = hash_iter_files(
655 file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
656 checksum_hash_algo,
657 );
658 files.extend(extra_tracked_files);
659
660 if let Some(ref profile_instr) = sess.opts.cg.profile_use {
662 files.extend(hash_iter_files(
663 iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
664 checksum_hash_algo,
665 ));
666 }
667 if let Some(ref profile_sample) = sess.opts.cg.profile_sample_use {
668 files.extend(hash_iter_files(
669 iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
670 checksum_hash_algo,
671 ));
672 }
673
674 for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
676 files.extend(hash_iter_files(
677 iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
678 checksum_hash_algo,
679 ));
680 }
681
682 if sess.binary_dep_depinfo() {
683 if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
684 if backend.contains('.') {
685 files.extend(hash_iter_files(
688 iter::once(backend.to_string()),
689 checksum_hash_algo,
690 ));
691 }
692 }
693
694 for &cnum in tcx.crates(()) {
695 let source = tcx.used_crate_source(cnum);
696 if let Some(path) = &source.dylib {
697 files.extend(hash_iter_files(
698 iter::once(escape_dep_filename(&path.display().to_string())),
699 checksum_hash_algo,
700 ));
701 }
702 if let Some(path) = &source.rlib {
703 files.extend(hash_iter_files(
704 iter::once(escape_dep_filename(&path.display().to_string())),
705 checksum_hash_algo,
706 ));
707 }
708 if let Some(path) = &source.rmeta {
709 files.extend(hash_iter_files(
710 iter::once(escape_dep_filename(&path.display().to_string())),
711 checksum_hash_algo,
712 ));
713 }
714 }
715 }
716
717 let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
718 for path in out_filenames {
719 file.write_fmt(format_args!("{0}: {1}\n\n", path.display(),
files.keys().map(String::as_str).intersperse(" ").collect::<String>()))writeln!(
720 file,
721 "{}: {}\n",
722 path.display(),
723 files.keys().map(String::as_str).intersperse(" ").collect::<String>()
724 )?;
725 }
726
727 for path in files.keys() {
731 file.write_fmt(format_args!("{0}:\n", path))writeln!(file, "{path}:")?;
732 }
733
734 let env_depinfo = sess.env_depinfo.borrow();
736 if !env_depinfo.is_empty() {
737 #[allow(rustc::potential_query_instability)]
739 let mut envs: Vec<_> = env_depinfo
740 .iter()
741 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
742 .collect();
743 envs.sort_unstable();
744 file.write_fmt(format_args!("\n"))writeln!(file)?;
745 for (k, v) in envs {
746 file.write_fmt(format_args!("# env-dep:{0}", k))write!(file, "# env-dep:{k}")?;
747 if let Some(v) = v {
748 file.write_fmt(format_args!("={0}", v))write!(file, "={v}")?;
749 }
750 file.write_fmt(format_args!("\n"))writeln!(file)?;
751 }
752 }
753
754 if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
757 files
758 .iter()
759 .filter_map(|(path, (file_len, hash_algo))| {
760 hash_algo.map(|hash_algo| (path, file_len, hash_algo))
761 })
762 .try_for_each(|(path, file_len, checksum_hash)| {
763 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}")
764 })?;
765 }
766
767 Ok(())
768 };
769
770 match deps_output {
771 OutFileName::Stdout => {
772 let mut file = BufWriter::new(io::stdout());
773 write_deps_to_file(&mut file)?;
774 }
775 OutFileName::Real(ref path) => {
776 let mut file = fs::File::create_buffered(path)?;
777 write_deps_to_file(&mut file)?;
778 }
779 }
780 };
781
782 match result {
783 Ok(_) => {
784 if sess.opts.json_artifact_notifications {
785 sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
786 }
787 }
788 Err(error) => {
789 sess.dcx()
790 .emit_fatal(diagnostics::ErrorWritingDependencies { path: deps_filename, error });
791 }
792 }
793}
794
795fn resolver_for_lowering_raw<'tcx>(
796 tcx: TyCtxt<'tcx>,
797 (): (),
798) -> (&'tcx Steal<ResolverAstLowering<'tcx>>, &'tcx Steal<ast::Crate>, &'tcx ResolverGlobalCtxt) {
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_structures::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 rustc_expand_queries::provide(&mut providers.queries);
909 rustc_const_eval::provide(providers);
910 rustc_middle::hir::provide(&mut providers.queries);
911 rustc_borrowck::provide(&mut providers.queries);
912 rustc_incremental::provide(providers);
913 rustc_mir_build::provide(providers);
914 rustc_mir_dataflow::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 = Untracked {
969 cstore,
970 source_span: AppendOnlyIndexVec::new(),
971 definitions,
972 stable_crate_ids,
973 local_crate_hash: OnceLock::new(),
974 };
975
976 dep_graph.assert_ignored();
980
981 let query_result_on_disk_cache =
982 rustc_incremental::load_query_result_cache(sess, incr_comp_session.as_ref());
983
984 let codegen_backend = &compiler.codegen_backend;
985 let mut providers = *DEFAULT_QUERY_PROVIDERS;
986 codegen_backend.provide(&mut providers);
987
988 if let Some(callback) = compiler.override_queries {
989 callback(sess, &mut providers);
990 }
991
992 let incremental = dep_graph.is_fully_enabled();
993 let track_present = incremental
994 || sess.opts.unstable_opts.incremental_verify_ich
995 || sess.prof.enabled()
996 || truecfg!(debug_assertions);
997
998 let gcx_cell = OnceLock::new();
1010 let arena = WorkerLocal::new(|_| Arena::default());
1011 let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
1012
1013 let res = TyCtxt::create_global_ctxt(
1014 &gcx_cell,
1015 &compiler.sess,
1016 crate_types,
1017 stable_crate_id,
1018 &arena,
1019 &hir_arena,
1020 untracked,
1021 incr_comp_session.as_ref(),
1022 dep_graph,
1023 rustc_query_impl::query_system(
1024 &arena,
1025 providers.queries,
1026 providers.extern_queries,
1027 query_result_on_disk_cache,
1028 incremental,
1029 track_present,
1030 ),
1031 providers.hooks,
1032 compiler.current_gcx.clone(),
1033 |tcx| {
1034 let feed = tcx.create_crate_num(stable_crate_id).unwrap();
1035 {
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);
1036 feed.crate_name(crate_name);
1037
1038 let feed = tcx.feed_unit_query();
1039 let features = tcx.arena.alloc(rustc_expand::config::features(
1040 tcx.sess,
1041 &pre_configured_attrs,
1042 crate_name,
1043 ));
1044 feed.features_query(features);
1045 feed.limits(limits::get_limits(&pre_configured_attrs, tcx.sess, features));
1046 feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
1047 feed.output_filenames(Arc::new(outputs));
1048
1049 let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(tcx)));
1057 let res = match res {
1058 Ok(res) => res,
1059 Err(err) => {
1060 tcx.alloc_self_profile_query_strings();
1061
1062 std::panic::resume_unwind(err);
1064 }
1065 };
1066
1067 tcx.finish();
1068 res
1069 },
1070 );
1071
1072 (res, incr_comp_session)
1073}
1074
1075struct DiagCallback<'tcx> {
1076 callback: Box<
1077 dyn for<'b> FnOnce(DiagCtxtHandle<'b>, Level, &dyn Any) -> Diag<'b> + DynSend + DynSync,
1078 >,
1079 tcx: TyCtxt<'tcx>,
1080}
1081
1082impl<'a, 'tcx> Diagnostic<'a> for DiagCallback<'tcx> {
1083 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
1084 (self.callback)(dcx, level, self.tcx.sess)
1085 }
1086}
1087
1088pub fn emit_delayed_lints(tcx: TyCtxt<'_>) {
1089 for owner_id in tcx.hir_crate_items(()).owners() {
1090 if let Some(delayed_lints) = tcx.opt_ast_lowering_delayed_lints(owner_id) {
1091 for lint in delayed_lints.steal() {
1092 tcx.emit_node_span_lint(
1093 lint.lint_id.lint,
1094 lint.id,
1095 lint.span.clone(),
1096 DiagCallback { callback: lint.callback, tcx },
1097 );
1098 }
1099 }
1100 }
1101}
1102
1103fn run_required_analyses(tcx: TyCtxt<'_>) {
1106 if tcx.sess.opts.unstable_opts.input_stats {
1107 rustc_passes::input_stats::print_hir_stats(tcx);
1108 }
1109 #[cfg(all(not(doc), debug_assertions))]
1112 rustc_passes::hir_id_validator::check_crate(tcx);
1113
1114 tcx.ensure_done().hir_crate_items(());
1118
1119 tcx.untracked().definitions.write().commit_end_of_determinism();
1120
1121 rustc_passes::delegation::check_glob_and_list_delegations_target_expr(tcx);
1122
1123 let sess = tcx.sess;
1124 sess.time("misc_checking_1", || {
1125 par_fns(&mut [
1126 &mut || {
1127 sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
1128 sess.time("check_externally_implementable_items", || {
1129 tcx.ensure_ok().check_externally_implementable_items(())
1130 });
1131
1132 sess.time("looking_for_derive_registrar", || {
1133 tcx.ensure_ok().proc_macro_decls_static(())
1134 });
1135
1136 CStore::from_tcx(tcx).report_unused_deps(tcx);
1137 },
1138 &mut || {
1139 tcx.ensure_ok().exportable_items(LOCAL_CRATE);
1140 tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
1141 tcx.par_hir_for_each_module(|module| {
1142 tcx.ensure_ok().check_mod_attrs(module);
1143 tcx.ensure_ok().check_mod_unstable_api_usage(module);
1144 });
1145 },
1146 &mut || {
1147 tcx.ensure_ok().limits(());
1152 },
1153 ]);
1154 });
1155
1156 sess.time("emit_ast_lowering_delayed_lints", || {
1157 emit_delayed_lints(tcx);
1158 });
1159
1160 rustc_hir_analysis::check_crate(tcx);
1161 tcx.untracked().definitions.freeze();
1167
1168 sess.time("MIR_borrow_checking", || {
1169 tcx.par_hir_body_owners(|def_id| {
1170 let not_typeck_child = !tcx.is_typeck_child(def_id.to_def_id());
1171 if not_typeck_child {
1172 tcx.ensure_ok().check_unsafety(def_id);
1174 }
1175 if tcx.is_trivial_const(def_id) {
1176 return;
1177 }
1178 if not_typeck_child {
1179 tcx.ensure_ok().mir_borrowck(def_id);
1180 tcx.ensure_ok().check_transmutes(def_id);
1181 if !tcx.sess.opts.unstable_opts.offload.is_empty() {
1182 tcx.ensure_ok().check_offloads(def_id);
1183 }
1184 }
1185 tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1186 tcx.ensure_ok().check_liveness(def_id);
1187
1188 if tcx.sess.opts.output_types.should_codegen()
1192 || tcx.hir_body_const_context(def_id).is_some()
1193 {
1194 tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1195 }
1196 if tcx.is_coroutine(def_id.to_def_id())
1197 && (!tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()))
1198 {
1199 tcx.ensure_ok()
1201 .layout_of(ty::TypingEnv::codegen(tcx, def_id.to_def_id()).as_query_input(
1202 tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
1203 ));
1204 }
1205 });
1206 });
1207
1208 sess.time("layout_testing", || layout_test::test_layout(tcx));
1209 sess.time("abi_testing", || abi_test::test_abi(tcx));
1210}
1211
1212fn analysis(tcx: TyCtxt<'_>, (): ()) {
1215 run_required_analyses(tcx);
1216
1217 let sess = tcx.sess;
1218
1219 if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1228 guar.raise_fatal();
1229 }
1230
1231 sess.time("misc_checking_3", || {
1232 par_fns(&mut [
1233 &mut || {
1234 tcx.ensure_ok().effective_visibilities(());
1235
1236 par_fns(&mut [
1237 &mut || {
1238 tcx.par_hir_for_each_module(|module| {
1239 tcx.ensure_ok().check_private_in_public(module)
1240 })
1241 },
1242 &mut || {
1243 tcx.par_hir_for_each_module(|module| {
1244 tcx.ensure_ok().check_mod_deathness(module)
1245 });
1246 },
1247 &mut || {
1248 sess.time("lint_checking", || {
1249 rustc_lint::check_crate(tcx);
1250 });
1251 },
1252 &mut || {
1253 tcx.ensure_ok().clashing_extern_declarations(());
1254 },
1255 ]);
1256 },
1257 &mut || {
1258 sess.time("privacy_checking_modules", || {
1259 tcx.par_hir_for_each_module(|module| {
1260 tcx.ensure_ok().check_mod_privacy(module);
1261 });
1262 });
1263 },
1264 ]);
1265
1266 sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1269
1270 let _ = tcx.all_diagnostic_items(());
1274
1275 let _ = tcx.all_canonical_symbols(());
1279 });
1280
1281 if tcx.sess.opts.unstable_opts.validate_mir {
1288 sess.time("ensuring_final_MIR_is_computable", || {
1289 tcx.par_hir_body_owners(|def_id| {
1290 if !tcx.is_trivial_const(def_id) {
1291 tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1292 }
1293 });
1294 });
1295 }
1296}
1297
1298pub(crate) fn start_codegen<'tcx>(
1301 codegen_backend: &dyn CodegenBackend,
1302 tcx: TyCtxt<'tcx>,
1303) -> (Box<dyn Any>, CrateInfo, EncodedMetadata) {
1304 tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen);
1305
1306 if let Some((def_id, _)) = tcx.entry_fn(())
1308 && {
{
'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)
1309 {
1310 tcx.ensure_ok().trigger_delayed_bug(def_id);
1311 }
1312
1313 if tcx.sess.opts.output_types.should_codegen() {
1316 rustc_symbol_mangling::test::dump_symbol_names_and_def_paths(tcx);
1317 }
1318
1319 if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
1323 guar.raise_fatal();
1324 }
1325
1326 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_interface/src/passes.rs:1326",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(1326u32),
::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());
1327
1328 let metadata = match rustc_metadata::fs::encode_and_write_metadata(tcx) {
1329 Ok(metadata) => metadata,
1330 Err(guar) => guar.raise_fatal(),
1331 };
1332
1333 let is_host_metadata = tcx
1334 .sess
1335 .opts
1336 .unstable_opts
1337 .offload
1338 .iter()
1339 .any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
rustc_session::config::Offload::HostMetadata(_) => true,
_ => false,
}matches!(o, rustc_session::config::Offload::HostMetadata(_)));
1340
1341 let codegen = tcx.sess.time("codegen_crate", || {
1342 if tcx.sess.opts.unstable_opts.no_codegen
1343 || !tcx.sess.opts.output_types.should_codegen()
1344 || is_host_metadata
1345 {
1346 tcx.sess.dcx().abort_if_errors();
1347
1348 if is_host_metadata {
1349 rustc_monomorphize::write_host_metadata_offload_manifest(tcx);
1350 }
1351
1352 Box::new(CompiledModules { modules: ::alloc::vec::Vec::new()vec![], allocator_module: None })
1354 } else {
1355 codegen_backend.codegen_crate(tcx)
1356 }
1357 });
1358
1359 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_interface/src/passes.rs:1359",
"rustc_interface::passes", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_interface/src/passes.rs"),
::tracing_core::__macro_support::Option::Some(1359u32),
::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());
1360
1361 if tcx.sess.opts.unstable_opts.print_type_sizes {
1364 tcx.sess.code_stats.print_type_sizes();
1365 }
1366
1367 let crate_info = CrateInfo::new(tcx, codegen_backend.target_cpu(tcx.sess));
1368
1369 (codegen, crate_info, metadata)
1370}
1371
1372pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1374 let attr_crate_name =
1382 parse_crate_name(sess, krate_attrs, ShouldEmit::EarlyFatal { also_emit_lints: true });
1383
1384 let validate = |name, span| {
1385 rustc_session::output::validate_crate_name(sess, name, span);
1386 name
1387 };
1388
1389 if let Some(crate_name) = &sess.opts.crate_name {
1390 let crate_name = Symbol::intern(crate_name);
1391 if let Some((attr_crate_name, span)) = attr_crate_name
1392 && attr_crate_name != crate_name
1393 {
1394 sess.dcx().emit_err(diagnostics::CrateNameDoesNotMatch {
1395 span,
1396 crate_name,
1397 attr_crate_name,
1398 });
1399 }
1400 return validate(crate_name, None);
1401 }
1402
1403 if let Some((crate_name, span)) = attr_crate_name {
1404 return validate(crate_name, Some(span));
1405 }
1406
1407 if let Input::File(ref path) = sess.io.input
1408 && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1409 {
1410 if file_stem.starts_with('-') {
1411 sess.dcx().emit_err(diagnostics::CrateNameInvalid { crate_name: file_stem });
1412 } else {
1413 return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1414 }
1415 }
1416
1417 sym::rust_out
1418}
1419
1420pub(crate) fn parse_crate_name(
1421 sess: &Session,
1422 attrs: &[ast::Attribute],
1423 emit_errors: ShouldEmit,
1424) -> Option<(Symbol, Span)> {
1425 let Attribute::Parsed(AttributeKind::CrateName { name, name_span, .. }) =
1426 AttributeParser::parse_limited_sym_should_emit(
1427 sess,
1428 attrs,
1429 &[sym::crate_name],
1430 DUMMY_SP,
1431 None,
1432 emit_errors,
1433 )?
1434 else {
1435 {
::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");
1436 };
1437
1438 Some((name, name_span))
1439}
1440
1441pub fn collect_crate_types(
1442 session: &Session,
1443 backend_crate_types: &[CrateType],
1444 codegen_backend_name: &'static str,
1445 attrs: &[ast::Attribute],
1446 crate_span: Span,
1447) -> Vec<CrateType> {
1448 if session.opts.test {
1451 if !session.target.executables {
1452 session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForTarget {
1453 crate_type: CrateType::Executable,
1454 target_triple: &session.opts.target_triple,
1455 });
1456 return Vec::new();
1457 }
1458 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];
1459 }
1460
1461 if session.opts.unstable_opts.build_sdylib_interface {
1463 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];
1464 }
1465
1466 #[allow(rustc::bad_opt_access)]
1471 let mut base = session.opts.crate_types.clone();
1472 if base.is_empty() {
1473 if let Some(Attribute::Parsed(AttributeKind::CrateType(crate_type))) =
1474 AttributeParser::parse_limited_sym_should_emit(
1475 session,
1476 attrs,
1477 &[sym::crate_type],
1478 crate_span,
1479 None,
1480 ShouldEmit::EarlyFatal { also_emit_lints: false },
1481 )
1482 {
1483 base.extend(crate_type);
1484 }
1485
1486 if base.is_empty() {
1487 base.push(default_output_for_target(session));
1488 } else {
1489 base.sort();
1490 base.dedup();
1491 }
1492 }
1493
1494 base.retain(|crate_type| {
1495 if invalid_output_for_target(session, *crate_type) {
1496 session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForTarget {
1497 crate_type: *crate_type,
1498 target_triple: &session.opts.target_triple,
1499 });
1500 false
1501 } else if !backend_crate_types.contains(crate_type) {
1502 session.dcx().emit_warn(diagnostics::UnsupportedCrateTypeForCodegenBackend {
1503 crate_type: *crate_type,
1504 codegen_backend: codegen_backend_name,
1505 });
1506 false
1507 } else {
1508 true
1509 }
1510 });
1511
1512 base
1513}
1514
1515fn default_output_for_target(sess: &Session) -> CrateType {
1525 if !sess.target.executables { CrateType::StaticLib } else { CrateType::Executable }
1526}