Skip to content

Commit 33e1daa

Browse files
Improve code
1 parent eedf1b6 commit 33e1daa

File tree

5 files changed

+147
-115
lines changed

5 files changed

+147
-115
lines changed

build_system/src/build.rs

+60-45
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use crate::config::set_config;
2-
use crate::utils::{get_gcc_path, run_command_with_env, run_command_with_output, walk_dir};
2+
use crate::utils::{
3+
get_gcc_path, run_command, run_command_with_env, run_command_with_output_and_env, walk_dir,
4+
};
35
use std::collections::HashMap;
46
use std::ffi::OsStr;
57
use std::fs;
@@ -9,7 +11,6 @@ use std::path::Path;
911
struct BuildArg {
1012
codegen_release_channel: bool,
1113
sysroot_release_channel: bool,
12-
no_default_features: bool,
1314
features: Vec<String>,
1415
gcc_path: String,
1516
}
@@ -21,27 +22,31 @@ impl BuildArg {
2122
gcc_path,
2223
..Default::default()
2324
};
25+
// We skip binary name and the `build` command.
2426
let mut args = std::env::args().skip(2);
2527

2628
while let Some(arg) = args.next() {
2729
match arg.as_str() {
2830
"--release" => build_arg.codegen_release_channel = true,
2931
"--release-sysroot" => build_arg.sysroot_release_channel = true,
30-
"--no-default-features" => build_arg.no_default_features = true,
32+
"--no-default-features" => {
33+
build_arg.features.push("--no-default-features".to_string());
34+
}
3135
"--features" => {
3236
if let Some(arg) = args.next() {
37+
build_arg.features.push("--features".to_string());
3338
build_arg.features.push(arg.as_str().into());
3439
} else {
35-
return Err(format!(
36-
"Expected a value after `--features`, found nothing"
37-
));
40+
return Err(
41+
"Expected a value after `--features`, found nothing".to_string()
42+
);
3843
}
3944
}
4045
"--help" => {
4146
Self::usage();
4247
return Ok(None);
4348
}
44-
a => return Err(format!("Unknown argument `{a}`")),
49+
arg => return Err(format!("Unknown argument `{}`", arg)),
4550
}
4651
}
4752
Ok(Some(build_arg))
@@ -68,37 +73,37 @@ fn build_sysroot(
6873
target_triple: &str,
6974
) -> Result<(), String> {
7075
std::env::set_current_dir("build_sysroot")
71-
.map_err(|e| format!("Failed to go to `build_sysroot` directory: {e:?}"))?;
76+
.map_err(|error| format!("Failed to go to `build_sysroot` directory: {:?}", error))?;
7277
// Cleanup for previous run
73-
// v Clean target dir except for build scripts and incremental cache
74-
let _e = walk_dir(
78+
// Clean target dir except for build scripts and incremental cache
79+
let _ = walk_dir(
7580
"target",
7681
|dir: &Path| {
7782
for top in &["debug", "release"] {
78-
let _e = fs::remove_dir_all(dir.join(top).join("build"));
79-
let _e = fs::remove_dir_all(dir.join(top).join("deps"));
80-
let _e = fs::remove_dir_all(dir.join(top).join("examples"));
81-
let _e = fs::remove_dir_all(dir.join(top).join("native"));
83+
let _ = fs::remove_dir_all(dir.join(top).join("build"));
84+
let _ = fs::remove_dir_all(dir.join(top).join("deps"));
85+
let _ = fs::remove_dir_all(dir.join(top).join("examples"));
86+
let _ = fs::remove_dir_all(dir.join(top).join("native"));
8287

83-
let _e = walk_dir(
88+
let _ = walk_dir(
8489
dir.join(top),
8590
|sub_dir: &Path| {
8691
if sub_dir
8792
.file_name()
88-
.map(|s| s.to_str().unwrap().starts_with("libsysroot"))
93+
.map(|filename| filename.to_str().unwrap().starts_with("libsysroot"))
8994
.unwrap_or(false)
9095
{
91-
let _e = fs::remove_dir_all(sub_dir);
96+
let _ = fs::remove_dir_all(sub_dir);
9297
}
9398
Ok(())
9499
},
95100
|file: &Path| {
96101
if file
97102
.file_name()
98-
.map(|s| s.to_str().unwrap().starts_with("libsysroot"))
103+
.map(|filename| filename.to_str().unwrap().starts_with("libsysroot"))
99104
.unwrap_or(false)
100105
{
101-
let _e = fs::remove_file(file);
106+
let _ = fs::remove_file(file);
102107
}
103108
Ok(())
104109
},
@@ -109,21 +114,21 @@ fn build_sysroot(
109114
|_| Ok(()),
110115
);
111116

112-
let _e = fs::remove_file("Cargo.lock");
113-
let _e = fs::remove_file("test_target/Cargo.lock");
114-
let _e = fs::remove_dir_all("sysroot");
117+
let _ = fs::remove_file("Cargo.lock");
118+
let _ = fs::remove_file("test_target/Cargo.lock");
119+
let _ = fs::remove_dir_all("sysroot");
115120

116121
// Builds libs
117122
let channel = if release_mode {
118123
let rustflags = env
119-
.get(&"RUSTFLAGS".to_owned())
124+
.get("RUSTFLAGS")
120125
.cloned()
121126
.unwrap_or_default();
122127
env.insert(
123-
"RUSTFLAGS".to_owned(),
124-
format!("{rustflags} -Zmir-opt-level=3"),
128+
"RUSTFLAGS".to_string(),
129+
format!("{} -Zmir-opt-level=3", rustflags),
125130
);
126-
run_command_with_output(
131+
run_command_with_output_and_env(
127132
&[
128133
&"cargo",
129134
&"build",
@@ -136,7 +141,7 @@ fn build_sysroot(
136141
)?;
137142
"release"
138143
} else {
139-
run_command_with_output(
144+
run_command_with_output_and_env(
140145
&[
141146
&"cargo",
142147
&"build",
@@ -152,12 +157,14 @@ fn build_sysroot(
152157
};
153158

154159
// Copy files to sysroot
155-
let sysroot_path = format!("sysroot/lib/rustlib/{target_triple}/lib/");
160+
let sysroot_path = format!("sysroot/lib/rustlib/{}/lib/", target_triple);
156161
fs::create_dir_all(&sysroot_path)
157-
.map_err(|e| format!("Failed to create directory `{sysroot_path}`: {e:?}"))?;
158-
let copier = |d: &Path| run_command_with_output(&[&"cp", &"-r", &d, &sysroot_path], None, None);
162+
.map_err(|error| format!("Failed to create directory `{}`: {:?}", sysroot_path, error))?;
163+
let copier = |dir_to_copy: &Path| {
164+
run_command(&[&"cp", &"-r", &dir_to_copy, &sysroot_path], None).map(|_| ())
165+
};
159166
walk_dir(
160-
&format!("target/{target_triple}/{channel}/deps"),
167+
&format!("target/{}/{}/deps", target_triple, channel),
161168
copier,
162169
copier,
163170
)?;
@@ -169,21 +176,25 @@ fn build_codegen(args: &BuildArg) -> Result<(), String> {
169176
let mut env = HashMap::new();
170177

171178
let current_dir =
172-
std::env::current_dir().map_err(|e| format!("`current_dir` failed: {e:?}"))?;
173-
env.insert(
174-
"RUST_COMPILER_RT_ROOT".to_owned(),
175-
format!("{}", current_dir.join("llvm/compiler-rt").display()),
176-
);
177-
env.insert("LD_LIBRARY_PATH".to_owned(), args.gcc_path.clone());
178-
env.insert("LIBRARY_PATH".to_owned(), args.gcc_path.clone());
179+
std::env::current_dir().map_err(|error| format!("`current_dir` failed: {:?}", error))?;
180+
if let Ok(rt_root) = std::env::var("RUST_COMPILER_RT_ROOT") {
181+
env.insert("RUST_COMPILER_RT_ROOT".to_string(), rt_root);
182+
} else {
183+
env.insert(
184+
"RUST_COMPILER_RT_ROOT".to_string(),
185+
format!("{}", current_dir.join("llvm/compiler-rt").display()),
186+
);
187+
}
188+
env.insert("LD_LIBRARY_PATH".to_string(), args.gcc_path.clone());
189+
env.insert("LIBRARY_PATH".to_string(), args.gcc_path.clone());
179190

180191
let mut command: Vec<&dyn AsRef<OsStr>> = vec![&"cargo", &"rustc"];
181192
if args.codegen_release_channel {
182193
command.push(&"--release");
183-
env.insert("CHANNEL".to_owned(), "release".to_owned());
184-
env.insert("CARGO_INCREMENTAL".to_owned(), "1".to_owned());
194+
env.insert("CHANNEL".to_string(), "release".to_string());
195+
env.insert("CARGO_INCREMENTAL".to_string(), "1".to_string());
185196
} else {
186-
env.insert("CHANNEL".to_owned(), "debug".to_owned());
197+
env.insert("CHANNEL".to_string(), "debug".to_string());
187198
}
188199
let ref_features = args.features.iter().map(|s| s.as_str()).collect::<Vec<_>>();
189200
for feature in &ref_features {
@@ -194,10 +205,14 @@ fn build_codegen(args: &BuildArg) -> Result<(), String> {
194205
let config = set_config(&mut env, &[], Some(&args.gcc_path))?;
195206

196207
// We voluntarily ignore the error.
197-
let _e = fs::remove_dir_all("target/out");
208+
let _ = fs::remove_dir_all("target/out");
198209
let gccjit_target = "target/out/gccjit";
199-
fs::create_dir_all(gccjit_target)
200-
.map_err(|e| format!("Failed to create directory `{gccjit_target}`: {e:?}"))?;
210+
fs::create_dir_all(gccjit_target).map_err(|error| {
211+
format!(
212+
"Failed to create directory `{}`: {:?}",
213+
gccjit_target, error
214+
)
215+
})?;
201216

202217
println!("[BUILD] sysroot");
203218
build_sysroot(
@@ -210,7 +225,7 @@ fn build_codegen(args: &BuildArg) -> Result<(), String> {
210225

211226
pub fn run() -> Result<(), String> {
212227
let args = match BuildArg::new()? {
213-
Some(a) => a,
228+
Some(args) => args,
214229
None => return Ok(()),
215230
};
216231
build_codegen(&args)?;

build_system/src/config.rs

+44-40
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,19 @@ pub fn set_config(
1414
test_flags: &[String],
1515
gcc_path: Option<&str>,
1616
) -> Result<ConfigInfo, String> {
17-
env.insert("CARGO_INCREMENTAL".to_owned(), "0".to_owned());
17+
env.insert("CARGO_INCREMENTAL".to_string(), "0".to_string());
1818

1919
let gcc_path = match gcc_path {
20-
Some(g) => g.to_owned(),
20+
Some(path) => path.to_string(),
2121
None => get_gcc_path()?,
2222
};
23-
env.insert("GCC_PATH".to_owned(), gcc_path.clone());
23+
env.insert("GCC_PATH".to_string(), gcc_path.clone());
2424

2525
let os_name = get_os_name()?;
2626
let dylib_ext = match os_name.as_str() {
2727
"Linux" => "so",
2828
"Darwin" => "dylib",
29-
os => return Err(format!("unsupported OS `{os}`")),
29+
os => return Err(format!("unsupported OS `{}`", os)),
3030
};
3131
let host_triple = get_rustc_host_triple()?;
3232
let mut linker = None;
@@ -44,77 +44,81 @@ pub fn set_config(
4444
linker = Some("-Clinker=aarch64-linux-gnu-gcc");
4545
run_wrapper = Some("qemu-aarch64 -L /usr/aarch64-linux-gnu");
4646
} else {
47-
return Err(format!("unknown non-native platform `{target_triple}`"));
47+
return Err(format!("unknown non-native platform `{}`", target_triple));
4848
}
4949
}
50-
// Since we don't support ThinLTO, disable LTO completely when not trying to do LTO.
51-
// TODO(antoyo): remove when we can handle ThinLTO.
52-
let disable_lto_lfags = "-Clto=off";
53-
let current_dir = std_env::current_dir().map_err(|e| format!("`current_dir` failed: {e:?}"))?;
50+
let current_dir =
51+
std_env::current_dir().map_err(|error| format!("`current_dir` failed: {:?}", error))?;
52+
let channel = if let Some(channel) = env.get("CHANNEL") {
53+
channel.as_str()
54+
} else {
55+
"debug"
56+
};
5457
let cg_backend_path = current_dir
5558
.join("target")
56-
.join(if let Some(channel) = env.get(&"CHANNEL".to_owned()) {
57-
channel.as_str()
58-
} else {
59-
"debug"
60-
})
61-
.join(&format!("librustc_codegen_gcc.{dylib_ext}"));
59+
.join(channel)
60+
.join(&format!("librustc_codegen_gcc.{}", dylib_ext));
6261
let sysroot_path = current_dir.join("build_sysroot/sysroot");
6362
let mut rustflags = Vec::new();
64-
if let Some(cg_rustflags) = env.get(&"CG_RUSTFLAGS".to_owned()) {
63+
if let Some(cg_rustflags) = env.get("CG_RUSTFLAGS") {
6564
rustflags.push(cg_rustflags.clone());
6665
}
6766
if let Some(linker) = linker {
68-
rustflags.push(linker.to_owned());
67+
rustflags.push(linker.to_string());
6968
}
7069
rustflags.extend_from_slice(&[
71-
"-Csymbol-mangling-version=v0".to_owned(),
72-
"-Cdebuginfo=2".to_owned(),
73-
disable_lto_lfags.to_owned(),
70+
"-Csymbol-mangling-version=v0".to_string(),
71+
"-Cdebuginfo=2".to_string(),
7472
format!("-Zcodegen-backend={}", cg_backend_path.display()),
75-
"--sysroot".to_owned(),
76-
format!("{}", sysroot_path.display()),
73+
"--sysroot".to_string(),
74+
sysroot_path.display().to_string(),
7775
]);
76+
77+
// Since we don't support ThinLTO, disable LTO completely when not trying to do LTO.
78+
// TODO(antoyo): remove when we can handle ThinLTO.
79+
if !env.contains_key(&"FAT_LTO".to_string()) {
80+
rustflags.push("-Clto=off".to_string());
81+
}
7882
rustflags.extend_from_slice(test_flags);
7983
// FIXME(antoyo): remove once the atomic shim is gone
8084
if os_name == "Darwin" {
8185
rustflags.extend_from_slice(&[
82-
"-Clink-arg=-undefined".to_owned(),
83-
"-Clink-arg=dynamic_lookup".to_owned(),
86+
"-Clink-arg=-undefined".to_string(),
87+
"-Clink-arg=dynamic_lookup".to_string(),
8488
]);
8589
}
86-
env.insert("RUSTFLAGS".to_owned(), rustflags.join(" "));
90+
env.insert("RUSTFLAGS".to_string(), rustflags.join(" "));
8791
// display metadata load errors
88-
env.insert("RUSTC_LOG".to_owned(), "warn".to_owned());
92+
env.insert("RUSTC_LOG".to_string(), "warn".to_string());
8993

94+
let sysroot = current_dir.join(&format!(
95+
"build_sysroot/sysroot/lib/rustlib/{}/lib",
96+
target_triple
97+
));
9098
let ld_library_path = format!(
9199
"{target}:{sysroot}:{gcc_path}",
92100
target = current_dir.join("target/out").display(),
93-
sysroot = current_dir
94-
.join(&format!(
95-
"build_sysroot/sysroot/lib/rustlib/{target_triple}/lib"
96-
),)
97-
.display(),
101+
sysroot = sysroot.display(),
98102
);
99-
env.insert("LD_LIBRARY_PATH".to_owned(), ld_library_path.clone());
100-
env.insert("DYLD_LIBRARY_PATH".to_owned(), ld_library_path);
103+
env.insert("LD_LIBRARY_PATH".to_string(), ld_library_path.clone());
104+
env.insert("DYLD_LIBRARY_PATH".to_string(), ld_library_path);
101105

102106
// NOTE: To avoid the -fno-inline errors, use /opt/gcc/bin/gcc instead of cc.
103107
// To do so, add a symlink for cc to /opt/gcc/bin/gcc in our PATH.
104108
// Another option would be to add the following Rust flag: -Clinker=/opt/gcc/bin/gcc
105109
let path = std::env::var("PATH").unwrap_or_default();
106-
env.insert("PATH".to_owned(), format!("/opt/gcc/bin:{path}"));
110+
env.insert("PATH".to_string(), format!("/opt/gcc/bin:{}", path));
107111

108-
let mut rustc_command = vec!["rustc".to_owned()];
112+
let mut rustc_command = vec!["rustc".to_string()];
109113
rustc_command.extend_from_slice(&rustflags);
110114
rustc_command.extend_from_slice(&[
111-
"-L".to_owned(),
112-
"crate=target/out".to_owned(),
113-
"--out-dir".to_owned(),
114-
"target/out".to_owned(),
115+
"-L".to_string(),
116+
"crate=target/out".to_string(),
117+
"--out-dir".to_string(),
118+
"target/out".to_string(),
115119
]);
116120
Ok(ConfigInfo {
117-
target_triple: target_triple.to_owned(),
121+
target_triple: target_triple.to_string(),
118122
rustc_command,
119123
run_wrapper,
120124
})

0 commit comments

Comments
 (0)