Skip to content

Commit

Permalink
Add a subcommand wrapper for zig cc and zig c++
Browse files Browse the repository at this point in the history
Co-authored-by: konstin <[email protected]>
  • Loading branch information
messense and konstin committed Jan 3, 2022
1 parent 33be362 commit 06556a7
Show file tree
Hide file tree
Showing 8 changed files with 242 additions and 90 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,10 @@ jobs:
with:
python-version: "3.10.0"
- name: test cross compiling with zig
if: matrix.os != 'windows-latest'
run: |
rustup target add aarch64-unknown-linux-gnu
cargo run -- build --no-sdist -i python -m test-crates/pyo3-pure/Cargo.toml --target aarch64-unknown-linux-gnu --zig
cargo run -- build --no-sdist -i python -m test-crates/pyo3-pure/Cargo.toml --target aarch64-unknown-linux-musl --zig
test-auditwheel:
name: Test Auditwheel
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ cc = "1.0.72"
clap = { version = "3.0.0", features = ["derive", "env", "wrap_help"] }
clap_complete = "3.0.0"
clap_complete_fig = "3.0.0"
semver = "1.0.4"

[dev-dependencies]
indoc = "1.0.3"
Expand Down
91 changes: 3 additions & 88 deletions src/compile.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
use crate::build_context::BridgeModel;
use crate::python_interpreter::InterpreterKind;
use crate::target::Arch;
use crate::{BuildContext, PlatformTag, PythonInterpreter};
use crate::zig::prepare_zig_linker;
use crate::{BuildContext, PythonInterpreter};
use anyhow::{anyhow, bail, Context, Result};
use fat_macho::FatWriter;
use fs_err::{self as fs, File};
use std::collections::HashMap;
use std::env;
#[cfg(target_family = "unix")]
use std::fs::OpenOptions;
use std::io::{BufReader, Read, Write};
#[cfg(target_family = "unix")]
use std::os::unix::fs::OpenOptionsExt;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::str;
Expand Down Expand Up @@ -105,87 +101,6 @@ fn compile_universal2(
Ok(result)
}

/// We want to use `zig cc` as linker and c compiler. We want to call `python -m ziglang cc`, but
/// cargo only accepts a path to an executable as linker, so we add a wrapper script. We then also
/// use the wrapper script to pass arguments and substitute an unsupported argument.
///
/// We create different files for different args because otherwise cargo might skip recompiling even
/// if the linker target changed
fn prepare_zig_linker(context: &BuildContext) -> Result<(PathBuf, PathBuf)> {
let target = &context.target;
let arch = if target.cross_compiling() {
if matches!(target.target_arch(), Arch::Armv7L) {
"armv7".to_string()
} else {
target.target_arch().to_string()
}
} else {
"native".to_string()
};
let (zig_cc, zig_cxx, cc_args) = match context.platform_tag {
// Not sure branch even has any use case, but it doesn't hurt to support it
None | Some(PlatformTag::Linux) => (
"./zigcc-gnu.sh".to_string(),
"./zigcxx-gnu.sh".to_string(),
format!("{}-linux-gnu", arch),
),
Some(PlatformTag::Musllinux { x, y }) => {
println!("⚠️ Warning: zig with musl is unstable");
(
format!("./zigcc-musl-{}-{}.sh", x, y),
format!("./zigcxx-musl-{}-{}.sh", x, y),
format!("{}-linux-musl", arch),
)
}
Some(PlatformTag::Manylinux { x, y }) => (
format!("./zigcc-gnu-{}-{}.sh", x, y),
format!("./zigcxx-gnu-{}-{}.sh", x, y),
// https://github.com/ziglang/zig/issues/10050#issuecomment-956204098
format!(
"${{@/-lgcc_s/-lunwind}} -target {}-linux-gnu.{}.{}",
arch, x, y
),
),
};

let zig_linker_dir = dirs::cache_dir()
// If the really is no cache dir, cwd will also do
.unwrap_or_else(|| PathBuf::from("."))
.join(env!("CARGO_PKG_NAME"))
.join(env!("CARGO_PKG_VERSION"));
fs::create_dir_all(&zig_linker_dir)?;
let zig_cc = zig_linker_dir.join(zig_cc);
let zig_cxx = zig_linker_dir.join(zig_cxx);

let mut zig_cc_file = create_linker_script(&zig_cc)?;
writeln!(&mut zig_cc_file, "#!/bin/bash")?;
writeln!(&mut zig_cc_file, "python -m ziglang cc {}", cc_args)?;
drop(zig_cc_file);

let mut zig_cxx_file = create_linker_script(&zig_cxx)?;
writeln!(&mut zig_cxx_file, "#!/bin/bash")?;
writeln!(&mut zig_cxx_file, "python -m ziglang c++ {}", cc_args)?;
drop(zig_cxx_file);

Ok((zig_cc, zig_cxx))
}

#[cfg(target_family = "unix")]
fn create_linker_script(path: &Path) -> Result<std::fs::File> {
let custom_linker_file = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.mode(0o700)
.open(path)?;
Ok(custom_linker_file)
}

#[cfg(not(target_family = "unix"))]
fn create_linker_script(path: &Path) -> Result<File> {
Ok(File::create(path)?)
}

fn compile_target(
context: &BuildContext,
python_interpreter: Option<&PythonInterpreter>,
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub use crate::new_project::{init_project, new_project, GenerateProjectOptions};
pub use crate::pyproject_toml::PyProjectToml;
pub use crate::python_interpreter::PythonInterpreter;
pub use crate::target::Target;
pub use crate::zig::Zig;
pub use auditwheel::PlatformTag;
#[cfg(feature = "upload")]
pub use {
Expand All @@ -62,3 +63,4 @@ mod source_distribution;
mod target;
#[cfg(feature = "upload")]
mod upload;
mod zig;
10 changes: 9 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use clap::{ArgEnum, IntoApp, Parser};
use clap_complete::Generator;
use maturin::{
develop, init_project, new_project, write_dist_info, BridgeModel, BuildOptions,
GenerateProjectOptions, PathWriter, PlatformTag, PythonInterpreter, Target,
GenerateProjectOptions, PathWriter, PlatformTag, PythonInterpreter, Target, Zig,
};
#[cfg(feature = "upload")]
use maturin::{upload_ui, PublishOpt};
Expand Down Expand Up @@ -163,6 +163,9 @@ enum Opt {
#[clap(name = "SHELL", parse(try_from_str))]
shell: Shell,
},
/// Zig linker wrapper
#[clap(subcommand)]
Zig(Zig),
}

/// Backend for the PEP 517 integration. Not for human consumption
Expand Down Expand Up @@ -449,6 +452,11 @@ fn run() -> Result<()> {
}
}
}
Opt::Zig(subcommand) => {
subcommand
.execute()
.context("Failed to create zig wrapper script")?;
}
}

Ok(())
Expand Down
Loading

0 comments on commit 06556a7

Please sign in to comment.