[naga] Remove naga::path_like. Use String instead. (#8284)

Delete the `naga::path_like` module, and simply using `String` and
`str` instead.

Nothing in Naga uses `Path` or `PathBuf` methods; indeed, Naga only
converts these values back and forth from string-like types with
`to_string_lossy` and `into`, such that using string-like, rather than
path-like, types actually simplifies the code.

This also avoids dead code warnings starting in Rust 1.89 that would
otherwise require distracting `#[cfg_attr]` conditionals.
This commit is contained in:
Jim Blandy 2025-10-01 09:08:18 -07:00 committed by GitHub
parent 5b194ec510
commit 43eccd28f8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 20 additions and 274 deletions

View File

@ -452,7 +452,7 @@ fn run() -> anyhow::Result<()> {
params.spv_in = naga::front::spv::Options {
adjust_coordinate_space: !args.keep_coordinate_space,
strict_capabilities: false,
block_ctx_dump_prefix: args.block_ctx_dir.clone().map(Into::into),
block_ctx_dump_prefix: args.block_ctx_dir.clone(),
};
params.entry_point.clone_from(&args.entry_point);
@ -482,7 +482,7 @@ fn run() -> anyhow::Result<()> {
params.compact = args.compact;
if args.bulk_validate {
return bulk_validate(args, &params);
return bulk_validate(&args, &params);
}
let mut files = args.files.iter();
@ -498,6 +498,8 @@ fn run() -> anyhow::Result<()> {
return Err(CliError("Input file path is not specified").into());
};
let file_name = input_path.to_string_lossy();
params.input_kind = args.input_kind;
params.shader_stage = args.shader_stage;
@ -516,7 +518,7 @@ fn run() -> anyhow::Result<()> {
.set(naga::back::spv::WriterFlags::DEBUG, true);
params.spv_out.debug_info = Some(naga::back::spv::DebugInfo {
source_code: input_text,
file_name: input_path.into(),
file_name: &file_name,
language,
})
} else {
@ -913,9 +915,9 @@ fn write_output(
Ok(())
}
fn bulk_validate(args: Args, params: &Parameters) -> anyhow::Result<()> {
fn bulk_validate(args: &Args, params: &Parameters) -> anyhow::Result<()> {
let mut invalid = vec![];
for input_path in args.files {
for input_path in &args.files {
let path = Path::new(&input_path);
let input = fs::read(path)?;

View File

@ -26,7 +26,6 @@ use spirv::Word;
use thiserror::Error;
use crate::arena::{Handle, HandleVec};
use crate::path_like::PathLikeRef;
use crate::proc::{BoundsCheckPolicies, TypeResolution};
#[derive(Clone)]
@ -96,7 +95,7 @@ impl IdGenerator {
#[derive(Debug, Clone)]
pub struct DebugInfo<'a> {
pub source_code: &'a str,
pub file_name: PathLikeRef<'a>,
pub file_name: &'a str,
pub language: SourceLanguage,
}

View File

@ -14,7 +14,6 @@ use super::{
use crate::{
arena::{Handle, HandleVec, UniqueArena},
back::spv::{BindingInfo, WrappedFunction},
path_like::PathLike,
proc::{Alignment, TypeResolution},
valid::{FunctionInfo, ModuleInfo},
};
@ -2519,10 +2518,8 @@ impl Writer {
if self.flags.contains(WriterFlags::DEBUG) {
if let Some(debug_info) = debug_info.as_ref() {
let source_file_id = self.id_gen.next();
self.debugs.push(Instruction::string(
&debug_info.file_name.to_string_lossy(),
source_file_id,
));
self.debugs
.push(Instruction::string(debug_info.file_name, source_file_id));
debug_info_inner = Some(DebugInfoInner {
source_code: debug_info.source_code,

View File

@ -44,7 +44,6 @@ use petgraph::graphmap::GraphMap;
use super::atomic_upgrade::Upgrades;
use crate::{
arena::{Arena, Handle, UniqueArena},
path_like::PathLikeOwned,
proc::{Alignment, Layouter},
FastHashMap, FastHashSet, FastIndexMap,
};
@ -384,7 +383,7 @@ pub struct Options {
pub adjust_coordinate_space: bool,
/// Only allow shaders with the known set of capabilities.
pub strict_capabilities: bool,
pub block_ctx_dump_prefix: Option<PathLikeOwned>,
pub block_ctx_dump_prefix: Option<String>,
}
impl Default for Options {

View File

@ -116,7 +116,6 @@ pub mod front;
pub mod ir;
pub mod keywords;
mod non_max_u32;
mod path_like;
pub mod proc;
mod racy_lock;
mod span;

View File

@ -1,238 +0,0 @@
//! [`PathLike`] and its supporting items, such as [`PathLikeRef`] and [`PathLikeOwned`].
//! This trait and these types provide a common denominator API for `Path`-like
//! types and operations in `std` and `no_std` contexts.
//!
//! # Usage
//!
//! - Store a [`PathLikeRef<'a>`] instead of a `&'a Path` in structs and enums.
//! - Store a [`PathLikeOwned`] instead of a `PathBuf` in structs and enums.
//! - Accept `impl PathLike` instead of `impl AsRef<Path>` for methods which directly
//! work with `Path`-like values.
//! - Accept `Into<PathLikeRef<'_>>` and/or `Into<PathLikeOwned>` in methods which
//! will store a `Path`-like value.
use alloc::{borrow::Cow, string::String};
use core::fmt;
mod sealed {
/// Seal for [`PathLike`](super::PathLike).
pub trait Sealed {}
}
/// A trait that abstracts over types accepted for conversion to the most
/// featureful path representation possible; that is:
///
/// - When `no_std` is active, this is implemented for:
/// - [`str`],
/// - [`String`],
/// - [`Cow<'_, str>`], and
/// - [`PathLikeRef`]
/// - Otherwise, types that implement `AsRef<Path>` (to extract a `&Path`).
///
/// This type is used as the type bounds for various diagnostic rendering methods, i.e.,
/// [`WithSpan::emit_to_string_with_path`](crate::span::WithSpan::emit_to_string_with_path).
pub trait PathLike: sealed::Sealed {
fn to_string_lossy(&self) -> Cow<'_, str>;
}
/// Abstraction over `Path` which falls back to [`str`] for `no_std` compatibility.
///
/// This type should be used for _storing_ a reference to a [`PathLike`].
/// Functions which accept a `Path` should prefer to use `impl PathLike`
/// or `impl Into<PathLikeRef<'_>>`.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PathLikeRef<'a>(&'a path_like_impls::PathInner);
impl fmt::Debug for PathLikeRef<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.0, f)
}
}
impl<'a> From<&'a str> for PathLikeRef<'a> {
fn from(value: &'a str) -> Self {
cfg_if::cfg_if! {
if #[cfg(std)] {
Self(std::path::Path::new(value))
} else {
Self(value)
}
}
}
}
/// Abstraction over `PathBuf` which falls back to [`String`] for `no_std` compatibility.
///
/// This type should be used for _storing_ an owned [`PathLike`].
/// Functions which accept a `PathBuf` should prefer to use `impl PathLike`
/// or `impl Into<PathLikeOwned>`.
#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PathLikeOwned(<path_like_impls::PathInner as alloc::borrow::ToOwned>::Owned);
impl fmt::Debug for PathLikeOwned {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl From<String> for PathLikeOwned {
fn from(value: String) -> Self {
cfg_if::cfg_if! {
if #[cfg(std)] {
Self(value.into())
} else {
Self(value)
}
}
}
}
#[cfg(std)]
mod path_like_impls {
//! Implementations of [`PathLike`] within an `std` context.
//!
//! Since `std` is available, we blanket implement [`PathLike`] for all types
//! implementing [`AsRef<Path>`].
use alloc::borrow::Cow;
use std::path::Path;
use super::{sealed, PathLike};
pub(super) type PathInner = Path;
impl<T: AsRef<Path> + ?Sized> PathLike for T {
fn to_string_lossy(&self) -> Cow<'_, str> {
self.as_ref().to_string_lossy()
}
}
impl<T: AsRef<Path> + ?Sized> sealed::Sealed for T {}
}
#[cfg(no_std)]
mod path_like_impls {
//! Implementations of [`PathLike`] within a `no_std` context.
//!
//! Without `std`, we cannot blanket implement on [`AsRef<Path>`].
//! Instead, we manually implement for a subset of types which are known
//! to implement [`AsRef<Path>`] when `std` is available.
//!
//! Implementing [`PathLike`] for a type which does _not_ implement [`AsRef<Path>`]
//! with `std` enabled breaks the additive requirement of Cargo features.
use alloc::{borrow::Cow, string::String};
use core::borrow::Borrow;
use super::{sealed, PathLike, PathLikeOwned, PathLikeRef};
pub(super) type PathInner = str;
impl PathLike for String {
fn to_string_lossy(&self) -> Cow<'_, str> {
Cow::Borrowed(self.as_str())
}
}
impl sealed::Sealed for String {}
impl PathLike for str {
fn to_string_lossy(&self) -> Cow<'_, str> {
Cow::Borrowed(self)
}
}
impl sealed::Sealed for str {}
impl PathLike for Cow<'_, str> {
fn to_string_lossy(&self) -> Cow<'_, str> {
Cow::Borrowed(self.borrow())
}
}
impl sealed::Sealed for Cow<'_, str> {}
impl<T: PathLike + ?Sized> PathLike for &T {
fn to_string_lossy(&self) -> Cow<'_, str> {
(*self).to_string_lossy()
}
}
impl<T: PathLike + ?Sized> sealed::Sealed for &T {}
impl PathLike for PathLikeRef<'_> {
fn to_string_lossy(&self) -> Cow<'_, str> {
Cow::Borrowed(self.0)
}
}
impl sealed::Sealed for PathLikeRef<'_> {}
impl PathLike for PathLikeOwned {
fn to_string_lossy(&self) -> Cow<'_, str> {
Cow::Borrowed(self.0.borrow())
}
}
impl sealed::Sealed for PathLikeOwned {}
}
#[cfg(std)]
mod path_like_owned_std_impls {
//! Traits which can only be implemented for [`PathLikeOwned`] with `std`.
use std::path::{Path, PathBuf};
use super::PathLikeOwned;
impl AsRef<Path> for PathLikeOwned {
fn as_ref(&self) -> &Path {
self.0.as_ref()
}
}
impl From<PathBuf> for PathLikeOwned {
fn from(value: PathBuf) -> Self {
Self(value)
}
}
impl From<PathLikeOwned> for PathBuf {
fn from(value: PathLikeOwned) -> Self {
value.0
}
}
impl AsRef<PathBuf> for PathLikeOwned {
fn as_ref(&self) -> &PathBuf {
&self.0
}
}
}
#[cfg(std)]
mod path_like_ref_std_impls {
//! Traits which can only be implemented for [`PathLikeRef`] with `std`.
use std::path::Path;
use super::PathLikeRef;
impl AsRef<Path> for PathLikeRef<'_> {
fn as_ref(&self) -> &Path {
self.0
}
}
impl<'a> From<&'a Path> for PathLikeRef<'a> {
fn from(value: &'a Path) -> Self {
Self(value)
}
}
impl<'a> From<PathLikeRef<'a>> for &'a Path {
fn from(value: PathLikeRef<'a>) -> Self {
value.0
}
}
}

View File

@ -6,7 +6,7 @@ use alloc::{
};
use core::{error::Error, fmt, ops::Range};
use crate::{error::replace_control_chars, path_like::PathLike, Arena, Handle, UniqueArena};
use crate::{error::replace_control_chars, Arena, Handle, UniqueArena};
/// A source code span, used for error reporting.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
@ -283,14 +283,12 @@ impl<E> WithSpan<E> {
/// Emits a summary of the error to standard error stream.
#[cfg(feature = "stderr")]
pub fn emit_to_stderr_with_path<P>(&self, source: &str, path: P)
pub fn emit_to_stderr_with_path(&self, source: &str, path: &str)
where
E: Error,
P: PathLike,
{
use codespan_reporting::{files, term};
let path = path.to_string_lossy();
let files = files::SimpleFile::new(path, replace_control_chars(source));
let config = term::Config::default();
@ -315,14 +313,12 @@ impl<E> WithSpan<E> {
}
/// Emits a summary of the error to a string.
pub fn emit_to_string_with_path<P>(&self, source: &str, path: P) -> String
pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String
where
E: Error,
P: PathLike,
{
use codespan_reporting::{files, term};
let path = path.to_string_lossy();
let files = files::SimpleFile::new(path, replace_control_chars(source));
let config = term::Config::default();

View File

@ -7,7 +7,7 @@ const DIR_OUT: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/out");
#[allow(unused_variables)]
fn check_targets(input: &Input, module: &mut naga::Module, source_code: Option<&str>) {
let params = input.read_parameters(DIR_IN);
let name = &input.file_name;
let name = input.file_name.display().to_string();
let targets = params.targets.unwrap();
@ -44,11 +44,7 @@ fn check_targets(input: &Input, module: &mut naga::Module, source_code: Option<&
.subgroup_operations(subgroup_operations)
.validate(module)
.unwrap_or_else(|err| {
panic!(
"Naga module validation failed on test `{}`:\n{:?}",
name.display(),
err
);
panic!("Naga module validation failed on test `{name}`:\n{err:?}");
});
let info = {
@ -73,11 +69,7 @@ fn check_targets(input: &Input, module: &mut naga::Module, source_code: Option<&
.subgroup_operations(subgroup_operations)
.validate(module)
.unwrap_or_else(|err| {
panic!(
"Post-compaction module validation failed on test '{}':\n<{:?}",
name.display(),
err,
)
panic!("Post-compaction module validation failed on test '{name}':\n<{err:?}")
})
};
@ -94,7 +86,7 @@ fn check_targets(input: &Input, module: &mut naga::Module, source_code: Option<&
if let Some(source_code) = source_code {
debug_info = Some(naga::back::spv::DebugInfo {
source_code,
file_name: name.as_path().into(),
file_name: &name,
// wgpu#6266: we technically know all the information here to
// produce the valid language but it's not too important for
// validation purposes

View File

@ -896,7 +896,7 @@ impl super::Device {
if let Some(ref debug) = naga_shader.debug_source {
temp_options.debug_info = Some(naga::back::spv::DebugInfo {
source_code: &debug.source_code,
file_name: debug.file_name.as_ref().into(),
file_name: debug.file_name.as_ref(),
language: naga::back::spv::SourceLanguage::WGSL,
})
}
@ -1932,7 +1932,7 @@ impl crate::Device for super::Device {
.as_ref()
.map(|d| naga::back::spv::DebugInfo {
source_code: d.source_code.as_ref(),
file_name: d.file_name.as_ref().into(),
file_name: d.file_name.as_ref(),
language: naga::back::spv::SourceLanguage::WGSL,
});
if !desc.runtime_checks.bounds_checks {