Skip to content

Commit

Permalink
Use Cargo's target information when possible
Browse files Browse the repository at this point in the history
rustc's target triples generally only have a vague resemblance to each
other and to the information needed by `cc`. Let's instead prefer
`CARGO_CFG_*` variables when available, since these contain the
information directly from the compiler itself.

In the cases where it isn't available (i.e. when running outside of a
build script), we fall back to parsing the target triple, but instead of
doing it in an ad-hoc fashion with string manipulation, we do it in a
more structured fashion up front.
  • Loading branch information
madsmtm committed Sep 30, 2024
1 parent 268fb9b commit 2fa692d
Show file tree
Hide file tree
Showing 5 changed files with 713 additions and 429 deletions.
35 changes: 2 additions & 33 deletions dev-tools/gen-target-info/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,11 @@
use gen_target_info::{get_target_specs_from_json, write_target_tuple_mapping, RustcTargetSpecs};
use std::{collections::BTreeMap, fs::File, io::Write as _};
use std::{fs::File, io::Write as _};

const PRELUDE: &str = r#"//! This file is generated code. Please edit the generator
//! in dev-tools/gen-target-info if you need to make changes.
"#;

fn generate_riscv_arch_mapping(f: &mut File, target_specs: &RustcTargetSpecs) {
let riscv_target_mapping = target_specs
.0
.iter()
.filter_map(|(target, target_spec)| {
let arch = target.split_once('-').unwrap().0;
(arch.contains("riscv") && arch != target_spec.arch)
.then_some((arch, &*target_spec.arch))
})
.collect::<BTreeMap<_, _>>();
write_target_tuple_mapping(f, "RISCV_ARCH_MAPPING", &riscv_target_mapping);
}

fn generate_windows_triple_mapping(f: &mut File, target_specs: &RustcTargetSpecs) {
let windows_target_mapping = target_specs
.0
.iter()
.filter_map(|(target, target_spec)| {
let rust_target_parts = target.splitn(4, '-').collect::<Vec<_>>();
let os = *rust_target_parts.get(2)?;
(os.contains("windows") && target != &*target_spec.llvm_target)
.then_some((&**target, &*target_spec.llvm_target))
})
.collect::<BTreeMap<_, _>>();
write_target_tuple_mapping(f, "WINDOWS_TRIPLE_MAPPING", &windows_target_mapping);
}

fn main() {
let target_specs = get_target_specs_from_json();

// Open file to write to
let manifest_dir = env!("CARGO_MANIFEST_DIR");

Expand All @@ -45,8 +15,7 @@ fn main() {
f.write_all(PRELUDE.as_bytes()).unwrap();

// Start generating
generate_riscv_arch_mapping(&mut f, &target_specs);
generate_windows_triple_mapping(&mut f, &target_specs);
// TODO

// Flush the data onto disk
f.flush().unwrap();
Expand Down
Loading

0 comments on commit 2fa692d

Please sign in to comment.