Skip to content

Commit 2ce16d1

Browse files
authored
Unrolled build for rust-lang#122811
Rollup merge of rust-lang#122811 - nnethercote:mv-SourceMap-init, r=WaffleLapkin Move `SourceMap` initialization So it happens at the same time as `SessionGlobals` initialization, rather than shortly afterward. r? `@WaffleLapkin`
2 parents 468f115 + 9b0ced0 commit 2ce16d1

File tree

10 files changed

+177
-177
lines changed

10 files changed

+177
-177
lines changed

compiler/rustc_hir/src/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ fn def_path_hash_depends_on_crate_id() {
1414
// the crate by changing the crate disambiguator (e.g. via bumping the
1515
// crate's version number).
1616

17-
create_session_globals_then(Edition::Edition2024, || {
17+
create_session_globals_then(Edition::Edition2024, None, || {
1818
let id0 = StableCrateId::new(Symbol::intern("foo"), false, vec!["1".to_string()], "");
1919
let id1 = StableCrateId::new(Symbol::intern("foo"), false, vec!["2".to_string()], "");
2020

compiler/rustc_interface/src/interface.rs

+61-48
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use rustc_ast::{LitKind, MetaItemKind};
55
use rustc_codegen_ssa::traits::CodegenBackend;
66
use rustc_data_structures::defer;
77
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8+
use rustc_data_structures::jobserver;
89
use rustc_data_structures::stable_hasher::StableHasher;
910
use rustc_data_structures::sync::Lrc;
1011
use rustc_errors::registry::Registry;
@@ -21,7 +22,7 @@ use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, OutFileN
2122
use rustc_session::filesearch::{self, sysroot_candidates};
2223
use rustc_session::parse::ParseSess;
2324
use rustc_session::{lint, CompilerIO, EarlyDiagCtxt, Session};
24-
use rustc_span::source_map::FileLoader;
25+
use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs};
2526
use rustc_span::symbol::sym;
2627
use rustc_span::FileName;
2728
use std::path::PathBuf;
@@ -323,6 +324,18 @@ pub struct Config {
323324
pub expanded_args: Vec<String>,
324325
}
325326

327+
/// Initialize jobserver before getting `jobserver::client` and `build_session`.
328+
pub(crate) fn initialize_checked_jobserver(early_dcx: &EarlyDiagCtxt) {
329+
jobserver::initialize_checked(|err| {
330+
#[allow(rustc::untranslatable_diagnostic)]
331+
#[allow(rustc::diagnostic_outside_of_impl)]
332+
early_dcx
333+
.early_struct_warn(err)
334+
.with_note("the build environment is likely misconfigured")
335+
.emit()
336+
});
337+
}
338+
326339
// JUSTIFICATION: before session exists, only config
327340
#[allow(rustc::bad_opt_access)]
328341
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
@@ -334,20 +347,25 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
334347

335348
// Check jobserver before run_in_thread_pool_with_globals, which call jobserver::acquire_thread
336349
let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
337-
early_dcx.initialize_checked_jobserver();
350+
initialize_checked_jobserver(&early_dcx);
351+
352+
crate::callbacks::setup_callbacks();
353+
354+
let sysroot = filesearch::materialize_sysroot(config.opts.maybe_sysroot.clone());
355+
let target = config::build_target_config(&early_dcx, &config.opts, &sysroot);
356+
let file_loader = config.file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
357+
let path_mapping = config.opts.file_path_mapping();
358+
let hash_kind = config.opts.unstable_opts.src_hash_algorithm(&target);
338359

339360
util::run_in_thread_pool_with_globals(
340361
config.opts.edition,
341362
config.opts.unstable_opts.threads,
363+
SourceMapInputs { file_loader, path_mapping, hash_kind },
342364
|current_gcx| {
343-
crate::callbacks::setup_callbacks();
344-
365+
// The previous `early_dcx` can't be reused here because it doesn't
366+
// impl `Send`. Creating a new one is fine.
345367
let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
346368

347-
let sysroot = filesearch::materialize_sysroot(config.opts.maybe_sysroot.clone());
348-
349-
let target = config::build_target_config(&early_dcx, &config.opts, &sysroot);
350-
351369
let codegen_backend = match config.make_codegen_backend {
352370
None => util::get_codegen_backend(
353371
&early_dcx,
@@ -372,9 +390,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
372390
config.opts.unstable_opts.translate_directionality_markers,
373391
) {
374392
Ok(bundle) => bundle,
375-
Err(e) => {
376-
early_dcx.early_fatal(format!("failed to load fluent bundle: {e}"));
377-
}
393+
Err(e) => early_dcx.early_fatal(format!("failed to load fluent bundle: {e}")),
378394
};
379395

380396
let mut locale_resources = Vec::from(config.locale_resources);
@@ -393,7 +409,6 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
393409
config.registry.clone(),
394410
locale_resources,
395411
config.lint_caps,
396-
config.file_loader,
397412
target,
398413
sysroot,
399414
util::rustc_version_str().unwrap_or("unknown"),
@@ -440,45 +455,43 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
440455
current_gcx,
441456
};
442457

443-
rustc_span::set_source_map(compiler.sess.psess.clone_source_map(), move || {
444-
// There are two paths out of `f`.
445-
// - Normal exit.
446-
// - Panic, e.g. triggered by `abort_if_errors`.
447-
//
448-
// We must run `finish_diagnostics` in both cases.
449-
let res = {
450-
// If `f` panics, `finish_diagnostics` will run during
451-
// unwinding because of the `defer`.
452-
let mut guar = None;
453-
let sess_abort_guard = defer(|| {
454-
guar = compiler.sess.finish_diagnostics(&config.registry);
455-
});
456-
457-
let res = f(&compiler);
458-
459-
// If `f` doesn't panic, `finish_diagnostics` will run
460-
// normally when `sess_abort_guard` is dropped.
461-
drop(sess_abort_guard);
462-
463-
// If `finish_diagnostics` emits errors (e.g. stashed
464-
// errors) we can't return an error directly, because the
465-
// return type of this function is `R`, not `Result<R, E>`.
466-
// But we need to communicate the errors' existence to the
467-
// caller, otherwise the caller might mistakenly think that
468-
// no errors occurred and return a zero exit code. So we
469-
// abort (panic) instead, similar to if `f` had panicked.
470-
if guar.is_some() {
471-
compiler.sess.dcx().abort_if_errors();
472-
}
458+
// There are two paths out of `f`.
459+
// - Normal exit.
460+
// - Panic, e.g. triggered by `abort_if_errors`.
461+
//
462+
// We must run `finish_diagnostics` in both cases.
463+
let res = {
464+
// If `f` panics, `finish_diagnostics` will run during
465+
// unwinding because of the `defer`.
466+
let mut guar = None;
467+
let sess_abort_guard = defer(|| {
468+
guar = compiler.sess.finish_diagnostics(&config.registry);
469+
});
470+
471+
let res = f(&compiler);
472+
473+
// If `f` doesn't panic, `finish_diagnostics` will run
474+
// normally when `sess_abort_guard` is dropped.
475+
drop(sess_abort_guard);
476+
477+
// If `finish_diagnostics` emits errors (e.g. stashed
478+
// errors) we can't return an error directly, because the
479+
// return type of this function is `R`, not `Result<R, E>`.
480+
// But we need to communicate the errors' existence to the
481+
// caller, otherwise the caller might mistakenly think that
482+
// no errors occurred and return a zero exit code. So we
483+
// abort (panic) instead, similar to if `f` had panicked.
484+
if guar.is_some() {
485+
compiler.sess.dcx().abort_if_errors();
486+
}
473487

474-
res
475-
};
488+
res
489+
};
476490

477-
let prof = compiler.sess.prof.clone();
478-
prof.generic_activity("drop_compiler").run(move || drop(compiler));
491+
let prof = compiler.sess.prof.clone();
492+
prof.generic_activity("drop_compiler").run(move || drop(compiler));
479493

480-
res
481-
})
494+
res
482495
},
483496
)
484497
}

compiler/rustc_interface/src/tests.rs

+48-50
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#![allow(rustc::bad_opt_access)]
2-
use crate::interface::parse_cfg;
2+
use crate::interface::{initialize_checked_jobserver, parse_cfg};
33
use rustc_data_structures::profiling::TimePassesFormat;
44
use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig};
55
use rustc_session::config::{
@@ -16,6 +16,7 @@ use rustc_session::search_paths::SearchPath;
1616
use rustc_session::utils::{CanonicalizedPath, NativeLib, NativeLibKind};
1717
use rustc_session::{build_session, filesearch, getopts, CompilerIO, EarlyDiagCtxt, Session};
1818
use rustc_span::edition::{Edition, DEFAULT_EDITION};
19+
use rustc_span::source_map::{RealFileLoader, SourceMapInputs};
1920
use rustc_span::symbol::sym;
2021
use rustc_span::{FileName, SourceFileHashAlgorithm};
2122
use rustc_target::spec::{CodeModel, LinkerFlavorCli, MergeFunctions, PanicStrategy, RelocModel};
@@ -25,42 +26,52 @@ use std::num::NonZero;
2526
use std::path::{Path, PathBuf};
2627
use std::sync::Arc;
2728

28-
fn mk_session(matches: getopts::Matches) -> (Session, Cfg) {
29+
fn sess_and_cfg<F>(args: &[&'static str], f: F)
30+
where
31+
F: FnOnce(Session, Cfg),
32+
{
2933
let mut early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
30-
early_dcx.initialize_checked_jobserver();
34+
initialize_checked_jobserver(&early_dcx);
3135

32-
let registry = registry::Registry::new(&[]);
36+
let matches = optgroups().parse(args).unwrap();
3337
let sessopts = build_session_options(&mut early_dcx, &matches);
34-
let temps_dir = sessopts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
35-
let io = CompilerIO {
36-
input: Input::Str { name: FileName::Custom(String::new()), input: String::new() },
37-
output_dir: None,
38-
output_file: None,
39-
temps_dir,
40-
};
41-
4238
let sysroot = filesearch::materialize_sysroot(sessopts.maybe_sysroot.clone());
43-
4439
let target = rustc_session::config::build_target_config(&early_dcx, &sessopts, &sysroot);
40+
let hash_kind = sessopts.unstable_opts.src_hash_algorithm(&target);
41+
let sm_inputs = Some(SourceMapInputs {
42+
file_loader: Box::new(RealFileLoader) as _,
43+
path_mapping: sessopts.file_path_mapping(),
44+
hash_kind,
45+
});
4546

46-
let sess = build_session(
47-
early_dcx,
48-
sessopts,
49-
io,
50-
None,
51-
registry,
52-
vec![],
53-
Default::default(),
54-
None,
55-
target,
56-
sysroot,
57-
"",
58-
None,
59-
Arc::default(),
60-
Default::default(),
61-
);
62-
let cfg = parse_cfg(&sess.dcx(), matches.opt_strs("cfg"));
63-
(sess, cfg)
47+
rustc_span::create_session_globals_then(DEFAULT_EDITION, sm_inputs, || {
48+
let temps_dir = sessopts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
49+
let io = CompilerIO {
50+
input: Input::Str { name: FileName::Custom(String::new()), input: String::new() },
51+
output_dir: None,
52+
output_file: None,
53+
temps_dir,
54+
};
55+
56+
let sess = build_session(
57+
early_dcx,
58+
sessopts,
59+
io,
60+
None,
61+
registry::Registry::new(&[]),
62+
vec![],
63+
Default::default(),
64+
target,
65+
sysroot,
66+
"",
67+
None,
68+
Arc::default(),
69+
Default::default(),
70+
);
71+
let cfg = parse_cfg(&sess.dcx(), matches.opt_strs("cfg"));
72+
let cfg = build_configuration(&sess, cfg);
73+
f(sess, cfg)
74+
});
6475
}
6576

6677
fn new_public_extern_entry<S, I>(locations: I) -> ExternEntry
@@ -125,21 +136,15 @@ fn assert_non_crate_hash_different(x: &Options, y: &Options) {
125136
// When the user supplies --test we should implicitly supply --cfg test
126137
#[test]
127138
fn test_switch_implies_cfg_test() {
128-
rustc_span::create_default_session_globals_then(|| {
129-
let matches = optgroups().parse(&["--test".to_string()]).unwrap();
130-
let (sess, cfg) = mk_session(matches);
131-
let cfg = build_configuration(&sess, cfg);
139+
sess_and_cfg(&["--test"], |_sess, cfg| {
132140
assert!(cfg.contains(&(sym::test, None)));
133-
});
141+
})
134142
}
135143

136144
// When the user supplies --test and --cfg test, don't implicitly add another --cfg test
137145
#[test]
138146
fn test_switch_implies_cfg_test_unless_cfg_test() {
139-
rustc_span::create_default_session_globals_then(|| {
140-
let matches = optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]).unwrap();
141-
let (sess, cfg) = mk_session(matches);
142-
let cfg = build_configuration(&sess, cfg);
147+
sess_and_cfg(&["--test", "--cfg=test"], |_sess, cfg| {
143148
let mut test_items = cfg.iter().filter(|&&(name, _)| name == sym::test);
144149
assert!(test_items.next().is_some());
145150
assert!(test_items.next().is_none());
@@ -148,22 +153,15 @@ fn test_switch_implies_cfg_test_unless_cfg_test() {
148153

149154
#[test]
150155
fn test_can_print_warnings() {
151-
rustc_span::create_default_session_globals_then(|| {
152-
let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
153-
let (sess, _) = mk_session(matches);
156+
sess_and_cfg(&["-Awarnings"], |sess, _cfg| {
154157
assert!(!sess.dcx().can_emit_warnings());
155158
});
156159

157-
rustc_span::create_default_session_globals_then(|| {
158-
let matches =
159-
optgroups().parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()]).unwrap();
160-
let (sess, _) = mk_session(matches);
160+
sess_and_cfg(&["-Awarnings", "-Dwarnings"], |sess, _cfg| {
161161
assert!(sess.dcx().can_emit_warnings());
162162
});
163163

164-
rustc_span::create_default_session_globals_then(|| {
165-
let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
166-
let (sess, _) = mk_session(matches);
164+
sess_and_cfg(&["-Adead_code"], |sess, _cfg| {
167165
assert!(sess.dcx().can_emit_warnings());
168166
});
169167
}

compiler/rustc_interface/src/util.rs

+11-5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use rustc_session::lint::{self, BuiltinLintDiag, LintBuffer};
1414
use rustc_session::{filesearch, Session};
1515
use rustc_span::edit_distance::find_best_match_for_name;
1616
use rustc_span::edition::Edition;
17+
use rustc_span::source_map::SourceMapInputs;
1718
use rustc_span::symbol::sym;
1819
use rustc_target::spec::Target;
1920
use session::output::{categorize_crate_type, CRATE_TYPES};
@@ -65,8 +66,9 @@ fn init_stack_size() -> usize {
6566
})
6667
}
6768

68-
pub(crate) fn run_in_thread_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
69+
fn run_in_thread_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
6970
edition: Edition,
71+
sm_inputs: SourceMapInputs,
7072
f: F,
7173
) -> R {
7274
// The "thread pool" is a single spawned thread in the non-parallel
@@ -84,7 +86,9 @@ pub(crate) fn run_in_thread_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: S
8486
// name contains null bytes.
8587
let r = builder
8688
.spawn_scoped(s, move || {
87-
rustc_span::create_session_globals_then(edition, || f(CurrentGcx::new()))
89+
rustc_span::create_session_globals_then(edition, Some(sm_inputs), || {
90+
f(CurrentGcx::new())
91+
})
8892
})
8993
.unwrap()
9094
.join();
@@ -100,15 +104,17 @@ pub(crate) fn run_in_thread_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: S
100104
pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
101105
edition: Edition,
102106
_threads: usize,
107+
sm_inputs: SourceMapInputs,
103108
f: F,
104109
) -> R {
105-
run_in_thread_with_globals(edition, f)
110+
run_in_thread_with_globals(edition, sm_inputs, f)
106111
}
107112

108113
#[cfg(parallel_compiler)]
109114
pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send, R: Send>(
110115
edition: Edition,
111116
threads: usize,
117+
sm_inputs: SourceMapInputs,
112118
f: F,
113119
) -> R {
114120
use rustc_data_structures::{defer, jobserver, sync::FromDyn};
@@ -120,7 +126,7 @@ pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send,
120126
let registry = sync::Registry::new(std::num::NonZero::new(threads).unwrap());
121127

122128
if !sync::is_dyn_thread_safe() {
123-
return run_in_thread_with_globals(edition, |current_gcx| {
129+
return run_in_thread_with_globals(edition, sm_inputs, |current_gcx| {
124130
// Register the thread for use with the `WorkerLocal` type.
125131
registry.register();
126132

@@ -169,7 +175,7 @@ pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send,
169175
// pool. Upon creation, each worker thread created gets a copy of the
170176
// session globals in TLS. This is possible because `SessionGlobals` impls
171177
// `Send` in the parallel compiler.
172-
rustc_span::create_session_globals_then(edition, || {
178+
rustc_span::create_session_globals_then(edition, Some(sm_inputs), || {
173179
rustc_span::with_session_globals(|session_globals| {
174180
let session_globals = FromDyn::from(session_globals);
175181
builder

0 commit comments

Comments
 (0)