1use std::any::Any;
2use std::ffi::{OsStr, OsString};
3use std::io::{self, BufWriter, Write};
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, LazyLock, OnceLock};
6use std::{env, fs, iter};
7
8use rustc_ast as ast;
9use rustc_attr_parsing::validate_attr;
10use rustc_codegen_ssa::traits::CodegenBackend;
11use rustc_data_structures::jobserver::Proxy;
12use rustc_data_structures::steal::Steal;
13use rustc_data_structures::sync::{AppendOnlyIndexVec, FreezeLock, WorkerLocal};
14use rustc_data_structures::{parallel, thousands};
15use rustc_errors::timings::TimingSection;
16use rustc_expand::base::{ExtCtxt, LintStoreExpand};
17use rustc_feature::Features;
18use rustc_fs_util::try_canonicalize;
19use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap};
20use rustc_hir::definitions::Definitions;
21use rustc_incremental::setup_dep_graph;
22use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore, unerased_lint_store};
23use rustc_metadata::EncodedMetadata;
24use rustc_metadata::creader::CStore;
25use rustc_middle::arena::Arena;
26use rustc_middle::dep_graph::DepsType;
27use rustc_middle::ty::{self, CurrentGcx, GlobalCtxt, RegisteredTools, TyCtxt};
28use rustc_middle::util::Providers;
29use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
30use rustc_passes::{abi_test, input_stats, layout_test};
31use rustc_resolve::{Resolver, ResolverOutputs};
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: &[Box<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 if ecx.nb_macro_errors > 0 {
211 sess.dcx().abort_if_errors();
212 }
213
214 sess.psess.buffered_lints.with_lock(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
217 buffered_lints.append(&mut ecx.buffered_early_lint);
218 });
219
220 sess.time("check_unused_macros", || {
221 ecx.check_unused_macros();
222 });
223
224 if ecx.reduced_recursion_limit.is_some() {
227 sess.dcx().abort_if_errors();
228 unreachable!();
229 }
230
231 if cfg!(windows) {
232 unsafe {
233 env::set_var("PATH", &old_path);
234 }
235 }
236
237 if ecx.sess.opts.unstable_opts.macro_stats {
238 print_macro_stats(&ecx);
239 }
240
241 krate
242 });
243
244 sess.time("maybe_building_test_harness", || {
245 rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
246 });
247
248 let has_proc_macro_decls = sess.time("AST_validation", || {
249 rustc_ast_passes::ast_validation::check_crate(
250 sess,
251 features,
252 &krate,
253 tcx.is_sdylib_interface_build(),
254 resolver.lint_buffer(),
255 )
256 });
257
258 let crate_types = tcx.crate_types();
259 let is_executable_crate = crate_types.contains(&CrateType::Executable);
260 let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
261
262 if crate_types.len() > 1 {
263 if is_executable_crate {
264 sess.dcx().emit_err(errors::MixedBinCrate);
265 }
266 if is_proc_macro_crate {
267 sess.dcx().emit_err(errors::MixedProcMacroCrate);
268 }
269 }
270 if crate_types.contains(&CrateType::Sdylib) && !tcx.features().export_stable() {
271 feature_err(sess, sym::export_stable, DUMMY_SP, "`sdylib` crate type is unstable").emit();
272 }
273
274 if is_proc_macro_crate && sess.panic_strategy() == PanicStrategy::Abort {
275 sess.dcx().emit_warn(errors::ProcMacroCratePanicAbort);
276 }
277
278 sess.time("maybe_create_a_macro_crate", || {
279 let is_test_crate = sess.is_test_crate();
280 rustc_builtin_macros::proc_macro_harness::inject(
281 &mut krate,
282 sess,
283 features,
284 resolver,
285 is_proc_macro_crate,
286 has_proc_macro_decls,
287 is_test_crate,
288 sess.dcx(),
289 )
290 });
291
292 resolver.resolve_crate(&krate);
295
296 CStore::from_tcx(tcx).report_incompatible_target_modifiers(tcx, &krate);
297 CStore::from_tcx(tcx).report_incompatible_async_drop_feature(tcx, &krate);
298 krate
299}
300
301fn print_macro_stats(ecx: &ExtCtxt<'_>) {
302 use std::fmt::Write;
303
304 let crate_name = ecx.ecfg.crate_name.as_str();
305 let crate_name = if crate_name == "build_script_build" {
306 let pkg_name =
308 std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "<unknown crate>".to_string());
309 format!("{pkg_name} build script")
310 } else {
311 crate_name.to_string()
312 };
313
314 #[allow(rustc::potential_query_instability)]
316 let mut macro_stats: Vec<_> = ecx
317 .macro_stats
318 .iter()
319 .map(|((name, kind), stat)| {
320 (stat.bytes, stat.lines, stat.uses, name, *kind)
322 })
323 .collect();
324 macro_stats.sort_unstable();
325 macro_stats.reverse(); let prefix = "macro-stats";
328 let name_w = 32;
329 let uses_w = 7;
330 let lines_w = 11;
331 let avg_lines_w = 11;
332 let bytes_w = 11;
333 let avg_bytes_w = 11;
334 let banner_w = name_w + uses_w + lines_w + avg_lines_w + bytes_w + avg_bytes_w;
335
336 let mut s = String::new();
342 _ = writeln!(s, "{prefix} {}", "=".repeat(banner_w));
343 _ = writeln!(s, "{prefix} MACRO EXPANSION STATS: {}", crate_name);
344 _ = writeln!(
345 s,
346 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
347 "Macro Name", "Uses", "Lines", "Avg Lines", "Bytes", "Avg Bytes",
348 );
349 _ = writeln!(s, "{prefix} {}", "-".repeat(banner_w));
350 if macro_stats.is_empty() {
353 _ = writeln!(s, "{prefix} (none)");
354 }
355 for (bytes, lines, uses, name, kind) in macro_stats {
356 let mut name = ExpnKind::Macro(kind, *name).descr();
357 let uses_with_underscores = thousands::usize_with_underscores(uses);
358 let avg_lines = lines as f64 / uses as f64;
359 let avg_bytes = bytes as f64 / uses as f64;
360
361 let mut uses_w = uses_w;
363 if name.len() + uses_with_underscores.len() >= name_w + uses_w {
364 _ = writeln!(s, "{prefix} {:<name_w$}", name);
368 name = String::new();
369 } else if name.len() >= name_w {
370 uses_w -= name.len() - name_w;
374 };
375
376 _ = writeln!(
377 s,
378 "{prefix} {:<name_w$}{:>uses_w$}{:>lines_w$}{:>avg_lines_w$}{:>bytes_w$}{:>avg_bytes_w$}",
379 name,
380 uses_with_underscores,
381 thousands::usize_with_underscores(lines),
382 thousands::f64p1_with_underscores(avg_lines),
383 thousands::usize_with_underscores(bytes),
384 thousands::f64p1_with_underscores(avg_bytes),
385 );
386 }
387 _ = writeln!(s, "{prefix} {}", "=".repeat(banner_w));
388 eprint!("{s}");
389}
390
391fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
392 let sess = tcx.sess;
393 let (resolver, krate) = &*tcx.resolver_for_lowering().borrow();
394 let mut lint_buffer = resolver.lint_buffer.steal();
395
396 if sess.opts.unstable_opts.input_stats {
397 input_stats::print_ast_stats(tcx, krate);
398 }
399
400 sess.time("complete_gated_feature_checking", || {
402 rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
403 });
404
405 sess.psess.buffered_lints.with_lock(|buffered_lints| {
407 info!("{} parse sess buffered_lints", buffered_lints.len());
408 for early_lint in buffered_lints.drain(..) {
409 lint_buffer.add_early_lint(early_lint);
410 }
411 });
412
413 sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
415 for (ident, mut spans) in identifiers.drain(..) {
416 spans.sort();
417 if ident == sym::ferris {
418 enum FerrisFix {
419 SnakeCase,
420 ScreamingSnakeCase,
421 PascalCase,
422 }
423
424 impl FerrisFix {
425 const fn as_str(self) -> &'static str {
426 match self {
427 FerrisFix::SnakeCase => "ferris",
428 FerrisFix::ScreamingSnakeCase => "FERRIS",
429 FerrisFix::PascalCase => "Ferris",
430 }
431 }
432 }
433
434 let first_span = spans[0];
435 let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
436 let ferris_fix = prev_source
437 .map_or(FerrisFix::SnakeCase, |source| {
438 let mut source_before_ferris = source.trim_end().split_whitespace().rev();
439 match source_before_ferris.next() {
440 Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
441 FerrisFix::PascalCase
442 }
443 Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
444 Some("mut") if source_before_ferris.next() == Some("static") => {
445 FerrisFix::ScreamingSnakeCase
446 }
447 _ => FerrisFix::SnakeCase,
448 }
449 })
450 .as_str();
451
452 sess.dcx().emit_err(errors::FerrisIdentifier { spans, first_span, ferris_fix });
453 } else {
454 sess.dcx().emit_err(errors::EmojiIdentifier { spans, ident });
455 }
456 }
457 });
458
459 let lint_store = unerased_lint_store(tcx.sess);
460 rustc_lint::check_ast_node(
461 sess,
462 Some(tcx),
463 tcx.features(),
464 false,
465 lint_store,
466 tcx.registered_tools(()),
467 Some(lint_buffer),
468 rustc_lint::BuiltinCombinedEarlyLintPass::new(),
469 (&**krate, &*krate.attrs),
470 )
471}
472
473fn env_var_os<'tcx>(tcx: TyCtxt<'tcx>, key: &'tcx OsStr) -> Option<&'tcx OsStr> {
474 let value = env::var_os(key);
475
476 let value_tcx = value.as_ref().map(|value| {
477 let encoded_bytes = tcx.arena.alloc_slice(value.as_encoded_bytes());
478 debug_assert_eq!(value.as_encoded_bytes(), encoded_bytes);
479 unsafe { OsStr::from_encoded_bytes_unchecked(encoded_bytes) }
483 });
484
485 tcx.sess.psess.env_depinfo.borrow_mut().insert((
491 Symbol::intern(&key.to_string_lossy()),
492 value.as_ref().and_then(|value| value.to_str()).map(|value| Symbol::intern(&value)),
493 ));
494
495 value_tcx
496}
497
498fn generated_output_paths(
500 tcx: TyCtxt<'_>,
501 outputs: &OutputFilenames,
502 exact_name: bool,
503 crate_name: Symbol,
504) -> Vec<PathBuf> {
505 let sess = tcx.sess;
506 let mut out_filenames = Vec::new();
507 for output_type in sess.opts.output_types.keys() {
508 let out_filename = outputs.path(*output_type);
509 let file = out_filename.as_path().to_path_buf();
510 match *output_type {
511 OutputType::Exe if !exact_name => {
514 for crate_type in tcx.crate_types().iter() {
515 let p = filename_for_input(sess, *crate_type, crate_name, outputs);
516 out_filenames.push(p.as_path().to_path_buf());
517 }
518 }
519 OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
520 }
522 OutputType::DepInfo if out_filename.is_stdout() => {
523 }
525 _ => {
526 out_filenames.push(file);
527 }
528 }
529 }
530 out_filenames
531}
532
533fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
534 let input_path = try_canonicalize(input_path).ok();
535 if input_path.is_none() {
536 return false;
537 }
538 output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
539}
540
541fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
542 output_paths.iter().find(|output_path| output_path.is_dir())
543}
544
545fn escape_dep_filename(filename: &str) -> String {
546 filename.replace(' ', "\\ ")
549}
550
551fn escape_dep_env(symbol: Symbol) -> String {
554 let s = symbol.as_str();
555 let mut escaped = String::with_capacity(s.len());
556 for c in s.chars() {
557 match c {
558 '\n' => escaped.push_str(r"\n"),
559 '\r' => escaped.push_str(r"\r"),
560 '\\' => escaped.push_str(r"\\"),
561 _ => escaped.push(c),
562 }
563 }
564 escaped
565}
566
567fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
568 let sess = tcx.sess;
570 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
571 return;
572 }
573 let deps_output = outputs.path(OutputType::DepInfo);
574 let deps_filename = deps_output.as_path();
575
576 let result: io::Result<()> = try {
577 let mut files: Vec<(String, u64, Option<SourceFileHash>)> = sess
580 .source_map()
581 .files()
582 .iter()
583 .filter(|fmap| fmap.is_real_file())
584 .filter(|fmap| !fmap.is_imported())
585 .map(|fmap| {
586 (
587 escape_dep_filename(&fmap.name.prefer_local().to_string()),
588 fmap.source_len.0 as u64,
589 fmap.checksum_hash,
590 )
591 })
592 .collect();
593
594 let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
595
596 let file_depinfo = sess.psess.file_depinfo.borrow();
599
600 let normalize_path = |path: PathBuf| {
601 let file = FileName::from(path);
602 escape_dep_filename(&file.prefer_local().to_string())
603 };
604
605 fn hash_iter_files<P: AsRef<Path>>(
608 it: impl Iterator<Item = P>,
609 checksum_hash_algo: Option<SourceFileHashAlgorithm>,
610 ) -> impl Iterator<Item = (P, u64, Option<SourceFileHash>)> {
611 it.map(move |path| {
612 match checksum_hash_algo.and_then(|algo| {
613 fs::File::open(path.as_ref())
614 .and_then(|mut file| {
615 SourceFileHash::new(algo, &mut file).map(|h| (file, h))
616 })
617 .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
618 .map_err(|e| {
619 tracing::error!(
620 "failed to compute checksum, omitting it from dep-info {} {e}",
621 path.as_ref().display()
622 )
623 })
624 .ok()
625 }) {
626 Some((file_len, checksum)) => (path, file_len, Some(checksum)),
627 None => (path, 0, None),
628 }
629 })
630 }
631
632 let extra_tracked_files = hash_iter_files(
633 file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
634 checksum_hash_algo,
635 );
636 files.extend(extra_tracked_files);
637
638 if let Some(ref profile_instr) = sess.opts.cg.profile_use {
640 files.extend(hash_iter_files(
641 iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
642 checksum_hash_algo,
643 ));
644 }
645 if let Some(ref profile_sample) = sess.opts.unstable_opts.profile_sample_use {
646 files.extend(hash_iter_files(
647 iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
648 checksum_hash_algo,
649 ));
650 }
651
652 for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
654 files.extend(hash_iter_files(
655 iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
656 checksum_hash_algo,
657 ));
658 }
659
660 if sess.binary_dep_depinfo() {
661 if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
662 if backend.contains('.') {
663 files.extend(hash_iter_files(
666 iter::once(backend.to_string()),
667 checksum_hash_algo,
668 ));
669 }
670 }
671
672 for &cnum in tcx.crates(()) {
673 let source = tcx.used_crate_source(cnum);
674 if let Some((path, _)) = &source.dylib {
675 files.extend(hash_iter_files(
676 iter::once(escape_dep_filename(&path.display().to_string())),
677 checksum_hash_algo,
678 ));
679 }
680 if let Some((path, _)) = &source.rlib {
681 files.extend(hash_iter_files(
682 iter::once(escape_dep_filename(&path.display().to_string())),
683 checksum_hash_algo,
684 ));
685 }
686 if let Some((path, _)) = &source.rmeta {
687 files.extend(hash_iter_files(
688 iter::once(escape_dep_filename(&path.display().to_string())),
689 checksum_hash_algo,
690 ));
691 }
692 }
693 }
694
695 let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
696 for path in out_filenames {
697 writeln!(
698 file,
699 "{}: {}\n",
700 path.display(),
701 files
702 .iter()
703 .map(|(path, _file_len, _checksum_hash_algo)| path.as_str())
704 .intersperse(" ")
705 .collect::<String>()
706 )?;
707 }
708
709 for (path, _file_len, _checksum_hash_algo) in &files {
713 writeln!(file, "{path}:")?;
714 }
715
716 let env_depinfo = sess.psess.env_depinfo.borrow();
718 if !env_depinfo.is_empty() {
719 #[allow(rustc::potential_query_instability)]
721 let mut envs: Vec<_> = env_depinfo
722 .iter()
723 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
724 .collect();
725 envs.sort_unstable();
726 writeln!(file)?;
727 for (k, v) in envs {
728 write!(file, "# env-dep:{k}")?;
729 if let Some(v) = v {
730 write!(file, "={v}")?;
731 }
732 writeln!(file)?;
733 }
734 }
735
736 if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
739 files
740 .iter()
741 .filter_map(|(path, file_len, hash_algo)| {
742 hash_algo.map(|hash_algo| (path, file_len, hash_algo))
743 })
744 .try_for_each(|(path, file_len, checksum_hash)| {
745 writeln!(file, "# checksum:{checksum_hash} file_len:{file_len} {path}")
746 })?;
747 }
748
749 Ok(())
750 };
751
752 match deps_output {
753 OutFileName::Stdout => {
754 let mut file = BufWriter::new(io::stdout());
755 write_deps_to_file(&mut file)?;
756 }
757 OutFileName::Real(ref path) => {
758 let mut file = fs::File::create_buffered(path)?;
759 write_deps_to_file(&mut file)?;
760 }
761 }
762 };
763
764 match result {
765 Ok(_) => {
766 if sess.opts.json_artifact_notifications {
767 sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
768 }
769 }
770 Err(error) => {
771 sess.dcx().emit_fatal(errors::ErrorWritingDependencies { path: deps_filename, error });
772 }
773 }
774}
775
776fn resolver_for_lowering_raw<'tcx>(
777 tcx: TyCtxt<'tcx>,
778 (): (),
779) -> (&'tcx Steal<(ty::ResolverAstLowering, Arc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
780 let arenas = Resolver::arenas();
781 let _ = tcx.registered_tools(()); let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
783 let mut resolver = Resolver::new(
784 tcx,
785 &pre_configured_attrs,
786 krate.spans.inner_span,
787 krate.spans.inject_use_span,
788 &arenas,
789 );
790 let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
791
792 tcx.untracked().cstore.freeze();
794
795 let ResolverOutputs {
796 global_ctxt: untracked_resolutions,
797 ast_lowering: untracked_resolver_for_lowering,
798 } = resolver.into_outputs();
799
800 let resolutions = tcx.arena.alloc(untracked_resolutions);
801 (tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Arc::new(krate)))), resolutions)
802}
803
804pub fn write_dep_info(tcx: TyCtxt<'_>) {
805 let _ = tcx.resolver_for_lowering();
809
810 let sess = tcx.sess;
811 let _timer = sess.timer("write_dep_info");
812 let crate_name = tcx.crate_name(LOCAL_CRATE);
813
814 let outputs = tcx.output_filenames(());
815 let output_paths =
816 generated_output_paths(tcx, &outputs, sess.io.output_file.is_some(), crate_name);
817
818 if let Some(input_path) = sess.io.input.opt_path() {
820 if sess.opts.will_create_output_file() {
821 if output_contains_path(&output_paths, input_path) {
822 sess.dcx().emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path });
823 }
824 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
825 sess.dcx().emit_fatal(errors::GeneratedFileConflictsWithDirectory {
826 input_path,
827 dir_path,
828 });
829 }
830 }
831 }
832
833 if let Some(ref dir) = sess.io.temps_dir {
834 if fs::create_dir_all(dir).is_err() {
835 sess.dcx().emit_fatal(errors::TempsDirError);
836 }
837 }
838
839 write_out_deps(tcx, &outputs, &output_paths);
840
841 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
842 && sess.opts.output_types.len() == 1;
843
844 if !only_dep_info {
845 if let Some(ref dir) = sess.io.output_dir {
846 if fs::create_dir_all(dir).is_err() {
847 sess.dcx().emit_fatal(errors::OutDirError);
848 }
849 }
850 }
851}
852
853pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
854 if !tcx.crate_types().contains(&rustc_session::config::CrateType::Sdylib) {
855 return;
856 }
857 let _timer = tcx.sess.timer("write_interface");
858 let (_, krate) = &*tcx.resolver_for_lowering().borrow();
859
860 let krate = rustc_ast_pretty::pprust::print_crate_as_interface(
861 krate,
862 tcx.sess.psess.edition,
863 &tcx.sess.psess.attr_id_generator,
864 );
865 let export_output = tcx.output_filenames(()).interface_path();
866 let mut file = fs::File::create_buffered(export_output).unwrap();
867 if let Err(err) = write!(file, "{}", krate) {
868 tcx.dcx().fatal(format!("error writing interface file: {}", err));
869 }
870}
871
872pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
873 let providers = &mut Providers::default();
874 providers.analysis = analysis;
875 providers.hir_crate = rustc_ast_lowering::lower_to_hir;
876 providers.resolver_for_lowering_raw = resolver_for_lowering_raw;
877 providers.stripped_cfg_items = |tcx, _| &tcx.resolutions(()).stripped_cfg_items[..];
878 providers.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
879 providers.early_lint_checks = early_lint_checks;
880 providers.env_var_os = env_var_os;
881 limits::provide(providers);
882 proc_macro_decls::provide(providers);
883 rustc_const_eval::provide(providers);
884 rustc_middle::hir::provide(providers);
885 rustc_borrowck::provide(providers);
886 rustc_incremental::provide(providers);
887 rustc_mir_build::provide(providers);
888 rustc_mir_transform::provide(providers);
889 rustc_monomorphize::provide(providers);
890 rustc_privacy::provide(providers);
891 rustc_query_impl::provide(providers);
892 rustc_resolve::provide(providers);
893 rustc_hir_analysis::provide(providers);
894 rustc_hir_typeck::provide(providers);
895 ty::provide(providers);
896 traits::provide(providers);
897 rustc_passes::provide(providers);
898 rustc_traits::provide(providers);
899 rustc_ty_utils::provide(providers);
900 rustc_metadata::provide(providers);
901 rustc_lint::provide(providers);
902 rustc_symbol_mangling::provide(providers);
903 rustc_codegen_ssa::provide(providers);
904 *providers
905});
906
907pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
908 compiler: &Compiler,
909 krate: rustc_ast::Crate,
910 f: F,
911) -> T {
912 let sess = &compiler.sess;
913
914 let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
915
916 let crate_name = get_crate_name(sess, &pre_configured_attrs);
917 let crate_types = collect_crate_types(sess, &pre_configured_attrs);
918 let stable_crate_id = StableCrateId::new(
919 crate_name,
920 crate_types.contains(&CrateType::Executable),
921 sess.opts.cg.metadata.clone(),
922 sess.cfg_version,
923 );
924
925 let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
926
927 let dep_type = DepsType { dep_names: rustc_query_impl::dep_kind_names() };
928 let dep_graph = setup_dep_graph(sess, crate_name, &dep_type);
929
930 let cstore =
931 FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
932 let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
933
934 let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
935 let untracked =
936 Untracked { cstore, source_span: AppendOnlyIndexVec::new(), definitions, stable_crate_ids };
937
938 dep_graph.assert_ignored();
942
943 let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess);
944
945 let codegen_backend = &compiler.codegen_backend;
946 let mut providers = *DEFAULT_QUERY_PROVIDERS;
947 codegen_backend.provide(&mut providers);
948
949 if let Some(callback) = compiler.override_queries {
950 callback(sess, &mut providers);
951 }
952
953 let incremental = dep_graph.is_fully_enabled();
954
955 let gcx_cell = OnceLock::new();
956 let arena = WorkerLocal::new(|_| Arena::default());
957 let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
958
959 let inner: Box<
962 dyn for<'tcx> FnOnce(
963 &'tcx Session,
964 CurrentGcx,
965 Arc<Proxy>,
966 &'tcx OnceLock<GlobalCtxt<'tcx>>,
967 &'tcx WorkerLocal<Arena<'tcx>>,
968 &'tcx WorkerLocal<rustc_hir::Arena<'tcx>>,
969 F,
970 ) -> T,
971 > = Box::new(move |sess, current_gcx, jobserver_proxy, gcx_cell, arena, hir_arena, f| {
972 TyCtxt::create_global_ctxt(
973 gcx_cell,
974 sess,
975 crate_types,
976 stable_crate_id,
977 arena,
978 hir_arena,
979 untracked,
980 dep_graph,
981 rustc_query_impl::query_callbacks(arena),
982 rustc_query_impl::query_system(
983 providers.queries,
984 providers.extern_queries,
985 query_result_on_disk_cache,
986 incremental,
987 ),
988 providers.hooks,
989 current_gcx,
990 jobserver_proxy,
991 |tcx| {
992 let feed = tcx.create_crate_num(stable_crate_id).unwrap();
993 assert_eq!(feed.key(), LOCAL_CRATE);
994 feed.crate_name(crate_name);
995
996 let feed = tcx.feed_unit_query();
997 feed.features_query(tcx.arena.alloc(rustc_expand::config::features(
998 tcx.sess,
999 &pre_configured_attrs,
1000 crate_name,
1001 )));
1002 feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
1003 feed.output_filenames(Arc::new(outputs));
1004
1005 let res = f(tcx);
1006 tcx.finish();
1008 res
1009 },
1010 )
1011 });
1012
1013 inner(
1014 &compiler.sess,
1015 compiler.current_gcx.clone(),
1016 Arc::clone(&compiler.jobserver_proxy),
1017 &gcx_cell,
1018 &arena,
1019 &hir_arena,
1020 f,
1021 )
1022}
1023
1024fn run_required_analyses(tcx: TyCtxt<'_>) {
1027 if tcx.sess.opts.unstable_opts.input_stats {
1028 rustc_passes::input_stats::print_hir_stats(tcx);
1029 }
1030 #[cfg(all(not(doc), debug_assertions))]
1033 rustc_passes::hir_id_validator::check_crate(tcx);
1034
1035 tcx.ensure_done().hir_crate_items(());
1039
1040 let sess = tcx.sess;
1041 sess.time("misc_checking_1", || {
1042 parallel!(
1043 {
1044 sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
1045
1046 sess.time("looking_for_derive_registrar", || {
1047 tcx.ensure_ok().proc_macro_decls_static(())
1048 });
1049
1050 CStore::from_tcx(tcx).report_unused_deps(tcx);
1051 },
1052 {
1053 tcx.ensure_ok().exportable_items(LOCAL_CRATE);
1054 tcx.ensure_ok().stable_order_of_exportable_impls(LOCAL_CRATE);
1055 tcx.par_hir_for_each_module(|module| {
1056 tcx.ensure_ok().check_mod_attrs(module);
1057 tcx.ensure_ok().check_mod_unstable_api_usage(module);
1058 });
1059 },
1060 {
1061 tcx.ensure_ok().limits(());
1066 }
1067 );
1068 });
1069
1070 rustc_hir_analysis::check_crate(tcx);
1071 tcx.untracked().definitions.freeze();
1077
1078 sess.time("MIR_borrow_checking", || {
1079 tcx.par_hir_body_owners(|def_id| {
1080 if !tcx.is_typeck_child(def_id.to_def_id()) {
1081 tcx.ensure_ok().check_unsafety(def_id);
1083 tcx.ensure_ok().mir_borrowck(def_id);
1084 tcx.ensure_ok().check_transmutes(def_id);
1085 }
1086 tcx.ensure_ok().has_ffi_unwind_calls(def_id);
1087
1088 if tcx.sess.opts.output_types.should_codegen()
1092 || tcx.hir_body_const_context(def_id).is_some()
1093 {
1094 tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
1095 }
1096 if tcx.is_coroutine(def_id.to_def_id()) {
1097 tcx.ensure_ok().mir_coroutine_witnesses(def_id);
1098 let _ = tcx.ensure_ok().check_coroutine_obligations(
1099 tcx.typeck_root_def_id(def_id.to_def_id()).expect_local(),
1100 );
1101 if !tcx.is_async_drop_in_place_coroutine(def_id.to_def_id()) {
1102 tcx.ensure_ok().layout_of(
1104 ty::TypingEnv::post_analysis(tcx, def_id.to_def_id())
1105 .as_query_input(tcx.type_of(def_id).instantiate_identity()),
1106 );
1107 }
1108 }
1109 });
1110 });
1111
1112 sess.time("layout_testing", || layout_test::test_layout(tcx));
1113 sess.time("abi_testing", || abi_test::test_abi(tcx));
1114
1115 if tcx.sess.opts.unstable_opts.validate_mir {
1120 sess.time("ensuring_final_MIR_is_computable", || {
1121 tcx.par_hir_body_owners(|def_id| {
1122 tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
1123 });
1124 });
1125 }
1126}
1127
1128fn analysis(tcx: TyCtxt<'_>, (): ()) {
1131 run_required_analyses(tcx);
1132
1133 let sess = tcx.sess;
1134
1135 if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
1144 guar.raise_fatal();
1145 }
1146
1147 sess.time("misc_checking_3", || {
1148 parallel!(
1149 {
1150 tcx.ensure_ok().effective_visibilities(());
1151
1152 parallel!(
1153 {
1154 tcx.par_hir_for_each_module(|module| {
1155 tcx.ensure_ok().check_private_in_public(module)
1156 })
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}