Skip to content

Commit 1cb8684

Browse files
authored
Rollup merge of #103792 - JhonnyBillM:migrate-codegen-ssa-to-diagnostics-structs-pt2, r=davidtwco
Migrate `codegen_ssa` to diagnostics structs - [Part 2] Completes migrating `link.rs` in `codegen_ssa` module. _Part 1 - https://github.com/rust-lang/rust/pull/102612_ r? `@davidtwco`
2 parents c38ee06 + 540c3f9 commit 1cb8684

File tree

5 files changed

+298
-99
lines changed

5 files changed

+298
-99
lines changed

compiler/rustc_codegen_ssa/src/back/archive.rs

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@ use rustc_span::symbol::Symbol;
66

77
use object::read::archive::ArchiveFile;
88

9-
use std::fmt::Display;
109
use std::fs::File;
1110
use std::io;
1211
use std::path::{Path, PathBuf};
1312

13+
use crate::errors::ExtractBundledLibsError;
14+
1415
pub trait ArchiveBuilderBuilder {
1516
fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box<dyn ArchiveBuilder<'a> + 'a>;
1617

@@ -28,32 +29,35 @@ pub trait ArchiveBuilderBuilder {
2829
is_direct_dependency: bool,
2930
) -> PathBuf;
3031

31-
fn extract_bundled_libs(
32-
&self,
33-
rlib: &Path,
32+
fn extract_bundled_libs<'a>(
33+
&'a self,
34+
rlib: &'a Path,
3435
outdir: &Path,
3536
bundled_lib_file_names: &FxHashSet<Symbol>,
36-
) -> Result<(), String> {
37-
let message = |msg: &str, e: &dyn Display| format!("{} '{}': {}", msg, &rlib.display(), e);
37+
) -> Result<(), ExtractBundledLibsError<'_>> {
3838
let archive_map = unsafe {
39-
Mmap::map(File::open(rlib).map_err(|e| message("failed to open file", &e))?)
40-
.map_err(|e| message("failed to mmap file", &e))?
39+
Mmap::map(
40+
File::open(rlib)
41+
.map_err(|e| ExtractBundledLibsError::OpenFile { rlib, error: Box::new(e) })?,
42+
)
43+
.map_err(|e| ExtractBundledLibsError::MmapFile { rlib, error: Box::new(e) })?
4144
};
4245
let archive = ArchiveFile::parse(&*archive_map)
43-
.map_err(|e| message("failed to parse archive", &e))?;
46+
.map_err(|e| ExtractBundledLibsError::ParseArchive { rlib, error: Box::new(e) })?;
4447

4548
for entry in archive.members() {
46-
let entry = entry.map_err(|e| message("failed to read entry", &e))?;
49+
let entry = entry
50+
.map_err(|e| ExtractBundledLibsError::ReadEntry { rlib, error: Box::new(e) })?;
4751
let data = entry
4852
.data(&*archive_map)
49-
.map_err(|e| message("failed to get data from archive member", &e))?;
53+
.map_err(|e| ExtractBundledLibsError::ArchiveMember { rlib, error: Box::new(e) })?;
5054
let name = std::str::from_utf8(entry.name())
51-
.map_err(|e| message("failed to convert name", &e))?;
55+
.map_err(|e| ExtractBundledLibsError::ConvertName { rlib, error: Box::new(e) })?;
5256
if !bundled_lib_file_names.contains(&Symbol::intern(name)) {
5357
continue; // We need to extract only native libraries.
5458
}
5559
std::fs::write(&outdir.join(&name), data)
56-
.map_err(|e| message("failed to write file", &e))?;
60+
.map_err(|e| ExtractBundledLibsError::WriteFile { rlib, error: Box::new(e) })?;
5761
}
5862
Ok(())
5963
}

compiler/rustc_codegen_ssa/src/back/link.rs

Lines changed: 47 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -919,29 +919,17 @@ fn link_natively<'a>(
919919
)
920920
.is_some();
921921

922-
sess.note_without_error("`link.exe` returned an unexpected error");
922+
sess.emit_note(errors::LinkExeUnexpectedError);
923923
if is_vs_installed && has_linker {
924924
// the linker is broken
925-
sess.note_without_error(
926-
"the Visual Studio build tools may need to be repaired \
927-
using the Visual Studio installer",
928-
);
929-
sess.note_without_error(
930-
"or a necessary component may be missing from the \
931-
\"C++ build tools\" workload",
932-
);
925+
sess.emit_note(errors::RepairVSBuildTools);
926+
sess.emit_note(errors::MissingCppBuildToolComponent);
933927
} else if is_vs_installed {
934928
// the linker is not installed
935-
sess.note_without_error(
936-
"in the Visual Studio installer, ensure the \
937-
\"C++ build tools\" workload is selected",
938-
);
929+
sess.emit_note(errors::SelectCppBuildToolWorkload);
939930
} else {
940931
// visual studio is not installed
941-
sess.note_without_error(
942-
"you may need to install Visual Studio build tools with the \
943-
\"C++ build tools\" workload",
944-
);
932+
sess.emit_note(errors::VisualStudioNotInstalled);
945933
}
946934
}
947935
}
@@ -954,35 +942,20 @@ fn link_natively<'a>(
954942
Err(e) => {
955943
let linker_not_found = e.kind() == io::ErrorKind::NotFound;
956944

957-
let mut linker_error = {
958-
if linker_not_found {
959-
sess.struct_err(&format!("linker `{}` not found", linker_path.display()))
960-
} else {
961-
sess.struct_err(&format!(
962-
"could not exec the linker `{}`",
963-
linker_path.display()
964-
))
965-
}
966-
};
967-
968-
linker_error.note(&e.to_string());
969-
970-
if !linker_not_found {
971-
linker_error.note(&format!("{:?}", &cmd));
945+
if linker_not_found {
946+
sess.emit_err(errors::LinkerNotFound { linker_path, error: e });
947+
} else {
948+
sess.emit_err(errors::UnableToExeLinker {
949+
linker_path,
950+
error: e,
951+
command_formatted: format!("{:?}", &cmd),
952+
});
972953
}
973954

974-
linker_error.emit();
975-
976955
if sess.target.is_like_msvc && linker_not_found {
977-
sess.note_without_error(
978-
"the msvc targets depend on the msvc linker \
979-
but `link.exe` was not found",
980-
);
981-
sess.note_without_error(
982-
"please ensure that Visual Studio 2017 or later, or Build Tools \
983-
for Visual Studio were installed with the Visual C++ option.",
984-
);
985-
sess.note_without_error("VS Code is a different product, and is not sufficient.");
956+
sess.emit_note(errors::MsvcMissingLinker);
957+
sess.emit_note(errors::CheckInstalledVisualStudio);
958+
sess.emit_note(errors::UnsufficientVSCodeProduct);
986959
}
987960
sess.abort_if_errors();
988961
}
@@ -1007,15 +980,13 @@ fn link_natively<'a>(
1007980
if !prog.status.success() {
1008981
let mut output = prog.stderr.clone();
1009982
output.extend_from_slice(&prog.stdout);
1010-
sess.struct_warn(&format!(
1011-
"processing debug info with `dsymutil` failed: {}",
1012-
prog.status
1013-
))
1014-
.note(&escape_string(&output))
1015-
.emit();
983+
sess.emit_warning(errors::ProcessingDymutilFailed {
984+
status: prog.status,
985+
output: escape_string(&output),
986+
});
1016987
}
1017988
}
1018-
Err(e) => sess.fatal(&format!("unable to run `dsymutil`: {}", e)),
989+
Err(error) => sess.emit_fatal(errors::UnableToRunDsymutil { error }),
1019990
}
1020991
}
1021992

@@ -1092,15 +1063,14 @@ fn strip_symbols_with_external_utility<'a>(
10921063
if !prog.status.success() {
10931064
let mut output = prog.stderr.clone();
10941065
output.extend_from_slice(&prog.stdout);
1095-
sess.struct_warn(&format!(
1096-
"stripping debug info with `{}` failed: {}",
1097-
util, prog.status
1098-
))
1099-
.note(&escape_string(&output))
1100-
.emit();
1066+
sess.emit_warning(errors::StrippingDebugInfoFailed {
1067+
util,
1068+
status: prog.status,
1069+
output: escape_string(&output),
1070+
});
11011071
}
11021072
}
1103-
Err(e) => sess.fatal(&format!("unable to run `{}`: {}", util, e)),
1073+
Err(error) => sess.emit_fatal(errors::UnableToRun { util, error }),
11041074
}
11051075
}
11061076

@@ -1251,7 +1221,7 @@ pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
12511221
)),
12521222
(Some(linker), None) => {
12531223
let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
1254-
sess.fatal("couldn't extract file stem from specified linker")
1224+
sess.emit_fatal(errors::LinkerFileStem);
12551225
});
12561226

12571227
let flavor = if stem == "emcc" {
@@ -1378,13 +1348,9 @@ fn print_native_static_libs(sess: &Session, all_native_libs: &[NativeLib]) {
13781348
})
13791349
.collect();
13801350
if !lib_args.is_empty() {
1381-
sess.note_without_error(
1382-
"Link against the following native artifacts when linking \
1383-
against this static library. The order and any duplication \
1384-
can be significant on some platforms.",
1385-
);
1351+
sess.emit_note(errors::StaticLibraryNativeArtifacts);
13861352
// Prefix for greppability
1387-
sess.note_without_error(&format!("native-static-libs: {}", &lib_args.join(" ")));
1353+
sess.emit_note(errors::NativeStaticLibs { arguments: lib_args.join(" ") });
13881354
}
13891355
}
13901356

@@ -1688,14 +1654,14 @@ fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_ty
16881654
match (crate_type, &sess.target.link_script) {
16891655
(CrateType::Cdylib | CrateType::Executable, Some(script)) => {
16901656
if !sess.target.linker_flavor.is_gnu() {
1691-
sess.fatal("can only use link script when linking with GNU-like linker");
1657+
sess.emit_fatal(errors::LinkScriptUnavailable);
16921658
}
16931659

16941660
let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
16951661

16961662
let path = tmpdir.join(file_name);
1697-
if let Err(e) = fs::write(&path, script.as_ref()) {
1698-
sess.fatal(&format!("failed to write link script to {}: {}", path.display(), e));
1663+
if let Err(error) = fs::write(&path, script.as_ref()) {
1664+
sess.emit_fatal(errors::LinkScriptWriteFailure { path, error });
16991665
}
17001666

17011667
cmd.arg("--script");
@@ -1841,8 +1807,8 @@ fn add_linked_symbol_object(
18411807

18421808
let path = tmpdir.join("symbols.o");
18431809
let result = std::fs::write(&path, file.write().unwrap());
1844-
if let Err(e) = result {
1845-
sess.fatal(&format!("failed to write {}: {}", path.display(), e));
1810+
if let Err(error) = result {
1811+
sess.emit_fatal(errors::FailedToWrite { path, error });
18461812
}
18471813
cmd.add_object(&path);
18481814
}
@@ -2299,14 +2265,10 @@ fn collect_natvis_visualizers(
22992265
visualizer_paths.push(visualizer_out_file);
23002266
}
23012267
Err(error) => {
2302-
sess.warn(
2303-
format!(
2304-
"Unable to write debugger visualizer file `{}`: {} ",
2305-
visualizer_out_file.display(),
2306-
error
2307-
)
2308-
.as_str(),
2309-
);
2268+
sess.emit_warning(errors::UnableToWriteDebuggerVisualizer {
2269+
path: visualizer_out_file,
2270+
error,
2271+
});
23102272
}
23112273
};
23122274
}
@@ -2484,7 +2446,7 @@ fn add_upstream_rust_crates<'a>(
24842446
let rlib = &src.rlib.as_ref().unwrap().0;
24852447
archive_builder_builder
24862448
.extract_bundled_libs(rlib, tmpdir, &bundled_libs)
2487-
.unwrap_or_else(|e| sess.fatal(e));
2449+
.unwrap_or_else(|e| sess.emit_fatal(e));
24882450
}
24892451

24902452
let mut last = (None, NativeLibKind::Unspecified, None);
@@ -2641,7 +2603,7 @@ fn add_upstream_rust_crates<'a>(
26412603
|| !codegen_results.crate_info.is_no_builtins.contains(&cnum);
26422604

26432605
let mut archive = archive_builder_builder.new_archive_builder(sess);
2644-
if let Err(e) = archive.add_archive(
2606+
if let Err(error) = archive.add_archive(
26452607
cratepath,
26462608
Box::new(move |f| {
26472609
if f == METADATA_FILENAME {
@@ -2681,7 +2643,7 @@ fn add_upstream_rust_crates<'a>(
26812643
false
26822644
}),
26832645
) {
2684-
sess.fatal(&format!("failed to build archive from rlib: {}", e));
2646+
sess.emit_fatal(errors::RlibArchiveBuildFailure { error });
26852647
}
26862648
if archive.build(&dst) {
26872649
link_upstream(&dst);
@@ -2813,14 +2775,14 @@ fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
28132775
("arm", "watchos") => "watchos",
28142776
(_, "macos") => "macosx",
28152777
_ => {
2816-
sess.err(&format!("unsupported arch `{}` for os `{}`", arch, os));
2778+
sess.emit_err(errors::UnsupportedArch { arch, os });
28172779
return;
28182780
}
28192781
};
28202782
let sdk_root = match get_apple_sdk_root(sdk_name) {
28212783
Ok(s) => s,
28222784
Err(e) => {
2823-
sess.err(&e);
2785+
sess.emit_err(e);
28242786
return;
28252787
}
28262788
};
@@ -2836,7 +2798,7 @@ fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
28362798
}
28372799
}
28382800

2839-
fn get_apple_sdk_root(sdk_name: &str) -> Result<String, String> {
2801+
fn get_apple_sdk_root(sdk_name: &str) -> Result<String, errors::AppleSdkRootError<'_>> {
28402802
// Following what clang does
28412803
// (https://github.com/llvm/llvm-project/blob/
28422804
// 296a80102a9b72c3eda80558fb78a3ed8849b341/clang/lib/Driver/ToolChains/Darwin.cpp#L1661-L1678)
@@ -2886,7 +2848,7 @@ fn get_apple_sdk_root(sdk_name: &str) -> Result<String, String> {
28862848

28872849
match res {
28882850
Ok(output) => Ok(output.trim().to_string()),
2889-
Err(e) => Err(format!("failed to get {} SDK path: {}", sdk_name, e)),
2851+
Err(error) => Err(errors::AppleSdkRootError::SdkPath { sdk_name, error }),
28902852
}
28912853
}
28922854

@@ -2919,7 +2881,7 @@ fn add_gcc_ld_path(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
29192881
}
29202882
}
29212883
} else {
2922-
sess.fatal("option `-Z gcc-ld` is used even though linker flavor is not gcc");
2884+
sess.emit_fatal(errors::OptionGccOnly);
29232885
}
29242886
}
29252887
}

0 commit comments

Comments
 (0)