Skip to content

Commit d5f2b8e

Browse files
committed
Only depend on CFG_VERSION in rustc_interface
this avoids having to rebuild the whole compiler on each commit when `omit-git-hash = false`.
1 parent 0dddad0 commit d5f2b8e

File tree

24 files changed

+97
-71
lines changed

24 files changed

+97
-71
lines changed

compiler/rustc_attr/src/builtin.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@ use crate::session_diagnostics::{self, IncorrectReprFormatGenericCause};
2323
pub const VERSION_PLACEHOLDER: &str = "CURRENT_RUSTC_VERSION";
2424

2525
pub fn rust_version_symbol() -> Symbol {
26-
let version = option_env!("CFG_VERSION").unwrap_or("<current>");
27-
let version = version.split(' ').next().unwrap();
26+
let version = option_env!("CFG_RELEASE").unwrap_or("<current>");
2827
Symbol::intern(&version)
2928
}
3029

compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -806,8 +806,7 @@ pub fn build_compile_unit_di_node<'ll, 'tcx>(
806806
name_in_debuginfo.push(codegen_unit_name);
807807

808808
debug!("build_compile_unit_di_node: {:?}", name_in_debuginfo);
809-
let rustc_producer =
810-
format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
809+
let rustc_producer = format!("rustc version {}", tcx.sess.cfg_version);
811810
// FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
812811
let producer = format!("clang LLVM ({})", rustc_producer);
813812

compiler/rustc_codegen_ssa/src/lib.rs

+7-9
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
3636
use rustc_session::config::{CrateType, OutputFilenames, OutputType, RUST_CGU_EXT};
3737
use rustc_session::cstore::{self, CrateSource};
3838
use rustc_session::utils::NativeLibKind;
39+
use rustc_session::Session;
3940
use rustc_span::symbol::Symbol;
4041
use rustc_span::DebuggerVisualizerFile;
4142
use std::collections::BTreeSet;
@@ -175,11 +176,11 @@ pub struct CodegenResults {
175176
pub crate_info: CrateInfo,
176177
}
177178

178-
pub enum CodegenErrors<'a> {
179+
pub enum CodegenErrors {
179180
WrongFileType,
180181
EmptyVersionNumber,
181182
EncodingVersionMismatch { version_array: String, rlink_version: u32 },
182-
RustcVersionMismatch { rustc_version: String, current_version: &'a str },
183+
RustcVersionMismatch { rustc_version: String },
183184
}
184185

185186
pub fn provide(providers: &mut Providers) {
@@ -213,10 +214,9 @@ pub fn looks_like_rust_object_file(filename: &str) -> bool {
213214
const RLINK_VERSION: u32 = 1;
214215
const RLINK_MAGIC: &[u8] = b"rustlink";
215216

216-
const RUSTC_VERSION: Option<&str> = option_env!("CFG_VERSION");
217-
218217
impl CodegenResults {
219218
pub fn serialize_rlink(
219+
sess: &Session,
220220
rlink_file: &Path,
221221
codegen_results: &CodegenResults,
222222
) -> Result<usize, io::Error> {
@@ -225,12 +225,12 @@ impl CodegenResults {
225225
// `emit_raw_bytes` is used to make sure that the version representation does not depend on
226226
// Encoder's inner representation of `u32`.
227227
encoder.emit_raw_bytes(&RLINK_VERSION.to_be_bytes());
228-
encoder.emit_str(RUSTC_VERSION.unwrap());
228+
encoder.emit_str(sess.cfg_version);
229229
Encodable::encode(codegen_results, &mut encoder);
230230
encoder.finish()
231231
}
232232

233-
pub fn deserialize_rlink<'a>(data: Vec<u8>) -> Result<Self, CodegenErrors<'a>> {
233+
pub fn deserialize_rlink(sess: &Session, data: Vec<u8>) -> Result<Self, CodegenErrors> {
234234
// The Decodable machinery is not used here because it panics if the input data is invalid
235235
// and because its internal representation may change.
236236
if !data.starts_with(RLINK_MAGIC) {
@@ -252,11 +252,9 @@ impl CodegenResults {
252252

253253
let mut decoder = MemDecoder::new(&data[4..], 0);
254254
let rustc_version = decoder.read_str();
255-
let current_version = RUSTC_VERSION.unwrap();
256-
if rustc_version != current_version {
255+
if rustc_version != sess.cfg_version {
257256
return Err(CodegenErrors::RustcVersionMismatch {
258257
rustc_version: rustc_version.to_string(),
259-
current_version,
260258
});
261259
}
262260

compiler/rustc_driver_impl/src/lib.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -568,7 +568,7 @@ pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Comp
568568
let rlink_data = fs::read(file).unwrap_or_else(|err| {
569569
sess.emit_fatal(RlinkUnableToRead { err });
570570
});
571-
let codegen_results = match CodegenResults::deserialize_rlink(rlink_data) {
571+
let codegen_results = match CodegenResults::deserialize_rlink(sess, rlink_data) {
572572
Ok(codegen) => codegen,
573573
Err(err) => {
574574
match err {
@@ -582,10 +582,10 @@ pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Comp
582582
rlink_version,
583583
})
584584
}
585-
CodegenErrors::RustcVersionMismatch { rustc_version, current_version } => {
585+
CodegenErrors::RustcVersionMismatch { rustc_version } => {
586586
sess.emit_fatal(RLinkRustcVersionMismatch {
587587
rustc_version,
588-
current_version,
588+
current_version: sess.cfg_version,
589589
})
590590
}
591591
};

compiler/rustc_hir/src/tests.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@ fn def_path_hash_depends_on_crate_id() {
1010
// the crate-id of the defining crate. This is a desirable property
1111
// because the crate-id can be more easily changed than the DefPath
1212
// of an item, so, in the case of a crate-local DefPathHash collision,
13-
// the user can simply "role the dice again" for all DefPathHashes in
13+
// the user can simply "roll the dice again" for all DefPathHashes in
1414
// the crate by changing the crate disambiguator (e.g. via bumping the
1515
// crate's version number).
1616

1717
create_session_if_not_set_then(Edition::Edition2024, |_| {
18-
let id0 = StableCrateId::new(Symbol::intern("foo"), false, vec!["1".to_string()]);
19-
let id1 = StableCrateId::new(Symbol::intern("foo"), false, vec!["2".to_string()]);
18+
let id0 = StableCrateId::new(Symbol::intern("foo"), false, vec!["1".to_string()], "");
19+
let id1 = StableCrateId::new(Symbol::intern("foo"), false, vec!["2".to_string()], "");
2020

2121
let h0 = mk_test_hash(id0);
2222
let h1 = mk_test_hash(id1);

compiler/rustc_hir_typeck/src/expr.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -721,7 +721,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
721721
// ICE this expression in particular (see #43162).
722722
if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind {
723723
if path.segments.len() == 1 && path.segments[0].ident.name == sym::rust {
724-
fatally_break_rust(self.tcx.sess);
724+
fatally_break_rust(self.tcx);
725725
}
726726
}
727727
}

compiler/rustc_hir_typeck/src/lib.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,6 @@ use rustc_middle::traits;
7171
use rustc_middle::ty::query::Providers;
7272
use rustc_middle::ty::{self, Ty, TyCtxt};
7373
use rustc_session::config;
74-
use rustc_session::Session;
7574
use rustc_span::def_id::{DefId, LocalDefId};
7675
use rustc_span::{sym, Span};
7776

@@ -437,8 +436,8 @@ enum TupleArgumentsFlag {
437436
TupleArguments,
438437
}
439438

440-
fn fatally_break_rust(sess: &Session) {
441-
let handler = sess.diagnostic();
439+
fn fatally_break_rust(tcx: TyCtxt<'_>) {
440+
let handler = tcx.sess.diagnostic();
442441
handler.span_bug_no_panic(
443442
MultiSpan::new(),
444443
"It looks like you're trying to break rust; would you like some ICE?",
@@ -450,7 +449,7 @@ fn fatally_break_rust(sess: &Session) {
450449
);
451450
handler.note_without_error(format!(
452451
"rustc {} running on {}",
453-
option_env!("CFG_VERSION").unwrap_or("unknown_version"),
452+
tcx.sess.cfg_version,
454453
config::host_triple(),
455454
));
456455
}

compiler/rustc_incremental/src/persist/file_format.rs

+15-20
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use rustc_data_structures::memmap::Mmap;
1414
use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
1515
use rustc_serialize::Encoder;
1616
use rustc_session::Session;
17+
use std::borrow::Cow;
1718
use std::env;
1819
use std::fs;
1920
use std::io::{self, Read};
@@ -25,17 +26,12 @@ const FILE_MAGIC: &[u8] = b"RSIC";
2526
/// Change this if the header format changes.
2627
const HEADER_FORMAT_VERSION: u16 = 0;
2728

28-
/// A version string that hopefully is always different for compiler versions
29-
/// with different encodings of incremental compilation artifacts. Contains
30-
/// the Git commit hash.
31-
const RUSTC_VERSION: Option<&str> = option_env!("CFG_VERSION");
32-
33-
pub(crate) fn write_file_header(stream: &mut FileEncoder, nightly_build: bool) {
29+
pub(crate) fn write_file_header(stream: &mut FileEncoder, sess: &Session) {
3430
stream.emit_raw_bytes(FILE_MAGIC);
3531
stream
3632
.emit_raw_bytes(&[(HEADER_FORMAT_VERSION >> 0) as u8, (HEADER_FORMAT_VERSION >> 8) as u8]);
3733

38-
let rustc_version = rustc_version(nightly_build);
34+
let rustc_version = rustc_version(sess.is_nightly_build(), sess.cfg_version);
3935
assert_eq!(rustc_version.len(), (rustc_version.len() as u8) as usize);
4036
stream.emit_raw_bytes(&[rustc_version.len() as u8]);
4137
stream.emit_raw_bytes(rustc_version.as_bytes());
@@ -73,7 +69,7 @@ where
7369
}
7470
};
7571

76-
write_file_header(&mut encoder, sess.is_nightly_build());
72+
write_file_header(&mut encoder, sess);
7773

7874
match encode(encoder) {
7975
Ok(position) => {
@@ -100,9 +96,10 @@ where
10096
/// - Returns `Err(..)` if some kind of IO error occurred while reading the
10197
/// file.
10298
pub fn read_file(
103-
report_incremental_info: bool,
10499
path: &Path,
105-
nightly_build: bool,
100+
report_incremental_info: bool,
101+
is_nightly_build: bool,
102+
cfg_version: &'static str,
106103
) -> io::Result<Option<(Mmap, usize)>> {
107104
let file = match fs::File::open(path) {
108105
Ok(file) => file,
@@ -152,7 +149,7 @@ pub fn read_file(
152149
let mut buffer = vec![0; rustc_version_str_len];
153150
file.read_exact(&mut buffer)?;
154151

155-
if buffer != rustc_version(nightly_build).as_bytes() {
152+
if buffer != rustc_version(is_nightly_build, cfg_version).as_bytes() {
156153
report_format_mismatch(report_incremental_info, path, "Different compiler version");
157154
return Ok(None);
158155
}
@@ -174,17 +171,15 @@ fn report_format_mismatch(report_incremental_info: bool, file: &Path, message: &
174171
}
175172
}
176173

177-
fn rustc_version(nightly_build: bool) -> String {
174+
/// A version string that hopefully is always different for compiler versions
175+
/// with different encodings of incremental compilation artifacts. Contains
176+
/// the Git commit hash.
177+
fn rustc_version(nightly_build: bool, cfg_version: &'static str) -> Cow<'static, str> {
178178
if nightly_build {
179-
if let Some(val) = env::var_os("RUSTC_FORCE_RUSTC_VERSION") {
180-
return val.to_string_lossy().into_owned();
179+
if let Ok(val) = env::var("RUSTC_FORCE_RUSTC_VERSION") {
180+
return val.into();
181181
}
182182
}
183183

184-
RUSTC_VERSION
185-
.expect(
186-
"Cannot use rustc without explicit version for \
187-
incremental compilation",
188-
)
189-
.to_string()
184+
cfg_version.into()
190185
}

compiler/rustc_incremental/src/persist/load.rs

+20-12
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,22 @@ impl<T: Default> LoadResult<T> {
7373
}
7474
}
7575

76-
fn load_data(
77-
report_incremental_info: bool,
76+
fn load_data(path: &Path, sess: &Session) -> LoadResult<(Mmap, usize)> {
77+
load_data_no_sess(
78+
path,
79+
sess.opts.unstable_opts.incremental_info,
80+
sess.is_nightly_build(),
81+
sess.cfg_version,
82+
)
83+
}
84+
85+
fn load_data_no_sess(
7886
path: &Path,
79-
nightly_build: bool,
87+
report_incremental_info: bool,
88+
is_nightly_build: bool,
89+
cfg_version: &'static str,
8090
) -> LoadResult<(Mmap, usize)> {
81-
match file_format::read_file(report_incremental_info, path, nightly_build) {
91+
match file_format::read_file(path, report_incremental_info, is_nightly_build, cfg_version) {
8292
Ok(Some(data_and_pos)) => LoadResult::Ok { data: data_and_pos },
8393
Ok(None) => {
8494
// The file either didn't exist or was produced by an incompatible
@@ -138,14 +148,13 @@ pub fn load_dep_graph(sess: &Session) -> DepGraphFuture {
138148
let expected_hash = sess.opts.dep_tracking_hash(false);
139149

140150
let mut prev_work_products = FxHashMap::default();
141-
let nightly_build = sess.is_nightly_build();
142151

143152
// If we are only building with -Zquery-dep-graph but without an actual
144153
// incr. comp. session directory, we skip this. Otherwise we'd fail
145154
// when trying to load work products.
146155
if sess.incr_comp_session_dir_opt().is_some() {
147156
let work_products_path = work_products_path(sess);
148-
let load_result = load_data(report_incremental_info, &work_products_path, nightly_build);
157+
let load_result = load_data(&work_products_path, sess);
149158

150159
if let LoadResult::Ok { data: (work_products_data, start_pos) } = load_result {
151160
// Decode the list of work_products
@@ -173,10 +182,13 @@ pub fn load_dep_graph(sess: &Session) -> DepGraphFuture {
173182
}
174183
}
175184

185+
let is_nightly_build = sess.is_nightly_build();
186+
let cfg_version = sess.cfg_version;
187+
176188
MaybeAsync::Async(std::thread::spawn(move || {
177189
let _prof_timer = prof.generic_activity("incr_comp_load_dep_graph");
178190

179-
match load_data(report_incremental_info, &path, nightly_build) {
191+
match load_data_no_sess(&path, report_incremental_info, is_nightly_build, cfg_version) {
180192
LoadResult::DataOutOfDate => LoadResult::DataOutOfDate,
181193
LoadResult::LoadDepGraph(path, err) => LoadResult::LoadDepGraph(path, err),
182194
LoadResult::DecodeIncrCache(err) => LoadResult::DecodeIncrCache(err),
@@ -218,11 +230,7 @@ pub fn load_query_result_cache(sess: &Session) -> Option<OnDiskCache<'_>> {
218230

219231
let _prof_timer = sess.prof.generic_activity("incr_comp_load_query_result_cache");
220232

221-
match load_data(
222-
sess.opts.unstable_opts.incremental_info,
223-
&query_cache_path(sess),
224-
sess.is_nightly_build(),
225-
) {
233+
match load_data(&query_cache_path(sess), sess) {
226234
LoadResult::Ok { data: (bytes, start_pos) } => {
227235
Some(OnDiskCache::new(sess, bytes, start_pos))
228236
}

compiler/rustc_incremental/src/persist/save.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ pub fn build_dep_graph(
164164
}
165165
};
166166

167-
file_format::write_file_header(&mut encoder, sess.is_nightly_build());
167+
file_format::write_file_header(&mut encoder, sess);
168168

169169
// First encode the commandline arguments hash
170170
sess.opts.dep_tracking_hash(false).encode(&mut encoder);

compiler/rustc_interface/src/passes.rs

+1
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ pub fn register_plugins<'a>(
8989
crate_name,
9090
sess.crate_types().contains(&CrateType::Executable),
9191
sess.opts.cg.metadata.clone(),
92+
sess.cfg_version,
9293
);
9394
sess.stable_crate_id.set(stable_crate_id).expect("not yet initialized");
9495
rustc_incremental::prepare_session_directory(sess, crate_name, stable_crate_id)?;

compiler/rustc_interface/src/queries.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ impl Linker {
369369

370370
if sess.opts.unstable_opts.no_link {
371371
let rlink_file = self.prepare_outputs.with_extension(config::RLINK_EXT);
372-
CodegenResults::serialize_rlink(&rlink_file, &codegen_results)
372+
CodegenResults::serialize_rlink(sess, &rlink_file, &codegen_results)
373373
.map_err(|error| sess.emit_fatal(FailedWritingFile { path: &rlink_file, error }))?;
374374
return Ok(());
375375
}

compiler/rustc_interface/src/tests.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ fn mk_session(matches: getopts::Matches) -> (Session, CfgSpecs) {
5252
output_file: None,
5353
temps_dir,
5454
};
55-
let sess = build_session(sessopts, io, None, registry, vec![], Default::default(), None, None);
55+
let sess =
56+
build_session(sessopts, io, None, registry, vec![], Default::default(), None, None, "");
5657
(sess, cfg)
5758
}
5859

compiler/rustc_interface/src/util.rs

+1
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ pub fn create_session(
104104
lint_caps,
105105
file_loader,
106106
target_override,
107+
rustc_version_str().unwrap_or("unknown"),
107108
);
108109

109110
codegen_backend.init(&sess);

compiler/rustc_metadata/src/locator.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ pub(crate) struct CrateLocator<'a> {
246246
only_needs_metadata: bool,
247247
sysroot: &'a Path,
248248
metadata_loader: &'a dyn MetadataLoader,
249+
cfg_version: &'static str,
249250

250251
// Immutable per-search configuration.
251252
crate_name: Symbol,
@@ -323,6 +324,7 @@ impl<'a> CrateLocator<'a> {
323324
only_needs_metadata,
324325
sysroot: &sess.sysroot,
325326
metadata_loader,
327+
cfg_version: sess.cfg_version,
326328
crate_name,
327329
exact_paths: if hash.is_none() {
328330
sess.opts
@@ -655,7 +657,7 @@ impl<'a> CrateLocator<'a> {
655657
}
656658

657659
fn crate_matches(&mut self, metadata: &MetadataBlob, libpath: &Path) -> Option<Svh> {
658-
let rustc_version = rustc_version();
660+
let rustc_version = rustc_version(self.cfg_version);
659661
let found_version = metadata.get_rustc_version();
660662
if found_version != rustc_version {
661663
info!("Rejecting via version: expected {} got {}", rustc_version, found_version);
@@ -1097,7 +1099,7 @@ impl CrateError {
10971099
crate_name,
10981100
add_info,
10991101
found_crates,
1100-
rustc_version: rustc_version(),
1102+
rustc_version: rustc_version(sess.cfg_version),
11011103
});
11021104
} else if !locator.crate_rejections.via_invalid.is_empty() {
11031105
let mut crate_rejections = Vec::new();

compiler/rustc_metadata/src/rmeta/encoder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2267,7 +2267,7 @@ fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) {
22672267
};
22682268

22692269
// Encode the rustc version string in a predictable location.
2270-
rustc_version().encode(&mut ecx);
2270+
rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
22712271

22722272
// Encode all the entries and extra information in the crate,
22732273
// culminating in the `CrateRoot` which points to all of it.

0 commit comments

Comments
 (0)