Skip to content

Commit 0aa8bc0

Browse files
Improve code
1 parent 895af10 commit 0aa8bc0

File tree

5 files changed

+114
-89
lines changed

5 files changed

+114
-89
lines changed

build_system/src/build.rs

+46-38
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,13 +22,16 @@ 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() {
3337
build_arg.features.push(arg.as_str().into());
@@ -41,7 +45,7 @@ impl BuildArg {
4145
Self::usage();
4246
return Ok(None);
4347
}
44-
a => return Err(format!("Unknown argument `{a}`")),
48+
arg => return Err(format!("Unknown argument `{}`", arg)),
4549
}
4650
}
4751
Ok(Some(build_arg))
@@ -70,25 +74,25 @@ fn build_sysroot(
7074
std::env::set_current_dir("build_sysroot")
7175
.map_err(|e| format!("Failed to go to `build_sysroot` directory: {e:?}"))?;
7276
// Cleanup for previous run
73-
// v Clean target dir except for build scripts and incremental cache
74-
let _e = walk_dir(
77+
// Clean target dir except for build scripts and incremental cache
78+
let _ = walk_dir(
7579
"target",
7680
|dir: &Path| {
7781
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"));
82+
let _ = fs::remove_dir_all(dir.join(top).join("build"));
83+
let _ = fs::remove_dir_all(dir.join(top).join("deps"));
84+
let _ = fs::remove_dir_all(dir.join(top).join("examples"));
85+
let _ = fs::remove_dir_all(dir.join(top).join("native"));
8286

83-
let _e = walk_dir(
87+
let _ = walk_dir(
8488
dir.join(top),
8589
|sub_dir: &Path| {
8690
if sub_dir
8791
.file_name()
8892
.map(|s| s.to_str().unwrap().starts_with("libsysroot"))
8993
.unwrap_or(false)
9094
{
91-
let _e = fs::remove_dir_all(sub_dir);
95+
let _ = fs::remove_dir_all(sub_dir);
9296
}
9397
Ok(())
9498
},
@@ -98,7 +102,7 @@ fn build_sysroot(
98102
.map(|s| s.to_str().unwrap().starts_with("libsysroot"))
99103
.unwrap_or(false)
100104
{
101-
let _e = fs::remove_file(file);
105+
let _ = fs::remove_file(file);
102106
}
103107
Ok(())
104108
},
@@ -109,21 +113,21 @@ fn build_sysroot(
109113
|_| Ok(()),
110114
);
111115

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");
116+
let _ = fs::remove_file("Cargo.lock");
117+
let _ = fs::remove_file("test_target/Cargo.lock");
118+
let _ = fs::remove_dir_all("sysroot");
115119

116120
// Builds libs
117121
let channel = if release_mode {
118122
let rustflags = env
119-
.get(&"RUSTFLAGS".to_owned())
123+
.get(&"RUSTFLAGS".to_string())
120124
.cloned()
121125
.unwrap_or_default();
122126
env.insert(
123-
"RUSTFLAGS".to_owned(),
124-
format!("{rustflags} -Zmir-opt-level=3"),
127+
"RUSTFLAGS".to_string(),
128+
format!("{} -Zmir-opt-level=3", rustflags),
125129
);
126-
run_command_with_output(
130+
run_command_with_output_and_env(
127131
&[
128132
&"cargo",
129133
&"build",
@@ -136,7 +140,7 @@ fn build_sysroot(
136140
)?;
137141
"release"
138142
} else {
139-
run_command_with_output(
143+
run_command_with_output_and_env(
140144
&[
141145
&"cargo",
142146
&"build",
@@ -152,12 +156,12 @@ fn build_sysroot(
152156
};
153157

154158
// Copy files to sysroot
155-
let sysroot_path = format!("sysroot/lib/rustlib/{target_triple}/lib/");
159+
let sysroot_path = format!("sysroot/lib/rustlib/{}/lib/", target_triple);
156160
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);
161+
.map_err(|e| format!("Failed to create directory `{}`: {:?}", sysroot_path, e))?;
162+
let copier = |d: &Path| run_command(&[&"cp", &"-r", &d, &sysroot_path], None).map(|_| ());
159163
walk_dir(
160-
&format!("target/{target_triple}/{channel}/deps"),
164+
&format!("target/{}/{}/deps", target_triple, channel),
161165
copier,
162166
copier,
163167
)?;
@@ -169,21 +173,25 @@ fn build_codegen(args: &BuildArg) -> Result<(), String> {
169173
let mut env = HashMap::new();
170174

171175
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());
176+
std::env::current_dir().map_err(|e| format!("`current_dir` failed: {:?}", e))?;
177+
if let Ok(rt_root) = std::env::var("RUST_COMPILER_RT_ROOT") {
178+
env.insert("RUST_COMPILER_RT_ROOT".to_string(), rt_root);
179+
} else {
180+
env.insert(
181+
"RUST_COMPILER_RT_ROOT".to_string(),
182+
format!("{}", current_dir.join("llvm/compiler-rt").display()),
183+
);
184+
}
185+
env.insert("LD_LIBRARY_PATH".to_string(), args.gcc_path.clone());
186+
env.insert("LIBRARY_PATH".to_string(), args.gcc_path.clone());
179187

180188
let mut command: Vec<&dyn AsRef<OsStr>> = vec![&"cargo", &"rustc"];
181189
if args.codegen_release_channel {
182190
command.push(&"--release");
183-
env.insert("CHANNEL".to_owned(), "release".to_owned());
184-
env.insert("CARGO_INCREMENTAL".to_owned(), "1".to_owned());
191+
env.insert("CHANNEL".to_string(), "release".to_string());
192+
env.insert("CARGO_INCREMENTAL".to_string(), "1".to_string());
185193
} else {
186-
env.insert("CHANNEL".to_owned(), "debug".to_owned());
194+
env.insert("CHANNEL".to_string(), "debug".to_string());
187195
}
188196
let ref_features = args.features.iter().map(|s| s.as_str()).collect::<Vec<_>>();
189197
for feature in &ref_features {
@@ -194,10 +202,10 @@ fn build_codegen(args: &BuildArg) -> Result<(), String> {
194202
let config = set_config(&mut env, &[], Some(&args.gcc_path))?;
195203

196204
// We voluntarily ignore the error.
197-
let _e = fs::remove_dir_all("target/out");
205+
let _ = fs::remove_dir_all("target/out");
198206
let gccjit_target = "target/out/gccjit";
199207
fs::create_dir_all(gccjit_target)
200-
.map_err(|e| format!("Failed to create directory `{gccjit_target}`: {e:?}"))?;
208+
.map_err(|e| format!("Failed to create directory `{}`: {:?}", gccjit_target, e))?;
201209

202210
println!("[BUILD] sysroot");
203211
build_sysroot(
@@ -210,7 +218,7 @@ fn build_codegen(args: &BuildArg) -> Result<(), String> {
210218

211219
pub fn run() -> Result<(), String> {
212220
let args = match BuildArg::new()? {
213-
Some(a) => a,
221+
Some(args) => args,
214222
None => return Ok(()),
215223
};
216224
build_codegen(&args)?;

build_system/src/config.rs

+40-34
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,13 @@ 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(g) => g.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() {
@@ -49,72 +49,78 @@ pub fn set_config(
4949
}
5050
// Since we don't support ThinLTO, disable LTO completely when not trying to do LTO.
5151
// TODO(antoyo): remove when we can handle ThinLTO.
52-
let disable_lto_lfags = "-Clto=off";
52+
let disable_lto_lfags = if env.get(&"CHANNEL".to_string()).is_some() {
53+
""
54+
} else {
55+
"-Clto=off"
56+
}
57+
.to_string();
5358
let current_dir = std_env::current_dir().map_err(|e| format!("`current_dir` failed: {e:?}"))?;
59+
let channel = if let Some(channel) = env.get(&"CHANNEL".to_string()) {
60+
channel.as_str()
61+
} else {
62+
"debug"
63+
};
5464
let cg_backend_path = current_dir
5565
.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}"));
66+
.join(channel)
67+
.join(&format!("librustc_codegen_gcc.{}", dylib_ext));
6268
let sysroot_path = current_dir.join("build_sysroot/sysroot");
6369
let mut rustflags = Vec::new();
64-
if let Some(cg_rustflags) = env.get(&"CG_RUSTFLAGS".to_owned()) {
70+
if let Some(cg_rustflags) = env.get(&"CG_RUSTFLAGS".to_string()) {
6571
rustflags.push(cg_rustflags.clone());
6672
}
6773
if let Some(linker) = linker {
68-
rustflags.push(linker.to_owned());
74+
rustflags.push(linker.to_string());
6975
}
7076
rustflags.extend_from_slice(&[
71-
"-Csymbol-mangling-version=v0".to_owned(),
72-
"-Cdebuginfo=2".to_owned(),
73-
disable_lto_lfags.to_owned(),
77+
"-Csymbol-mangling-version=v0".to_string(),
78+
"-Cdebuginfo=2".to_string(),
79+
disable_lto_lfags,
7480
format!("-Zcodegen-backend={}", cg_backend_path.display()),
75-
"--sysroot".to_owned(),
81+
"--sysroot".to_string(),
7682
format!("{}", sysroot_path.display()),
7783
]);
7884
rustflags.extend_from_slice(test_flags);
7985
// FIXME(antoyo): remove once the atomic shim is gone
8086
if os_name == "Darwin" {
8187
rustflags.extend_from_slice(&[
82-
"-Clink-arg=-undefined".to_owned(),
83-
"-Clink-arg=dynamic_lookup".to_owned(),
88+
"-Clink-arg=-undefined".to_string(),
89+
"-Clink-arg=dynamic_lookup".to_string(),
8490
]);
8591
}
86-
env.insert("RUSTFLAGS".to_owned(), rustflags.join(" "));
92+
env.insert("RUSTFLAGS".to_string(), rustflags.join(" "));
8793
// display metadata load errors
88-
env.insert("RUSTC_LOG".to_owned(), "warn".to_owned());
94+
env.insert("RUSTC_LOG".to_string(), "warn".to_string());
8995

96+
let sysroot = current_dir.join(&format!(
97+
"build_sysroot/sysroot/lib/rustlib/{}/lib",
98+
target_triple
99+
));
90100
let ld_library_path = format!(
91101
"{target}:{sysroot}:{gcc_path}",
92102
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(),
103+
sysroot = sysroot.display(),
98104
);
99-
env.insert("LD_LIBRARY_PATH".to_owned(), ld_library_path.clone());
100-
env.insert("DYLD_LIBRARY_PATH".to_owned(), ld_library_path);
105+
env.insert("LD_LIBRARY_PATH".to_string(), ld_library_path.clone());
106+
env.insert("DYLD_LIBRARY_PATH".to_string(), ld_library_path);
101107

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

108-
let mut rustc_command = vec!["rustc".to_owned()];
114+
let mut rustc_command = vec!["rustc".to_string()];
109115
rustc_command.extend_from_slice(&rustflags);
110116
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(),
117+
"-L".to_string(),
118+
"crate=target/out".to_string(),
119+
"--out-dir".to_string(),
120+
"target/out".to_string(),
115121
]);
116122
Ok(ConfigInfo {
117-
target_triple: target_triple.to_owned(),
123+
target_triple: target_triple.to_string(),
118124
rustc_command,
119125
run_wrapper,
120126
})

build_system/src/prepare.rs

+6-8
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::path::Path;
77
fn prepare_libcore(sysroot_path: &Path) -> Result<(), String> {
88
let rustc_path = match get_rustc_path() {
99
Some(path) => path,
10-
None => return Err("`rustc` path not found".to_owned()),
10+
None => return Err("`rustc` path not found".to_string()),
1111
};
1212

1313
let parent = match rustc_path.parent() {
@@ -20,7 +20,7 @@ fn prepare_libcore(sysroot_path: &Path) -> Result<(), String> {
2020
.canonicalize()
2121
.map_err(|e| format!("Failed to canonicalize path: {e:?}"))?;
2222
if !rustlib_dir.is_dir() {
23-
return Err("Please install `rust-src` component".to_owned());
23+
return Err("Please install `rust-src` component".to_string());
2424
}
2525

2626
let sysroot_dir = sysroot_path.join("sysroot_src");
@@ -90,8 +90,8 @@ fn prepare_libcore(sysroot_path: &Path) -> Result<(), String> {
9090
for file_path in patches {
9191
println!("[GIT] apply `{}`", file_path.display());
9292
let path = Path::new("../..").join(file_path);
93-
run_command_with_output(&[&"git", &"apply", &path], Some(&sysroot_dir), None)?;
94-
run_command_with_output(&[&"git", &"add", &"-A"], Some(&sysroot_dir), None)?;
93+
run_command_with_output(&[&"git", &"apply", &path], Some(&sysroot_dir))?;
94+
run_command_with_output(&[&"git", &"add", &"-A"], Some(&sysroot_dir))?;
9595
run_command_with_output(
9696
&[
9797
&"git",
@@ -101,7 +101,6 @@ fn prepare_libcore(sysroot_path: &Path) -> Result<(), String> {
101101
&format!("Patch {}", path.display()),
102102
],
103103
Some(&sysroot_dir),
104-
None,
105104
)?;
106105
}
107106
println!("Successfully prepared libcore for building");
@@ -139,12 +138,11 @@ where
139138
"crate_patches",
140139
|_| Ok(()),
141140
|file_path| {
142-
let s = file_path.as_os_str().to_str().unwrap();
143-
if s.contains(&filter) && s.ends_with(".patch") {
141+
let patch = file_path.as_os_str().to_str().unwrap();
142+
if patch.contains(&filter) && patch.ends_with(".patch") {
144143
run_command_with_output(
145144
&[&"git", &"am", &file_path.canonicalize().unwrap()],
146145
Some(&repo_path),
147-
None,
148146
)?;
149147
}
150148
Ok(())

build_system/src/rustc_info.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@ pub fn get_rustc_path() -> Option<PathBuf> {
88
}
99
run_command(&[&"rustup", &"which", &"rustc"], None)
1010
.ok()
11-
.map(|out| Path::new(String::from_utf8(out.stdout).unwrap().trim()).to_owned())
11+
.map(|out| Path::new(String::from_utf8(out.stdout).unwrap().trim()).to_path_buf())
1212
}

0 commit comments

Comments
 (0)