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_codegen_ssa::traits::CodegenBackend;
10use rustc_data_structures::jobserver::Proxy;
11use rustc_data_structures::steal::Steal;
12use rustc_data_structures::sync::{AppendOnlyIndexVec, FreezeLock, WorkerLocal};
13use rustc_data_structures::{parallel, thousands};
14use rustc_errors::timings::TimingSection;
15use rustc_expand::base::{ExtCtxt, LintStoreExpand};
16use rustc_feature::Features;
17use rustc_fs_util::try_canonicalize;
18use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap};
19use rustc_hir::definitions::Definitions;
20use rustc_incremental::setup_dep_graph;
21use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore, unerased_lint_store};
22use rustc_metadata::EncodedMetadata;
23use rustc_metadata::creader::CStore;
24use rustc_middle::arena::Arena;
25use rustc_middle::dep_graph::DepsType;
26use rustc_middle::ty::{self, CurrentGcx, GlobalCtxt, RegisteredTools, TyCtxt};
27use rustc_middle::util::Providers;
28use rustc_parse::{
29 new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal, validate_attr,
30};
31use rustc_passes::{abi_test, input_stats, layout_test};
32use rustc_resolve::Resolver;
33use rustc_session::config::{CrateType, Input, OutFileName, OutputFilenames, OutputType};
34use rustc_session::cstore::Untracked;
35use rustc_session::output::{collect_crate_types, filename_for_input};
36use rustc_session::parse::feature_err;
37use rustc_session::search_paths::PathKind;
38use rustc_session::{Limit, Session};
39use rustc_span::{
40 DUMMY_SP, ErrorGuaranteed, ExpnKind, FileName, SourceFileHash, SourceFileHashAlgorithm, Span,
41 Symbol, sym,
42};
43use rustc_target::spec::PanicStrategy;
44use rustc_trait_selection::traits;
45use tracing::{info, instrument};
46
47use crate::interface::Compiler;
48use crate::{errors, limits, proc_macro_decls, util};
49
50pub fn parse<'a>(sess: &'a Session) -> ast::Crate {
51 let mut krate = sess
52 .time("parse_crate", || {
53 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
54 Input::File(file) => new_parser_from_file(&sess.psess, file, None),
55 Input::Str { input, name } => {
56 new_parser_from_source_str(&sess.psess, name.clone(), input.clone())
57 }
58 });
59 parser.parse_crate_mod()
60 })
61 .unwrap_or_else(|parse_error| {
62 let guar: ErrorGuaranteed = parse_error.emit();
63 guar.raise_fatal();
64 });
65
66 rustc_builtin_macros::cmdline_attrs::inject(
67 &mut krate,
68 &sess.psess,
69 &sess.opts.unstable_opts.crate_attr,
70 );
71
72 krate
73}
74
75fn pre_expansion_lint<'a>(
76 sess: &Session,
77 features: &Features,
78 lint_store: &LintStore,
79 registered_tools: &RegisteredTools,
80 check_node: impl EarlyCheckNode<'a>,
81 node_name: Symbol,
82) {
83 sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
84 || {
85 rustc_lint::check_ast_node(
86 sess,
87 None,
88 features,
89 true,
90 lint_store,
91 registered_tools,
92 None,
93 rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
94 check_node,
95 );
96 },
97 );
98}
99
100struct LintStoreExpandImpl<'a>(&'a LintStore);
102
103impl LintStoreExpand for LintStoreExpandImpl<'_> {
104 fn pre_expansion_lint(
105 &self,
106 sess: &Session,
107 features: &Features,
108 registered_tools: &RegisteredTools,
109 node_id: ast::NodeId,
110 attrs: &[ast::Attribute],
111 items: &[rustc_ast::ptr::P<ast::Item>],
112 name: Symbol,
113 ) {
114 pre_expansion_lint(sess, features, self.0, registered_tools, (node_id, attrs, items), name);
115 }
116}
117
118#[instrument(level = "trace", skip(krate, resolver))]
123fn configure_and_expand(
124 mut krate: ast::Crate,
125 pre_configured_attrs: &[ast::Attribute],
126 resolver: &mut Resolver<'_, '_>,
127) -> ast::Crate {
128 let tcx = resolver.tcx();
129 let sess = tcx.sess;
130 let features = tcx.features();
131 let lint_store = unerased_lint_store(tcx.sess);
132 let crate_name = tcx.crate_name(LOCAL_CRATE);
133 let lint_check_node = (&krate, pre_configured_attrs);
134 pre_expansion_lint(
135 sess,
136 features,
137 lint_store,
138 tcx.registered_tools(()),
139 lint_check_node,
140 crate_name,
141 );
142 rustc_builtin_macros::register_builtin_macros(resolver);
143
144 let num_standard_library_imports = sess.time("crate_injection", || {
145 rustc_builtin_macros::standard_library_imports::inject(
146 &mut krate,
147 pre_configured_attrs,
148 resolver,
149 sess,
150 features,
151 )
152 });
153
154 util::check_attr_crate_type(sess, pre_configured_attrs, resolver.lint_buffer());
155
156 krate = sess.time("macro_expand_crate", || {
158 let mut old_path = OsString::new();
172 if cfg!(windows) {
173 old_path = env::var_os("PATH").unwrap_or(old_path);
174 let mut new_path = Vec::from_iter(
175 sess.host_filesearch().search_paths(PathKind::All).map(|p| p.dir.clone()),
176 );
177 for path in env::split_paths(&old_path) {
178 if !new_path.contains(&path) {
179 new_path.push(path);
180 }
181 }
182 unsafe {
183 env::set_var(
184 "PATH",
185 &env::join_paths(
186 new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
187 )
188 .unwrap(),
189 );
190 }
191 }
192
193 let recursion_limit = get_recursion_limit(pre_configured_attrs, sess);
195 let cfg = rustc_expand::expand::ExpansionConfig {
196 crate_name,
197 features,
198 recursion_limit,
199 trace_mac: sess.opts.unstable_opts.trace_macros,
200 should_test: sess.is_test_crate(),
201 span_debug: sess.opts.unstable_opts.span_debug,
202 proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
203 };
204
205 let lint_store = LintStoreExpandImpl(lint_store);
206 let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
207 ecx.num_standard_library_imports = num_standard_library_imports;
208 let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
210
211 sess.psess.buffered_lints.with_lock(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
214 buffered_lints.append(&mut ecx.buffered_early_lint);
215 });
216
217 sess.time("check_unused_macros", || {
218 ecx.check_unused_macros();
219 });
220
221 if ecx.reduced_recursion_limit.is_some() {
224 sess.dcx().abort_if_errors();
225 unreachable!();
226 }
227
228 if cfg!(windows) {
229 unsafe {
230 env::set_var("PATH", &old_path);
231 }
232 }
233
234 if ecx.sess.opts.unstable_opts.macro_stats {
235 print_macro_stats(&ecx);
236 }
237
238 krate
239 });
240
241 sess.time("maybe_building_test_harness", || {
242 rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
243 });
244
245 let has_proc_macro_decls = sess.time("AST_validation", || {
246 rustc_ast_passes::ast_validation::check_crate(
247 sess,
248 features,
249 &krate,
250 tcx.is_sdylib_interface_build(),
251 resolver.lint_buffer(),
252 )
253 });
254
255 let crate_types = tcx.crate_types();
256 let is_executable_crate = crate_types.contains(&CrateType::Executable);
257 let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
258
259 if crate_types.len() > 1 {
260 if is_executable_crate {
261 sess.dcx().emit_err(errors::MixedBinCrate);
262 }
263 if is_proc_macro_crate {
264 sess.dcx().emit_err(errors::MixedProcMacroCrate);
265 }
266 }
267 if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() {
268 feature_err(sess, sym::export_stable, DUMMY_SP, "`sdylib` crate type is unstable").emit();
269 }
270
271 if is_proc_macro_crate && sess.panic_strategy() == PanicStrategy::Abort {
272 sess.dcx().emit_warn(errors::ProcMacroCratePanicAbort);
273 }
274
275 sess.time("maybe_create_a_macro_crate", || {
276 let is_test_crate = sess.is_test_crate();
277 rustc_builtin_macros::proc_macro_harness::inject(
278 &mut krate,
279 sess,
280 features,
281 resolver,
282 is_proc_macro_crate,
283 has_proc_macro_decls,
284 is_test_crate,
285 sess.dcx(),
286 )
287 });
288
289 resolver.resolve_crate(&krate);
292
293 CStore::from_tcx(tcx).report_incompatible_target_modifiers(tcx, &krate);
294 CStore::from_tcx(tcx).report_incompatible_async_drop_feature(tcx, &krate);
295 krate
296}
297
298fn print_macro_stats(ecx: &ExtCtxt<'_>) {
299 use std::fmt::Write;
300
301 let crate_name = ecx.ecfg.crate_name.as_str();
302 let crate_name = if crate_name == "build_script_build" {
303 let pkg_name =
305 std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "<unknown crate>".to_string());
306 format!("{pkg_name} build script")
307 } else {
308 crate_name.to_string()
309 };
310
311 #[allow(rustc::potential_query_instability)]
313 let mut macro_stats: Vec<_> = ecx
314 .macro_stats
315 .iter()
316 .map(|((name, kind), stat)| {
317 (stat.bytes, stat.lines, stat.uses, name, *kind)
319 })
320 .collect();
321 macro_stats.sort_unstable();
322 macro_stats.reverse(); let prefix = "macro-stats";
325 let name_w = 32;
326 let uses_w = 7;
327 let lines_w = 11;
328 let avg_lines_w = 11;
329 let bytes_w = 11;
330 let avg_bytes_w = 11;
331 let banner_w = name_w + uses_w + lines_w + avg_lines_w + bytes_w + avg_bytes_w;
332
333 let mut s = String::new();
339 _ = writeln!(s, "{prefix} {}", "=".repeat(banner_w));
340 _ = writeln!(s, "{prefix} MACRO EXPANSION STATS: {}", crate_name);
341 _ = writeln!(
342 s,
343 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
344 "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
345 );
346 _ = writeln!(s, "{prefix} {}", "-".repeat(banner_w));
347 if macro_stats.is_empty() {
350 _ = writeln!(s, "{prefix} (none)");
351 }
352 for (bytes, lines, uses, name, kind) in macro_stats {
353 let mut name = ExpnKind::Macro(kind, *name).descr();
354 let uses_with_underscores = thousands::usize_with_underscores(uses);
355 let avg_lines = lines as f64 / uses as f64;
356 let avg_bytes = bytes as f64 / uses as f64;
357
358 let mut uses_w = uses_w;
360 if name.len() + uses_with_underscores.len() >= name_w + uses_w {
361 _ = writeln!(s, "{prefix} {:<name_w$}", name);
365 name = String::new();
366 } else if name.len() >= name_w {
367 uses_w = uses_with_underscores.len() + 1
371 };
372
373 _ = writeln!(
374 s,
375 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
376 name,
377 uses_with_underscores,
378 thousands::usize_with_underscores(lines),
379 thousands::f64p1_with_underscores(avg_lines),
380 thousands::usize_with_underscores(bytes),
381 thousands::f64p1_with_underscores(avg_bytes),
382 );
383 }
384 _ = writeln!(s, "{prefix} {}", "=".repeat(banner_w));
385 eprint!("{s}");
386}
387
388fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
389 let sess = tcx.sess;
390 let (resolver, krate) = &*tcx.resolver_for_lowering().borrow();
391 let mut lint_buffer = resolver.lint_buffer.steal();
392
393 if sess.opts.unstable_opts.input_stats {
394 input_stats::print_ast_stats(tcx, krate);
395 }
396
397 sess.time("complete_gated_feature_checking", || {
399 rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
400 });
401
402 sess.psess.buffered_lints.with_lock(|buffered_lints| {
404 info!("{} parse sess buffered_lints", buffered_lints.len());
405 for early_lint in buffered_lints.drain(..) {
406 lint_buffer.add_early_lint(early_lint);
407 }
408 });
409
410 sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
412 for (ident, mut spans) in identifiers.drain(..) {
413 spans.sort();
414 if ident == sym::ferris {
415 enum FerrisFix {
416 SnakeCase,
417 ScreamingSnakeCase,
418 PascalCase,
419 }
420
421 impl FerrisFix {
422 const fn as_str(self) -> &'static str {
423 match self {
424 FerrisFix::SnakeCase => "ferris",
425 FerrisFix::ScreamingSnakeCase => "FERRIS",
426 FerrisFix::PascalCase => "Ferris",
427 }
428 }
429 }
430
431 let first_span = spans[0];
432 let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
433 let ferris_fix = prev_source
434 .map_or(FerrisFix::SnakeCase, |source| {
435 let mut source_before_ferris = source.trim_end().split_whitespace().rev();
436 match source_before_ferris.next() {
437 Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
438 FerrisFix::PascalCase
439 }
440 Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
441 Some("mut") if source_before_ferris.next() == Some("static") => {
442 FerrisFix::ScreamingSnakeCase
443 }
444 _ => FerrisFix::SnakeCase,
445 }
446 })
447 .as_str();
448
449 sess.dcx().emit_err(errors::FerrisIdentifier { spans, first_span, ferris_fix });
450 } else {
451 sess.dcx().emit_err(errors::EmojiIdentifier { spans, ident });
452 }
453 }
454 });
455
456 let lint_store = unerased_lint_store(tcx.sess);
457 rustc_lint::check_ast_node(
458 sess,
459 Some(tcx),
460 tcx.features(),
461 false,
462 lint_store,
463 tcx.registered_tools(()),
464 Some(lint_buffer),
465 rustc_lint::BuiltinCombinedEarlyLintPass::new(),
466 (&**krate, &*krate.attrs),
467 )
468}
469
470fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
471 let value = env::var_os(key);
472
473 let value_tcx = value.as_ref().map(|value| {
474 let encoded_bytes = tcx.arena.alloc_slice(value.as_encoded_bytes());
475 debug_assert_eq!(value.as_encoded_bytes(), encoded_bytes);
476 unsafe { OsStr::from_encoded_bytes_unchecked(encoded_bytes) }
480 });
481
482 tcx.sess.psess.env_depinfo.borrow_mut().insert((
488 Symbol::intern(&key.to_string_lossy()),
489 value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(&value)),
490 ));
491
492 value_tcx
493}
494
495fn generated_output_paths(
497 tcx: TyCtxt<'_>,
498 outputs: &OutputFilenames,
499 exact_name: bool,
500 crate_name: Symbol,
501) -> Vec<PathBuf> {
502 let sess = tcx.sess;
503 let mut out_filenames = Vec::new();
504 for output_type in sess.opts.output_types.keys() {
505 let out_filename = outputs.path(*output_type);
506 let file = out_filename.as_path().to_path_buf();
507 match *output_type {
508 OutputType::Exe if !exact_name => {
511 for crate_type in tcx.crate_types().iter() {
512 let p = filename_for_input(sess, *crate_type, crate_name, outputs);
513 out_filenames.push(p.as_path().to_path_buf());
514 }
515 }
516 OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
517 }
519 OutputType::DepInfo if out_filename.is_stdout() => {
520 }
522 _ => {
523 out_filenames.push(file);
524 }
525 }
526 }
527 out_filenames
528}
529
530fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
531 let input_path = try_canonicalize(input_path).ok();
532 if input_path.is_none() {
533 return false;
534 }
535 output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
536}
537
538fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
539 output_paths.iter().find(|output_path| output_path.is_dir())
540}
541
542fn escape_dep_filename(filename: &str) -> String {
543 filename.replace(' ', "\\ ")
546}
547
548fn escape_dep_env(symbol: Symbol) -> String {
551 let s = symbol.as_str();
552 let mut escaped = String::with_capacity(s.len());
553 for c in s.chars() {
554 match c {
555 '\n' => escaped.push_str(r"\n"),
556 '\r' => escaped.push_str(r"\r"),
557 '\\' => escaped.push_str(r"\\"),
558 _ => escaped.push(c),
559 }
560 }
561 escaped
562}
563
564fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
565 let sess = tcx.sess;
567 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
568 return;
569 }
570 let deps_output = outputs.path(OutputType::DepInfo);
571 let deps_filename = deps_output.as_path();
572
573 let result: io::Result<()> = try {
574 let mut files: Vec<(String, u64, Option<SourceFileHash>)> = sess
577 .source_map()
578 .files()
579 .iter()
580 .filter(|fmap| fmap.is_real_file())
581 .filter(|fmap| !fmap.is_imported())
582 .map(|fmap| {
583 (
584 escape_dep_filename(&fmap.name.prefer_local().to_string()),
585 fmap.source_len.0 as u64,
586 fmap.checksum_hash,
587 )
588 })
589 .collect();
590
591 let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
592
593 let file_depinfo = sess.psess.file_depinfo.borrow();
596
597 let normalize_path = |path: PathBuf| {
598 let file = FileName::from(path);
599 escape_dep_filename(&file.prefer_local().to_string())
600 };
601
602 fn hash_iter_files<P: AsRef<Path>>(
605 it: impl Iterator<Item = P>,
606 checksum_hash_algo: Option<SourceFileHashAlgorithm>,
607 ) -> impl Iterator<Item = (P, u64, Option<SourceFileHash>)> {
608 it.map(move |path| {
609 match checksum_hash_algo.and_then(|algo| {
610 fs::File::open(path.as_ref())
611 .and_then(|mut file| {
612 SourceFileHash::new(algo, &mut file).map(|h| (file, h))
613 })
614 .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
615 .map_err(|e| {
616 tracing::error!(
617 "failed to compute checksum, omitting it from dep-info {} {e}",
618 path.as_ref().display()
619 )
620 })
621 .ok()
622 }) {
623 Some((file_len, checksum)) => (path, file_len, Some(checksum)),
624 None => (path, 0, None),
625 }
626 })
627 }
628
629 let extra_tracked_files = hash_iter_files(
630 file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
631 checksum_hash_algo,
632 );
633 files.extend(extra_tracked_files);
634
635 if let Some(ref profile_instr) = sess.opts.cg.profile_use {
637 files.extend(hash_iter_files(
638 iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
639 checksum_hash_algo,
640 ));
641 }
642 if let Some(ref profile_sample) = sess.opts.unstable_opts.profile_sample_use {
643 files.extend(hash_iter_files(
644 iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
645 checksum_hash_algo,
646 ));
647 }
648
649 for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
651 files.extend(hash_iter_files(
652 iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
653 checksum_hash_algo,
654 ));
655 }
656
657 if sess.binary_dep_depinfo() {
658 if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
659 if backend.contains('.') {
660 files.extend(hash_iter_files(
663 iter::once(backend.to_string()),
664 checksum_hash_algo,
665 ));
666 }
667 }
668
669 for &cnum in tcx.crates(()) {
670 let source = tcx.used_crate_source(cnum);
671 if let Some((path, _)) = &source.dylib {
672 files.extend(hash_iter_files(
673 iter::once(escape_dep_filename(&path.display().to_string())),
674 checksum_hash_algo,
675 ));
676 }
677 if let Some((path, _)) = &source.rlib {
678 files.extend(hash_iter_files(
679 iter::once(escape_dep_filename(&path.display().to_string())),
680 checksum_hash_algo,
681 ));
682 }
683 if let Some((path, _)) = &source.rmeta {
684 files.extend(hash_iter_files(
685 iter::once(escape_dep_filename(&path.display().to_string())),
686 checksum_hash_algo,
687 ));
688 }
689 }
690 }
691
692 let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
693 for path in out_filenames {
694 writeln!(
695 file,
696 "{}: {}\n",
697 path.display(),
698 files
699 .iter()
700 .map(|(path, _file_len, _checksum_hash_algo)| path.as_str())
701 .intersperse(" ")
702 .collect::<String>()
703 )?;
704 }
705
706 for (path, _file_len, _checksum_hash_algo) in &files {
710 writeln!(file, "{path}:")?;
711 }
712
713 let env_depinfo = sess.psess.env_depinfo.borrow();
715 if !env_depinfo.is_empty() {
716 #[allow(rustc::potential_query_instability)]
718 let mut envs: Vec<_> = env_depinfo
719 .iter()
720 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
721 .collect();
722 envs.sort_unstable();
723 writeln!(file)?;
724 for (k, v) in envs {
725 write!(file, "# env-dep:{k}")?;
726 if let Some(v) = v {
727 write!(file, "={v}")?;
728 }
729 writeln!(file)?;
730 }
731 }
732
733 if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
736 files
737 .iter()
738 .filter_map(|(path, file_len, hash_algo)| {
739 hash_algo.map(|hash_algo| (path, file_len, hash_algo))
740 })
741 .try_for_each(|(path, file_len, checksum_hash)| {
742 writeln!(file, "# checksum:{checksum_hash} file_len:{file_len} {path}")
743 })?;
744 }
745
746 Ok(())
747 };
748
749 match deps_output {
750 OutFileName::Stdout => {
751 let mut file = BufWriter::new(io::stdout());
752 write_deps_to_file(&mut file)?;
753 }
754 OutFileName::Real(ref path) => {
755 let mut file = fs::File::create_buffered(path)?;
756 write_deps_to_file(&mut file)?;
757 }
758 }
759 };
760
761 match result {
762 Ok(_) => {
763 if sess.opts.json_artifact_notifications {
764 sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
765 }
766 }
767 Err(error) => {
768 sess.dcx().emit_fatal(errors::ErrorWritingDependencies { path: deps_filename, error });
769 }
770 }
771}
772
773fn resolver_for_lowering_raw<'tcx>(
774 tcx: TyCtxt<'tcx>,
775 (): (),
776) -> (&'tcx Steal<(ty::ResolverAstLowering, Arc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
777 let arenas = Resolver::arenas();
778 let _ = tcx.registered_tools(()); let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
780 let mut resolver = Resolver::new(
781 tcx,
782 &pre_configured_attrs,
783 krate.spans.inner_span,
784 krate.spans.inject_use_span,
785 &arenas,
786 );
787 let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
788
789 tcx.untracked().cstore.freeze();
791
792 let ty::ResolverOutputs {
793 global_ctxt: untracked_resolutions,
794 ast_lowering: untracked_resolver_for_lowering,
795 } = resolver.into_outputs();
796
797 let resolutions = tcx.arena.alloc(untracked_resolutions);
798 (tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Arc::new(krate)))), resolutions)
799}
800
801pub fn write_dep_info(tcx: TyCtxt<'_>) {
802 let _ = tcx.resolver_for_lowering();
806
807 let sess = tcx.sess;
808 let _timer = sess.timer("write_dep_info");
809 let crate_name = tcx.crate_name(LOCAL_CRATE);
810
811 let outputs = tcx.output_filenames(());
812 let output_paths =
813 generated_output_paths(tcx, &outputs, sess.io.output_file.is_some(), crate_name);
814
815 if let Some(input_path) = sess.io.input.opt_path() {
817 if sess.opts.will_create_output_file() {
818 if output_contains_path(&output_paths, input_path) {
819 sess.dcx().emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path });
820 }
821 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
822 sess.dcx().emit_fatal(errors::GeneratedFileConflictsWithDirectory {
823 input_path,
824 dir_path,
825 });
826 }
827 }
828 }
829
830 if let Some(ref dir) = sess.io.temps_dir {
831 if fs::create_dir_all(dir).is_err() {
832 sess.dcx().emit_fatal(errors::TempsDirError);
833 }
834 }
835
836 write_out_deps(tcx, &outputs, &output_paths);
837
838 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
839 && sess.opts.output_types.len() == 1;
840
841 if !only_dep_info {
842 if let Some(ref dir) = sess.io.output_dir {
843 if fs::create_dir_all(dir).is_err() {
844 sess.dcx().emit_fatal(errors::OutDirError);
845 }
846 }
847 }
848}
849
850pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
851 if !tcx.crate_types().contains(&rustc_session::config::CrateType::Sdylib) {
852 return;
853 }
854 let _timer = tcx.sess.timer("write_interface");
855 let (_, krate) = &*tcx.resolver_for_lowering().borrow();
856
857 let krate = rustc_ast_pretty::pprust::print_crate_as_interface(
858 krate,
859 tcx.sess.psess.edition,
860 &tcx.sess.psess.attr_id_generator,
861 );
862 let export_output = tcx.output_filenames(()).interface_path();
863 let mut file = fs::File::create_buffered(export_output).unwrap();
864 if let Err(err) = write!(file, "{}", krate) {
865 tcx.dcx().fatal(format!("error writing interface file: {}", err));
866 }
867}
868
869pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
870 let providers = &mut Providers::default();
871 providers.analysis = analysis;
872 providers.hir_crate = rustc_ast_lowering::lower_to_hir;
873 providers.resolver_for_lowering_raw = resolver_for_lowering_raw;
874 providers.stripped_cfg_items = |tcx, _| &tcx.resolutions(()).stripped_cfg_items[..];
875 providers.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
876 providers.early_lint_checks = early_lint_checks;
877 providers.env_var_os = env_var_os;
878 limits::provide(providers);
879 proc_macro_decls::provide(providers);
880 rustc_const_eval::provide(providers);
881 rustc_middle::hir::provide(providers);
882 rustc_borrowck::provide(providers);
883 rustc_incremental::provide(providers);
884 rustc_mir_build::provide(providers);
885 rustc_mir_transform::provide(providers);
886 rustc_monomorphize::provide(providers);
887 rustc_privacy::provide(providers);
888 rustc_query_impl::provide(providers);
889 rustc_resolve::provide(providers);
890 rustc_hir_analysis::provide(providers);
891 rustc_hir_typeck::provide(providers);
892 ty::provide(providers);
893 traits::provide(providers);
894 rustc_passes::provide(providers);
895 rustc_traits::provide(providers);
896 rustc_ty_utils::provide(providers);
897 rustc_metadata::provide(providers);
898 rustc_lint::provide(providers);
899 rustc_symbol_mangling::provide(providers);
900 rustc_codegen_ssa::provide(providers);
901 *providers
902});
903
904pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
905 compiler: &Compiler,
906 krate: rustc_ast::Crate,
907 f: F,
908) -> T {
909 let sess = &compiler.sess;
910
911 let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
912
913 let crate_name = get_crate_name(sess, &pre_configured_attrs);
914 let crate_types = collect_crate_types(sess, &pre_configured_attrs);
915 let stable_crate_id = StableCrateId::new(
916 crate_name,
917 crate_types.contains(&CrateType::Executable),
918 sess.opts.cg.metadata.clone(),
919 sess.cfg_version,
920 );
921
922 let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
923
924 let dep_type = DepsType { dep_names: rustc_query_impl::dep_kind_names() };
925 let dep_graph = setup_dep_graph(sess, crate_name, &dep_type);
926
927 let cstore =
928 FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
929 let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
930
931 let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
932 let untracked =
933 Untracked { cstore, source_span: AppendOnlyIndexVec::new(), definitions, stable_crate_ids };
934
935 dep_graph.assert_ignored();
939
940 let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess);
941
942 let codegen_backend = &compiler.codegen_backend;
943 let mut providers = *DEFAULT_QUERY_PROVIDERS;
944 codegen_backend.provide(&mut providers);
945
946 if let Some(callback) = compiler.override_queries {
947 callback(sess, &mut providers);
948 }
949
950 let incremental = dep_graph.is_fully_enabled();
951
952 let gcx_cell = OnceLock::new();
953 let arena = WorkerLocal::new(|_| Arena::default());
954 let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
955
956 let inner: Box<
959 dyn for<'tcx> FnOnce(
960 &'tcx Session,
961 CurrentGcx,
962 Arc<Proxy>,
963 &'tcx OnceLock<GlobalCtxt<'tcx>>,
964 &'tcx WorkerLocal<Arena<'tcx>>,
965 &'tcx WorkerLocal<rustc_hir::Arena<'tcx>>,
966 F,
967 ) -> T,
968 > = Box::new(move |sess, current_gcx, jobserver_proxy, gcx_cell, arena, hir_arena, f| {
969 TyCtxt::create_global_ctxt(
970 gcx_cell,
971 sess,
972 crate_types,
973 stable_crate_id,
974 arena,
975 hir_arena,
976 untracked,
977 dep_graph,
978 rustc_query_impl::query_callbacks(arena),
979 rustc_query_impl::query_system(
980 providers.queries,
981 providers.extern_queries,
982 query_result_on_disk_cache,
983 incremental,
984 ),
985 providers.hooks,
986 current_gcx,
987 jobserver_proxy,
988 |tcx| {
989 let feed = tcx.create_crate_num(stable_crate_id).unwrap();
990 assert_eq!(feed.key(), LOCAL_CRATE);
991 feed.crate_name(crate_name);
992
993 let feed = tcx.feed_unit_query();
994 feed.features_query(tcx.arena.alloc(rustc_expand::config::features(
995 tcx.sess,
996 &pre_configured_attrs,
997 crate_name,
998 )));
999 feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
1000 feed.output_filenames(Arc::new(outputs));
1001
1002 let res = f(tcx);
1003 tcx.finish();
1005 res
1006 },
1007 )
1008 });
1009
1010 inner(
1011 &compiler.sess,
1012 compiler.current_gcx.clone(),
1013 Arc::clone(&compiler.jobserver_proxy),
1014 &gcx_cell,
1015 &arena,
1016 &hir_arena,
1017 f,
1018 )
1019}
1020
1021fn run_required_analyses(tcx: TyCtxt<'_>) {
1024 if tcx.sess.opts.unstable_opts.input_stats {
1025 rustc_passes::input_stats::print_hir_stats(tcx);
1026 }
1027 #[cfg(all(not(doc), debug_assertions))]
1030 rustc_passes::hir_id_validator::check_crate(tcx);
1031
1032 tcx.ensure_done().hir_crate_items(());
1036
1037 let sess = tcx.sess;
1038 sess.time("misc_checking_1", || {
1039 parallel!(
1040 {
1041 sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
1042
1043 sess.time("looking_for_derive_registrar", || {
1044 tcx.ensure_ok().proc_macro_decls_static(())
1045 });
1046
1047 CStore::from_tcx(tcx).report_unused_deps(tcx);
1048 },
1049 {
1050 tcx.ensure_ok().exportable_items(LOCAL_CRATE);
1051 tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
1052 tcx.par_hir_for_each_module(|module| {
1053 tcx.ensure_ok().check_mod_attrs(module);
1054 tcx.ensure_ok().check_mod_unstable_api_usage(module);
1055 });
1056 },
1057 {
1058 sess.time("unused_lib_feature_checking", || {
1059 rustc_passes::stability::check_unused_or_stable_features(tcx)
1060 });
1061 },
1062 {
1063 tcx.ensure_ok().limits(());
1068 tcx.ensure_ok().stability_index(());
1069 }
1070 );
1071 });
1072
1073 rustc_hir_analysis::check_crate(tcx);
1074 tcx.untracked().definitions.freeze();
1080
1081 sess.time("MIR_borrow_checking", || {
1082 tcx.par_hir_body_owners(|def_id| {
1083 if !tcx.is_typeck_child(def_id.to_def_id()) {
1084 tcx.ensure_ok().check_unsafety(def_id);
1086 tcx.ensure_ok().mir_borrowck(def_id)
1087 }
1088 tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1089
1090 if tcx.sess.opts.output_types.should_codegen()
1094 || tcx.hir_body_const_context(def_id).is_some()
1095 {
1096 tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1097 }
1098 if tcx.is_coroutine(def_id.to_def_id()) {
1099 tcx.ensure_ok().mir_coroutine_witnesses(def_id);
1100 let _ = tcx.ensure_ok().check_coroutine_obligations(
1101 tcx.typeck_root_def_id(def_id.to_def_id()).expect_local(),
1102 );
1103 if !tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()) {
1104 tcx.ensure_ok().layout_of(
1106 ty::TypingEnv::post_analysis(tcx, def_id.to_def_id())
1107 .as_query_input(tcx.type_of(def_id).instantiate_identity()),
1108 );
1109 }
1110 }
1111 });
1112 });
1113
1114 sess.time("layout_testing", || layout_test::test_layout(tcx));
1115 sess.time("abi_testing", || abi_test::test_abi(tcx));
1116
1117 if tcx.sess.opts.unstable_opts.validate_mir {
1122 sess.time("ensuring_final_MIR_is_computable", || {
1123 tcx.par_hir_body_owners(|def_id| {
1124 tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1125 });
1126 });
1127 }
1128}
1129
1130fn analysis(tcx: TyCtxt<'_>, (): ()) {
1133 run_required_analyses(tcx);
1134
1135 let sess = tcx.sess;
1136
1137 if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1146 guar.raise_fatal();
1147 }
1148
1149 sess.time("misc_checking_3", || {
1150 parallel!(
1151 {
1152 tcx.ensure_ok().effective_visibilities(());
1153
1154 parallel!(
1155 {
1156 tcx.ensure_ok().check_private_in_public(());
1157 },
1158 {
1159 tcx.par_hir_for_each_module(|module| {
1160 tcx.ensure_ok().check_mod_deathness(module)
1161 });
1162 },
1163 {
1164 sess.time("lint_checking", || {
1165 rustc_lint::check_crate(tcx);
1166 });
1167 },
1168 {
1169 tcx.ensure_ok().clashing_extern_declarations(());
1170 }
1171 );
1172 },
1173 {
1174 sess.time("privacy_checking_modules", || {
1175 tcx.par_hir_for_each_module(|module| {
1176 tcx.ensure_ok().check_mod_privacy(module);
1177 });
1178 });
1179 }
1180 );
1181
1182 sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1185
1186 let _ = tcx.all_diagnostic_items(());
1190 });
1191}
1192
1193pub(crate) fn start_codegen<'tcx>(
1196 codegen_backend: &dyn CodegenBackend,
1197 tcx: TyCtxt<'tcx>,
1198) -> (Box<dyn Any>, EncodedMetadata) {
1199 tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen);
1200
1201 if let Some((def_id, _)) = tcx.entry_fn(())
1203 && tcx.has_attr(def_id, sym::rustc_delayed_bug_from_inside_query)
1204 {
1205 tcx.ensure_ok().trigger_delayed_bug(def_id);
1206 }
1207
1208 if tcx.sess.opts.output_types.should_codegen() {
1211 rustc_symbol_mangling::test::report_symbol_names(tcx);
1212 }
1213
1214 if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
1218 guar.raise_fatal();
1219 }
1220
1221 info!("Pre-codegen\n{:?}", tcx.debug_stats());
1222
1223 let metadata = rustc_metadata::fs::encode_and_write_metadata(tcx);
1224
1225 let codegen = tcx.sess.time("codegen_crate", move || codegen_backend.codegen_crate(tcx));
1226
1227 info!("Post-codegen\n{:?}", tcx.debug_stats());
1228
1229 if tcx.sess.opts.unstable_opts.print_type_sizes {
1232 tcx.sess.code_stats.print_type_sizes();
1233 }
1234
1235 (codegen, metadata)
1236}
1237
1238pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1240 let attr_crate_name =
1248 validate_and_find_value_str_builtin_attr(sym::crate_name, sess, krate_attrs);
1249
1250 let validate = |name, span| {
1251 rustc_session::output::validate_crate_name(sess, name, span);
1252 name
1253 };
1254
1255 if let Some(crate_name) = &sess.opts.crate_name {
1256 let crate_name = Symbol::intern(crate_name);
1257 if let Some((attr_crate_name, span)) = attr_crate_name
1258 && attr_crate_name != crate_name
1259 {
1260 sess.dcx().emit_err(errors::CrateNameDoesNotMatch {
1261 span,
1262 crate_name,
1263 attr_crate_name,
1264 });
1265 }
1266 return validate(crate_name, None);
1267 }
1268
1269 if let Some((crate_name, span)) = attr_crate_name {
1270 return validate(crate_name, Some(span));
1271 }
1272
1273 if let Input::File(ref path) = sess.io.input
1274 && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1275 {
1276 if file_stem.starts_with('-') {
1277 sess.dcx().emit_err(errors::CrateNameInvalid { crate_name: file_stem });
1278 } else {
1279 return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1280 }
1281 }
1282
1283 sym::rust_out
1284}
1285
1286fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1287 let _ = validate_and_find_value_str_builtin_attr(sym::recursion_limit, sess, krate_attrs);
1291 crate::limits::get_recursion_limit(krate_attrs, sess)
1292}
1293
1294fn validate_and_find_value_str_builtin_attr(
1305 name: Symbol,
1306 sess: &Session,
1307 krate_attrs: &[ast::Attribute],
1308) -> Option<(Symbol, Span)> {
1309 let mut result = None;
1310 for attr in ast::attr::filter_by_name(krate_attrs, name) {
1312 let Some(value) = attr.value_str() else {
1313 validate_attr::emit_fatal_malformed_builtin_attribute(&sess.psess, attr, name)
1314 };
1315 result.get_or_insert((value, attr.span));
1317 }
1318 result
1319}