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 #[allow(rustc::potential_query_instability)]
303 let mut macro_stats: Vec<_> = ecx
304 .macro_stats
305 .iter()
306 .map(|((name, kind), stat)| {
307 (stat.bytes, stat.lines, stat.uses, name, *kind)
309 })
310 .collect();
311 macro_stats.sort_unstable();
312 macro_stats.reverse(); let prefix = "macro-stats";
315 let name_w = 32;
316 let uses_w = 7;
317 let lines_w = 11;
318 let avg_lines_w = 11;
319 let bytes_w = 11;
320 let avg_bytes_w = 11;
321 let banner_w = name_w + uses_w + lines_w + avg_lines_w + bytes_w + avg_bytes_w;
322
323 let mut s = String::new();
329 _ = writeln!(s, "{prefix} {}", "=".repeat(banner_w));
330 _ = writeln!(s, "{prefix} MACRO EXPANSION STATS: {}", ecx.ecfg.crate_name);
331 _ = writeln!(
332 s,
333 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
334 "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
335 );
336 _ = writeln!(s, "{prefix} {}", "-".repeat(banner_w));
337 if macro_stats.is_empty() {
340 _ = writeln!(s, "{prefix} (none)");
341 }
342 for (bytes, lines, uses, name, kind) in macro_stats {
343 let mut name = ExpnKind::Macro(kind, *name).descr();
344 let avg_lines = lines as f64 / uses as f64;
345 let avg_bytes = bytes as f64 / uses as f64;
346 if name.len() >= name_w {
347 _ = writeln!(s, "{prefix} {:<name_w$}", name);
351 name = String::new();
352 }
353 _ = writeln!(
354 s,
355 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
356 name,
357 thousands::usize_with_underscores(uses),
358 thousands::usize_with_underscores(lines),
359 thousands::f64p1_with_underscores(avg_lines),
360 thousands::usize_with_underscores(bytes),
361 thousands::f64p1_with_underscores(avg_bytes),
362 );
363 }
364 _ = writeln!(s, "{prefix} {}", "=".repeat(banner_w));
365 eprint!("{s}");
366}
367
368fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
369 let sess = tcx.sess;
370 let (resolver, krate) = &*tcx.resolver_for_lowering().borrow();
371 let mut lint_buffer = resolver.lint_buffer.steal();
372
373 if sess.opts.unstable_opts.input_stats {
374 input_stats::print_ast_stats(tcx, krate);
375 }
376
377 sess.time("complete_gated_feature_checking", || {
379 rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
380 });
381
382 sess.psess.buffered_lints.with_lock(|buffered_lints| {
384 info!("{} parse sess buffered_lints", buffered_lints.len());
385 for early_lint in buffered_lints.drain(..) {
386 lint_buffer.add_early_lint(early_lint);
387 }
388 });
389
390 sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
392 for (ident, mut spans) in identifiers.drain(..) {
393 spans.sort();
394 if ident == sym::ferris {
395 enum FerrisFix {
396 SnakeCase,
397 ScreamingSnakeCase,
398 PascalCase,
399 }
400
401 impl FerrisFix {
402 const fn as_str(self) -> &'static str {
403 match self {
404 FerrisFix::SnakeCase => "ferris",
405 FerrisFix::ScreamingSnakeCase => "FERRIS",
406 FerrisFix::PascalCase => "Ferris",
407 }
408 }
409 }
410
411 let first_span = spans[0];
412 let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
413 let ferris_fix = prev_source
414 .map_or(FerrisFix::SnakeCase, |source| {
415 let mut source_before_ferris = source.trim_end().split_whitespace().rev();
416 match source_before_ferris.next() {
417 Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
418 FerrisFix::PascalCase
419 }
420 Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
421 Some("mut") if source_before_ferris.next() == Some("static") => {
422 FerrisFix::ScreamingSnakeCase
423 }
424 _ => FerrisFix::SnakeCase,
425 }
426 })
427 .as_str();
428
429 sess.dcx().emit_err(errors::FerrisIdentifier { spans, first_span, ferris_fix });
430 } else {
431 sess.dcx().emit_err(errors::EmojiIdentifier { spans, ident });
432 }
433 }
434 });
435
436 let lint_store = unerased_lint_store(tcx.sess);
437 rustc_lint::check_ast_node(
438 sess,
439 Some(tcx),
440 tcx.features(),
441 false,
442 lint_store,
443 tcx.registered_tools(()),
444 Some(lint_buffer),
445 rustc_lint::BuiltinCombinedEarlyLintPass::new(),
446 (&**krate, &*krate.attrs),
447 )
448}
449
450fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
451 let value = env::var_os(key);
452
453 let value_tcx = value.as_ref().map(|value| {
454 let encoded_bytes = tcx.arena.alloc_slice(value.as_encoded_bytes());
455 debug_assert_eq!(value.as_encoded_bytes(), encoded_bytes);
456 unsafe { OsStr::from_encoded_bytes_unchecked(encoded_bytes) }
460 });
461
462 tcx.sess.psess.env_depinfo.borrow_mut().insert((
468 Symbol::intern(&key.to_string_lossy()),
469 value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(&value)),
470 ));
471
472 value_tcx
473}
474
475fn generated_output_paths(
477 tcx: TyCtxt<'_>,
478 outputs: &OutputFilenames,
479 exact_name: bool,
480 crate_name: Symbol,
481) -> Vec<PathBuf> {
482 let sess = tcx.sess;
483 let mut out_filenames = Vec::new();
484 for output_type in sess.opts.output_types.keys() {
485 let out_filename = outputs.path(*output_type);
486 let file = out_filename.as_path().to_path_buf();
487 match *output_type {
488 OutputType::Exe if !exact_name => {
491 for crate_type in tcx.crate_types().iter() {
492 let p = filename_for_input(sess, *crate_type, crate_name, outputs);
493 out_filenames.push(p.as_path().to_path_buf());
494 }
495 }
496 OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
497 }
499 OutputType::DepInfo if out_filename.is_stdout() => {
500 }
502 _ => {
503 out_filenames.push(file);
504 }
505 }
506 }
507 out_filenames
508}
509
510fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
511 let input_path = try_canonicalize(input_path).ok();
512 if input_path.is_none() {
513 return false;
514 }
515 output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
516}
517
518fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
519 output_paths.iter().find(|output_path| output_path.is_dir())
520}
521
522fn escape_dep_filename(filename: &str) -> String {
523 filename.replace(' ', "\\ ")
526}
527
528fn escape_dep_env(symbol: Symbol) -> String {
531 let s = symbol.as_str();
532 let mut escaped = String::with_capacity(s.len());
533 for c in s.chars() {
534 match c {
535 '\n' => escaped.push_str(r"\n"),
536 '\r' => escaped.push_str(r"\r"),
537 '\\' => escaped.push_str(r"\\"),
538 _ => escaped.push(c),
539 }
540 }
541 escaped
542}
543
544fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
545 let sess = tcx.sess;
547 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
548 return;
549 }
550 let deps_output = outputs.path(OutputType::DepInfo);
551 let deps_filename = deps_output.as_path();
552
553 let result: io::Result<()> = try {
554 let mut files: Vec<(String, u64, Option<SourceFileHash>)> = sess
557 .source_map()
558 .files()
559 .iter()
560 .filter(|fmap| fmap.is_real_file())
561 .filter(|fmap| !fmap.is_imported())
562 .map(|fmap| {
563 (
564 escape_dep_filename(&fmap.name.prefer_local().to_string()),
565 fmap.source_len.0 as u64,
566 fmap.checksum_hash,
567 )
568 })
569 .collect();
570
571 let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
572
573 let file_depinfo = sess.psess.file_depinfo.borrow();
576
577 let normalize_path = |path: PathBuf| {
578 let file = FileName::from(path);
579 escape_dep_filename(&file.prefer_local().to_string())
580 };
581
582 fn hash_iter_files<P: AsRef<Path>>(
585 it: impl Iterator<Item = P>,
586 checksum_hash_algo: Option<SourceFileHashAlgorithm>,
587 ) -> impl Iterator<Item = (P, u64, Option<SourceFileHash>)> {
588 it.map(move |path| {
589 match checksum_hash_algo.and_then(|algo| {
590 fs::File::open(path.as_ref())
591 .and_then(|mut file| {
592 SourceFileHash::new(algo, &mut file).map(|h| (file, h))
593 })
594 .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
595 .map_err(|e| {
596 tracing::error!(
597 "failed to compute checksum, omitting it from dep-info {} {e}",
598 path.as_ref().display()
599 )
600 })
601 .ok()
602 }) {
603 Some((file_len, checksum)) => (path, file_len, Some(checksum)),
604 None => (path, 0, None),
605 }
606 })
607 }
608
609 let extra_tracked_files = hash_iter_files(
610 file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
611 checksum_hash_algo,
612 );
613 files.extend(extra_tracked_files);
614
615 if let Some(ref profile_instr) = sess.opts.cg.profile_use {
617 files.extend(hash_iter_files(
618 iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
619 checksum_hash_algo,
620 ));
621 }
622 if let Some(ref profile_sample) = sess.opts.unstable_opts.profile_sample_use {
623 files.extend(hash_iter_files(
624 iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
625 checksum_hash_algo,
626 ));
627 }
628
629 for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
631 files.extend(hash_iter_files(
632 iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
633 checksum_hash_algo,
634 ));
635 }
636
637 if sess.binary_dep_depinfo() {
638 if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
639 if backend.contains('.') {
640 files.extend(hash_iter_files(
643 iter::once(backend.to_string()),
644 checksum_hash_algo,
645 ));
646 }
647 }
648
649 for &cnum in tcx.crates(()) {
650 let source = tcx.used_crate_source(cnum);
651 if let Some((path, _)) = &source.dylib {
652 files.extend(hash_iter_files(
653 iter::once(escape_dep_filename(&path.display().to_string())),
654 checksum_hash_algo,
655 ));
656 }
657 if let Some((path, _)) = &source.rlib {
658 files.extend(hash_iter_files(
659 iter::once(escape_dep_filename(&path.display().to_string())),
660 checksum_hash_algo,
661 ));
662 }
663 if let Some((path, _)) = &source.rmeta {
664 files.extend(hash_iter_files(
665 iter::once(escape_dep_filename(&path.display().to_string())),
666 checksum_hash_algo,
667 ));
668 }
669 }
670 }
671
672 let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
673 for path in out_filenames {
674 writeln!(
675 file,
676 "{}: {}\n",
677 path.display(),
678 files
679 .iter()
680 .map(|(path, _file_len, _checksum_hash_algo)| path.as_str())
681 .intersperse(" ")
682 .collect::<String>()
683 )?;
684 }
685
686 for (path, _file_len, _checksum_hash_algo) in &files {
690 writeln!(file, "{path}:")?;
691 }
692
693 let env_depinfo = sess.psess.env_depinfo.borrow();
695 if !env_depinfo.is_empty() {
696 #[allow(rustc::potential_query_instability)]
698 let mut envs: Vec<_> = env_depinfo
699 .iter()
700 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
701 .collect();
702 envs.sort_unstable();
703 writeln!(file)?;
704 for (k, v) in envs {
705 write!(file, "# env-dep:{k}")?;
706 if let Some(v) = v {
707 write!(file, "={v}")?;
708 }
709 writeln!(file)?;
710 }
711 }
712
713 if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
716 files
717 .iter()
718 .filter_map(|(path, file_len, hash_algo)| {
719 hash_algo.map(|hash_algo| (path, file_len, hash_algo))
720 })
721 .try_for_each(|(path, file_len, checksum_hash)| {
722 writeln!(file, "# checksum:{checksum_hash} file_len:{file_len} {path}")
723 })?;
724 }
725
726 Ok(())
727 };
728
729 match deps_output {
730 OutFileName::Stdout => {
731 let mut file = BufWriter::new(io::stdout());
732 write_deps_to_file(&mut file)?;
733 }
734 OutFileName::Real(ref path) => {
735 let mut file = fs::File::create_buffered(path)?;
736 write_deps_to_file(&mut file)?;
737 }
738 }
739 };
740
741 match result {
742 Ok(_) => {
743 if sess.opts.json_artifact_notifications {
744 sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
745 }
746 }
747 Err(error) => {
748 sess.dcx().emit_fatal(errors::ErrorWritingDependencies { path: deps_filename, error });
749 }
750 }
751}
752
753fn resolver_for_lowering_raw<'tcx>(
754 tcx: TyCtxt<'tcx>,
755 (): (),
756) -> (&'tcx Steal<(ty::ResolverAstLowering, Arc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
757 let arenas = Resolver::arenas();
758 let _ = tcx.registered_tools(()); let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
760 let mut resolver = Resolver::new(
761 tcx,
762 &pre_configured_attrs,
763 krate.spans.inner_span,
764 krate.spans.inject_use_span,
765 &arenas,
766 );
767 let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
768
769 tcx.untracked().cstore.freeze();
771
772 let ty::ResolverOutputs {
773 global_ctxt: untracked_resolutions,
774 ast_lowering: untracked_resolver_for_lowering,
775 } = resolver.into_outputs();
776
777 let resolutions = tcx.arena.alloc(untracked_resolutions);
778 (tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Arc::new(krate)))), resolutions)
779}
780
781pub fn write_dep_info(tcx: TyCtxt<'_>) {
782 let _ = tcx.resolver_for_lowering();
786
787 let sess = tcx.sess;
788 let _timer = sess.timer("write_dep_info");
789 let crate_name = tcx.crate_name(LOCAL_CRATE);
790
791 let outputs = tcx.output_filenames(());
792 let output_paths =
793 generated_output_paths(tcx, &outputs, sess.io.output_file.is_some(), crate_name);
794
795 if let Some(input_path) = sess.io.input.opt_path() {
797 if sess.opts.will_create_output_file() {
798 if output_contains_path(&output_paths, input_path) {
799 sess.dcx().emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path });
800 }
801 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
802 sess.dcx().emit_fatal(errors::GeneratedFileConflictsWithDirectory {
803 input_path,
804 dir_path,
805 });
806 }
807 }
808 }
809
810 if let Some(ref dir) = sess.io.temps_dir {
811 if fs::create_dir_all(dir).is_err() {
812 sess.dcx().emit_fatal(errors::TempsDirError);
813 }
814 }
815
816 write_out_deps(tcx, &outputs, &output_paths);
817
818 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
819 && sess.opts.output_types.len() == 1;
820
821 if !only_dep_info {
822 if let Some(ref dir) = sess.io.output_dir {
823 if fs::create_dir_all(dir).is_err() {
824 sess.dcx().emit_fatal(errors::OutDirError);
825 }
826 }
827 }
828}
829
830pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
831 if !tcx.crate_types().contains(&rustc_session::config::CrateType::Sdylib) {
832 return;
833 }
834 let _timer = tcx.sess.timer("write_interface");
835 let (_, krate) = &*tcx.resolver_for_lowering().borrow();
836
837 let krate = rustc_ast_pretty::pprust::print_crate_as_interface(
838 krate,
839 tcx.sess.psess.edition,
840 &tcx.sess.psess.attr_id_generator,
841 );
842 let export_output = tcx.output_filenames(()).interface_path();
843 let mut file = fs::File::create_buffered(export_output).unwrap();
844 if let Err(err) = write!(file, "{}", krate) {
845 tcx.dcx().fatal(format!("error writing interface file: {}", err));
846 }
847}
848
849pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
850 let providers = &mut Providers::default();
851 providers.analysis = analysis;
852 providers.hir_crate = rustc_ast_lowering::lower_to_hir;
853 providers.resolver_for_lowering_raw = resolver_for_lowering_raw;
854 providers.stripped_cfg_items =
855 |tcx, _| tcx.arena.alloc_from_iter(tcx.resolutions(()).stripped_cfg_items.steal());
856 providers.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
857 providers.early_lint_checks = early_lint_checks;
858 providers.env_var_os = env_var_os;
859 limits::provide(providers);
860 proc_macro_decls::provide(providers);
861 rustc_const_eval::provide(providers);
862 rustc_middle::hir::provide(providers);
863 rustc_borrowck::provide(providers);
864 rustc_incremental::provide(providers);
865 rustc_mir_build::provide(providers);
866 rustc_mir_transform::provide(providers);
867 rustc_monomorphize::provide(providers);
868 rustc_privacy::provide(providers);
869 rustc_query_impl::provide(providers);
870 rustc_resolve::provide(providers);
871 rustc_hir_analysis::provide(providers);
872 rustc_hir_typeck::provide(providers);
873 ty::provide(providers);
874 traits::provide(providers);
875 rustc_passes::provide(providers);
876 rustc_traits::provide(providers);
877 rustc_ty_utils::provide(providers);
878 rustc_metadata::provide(providers);
879 rustc_lint::provide(providers);
880 rustc_symbol_mangling::provide(providers);
881 rustc_codegen_ssa::provide(providers);
882 *providers
883});
884
885pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
886 compiler: &Compiler,
887 krate: rustc_ast::Crate,
888 f: F,
889) -> T {
890 let sess = &compiler.sess;
891
892 let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
893
894 let crate_name = get_crate_name(sess, &pre_configured_attrs);
895 let crate_types = collect_crate_types(sess, &pre_configured_attrs);
896 let stable_crate_id = StableCrateId::new(
897 crate_name,
898 crate_types.contains(&CrateType::Executable),
899 sess.opts.cg.metadata.clone(),
900 sess.cfg_version,
901 );
902
903 let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
904
905 let dep_type = DepsType { dep_names: rustc_query_impl::dep_kind_names() };
906 let dep_graph = setup_dep_graph(sess, crate_name, &dep_type);
907
908 let cstore =
909 FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
910 let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
911
912 let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
913 let untracked =
914 Untracked { cstore, source_span: AppendOnlyIndexVec::new(), definitions, stable_crate_ids };
915
916 dep_graph.assert_ignored();
920
921 let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess);
922
923 let codegen_backend = &compiler.codegen_backend;
924 let mut providers = *DEFAULT_QUERY_PROVIDERS;
925 codegen_backend.provide(&mut providers);
926
927 if let Some(callback) = compiler.override_queries {
928 callback(sess, &mut providers);
929 }
930
931 let incremental = dep_graph.is_fully_enabled();
932
933 let gcx_cell = OnceLock::new();
934 let arena = WorkerLocal::new(|_| Arena::default());
935 let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
936
937 let inner: Box<
940 dyn for<'tcx> FnOnce(
941 &'tcx Session,
942 CurrentGcx,
943 Arc<Proxy>,
944 &'tcx OnceLock<GlobalCtxt<'tcx>>,
945 &'tcx WorkerLocal<Arena<'tcx>>,
946 &'tcx WorkerLocal<rustc_hir::Arena<'tcx>>,
947 F,
948 ) -> T,
949 > = Box::new(move |sess, current_gcx, jobserver_proxy, gcx_cell, arena, hir_arena, f| {
950 TyCtxt::create_global_ctxt(
951 gcx_cell,
952 sess,
953 crate_types,
954 stable_crate_id,
955 arena,
956 hir_arena,
957 untracked,
958 dep_graph,
959 rustc_query_impl::query_callbacks(arena),
960 rustc_query_impl::query_system(
961 providers.queries,
962 providers.extern_queries,
963 query_result_on_disk_cache,
964 incremental,
965 ),
966 providers.hooks,
967 current_gcx,
968 jobserver_proxy,
969 |tcx| {
970 let feed = tcx.create_crate_num(stable_crate_id).unwrap();
971 assert_eq!(feed.key(), LOCAL_CRATE);
972 feed.crate_name(crate_name);
973
974 let feed = tcx.feed_unit_query();
975 feed.features_query(tcx.arena.alloc(rustc_expand::config::features(
976 tcx.sess,
977 &pre_configured_attrs,
978 crate_name,
979 )));
980 feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
981 feed.output_filenames(Arc::new(outputs));
982
983 let res = f(tcx);
984 tcx.finish();
986 res
987 },
988 )
989 });
990
991 inner(
992 &compiler.sess,
993 compiler.current_gcx.clone(),
994 Arc::clone(&compiler.jobserver_proxy),
995 &gcx_cell,
996 &arena,
997 &hir_arena,
998 f,
999 )
1000}
1001
1002fn run_required_analyses(tcx: TyCtxt<'_>) {
1005 if tcx.sess.opts.unstable_opts.input_stats {
1006 rustc_passes::input_stats::print_hir_stats(tcx);
1007 }
1008 #[cfg(all(not(doc), debug_assertions))]
1011 rustc_passes::hir_id_validator::check_crate(tcx);
1012
1013 tcx.ensure_done().hir_crate_items(());
1017
1018 let sess = tcx.sess;
1019 sess.time("misc_checking_1", || {
1020 parallel!(
1021 {
1022 sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
1023
1024 sess.time("looking_for_derive_registrar", || {
1025 tcx.ensure_ok().proc_macro_decls_static(())
1026 });
1027
1028 CStore::from_tcx(tcx).report_unused_deps(tcx);
1029 },
1030 {
1031 tcx.ensure_ok().exportable_items(LOCAL_CRATE);
1032 tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
1033 tcx.par_hir_for_each_module(|module| {
1034 tcx.ensure_ok().check_mod_attrs(module);
1035 tcx.ensure_ok().check_mod_unstable_api_usage(module);
1036 });
1037 },
1038 {
1039 sess.time("unused_lib_feature_checking", || {
1040 rustc_passes::stability::check_unused_or_stable_features(tcx)
1041 });
1042 },
1043 {
1044 tcx.ensure_ok().limits(());
1049 tcx.ensure_ok().stability_index(());
1050 }
1051 );
1052 });
1053
1054 rustc_hir_analysis::check_crate(tcx);
1055 tcx.untracked().definitions.freeze();
1061
1062 sess.time("MIR_borrow_checking", || {
1063 tcx.par_hir_body_owners(|def_id| {
1064 if !tcx.is_typeck_child(def_id.to_def_id()) {
1065 tcx.ensure_ok().check_unsafety(def_id);
1067 tcx.ensure_ok().mir_borrowck(def_id)
1068 }
1069 tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1070
1071 if tcx.sess.opts.output_types.should_codegen()
1075 || tcx.hir_body_const_context(def_id).is_some()
1076 {
1077 tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1078 }
1079 if tcx.is_coroutine(def_id.to_def_id()) {
1080 tcx.ensure_ok().mir_coroutine_witnesses(def_id);
1081 let _ = tcx.ensure_ok().check_coroutine_obligations(
1082 tcx.typeck_root_def_id(def_id.to_def_id()).expect_local(),
1083 );
1084 if !tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()) {
1085 tcx.ensure_ok().layout_of(
1087 ty::TypingEnv::post_analysis(tcx, def_id.to_def_id())
1088 .as_query_input(tcx.type_of(def_id).instantiate_identity()),
1089 );
1090 }
1091 }
1092 });
1093 });
1094
1095 sess.time("layout_testing", || layout_test::test_layout(tcx));
1096 sess.time("abi_testing", || abi_test::test_abi(tcx));
1097
1098 if tcx.sess.opts.unstable_opts.validate_mir {
1103 sess.time("ensuring_final_MIR_is_computable", || {
1104 tcx.par_hir_body_owners(|def_id| {
1105 tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1106 });
1107 });
1108 }
1109}
1110
1111fn analysis(tcx: TyCtxt<'_>, (): ()) {
1114 run_required_analyses(tcx);
1115
1116 let sess = tcx.sess;
1117
1118 if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1127 guar.raise_fatal();
1128 }
1129
1130 sess.time("misc_checking_3", || {
1131 parallel!(
1132 {
1133 tcx.ensure_ok().effective_visibilities(());
1134
1135 parallel!(
1136 {
1137 tcx.ensure_ok().check_private_in_public(());
1138 },
1139 {
1140 tcx.par_hir_for_each_module(|module| {
1141 tcx.ensure_ok().check_mod_deathness(module)
1142 });
1143 },
1144 {
1145 sess.time("lint_checking", || {
1146 rustc_lint::check_crate(tcx);
1147 });
1148 },
1149 {
1150 tcx.ensure_ok().clashing_extern_declarations(());
1151 }
1152 );
1153 },
1154 {
1155 sess.time("privacy_checking_modules", || {
1156 tcx.par_hir_for_each_module(|module| {
1157 tcx.ensure_ok().check_mod_privacy(module);
1158 });
1159 });
1160 }
1161 );
1162
1163 sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1166
1167 let _ = tcx.all_diagnostic_items(());
1171 });
1172}
1173
1174pub(crate) fn start_codegen<'tcx>(
1177 codegen_backend: &dyn CodegenBackend,
1178 tcx: TyCtxt<'tcx>,
1179) -> (Box<dyn Any>, EncodedMetadata) {
1180 tcx.sess.timings.start_section(tcx.sess.dcx(), TimingSection::Codegen);
1181
1182 if let Some((def_id, _)) = tcx.entry_fn(())
1184 && tcx.has_attr(def_id, sym::rustc_delayed_bug_from_inside_query)
1185 {
1186 tcx.ensure_ok().trigger_delayed_bug(def_id);
1187 }
1188
1189 if tcx.sess.opts.output_types.should_codegen() {
1192 rustc_symbol_mangling::test::report_symbol_names(tcx);
1193 }
1194
1195 if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
1199 guar.raise_fatal();
1200 }
1201
1202 info!("Pre-codegen\n{:?}", tcx.debug_stats());
1203
1204 let metadata = rustc_metadata::fs::encode_and_write_metadata(tcx);
1205
1206 let codegen = tcx.sess.time("codegen_crate", move || codegen_backend.codegen_crate(tcx));
1207
1208 info!("Post-codegen\n{:?}", tcx.debug_stats());
1209
1210 if tcx.sess.opts.unstable_opts.print_type_sizes {
1213 tcx.sess.code_stats.print_type_sizes();
1214 }
1215
1216 (codegen, metadata)
1217}
1218
1219pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1221 let attr_crate_name =
1229 validate_and_find_value_str_builtin_attr(sym::crate_name, sess, krate_attrs);
1230
1231 let validate = |name, span| {
1232 rustc_session::output::validate_crate_name(sess, name, span);
1233 name
1234 };
1235
1236 if let Some(crate_name) = &sess.opts.crate_name {
1237 let crate_name = Symbol::intern(crate_name);
1238 if let Some((attr_crate_name, span)) = attr_crate_name
1239 && attr_crate_name != crate_name
1240 {
1241 sess.dcx().emit_err(errors::CrateNameDoesNotMatch {
1242 span,
1243 crate_name,
1244 attr_crate_name,
1245 });
1246 }
1247 return validate(crate_name, None);
1248 }
1249
1250 if let Some((crate_name, span)) = attr_crate_name {
1251 return validate(crate_name, Some(span));
1252 }
1253
1254 if let Input::File(ref path) = sess.io.input
1255 && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1256 {
1257 if file_stem.starts_with('-') {
1258 sess.dcx().emit_err(errors::CrateNameInvalid { crate_name: file_stem });
1259 } else {
1260 return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1261 }
1262 }
1263
1264 sym::rust_out
1265}
1266
1267fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1268 let _ = validate_and_find_value_str_builtin_attr(sym::recursion_limit, sess, krate_attrs);
1272 crate::limits::get_recursion_limit(krate_attrs, sess)
1273}
1274
1275fn validate_and_find_value_str_builtin_attr(
1286 name: Symbol,
1287 sess: &Session,
1288 krate_attrs: &[ast::Attribute],
1289) -> Option<(Symbol, Span)> {
1290 let mut result = None;
1291 for attr in ast::attr::filter_by_name(krate_attrs, name) {
1293 let Some(value) = attr.value_str() else {
1294 validate_attr::emit_fatal_malformed_builtin_attribute(&sess.psess, attr, name)
1295 };
1296 result.get_or_insert((value, attr.span));
1298 }
1299 result
1300}