Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion crates/cargo-gpu/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ dunce.workspace = true
tempfile.workspace = true
test-log.workspace = true
cargo_metadata = { workspace = true, features = ["builder"] }
cargo-util-schemas.workspace = true

[lints]
workspace = true
16 changes: 10 additions & 6 deletions crates/cargo-gpu/src/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
use std::path::{Path, PathBuf};

use anyhow::Context as _;
use rustc_codegen_spirv_cache::cache::cache_dir;
use spirv_builder::SpirvBuilder;

use crate::{
use rustc_codegen_spirv_cache::{
cache::cache_dir,
spirv_source::{
get_channel_from_rustc_codegen_spirv_build_script, query_metadata, FindPackage as _,
SpirvSource,
},
target_specs::update_target_specs_files,
};
use spirv_builder::SpirvBuilder;

use crate::target_specs::update_target_specs_files;

/// Represents a functional backend installation, whether it was cached or just installed.
#[derive(Clone, Debug, Default)]
Expand Down Expand Up @@ -75,8 +75,9 @@ pub struct Install {
pub shader_crate: PathBuf,

#[expect(
rustdoc::bare_urls,
clippy::doc_markdown,
reason = "The URL should appear literally like this. But Clippy wants a markdown clickable link"
reason = "The URL should appear literally like this. But Clippy & rustdoc want a markdown clickable link"
)]
/// Source of `spirv-builder` dependency
/// Eg: "https://github.com/Rust-GPU/rust-gpu"
Expand Down Expand Up @@ -182,6 +183,9 @@ impl Install {
new_path.push("crates/spirv-builder");
format!("path = \"{new_path}\"\nversion = \"{version}\"")
}
// TODO: remove this once this module moves to rustc_codegen_spirv-cache
#[expect(clippy::todo, reason = "temporary allow this")]
_ => todo!(),
};
let cargo_toml = format!(
r#"
Expand Down
14 changes: 0 additions & 14 deletions crates/cargo-gpu/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ mod linkage;
mod lockfile;
mod metadata;
mod show;
mod spirv_source;
mod target_specs;
mod test;

Expand Down Expand Up @@ -163,16 +162,3 @@ pub struct Cli {
#[clap(subcommand)]
pub command: Command,
}

/// Returns a string suitable to use as a directory.
///
/// Created from the spirv-builder source dep and the rustc channel.
fn to_dirname(text: &str) -> String {
text.replace(
[std::path::MAIN_SEPARATOR, '\\', '/', '.', ':', '@', '='],
"_",
)
.split(['{', '}', ' ', '\n', '"', '\''])
.collect::<Vec<_>>()
.concat()
}
8 changes: 4 additions & 4 deletions crates/cargo-gpu/src/show.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
use std::{fs, path::Path};

use anyhow::bail;
use rustc_codegen_spirv_cache::cache::cache_dir;

use crate::{
use rustc_codegen_spirv_cache::{
cache::cache_dir,
spirv_source::{query_metadata, SpirvSource},
target_specs::update_target_specs_files,
};

use crate::target_specs::update_target_specs_files;

/// Show the computed source of the spirv-std dependency.
#[derive(Clone, Debug, clap::Parser)]
pub struct SpirvSourceDep {
Expand Down
7 changes: 4 additions & 3 deletions crates/cargo-gpu/src/target_specs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@ use std::path::{Path, PathBuf};

use anyhow::Context as _;
use cargo_metadata::Metadata;
use rustc_codegen_spirv_cache::cache::cache_dir;

use crate::spirv_source::{FindPackage as _, SpirvSource};
use rustc_codegen_spirv_cache::{
cache::cache_dir,
spirv_source::{FindPackage as _, SpirvSource},
};

/// Extract legacy target specs from our executable into some directory
pub fn write_legacy_target_specs(target_spec_dir: &Path) -> anyhow::Result<()> {
Expand Down
1 change: 1 addition & 0 deletions crates/cargo-gpu/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ fn copy_dir_all(
}
Ok(())
}

pub fn shader_crate_template_path() -> std::path::PathBuf {
let project_base = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
project_base.join("../shader-crate-template")
Expand Down
7 changes: 7 additions & 0 deletions crates/rustc_codegen_spirv-cache/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,14 @@ license.workspace = true

[dependencies]
thiserror.workspace = true
anyhow.workspace = true
log.workspace = true
directories.workspace = true
cargo_metadata.workspace = true

[dev-dependencies]
test-log.workspace = true
cargo-util-schemas.workspace = true

[lints]
workspace = true
1 change: 1 addition & 0 deletions crates/rustc_codegen_spirv-cache/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@
//! of `rustc_codegen_spirv` and their associated toolchains for you.

pub mod cache;
pub mod spirv_source;
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
//! version. Then with that we `git checkout` the `rust-gpu` repo that corresponds to that version.
//! From there we can look at the source code to get the required Rust toolchain.

// TODO: remove this & fix documentation
#![expect(clippy::missing_errors_doc, reason = "temporary allow")]

use std::{
fs,
path::{Path, PathBuf},
Expand All @@ -15,11 +18,13 @@ use cargo_metadata::{
semver::Version,
Metadata, MetadataCommand, Package,
};
use rustc_codegen_spirv_cache::cache::cache_dir;

use crate::cache::cache_dir;

#[expect(
rustdoc::bare_urls,
clippy::doc_markdown,
reason = "The URL should appear literally like this. But Clippy wants a markdown clickable link"
reason = "The URL should appear literally like this. But Clippy & rustdoc want a markdown clickable link"
)]
/// The source and version of `rust-gpu`.
/// Eg:
Expand All @@ -29,6 +34,7 @@ use rustc_codegen_spirv_cache::cache::cache_dir;
/// - a revision of "abc213"
/// * a local Path
#[derive(Eq, PartialEq, Clone, Debug)]
#[non_exhaustive]
pub enum SpirvSource {
/// If the shader specifies a simple version like `spirv-std = "0.9.0"` then the source of
/// `rust-gpu` is the conventional crates.io version.
Expand Down Expand Up @@ -58,6 +64,7 @@ impl core::fmt::Display for SpirvSource {
clippy::min_ident_chars,
reason = "It's a core library trait implementation"
)]
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::CratesIO(version) => version.fmt(f),
Expand All @@ -79,6 +86,7 @@ impl core::fmt::Display for SpirvSource {

impl SpirvSource {
/// Figures out which source of `rust-gpu` to use
#[inline]
pub fn new(
shader_crate_path: &Path,
maybe_rust_gpu_source: Option<&str>,
Expand All @@ -105,6 +113,7 @@ impl SpirvSource {
}

/// Look into the shader crate to get the version of `rust-gpu` it's using.
#[inline]
pub fn get_rust_gpu_deps_from_shader(shader_crate_path: &Path) -> anyhow::Result<Self> {
let crate_metadata = query_metadata(shader_crate_path)?;
let spirv_std_package = crate_metadata.find_package("spirv-std")?;
Expand All @@ -120,19 +129,25 @@ impl SpirvSource {
/// Convert the `SpirvSource` to a cache directory in which we can build it.
/// It needs to be dynamically created because an end-user might want to swap out the source,
/// maybe using their own fork for example.
#[inline]
pub fn install_dir(&self) -> anyhow::Result<PathBuf> {
match self {
Self::Path {
rust_gpu_repo_root, ..
} => Ok(rust_gpu_repo_root.as_std_path().to_owned()),
Self::CratesIO { .. } | Self::Git { .. } => {
let dir = crate::to_dirname(self.to_string().as_ref());
let dir = to_dirname(self.to_string().as_ref());
Ok(cache_dir()?.join("codegen").join(dir))
}
}
}

/// Returns true if self is a Path
#[expect(
clippy::must_use_candidate,
reason = "calculations are cheap, `bool` is `Copy`"
)]
#[inline]
pub const fn is_path(&self) -> bool {
matches!(self, Self::Path { .. })
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The point of #[must_use] is for you to notice that some function is needlessly called. This isn't about performance, LLVM will inline and remove the call for you, this is about clean code.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've thought that #[must_use] should be used if the result of this function should be used in some way (to handle errors, in a builder pattern and so on).
I'm not aware of any "some function is needlessly called" usage of this lint.

Expand Down Expand Up @@ -191,7 +206,21 @@ impl SpirvSource {
}
}

/// Returns a string suitable to use as a directory.
///
/// Created from the spirv-builder source dep and the rustc channel.
fn to_dirname(text: &str) -> String {
text.replace(
[std::path::MAIN_SEPARATOR, '\\', '/', '.', ':', '@', '='],
"_",
)
.split(['{', '}', ' ', '\n', '"', '\''])
.collect::<Vec<_>>()
.concat()
}

/// get the Package metadata from some crate
#[inline]
pub fn query_metadata(crate_path: &Path) -> anyhow::Result<Metadata> {
log::debug!("Running `cargo metadata` on `{}`", crate_path.display());
let metadata = MetadataCommand::new()
Expand All @@ -211,6 +240,7 @@ pub trait FindPackage {
}

impl FindPackage for Metadata {
#[inline]
fn find_package(&self, crate_name: &str) -> anyhow::Result<&Package> {
if let Some(package) = self
.packages
Expand All @@ -229,6 +259,7 @@ impl FindPackage for Metadata {
}

/// Parse the `rust-toolchain.toml` in the working tree of the checked-out version of the `rust-gpu` repo.
#[inline]
pub fn get_channel_from_rustc_codegen_spirv_build_script(
rustc_codegen_spirv_package: &Package,
) -> anyhow::Result<String> {
Expand Down Expand Up @@ -257,9 +288,14 @@ mod test {
use cargo_metadata::{PackageBuilder, PackageId, Source};
use cargo_util_schemas::manifest::PackageName;

pub fn shader_crate_template_path() -> std::path::PathBuf {
let project_base = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
project_base.join("../shader-crate-template")
}

#[test_log::test]
fn parsing_spirv_std_dep_for_shader_template() {
let shader_template_path = crate::test::shader_crate_template_path();
let shader_template_path = shader_crate_template_path();
let source = SpirvSource::get_rust_gpu_deps_from_shader(&shader_template_path).unwrap();
assert_eq!(
source,
Expand All @@ -278,7 +314,7 @@ mod test {

#[test_log::test]
fn cached_checkout_dir_sanity() {
let shader_template_path = crate::test::shader_crate_template_path();
let shader_template_path = shader_crate_template_path();
let source = SpirvSource::get_rust_gpu_deps_from_shader(&shader_template_path).unwrap();
let dir = source.install_dir().unwrap();
let name = dir
Expand Down