1use std::any::Any;
2use std::ffi::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::parallel;
11use rustc_data_structures::steal::Steal;
12use rustc_data_structures::sync::{AppendOnlyIndexVec, FreezeLock, WorkerLocal};
13use rustc_expand::base::{ExtCtxt, LintStoreExpand};
14use rustc_feature::Features;
15use rustc_fs_util::try_canonicalize;
16use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap};
17use rustc_hir::definitions::Definitions;
18use rustc_incremental::setup_dep_graph;
19use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore, unerased_lint_store};
20use rustc_metadata::creader::CStore;
21use rustc_middle::arena::Arena;
22use rustc_middle::ty::{self, CurrentGcx, GlobalCtxt, RegisteredTools, TyCtxt};
23use rustc_middle::util::Providers;
24use rustc_parse::{
25 new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal, validate_attr,
26};
27use rustc_passes::{abi_test, input_stats, layout_test};
28use rustc_resolve::Resolver;
29use rustc_session::config::{CrateType, Input, OutFileName, OutputFilenames, OutputType};
30use rustc_session::cstore::Untracked;
31use rustc_session::output::{collect_crate_types, filename_for_input};
32use rustc_session::search_paths::PathKind;
33use rustc_session::{Limit, Session};
34use rustc_span::{
35 ErrorGuaranteed, FileName, SourceFileHash, SourceFileHashAlgorithm, Span, Symbol, sym,
36};
37use rustc_target::spec::PanicStrategy;
38use rustc_trait_selection::traits;
39use tracing::{info, instrument};
40
41use crate::interface::Compiler;
42use crate::{errors, limits, proc_macro_decls, util};
43
44pub fn parse<'a>(sess: &'a Session) -> ast::Crate {
45 let krate = sess
46 .time("parse_crate", || {
47 let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
48 Input::File(file) => new_parser_from_file(&sess.psess, file, None),
49 Input::Str { input, name } => {
50 new_parser_from_source_str(&sess.psess, name.clone(), input.clone())
51 }
52 });
53 parser.parse_crate_mod()
54 })
55 .unwrap_or_else(|parse_error| {
56 let guar: ErrorGuaranteed = parse_error.emit();
57 guar.raise_fatal();
58 });
59
60 if sess.opts.unstable_opts.input_stats {
61 input_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS", "ast-stats-1");
62 }
63
64 krate
65}
66
67fn pre_expansion_lint<'a>(
68 sess: &Session,
69 features: &Features,
70 lint_store: &LintStore,
71 registered_tools: &RegisteredTools,
72 check_node: impl EarlyCheckNode<'a>,
73 node_name: Symbol,
74) {
75 sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
76 || {
77 rustc_lint::check_ast_node(
78 sess,
79 None,
80 features,
81 true,
82 lint_store,
83 registered_tools,
84 None,
85 rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
86 check_node,
87 );
88 },
89 );
90}
91
92struct LintStoreExpandImpl<'a>(&'a LintStore);
94
95impl LintStoreExpand for LintStoreExpandImpl<'_> {
96 fn pre_expansion_lint(
97 &self,
98 sess: &Session,
99 features: &Features,
100 registered_tools: &RegisteredTools,
101 node_id: ast::NodeId,
102 attrs: &[ast::Attribute],
103 items: &[rustc_ast::ptr::P<ast::Item>],
104 name: Symbol,
105 ) {
106 pre_expansion_lint(sess, features, self.0, registered_tools, (node_id, attrs, items), name);
107 }
108}
109
110#[instrument(level = "trace", skip(krate, resolver))]
115fn configure_and_expand(
116 mut krate: ast::Crate,
117 pre_configured_attrs: &[ast::Attribute],
118 resolver: &mut Resolver<'_, '_>,
119) -> ast::Crate {
120 let tcx = resolver.tcx();
121 let sess = tcx.sess;
122 let features = tcx.features();
123 let lint_store = unerased_lint_store(tcx.sess);
124 let crate_name = tcx.crate_name(LOCAL_CRATE);
125 let lint_check_node = (&krate, pre_configured_attrs);
126 pre_expansion_lint(
127 sess,
128 features,
129 lint_store,
130 tcx.registered_tools(()),
131 lint_check_node,
132 crate_name,
133 );
134 rustc_builtin_macros::register_builtin_macros(resolver);
135
136 let num_standard_library_imports = sess.time("crate_injection", || {
137 rustc_builtin_macros::standard_library_imports::inject(
138 &mut krate,
139 pre_configured_attrs,
140 resolver,
141 sess,
142 features,
143 )
144 });
145
146 util::check_attr_crate_type(sess, pre_configured_attrs, resolver.lint_buffer());
147
148 krate = sess.time("macro_expand_crate", || {
150 let mut old_path = OsString::new();
164 if cfg!(windows) {
165 old_path = env::var_os("PATH").unwrap_or(old_path);
166 let mut new_path = Vec::from_iter(
167 sess.host_filesearch().search_paths(PathKind::All).map(|p| p.dir.clone()),
168 );
169 for path in env::split_paths(&old_path) {
170 if !new_path.contains(&path) {
171 new_path.push(path);
172 }
173 }
174 unsafe {
175 env::set_var(
176 "PATH",
177 &env::join_paths(
178 new_path.iter().filter(|p| env::join_paths(iter::once(p)).is_ok()),
179 )
180 .unwrap(),
181 );
182 }
183 }
184
185 let recursion_limit = get_recursion_limit(pre_configured_attrs, sess);
187 let cfg = rustc_expand::expand::ExpansionConfig {
188 crate_name: crate_name.to_string(),
189 features,
190 recursion_limit,
191 trace_mac: sess.opts.unstable_opts.trace_macros,
192 should_test: sess.is_test_crate(),
193 span_debug: sess.opts.unstable_opts.span_debug,
194 proc_macro_backtrace: sess.opts.unstable_opts.proc_macro_backtrace,
195 };
196
197 let lint_store = LintStoreExpandImpl(lint_store);
198 let mut ecx = ExtCtxt::new(sess, cfg, resolver, Some(&lint_store));
199 ecx.num_standard_library_imports = num_standard_library_imports;
200 let krate = sess.time("expand_crate", || ecx.monotonic_expander().expand_crate(krate));
202
203 sess.psess.buffered_lints.with_lock(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
206 buffered_lints.append(&mut ecx.buffered_early_lint);
207 });
208
209 sess.time("check_unused_macros", || {
210 ecx.check_unused_macros();
211 });
212
213 if ecx.reduced_recursion_limit.is_some() {
216 sess.dcx().abort_if_errors();
217 unreachable!();
218 }
219
220 if cfg!(windows) {
221 unsafe {
222 env::set_var("PATH", &old_path);
223 }
224 }
225
226 krate
227 });
228
229 sess.time("maybe_building_test_harness", || {
230 rustc_builtin_macros::test_harness::inject(&mut krate, sess, features, resolver)
231 });
232
233 let has_proc_macro_decls = sess.time("AST_validation", || {
234 rustc_ast_passes::ast_validation::check_crate(
235 sess,
236 features,
237 &krate,
238 resolver.lint_buffer(),
239 )
240 });
241
242 let crate_types = tcx.crate_types();
243 let is_executable_crate = crate_types.contains(&CrateType::Executable);
244 let is_proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
245
246 if crate_types.len() > 1 {
247 if is_executable_crate {
248 sess.dcx().emit_err(errors::MixedBinCrate);
249 }
250 if is_proc_macro_crate {
251 sess.dcx().emit_err(errors::MixedProcMacroCrate);
252 }
253 }
254
255 if is_proc_macro_crate && sess.panic_strategy() == PanicStrategy::Abort {
256 sess.dcx().emit_warn(errors::ProcMacroCratePanicAbort);
257 }
258
259 sess.time("maybe_create_a_macro_crate", || {
260 let is_test_crate = sess.is_test_crate();
261 rustc_builtin_macros::proc_macro_harness::inject(
262 &mut krate,
263 sess,
264 features,
265 resolver,
266 is_proc_macro_crate,
267 has_proc_macro_decls,
268 is_test_crate,
269 sess.dcx(),
270 )
271 });
272
273 resolver.resolve_crate(&krate);
276
277 CStore::from_tcx(tcx).report_incompatible_target_modifiers(tcx, &krate);
278 krate
279}
280
281fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
282 let sess = tcx.sess;
283 let (resolver, krate) = &*tcx.resolver_for_lowering().borrow();
284 let mut lint_buffer = resolver.lint_buffer.steal();
285
286 if sess.opts.unstable_opts.input_stats {
287 input_stats::print_ast_stats(krate, "POST EXPANSION AST STATS", "ast-stats-2");
288 }
289
290 sess.time("complete_gated_feature_checking", || {
292 rustc_ast_passes::feature_gate::check_crate(krate, sess, tcx.features());
293 });
294
295 sess.psess.buffered_lints.with_lock(|buffered_lints| {
297 info!("{} parse sess buffered_lints", buffered_lints.len());
298 for early_lint in buffered_lints.drain(..) {
299 lint_buffer.add_early_lint(early_lint);
300 }
301 });
302
303 sess.psess.bad_unicode_identifiers.with_lock(|identifiers| {
305 for (ident, mut spans) in identifiers.drain(..) {
306 spans.sort();
307 if ident == sym::ferris {
308 enum FerrisFix {
309 SnakeCase,
310 ScreamingSnakeCase,
311 PascalCase,
312 }
313
314 impl FerrisFix {
315 const fn as_str(self) -> &'static str {
316 match self {
317 FerrisFix::SnakeCase => "ferris",
318 FerrisFix::ScreamingSnakeCase => "FERRIS",
319 FerrisFix::PascalCase => "Ferris",
320 }
321 }
322 }
323
324 let first_span = spans[0];
325 let prev_source = sess.psess.source_map().span_to_prev_source(first_span);
326 let ferris_fix = prev_source
327 .map_or(FerrisFix::SnakeCase, |source| {
328 let mut source_before_ferris = source.trim_end().split_whitespace().rev();
329 match source_before_ferris.next() {
330 Some("struct" | "trait" | "mod" | "union" | "type" | "enum") => {
331 FerrisFix::PascalCase
332 }
333 Some("const" | "static") => FerrisFix::ScreamingSnakeCase,
334 Some("mut") if source_before_ferris.next() == Some("static") => {
335 FerrisFix::ScreamingSnakeCase
336 }
337 _ => FerrisFix::SnakeCase,
338 }
339 })
340 .as_str();
341
342 sess.dcx().emit_err(errors::FerrisIdentifier { spans, first_span, ferris_fix });
343 } else {
344 sess.dcx().emit_err(errors::EmojiIdentifier { spans, ident });
345 }
346 }
347 });
348
349 let lint_store = unerased_lint_store(tcx.sess);
350 rustc_lint::check_ast_node(
351 sess,
352 Some(tcx),
353 tcx.features(),
354 false,
355 lint_store,
356 tcx.registered_tools(()),
357 Some(lint_buffer),
358 rustc_lint::BuiltinCombinedEarlyLintPass::new(),
359 (&**krate, &*krate.attrs),
360 )
361}
362
363fn generated_output_paths(
365 tcx: TyCtxt<'_>,
366 outputs: &OutputFilenames,
367 exact_name: bool,
368 crate_name: Symbol,
369) -> Vec<PathBuf> {
370 let sess = tcx.sess;
371 let mut out_filenames = Vec::new();
372 for output_type in sess.opts.output_types.keys() {
373 let out_filename = outputs.path(*output_type);
374 let file = out_filename.as_path().to_path_buf();
375 match *output_type {
376 OutputType::Exe if !exact_name => {
379 for crate_type in tcx.crate_types().iter() {
380 let p = filename_for_input(sess, *crate_type, crate_name, outputs);
381 out_filenames.push(p.as_path().to_path_buf());
382 }
383 }
384 OutputType::DepInfo if sess.opts.unstable_opts.dep_info_omit_d_target => {
385 }
387 OutputType::DepInfo if out_filename.is_stdout() => {
388 }
390 _ => {
391 out_filenames.push(file);
392 }
393 }
394 }
395 out_filenames
396}
397
398fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
399 let input_path = try_canonicalize(input_path).ok();
400 if input_path.is_none() {
401 return false;
402 }
403 output_paths.iter().any(|output_path| try_canonicalize(output_path).ok() == input_path)
404}
405
406fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<&PathBuf> {
407 output_paths.iter().find(|output_path| output_path.is_dir())
408}
409
410fn escape_dep_filename(filename: &str) -> String {
411 filename.replace(' ', "\\ ")
414}
415
416fn escape_dep_env(symbol: Symbol) -> String {
419 let s = symbol.as_str();
420 let mut escaped = String::with_capacity(s.len());
421 for c in s.chars() {
422 match c {
423 '\n' => escaped.push_str(r"\n"),
424 '\r' => escaped.push_str(r"\r"),
425 '\\' => escaped.push_str(r"\\"),
426 _ => escaped.push(c),
427 }
428 }
429 escaped
430}
431
432fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[PathBuf]) {
433 let sess = tcx.sess;
435 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
436 return;
437 }
438 let deps_output = outputs.path(OutputType::DepInfo);
439 let deps_filename = deps_output.as_path();
440
441 let result: io::Result<()> = try {
442 let mut files: Vec<(String, u64, Option<SourceFileHash>)> = sess
445 .source_map()
446 .files()
447 .iter()
448 .filter(|fmap| fmap.is_real_file())
449 .filter(|fmap| !fmap.is_imported())
450 .map(|fmap| {
451 (
452 escape_dep_filename(&fmap.name.prefer_local().to_string()),
453 fmap.source_len.0 as u64,
454 fmap.checksum_hash,
455 )
456 })
457 .collect();
458
459 let checksum_hash_algo = sess.opts.unstable_opts.checksum_hash_algorithm;
460
461 let file_depinfo = sess.psess.file_depinfo.borrow();
464
465 let normalize_path = |path: PathBuf| {
466 let file = FileName::from(path);
467 escape_dep_filename(&file.prefer_local().to_string())
468 };
469
470 fn hash_iter_files<P: AsRef<Path>>(
473 it: impl Iterator<Item = P>,
474 checksum_hash_algo: Option<SourceFileHashAlgorithm>,
475 ) -> impl Iterator<Item = (P, u64, Option<SourceFileHash>)> {
476 it.map(move |path| {
477 match checksum_hash_algo.and_then(|algo| {
478 fs::File::open(path.as_ref())
479 .and_then(|mut file| {
480 SourceFileHash::new(algo, &mut file).map(|h| (file, h))
481 })
482 .and_then(|(file, h)| file.metadata().map(|m| (m.len(), h)))
483 .map_err(|e| {
484 tracing::error!(
485 "failed to compute checksum, omitting it from dep-info {} {e}",
486 path.as_ref().display()
487 )
488 })
489 .ok()
490 }) {
491 Some((file_len, checksum)) => (path, file_len, Some(checksum)),
492 None => (path, 0, None),
493 }
494 })
495 }
496
497 let extra_tracked_files = hash_iter_files(
498 file_depinfo.iter().map(|path_sym| normalize_path(PathBuf::from(path_sym.as_str()))),
499 checksum_hash_algo,
500 );
501 files.extend(extra_tracked_files);
502
503 if let Some(ref profile_instr) = sess.opts.cg.profile_use {
505 files.extend(hash_iter_files(
506 iter::once(normalize_path(profile_instr.as_path().to_path_buf())),
507 checksum_hash_algo,
508 ));
509 }
510 if let Some(ref profile_sample) = sess.opts.unstable_opts.profile_sample_use {
511 files.extend(hash_iter_files(
512 iter::once(normalize_path(profile_sample.as_path().to_path_buf())),
513 checksum_hash_algo,
514 ));
515 }
516
517 for debugger_visualizer in tcx.debugger_visualizers(LOCAL_CRATE) {
519 files.extend(hash_iter_files(
520 iter::once(normalize_path(debugger_visualizer.path.clone().unwrap())),
521 checksum_hash_algo,
522 ));
523 }
524
525 if sess.binary_dep_depinfo() {
526 if let Some(ref backend) = sess.opts.unstable_opts.codegen_backend {
527 if backend.contains('.') {
528 files.extend(hash_iter_files(
531 iter::once(backend.to_string()),
532 checksum_hash_algo,
533 ));
534 }
535 }
536
537 for &cnum in tcx.crates(()) {
538 let source = tcx.used_crate_source(cnum);
539 if let Some((path, _)) = &source.dylib {
540 files.extend(hash_iter_files(
541 iter::once(escape_dep_filename(&path.display().to_string())),
542 checksum_hash_algo,
543 ));
544 }
545 if let Some((path, _)) = &source.rlib {
546 files.extend(hash_iter_files(
547 iter::once(escape_dep_filename(&path.display().to_string())),
548 checksum_hash_algo,
549 ));
550 }
551 if let Some((path, _)) = &source.rmeta {
552 files.extend(hash_iter_files(
553 iter::once(escape_dep_filename(&path.display().to_string())),
554 checksum_hash_algo,
555 ));
556 }
557 }
558 }
559
560 let write_deps_to_file = |file: &mut dyn Write| -> io::Result<()> {
561 for path in out_filenames {
562 writeln!(
563 file,
564 "{}: {}\n",
565 path.display(),
566 files
567 .iter()
568 .map(|(path, _file_len, _checksum_hash_algo)| path.as_str())
569 .intersperse(" ")
570 .collect::<String>()
571 )?;
572 }
573
574 for (path, _file_len, _checksum_hash_algo) in &files {
578 writeln!(file, "{path}:")?;
579 }
580
581 let env_depinfo = sess.psess.env_depinfo.borrow();
583 if !env_depinfo.is_empty() {
584 #[allow(rustc::potential_query_instability)]
586 let mut envs: Vec<_> = env_depinfo
587 .iter()
588 .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env)))
589 .collect();
590 envs.sort_unstable();
591 writeln!(file)?;
592 for (k, v) in envs {
593 write!(file, "# env-dep:{k}")?;
594 if let Some(v) = v {
595 write!(file, "={v}")?;
596 }
597 writeln!(file)?;
598 }
599 }
600
601 if sess.opts.unstable_opts.checksum_hash_algorithm().is_some() {
604 files
605 .iter()
606 .filter_map(|(path, file_len, hash_algo)| {
607 hash_algo.map(|hash_algo| (path, file_len, hash_algo))
608 })
609 .try_for_each(|(path, file_len, checksum_hash)| {
610 writeln!(file, "# checksum:{checksum_hash} file_len:{file_len} {path}")
611 })?;
612 }
613
614 Ok(())
615 };
616
617 match deps_output {
618 OutFileName::Stdout => {
619 let mut file = BufWriter::new(io::stdout());
620 write_deps_to_file(&mut file)?;
621 }
622 OutFileName::Real(ref path) => {
623 let mut file = fs::File::create_buffered(path)?;
624 write_deps_to_file(&mut file)?;
625 }
626 }
627 };
628
629 match result {
630 Ok(_) => {
631 if sess.opts.json_artifact_notifications {
632 sess.dcx().emit_artifact_notification(deps_filename, "dep-info");
633 }
634 }
635 Err(error) => {
636 sess.dcx().emit_fatal(errors::ErrorWritingDependencies { path: deps_filename, error });
637 }
638 }
639}
640
641fn resolver_for_lowering_raw<'tcx>(
642 tcx: TyCtxt<'tcx>,
643 (): (),
644) -> (&'tcx Steal<(ty::ResolverAstLowering, Arc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
645 let arenas = Resolver::arenas();
646 let _ = tcx.registered_tools(()); let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
648 let mut resolver = Resolver::new(
649 tcx,
650 &pre_configured_attrs,
651 krate.spans.inner_span,
652 krate.spans.inject_use_span,
653 &arenas,
654 );
655 let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver);
656
657 tcx.untracked().cstore.freeze();
659
660 let ty::ResolverOutputs {
661 global_ctxt: untracked_resolutions,
662 ast_lowering: untracked_resolver_for_lowering,
663 } = resolver.into_outputs();
664
665 let resolutions = tcx.arena.alloc(untracked_resolutions);
666 (tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Arc::new(krate)))), resolutions)
667}
668
669pub fn write_dep_info(tcx: TyCtxt<'_>) {
670 let _ = tcx.resolver_for_lowering();
674
675 let sess = tcx.sess;
676 let _timer = sess.timer("write_dep_info");
677 let crate_name = tcx.crate_name(LOCAL_CRATE);
678
679 let outputs = tcx.output_filenames(());
680 let output_paths =
681 generated_output_paths(tcx, &outputs, sess.io.output_file.is_some(), crate_name);
682
683 if let Some(input_path) = sess.io.input.opt_path() {
685 if sess.opts.will_create_output_file() {
686 if output_contains_path(&output_paths, input_path) {
687 sess.dcx().emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path });
688 }
689 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
690 sess.dcx().emit_fatal(errors::GeneratedFileConflictsWithDirectory {
691 input_path,
692 dir_path,
693 });
694 }
695 }
696 }
697
698 if let Some(ref dir) = sess.io.temps_dir {
699 if fs::create_dir_all(dir).is_err() {
700 sess.dcx().emit_fatal(errors::TempsDirError);
701 }
702 }
703
704 write_out_deps(tcx, &outputs, &output_paths);
705
706 let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo)
707 && sess.opts.output_types.len() == 1;
708
709 if !only_dep_info {
710 if let Some(ref dir) = sess.io.output_dir {
711 if fs::create_dir_all(dir).is_err() {
712 sess.dcx().emit_fatal(errors::OutDirError);
713 }
714 }
715 }
716}
717
718pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
719 let providers = &mut Providers::default();
720 providers.analysis = analysis;
721 providers.hir_crate = rustc_ast_lowering::lower_to_hir;
722 providers.resolver_for_lowering_raw = resolver_for_lowering_raw;
723 providers.stripped_cfg_items =
724 |tcx, _| tcx.arena.alloc_from_iter(tcx.resolutions(()).stripped_cfg_items.steal());
725 providers.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
726 providers.early_lint_checks = early_lint_checks;
727 limits::provide(providers);
728 proc_macro_decls::provide(providers);
729 rustc_const_eval::provide(providers);
730 rustc_middle::hir::provide(providers);
731 rustc_borrowck::provide(providers);
732 rustc_incremental::provide(providers);
733 rustc_mir_build::provide(providers);
734 rustc_mir_transform::provide(providers);
735 rustc_monomorphize::provide(providers);
736 rustc_privacy::provide(providers);
737 rustc_query_impl::provide(providers);
738 rustc_resolve::provide(providers);
739 rustc_hir_analysis::provide(providers);
740 rustc_hir_typeck::provide(providers);
741 ty::provide(providers);
742 traits::provide(providers);
743 rustc_passes::provide(providers);
744 rustc_traits::provide(providers);
745 rustc_ty_utils::provide(providers);
746 rustc_metadata::provide(providers);
747 rustc_lint::provide(providers);
748 rustc_symbol_mangling::provide(providers);
749 rustc_codegen_ssa::provide(providers);
750 *providers
751});
752
753pub fn create_and_enter_global_ctxt<T, F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> T>(
754 compiler: &Compiler,
755 mut krate: rustc_ast::Crate,
756 f: F,
757) -> T {
758 let sess = &compiler.sess;
759
760 rustc_builtin_macros::cmdline_attrs::inject(
761 &mut krate,
762 &sess.psess,
763 &sess.opts.unstable_opts.crate_attr,
764 );
765
766 let pre_configured_attrs = rustc_expand::config::pre_configure_attrs(sess, &krate.attrs);
767
768 let crate_name = get_crate_name(sess, &pre_configured_attrs);
769 let crate_types = collect_crate_types(sess, &pre_configured_attrs);
770 let stable_crate_id = StableCrateId::new(
771 crate_name,
772 crate_types.contains(&CrateType::Executable),
773 sess.opts.cg.metadata.clone(),
774 sess.cfg_version,
775 );
776 let outputs = util::build_output_filenames(&pre_configured_attrs, sess);
777 let dep_graph = setup_dep_graph(sess, crate_name);
778
779 let cstore =
780 FreezeLock::new(Box::new(CStore::new(compiler.codegen_backend.metadata_loader())) as _);
781 let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
782
783 let stable_crate_ids = FreezeLock::new(StableCrateIdMap::default());
784 let untracked =
785 Untracked { cstore, source_span: AppendOnlyIndexVec::new(), definitions, stable_crate_ids };
786
787 dep_graph.assert_ignored();
791
792 let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess);
793
794 let codegen_backend = &compiler.codegen_backend;
795 let mut providers = *DEFAULT_QUERY_PROVIDERS;
796 codegen_backend.provide(&mut providers);
797
798 if let Some(callback) = compiler.override_queries {
799 callback(sess, &mut providers);
800 }
801
802 let incremental = dep_graph.is_fully_enabled();
803
804 let gcx_cell = OnceLock::new();
805 let arena = WorkerLocal::new(|_| Arena::default());
806 let hir_arena = WorkerLocal::new(|_| rustc_hir::Arena::default());
807
808 let inner: Box<
811 dyn for<'tcx> FnOnce(
812 &'tcx Session,
813 CurrentGcx,
814 &'tcx OnceLock<GlobalCtxt<'tcx>>,
815 &'tcx WorkerLocal<Arena<'tcx>>,
816 &'tcx WorkerLocal<rustc_hir::Arena<'tcx>>,
817 F,
818 ) -> T,
819 > = Box::new(move |sess, current_gcx, gcx_cell, arena, hir_arena, f| {
820 TyCtxt::create_global_ctxt(
821 gcx_cell,
822 sess,
823 crate_types,
824 stable_crate_id,
825 arena,
826 hir_arena,
827 untracked,
828 dep_graph,
829 rustc_query_impl::query_callbacks(arena),
830 rustc_query_impl::query_system(
831 providers.queries,
832 providers.extern_queries,
833 query_result_on_disk_cache,
834 incremental,
835 ),
836 providers.hooks,
837 current_gcx,
838 |tcx| {
839 let feed = tcx.create_crate_num(stable_crate_id).unwrap();
840 assert_eq!(feed.key(), LOCAL_CRATE);
841 feed.crate_name(crate_name);
842
843 let feed = tcx.feed_unit_query();
844 feed.features_query(tcx.arena.alloc(rustc_expand::config::features(
845 tcx.sess,
846 &pre_configured_attrs,
847 crate_name,
848 )));
849 feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
850 feed.output_filenames(Arc::new(outputs));
851
852 let res = f(tcx);
853 tcx.finish();
855 res
856 },
857 )
858 });
859
860 inner(&compiler.sess, compiler.current_gcx.clone(), &gcx_cell, &arena, &hir_arena, f)
861}
862
863fn run_required_analyses(tcx: TyCtxt<'_>) {
866 if tcx.sess.opts.unstable_opts.input_stats {
867 rustc_passes::input_stats::print_hir_stats(tcx);
868 }
869 #[cfg(all(not(doc), debug_assertions))]
872 rustc_passes::hir_id_validator::check_crate(tcx);
873 let sess = tcx.sess;
874 sess.time("misc_checking_1", || {
875 parallel!(
876 {
877 sess.time("looking_for_entry_point", || tcx.ensure_ok().entry_fn(()));
878
879 sess.time("looking_for_derive_registrar", || {
880 tcx.ensure_ok().proc_macro_decls_static(())
881 });
882
883 CStore::from_tcx(tcx).report_unused_deps(tcx);
884 },
885 {
886 tcx.par_hir_for_each_module(|module| {
887 tcx.ensure_ok().check_mod_loops(module);
888 tcx.ensure_ok().check_mod_attrs(module);
889 tcx.ensure_ok().check_mod_naked_functions(module);
890 tcx.ensure_ok().check_mod_unstable_api_usage(module);
891 });
892 },
893 {
894 sess.time("unused_lib_feature_checking", || {
895 rustc_passes::stability::check_unused_or_stable_features(tcx)
896 });
897 },
898 {
899 tcx.ensure_ok().limits(());
904 tcx.ensure_ok().stability_index(());
905 }
906 );
907 });
908
909 rustc_hir_analysis::check_crate(tcx);
910 sess.time("MIR_coroutine_by_move_body", || {
911 tcx.par_hir_body_owners(|def_id| {
912 if tcx.needs_coroutine_by_move_body_def_id(def_id.to_def_id()) {
913 tcx.ensure_done().coroutine_by_move_body_def_id(def_id);
914 }
915 });
916 });
917 tcx.untracked().definitions.freeze();
923
924 sess.time("MIR_borrow_checking", || {
925 tcx.par_hir_body_owners(|def_id| {
926 tcx.ensure_ok().check_unsafety(def_id);
929 tcx.ensure_ok().mir_borrowck(def_id)
930 });
931 });
932 sess.time("MIR_effect_checking", || {
933 tcx.par_hir_body_owners(|def_id| {
934 tcx.ensure_ok().has_ffi_unwind_calls(def_id);
935
936 if tcx.sess.opts.output_types.should_codegen()
940 || tcx.hir_body_const_context(def_id).is_some()
941 {
942 tcx.ensure_ok().mir_drops_elaborated_and_const_checked(def_id);
943 }
944 });
945 });
946 sess.time("coroutine_obligations", || {
947 tcx.par_hir_body_owners(|def_id| {
948 if tcx.is_coroutine(def_id.to_def_id()) {
949 tcx.ensure_ok().mir_coroutine_witnesses(def_id);
950 tcx.ensure_ok().check_coroutine_obligations(
951 tcx.typeck_root_def_id(def_id.to_def_id()).expect_local(),
952 );
953 tcx.ensure_ok().layout_of(
955 ty::TypingEnv::post_analysis(tcx, def_id.to_def_id())
956 .as_query_input(tcx.type_of(def_id).instantiate_identity()),
957 );
958 }
959 });
960 });
961
962 sess.time("layout_testing", || layout_test::test_layout(tcx));
963 sess.time("abi_testing", || abi_test::test_abi(tcx));
964
965 if tcx.sess.opts.unstable_opts.validate_mir {
970 sess.time("ensuring_final_MIR_is_computable", || {
971 tcx.par_hir_body_owners(|def_id| {
972 tcx.instance_mir(ty::InstanceKind::Item(def_id.into()));
973 });
974 });
975 }
976}
977
978fn analysis(tcx: TyCtxt<'_>, (): ()) {
981 run_required_analyses(tcx);
982
983 let sess = tcx.sess;
984
985 if let Some(guar) = sess.dcx().has_errors_excluding_lint_errors() {
994 guar.raise_fatal();
995 }
996
997 sess.time("misc_checking_3", || {
998 parallel!(
999 {
1000 tcx.ensure_ok().effective_visibilities(());
1001
1002 parallel!(
1003 {
1004 tcx.ensure_ok().check_private_in_public(());
1005 },
1006 {
1007 tcx.par_hir_for_each_module(|module| {
1008 tcx.ensure_ok().check_mod_deathness(module)
1009 });
1010 },
1011 {
1012 sess.time("lint_checking", || {
1013 rustc_lint::check_crate(tcx);
1014 });
1015 },
1016 {
1017 tcx.ensure_ok().clashing_extern_declarations(());
1018 }
1019 );
1020 },
1021 {
1022 sess.time("privacy_checking_modules", || {
1023 tcx.par_hir_for_each_module(|module| {
1024 tcx.ensure_ok().check_mod_privacy(module);
1025 });
1026 });
1027 }
1028 );
1029
1030 sess.time("check_lint_expectations", || tcx.ensure_ok().check_expectations(None));
1033
1034 let _ = tcx.all_diagnostic_items(());
1038 });
1039}
1040
1041fn check_for_rustc_errors_attr(tcx: TyCtxt<'_>) {
1045 let Some((def_id, _)) = tcx.entry_fn(()) else { return };
1046 for attr in tcx.get_attrs(def_id, sym::rustc_error) {
1047 match attr.meta_item_list() {
1048 Some(list)
1050 if list.iter().any(|list_item| {
1051 matches!(
1052 list_item.ident().map(|i| i.name),
1053 Some(sym::delayed_bug_from_inside_query)
1054 )
1055 }) =>
1056 {
1057 tcx.ensure_ok().trigger_delayed_bug(def_id);
1058 }
1059
1060 None => {
1062 tcx.dcx().emit_fatal(errors::RustcErrorFatal { span: tcx.def_span(def_id) });
1063 }
1064
1065 Some(_) => {
1067 tcx.dcx().emit_warn(errors::RustcErrorUnexpectedAnnotation {
1068 span: tcx.def_span(def_id),
1069 });
1070 }
1071 }
1072 }
1073}
1074
1075pub(crate) fn start_codegen<'tcx>(
1078 codegen_backend: &dyn CodegenBackend,
1079 tcx: TyCtxt<'tcx>,
1080) -> Box<dyn Any> {
1081 if let Some(guar) = tcx.sess.dcx().has_errors_or_delayed_bugs() {
1085 guar.raise_fatal();
1086 }
1087
1088 check_for_rustc_errors_attr(tcx);
1090
1091 info!("Pre-codegen\n{:?}", tcx.debug_stats());
1092
1093 let (metadata, need_metadata_module) = rustc_metadata::fs::encode_and_write_metadata(tcx);
1094
1095 let codegen = tcx.sess.time("codegen_crate", move || {
1096 codegen_backend.codegen_crate(tcx, metadata, need_metadata_module)
1097 });
1098
1099 if tcx.sess.opts.output_types.should_codegen() {
1102 rustc_symbol_mangling::test::report_symbol_names(tcx);
1103 }
1104
1105 info!("Post-codegen\n{:?}", tcx.debug_stats());
1106
1107 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
1108 if let Err(error) = rustc_mir_transform::dump_mir::emit_mir(tcx) {
1109 tcx.dcx().emit_fatal(errors::CantEmitMIR { error });
1110 }
1111 }
1112
1113 if tcx.sess.opts.unstable_opts.print_type_sizes {
1116 tcx.sess.code_stats.print_type_sizes();
1117 }
1118
1119 codegen
1120}
1121
1122pub fn get_crate_name(sess: &Session, krate_attrs: &[ast::Attribute]) -> Symbol {
1124 let attr_crate_name =
1132 validate_and_find_value_str_builtin_attr(sym::crate_name, sess, krate_attrs);
1133
1134 let validate = |name, span| {
1135 rustc_session::output::validate_crate_name(sess, name, span);
1136 name
1137 };
1138
1139 if let Some(crate_name) = &sess.opts.crate_name {
1140 let crate_name = Symbol::intern(crate_name);
1141 if let Some((attr_crate_name, span)) = attr_crate_name
1142 && attr_crate_name != crate_name
1143 {
1144 sess.dcx().emit_err(errors::CrateNameDoesNotMatch {
1145 span,
1146 crate_name,
1147 attr_crate_name,
1148 });
1149 }
1150 return validate(crate_name, None);
1151 }
1152
1153 if let Some((crate_name, span)) = attr_crate_name {
1154 return validate(crate_name, Some(span));
1155 }
1156
1157 if let Input::File(ref path) = sess.io.input
1158 && let Some(file_stem) = path.file_stem().and_then(|s| s.to_str())
1159 {
1160 if file_stem.starts_with('-') {
1161 sess.dcx().emit_err(errors::CrateNameInvalid { crate_name: file_stem });
1162 } else {
1163 return validate(Symbol::intern(&file_stem.replace('-', "_")), None);
1164 }
1165 }
1166
1167 sym::rust_out
1168}
1169
1170fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit {
1171 let _ = validate_and_find_value_str_builtin_attr(sym::recursion_limit, sess, krate_attrs);
1175 crate::limits::get_recursion_limit(krate_attrs, sess)
1176}
1177
1178fn validate_and_find_value_str_builtin_attr(
1189 name: Symbol,
1190 sess: &Session,
1191 krate_attrs: &[ast::Attribute],
1192) -> Option<(Symbol, Span)> {
1193 let mut result = None;
1194 for attr in ast::attr::filter_by_name(krate_attrs, name) {
1196 let Some(value) = attr.value_str() else {
1197 validate_attr::emit_fatal_malformed_builtin_attribute(&sess.psess, attr, name)
1198 };
1199 result.get_or_insert((value, attr.span));
1201 }
1202 result
1203}