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