mirror of
https://github.com/storytold/wgpu.git
synced 2026-11-21 15:00:57 +01:00
[naga wgsl-in] Use common type-formatting code.
Remove the `naga::front::wgsl::to_wgsl` module. Instead, use the implementations of `naga::common::wgsl`'s `TryToWgsl` and `TypeContext` traits.
This commit is contained in:
1 parent
3ec38a0a15
commit
e82f52135b
7 files changed
+50
-278
No files matched your search
@@ -1,5 +1,6 @@
|
||||
//! Formatting WGSL front end error messages.
|
||||
|
||||
use crate::common::wgsl::TryToWgsl;
|
||||
use crate::diagnostic_filter::ConflictingDiagnosticRuleError;
|
||||
use crate::proc::{Alignment, ConstantEvaluatorError, ResolveError};
|
||||
use crate::{Scalar, SourceLocation, Span};
|
||||
@@ -446,7 +447,7 @@ impl<'a> Error<'a> {
|
||||
Error::BadMatrixScalarKind(span, scalar) => ParseError {
|
||||
message: format!(
|
||||
"matrix scalar type must be floating-point, but found `{}`",
|
||||
scalar.to_wgsl()
|
||||
scalar.to_wgsl_for_diagnostics()
|
||||
),
|
||||
labels: vec![(span, "must be floating-point (e.g. `f32`)".into())],
|
||||
notes: vec![],
|
||||
@@ -469,7 +470,7 @@ impl<'a> Error<'a> {
|
||||
Error::BadTextureSampleType { span, scalar } => ParseError {
|
||||
message: format!(
|
||||
"texture sample type must be one of f32, i32 or u32, but found {}",
|
||||
scalar.to_wgsl()
|
||||
scalar.to_wgsl_for_diagnostics()
|
||||
),
|
||||
labels: vec![(span, "must be one of f32, i32 or u32".into())],
|
||||
notes: vec![],
|
||||
|
||||
@@ -7,6 +7,7 @@ use alloc::{
|
||||
};
|
||||
use core::num::NonZeroU32;
|
||||
|
||||
use crate::common::wgsl::TypeContext;
|
||||
use crate::front::wgsl::lower::{ExpressionContext, Lowerer};
|
||||
use crate::front::wgsl::parse::ast;
|
||||
use crate::front::wgsl::{Error, Result};
|
||||
@@ -71,7 +72,7 @@ impl Constructor<(Handle<crate::Type>, &crate::TypeInner)> {
|
||||
format!("mat{}x{}<?>", columns as u32, rows as u32,)
|
||||
}
|
||||
Self::PartialArray => "array<?, ?>".to_string(),
|
||||
Self::Type((handle, _inner)) => handle.to_wgsl(&ctx.module.to_ctx()),
|
||||
Self::Type((handle, _inner)) => ctx.type_to_string(handle),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -536,7 +537,7 @@ impl<'source> Lowerer<'source, '_> {
|
||||
|
||||
// Bad conversion (type cast)
|
||||
(Components::One { span, ty_inner, .. }, constructor) => {
|
||||
let from_type = ty_inner.to_wgsl(&ctx.module.to_ctx());
|
||||
let from_type = ctx.type_inner_to_string(ty_inner);
|
||||
return Err(Box::new(Error::BadTypeCast {
|
||||
span,
|
||||
from_type,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use alloc::{boxed::Box, string::String, vec::Vec};
|
||||
|
||||
use crate::common::wgsl::{TryToWgsl, TypeContext};
|
||||
use crate::front::wgsl::error::{
|
||||
AutoConversionError, AutoConversionLeafScalarError, ConcretizationFailedError,
|
||||
};
|
||||
@@ -53,9 +54,8 @@ impl<'source> super::ExpressionContext<'source, '_, '_> {
|
||||
match expr_inner.automatically_converts_to(goal_inner, types) {
|
||||
Some(scalars) => scalars,
|
||||
None => {
|
||||
let gctx = &self.module.to_ctx();
|
||||
let source_type = expr_resolution.to_wgsl(gctx);
|
||||
let dest_type = goal_ty.to_wgsl(gctx);
|
||||
let source_type = self.type_resolution_to_string(expr_resolution);
|
||||
let dest_type = self.type_resolution_to_string(goal_ty);
|
||||
|
||||
return Err(Box::new(super::Error::AutoConversion(Box::new(
|
||||
AutoConversionError {
|
||||
@@ -95,11 +95,10 @@ impl<'source> super::ExpressionContext<'source, '_, '_> {
|
||||
let expr_inner = expr_resolution.inner_with(types);
|
||||
|
||||
let make_error = || {
|
||||
let gctx = &self.module.to_ctx();
|
||||
let source_type = expr_resolution.to_wgsl(gctx);
|
||||
let source_type = self.type_resolution_to_string(expr_resolution);
|
||||
super::Error::AutoConversionLeafScalar(Box::new(AutoConversionLeafScalarError {
|
||||
dest_span: goal_span,
|
||||
dest_scalar: goal_scalar.to_wgsl(),
|
||||
dest_scalar: goal_scalar.to_wgsl_for_diagnostics(),
|
||||
source_span: expr_span,
|
||||
source_type,
|
||||
}))
|
||||
@@ -275,8 +274,8 @@ impl<'source> super::ExpressionContext<'source, '_, '_> {
|
||||
let expr_type = &self.typifier()[expr];
|
||||
super::Error::ConcretizationFailed(Box::new(ConcretizationFailedError {
|
||||
expr_span,
|
||||
expr_type: expr_type.to_wgsl(&self.module.to_ctx()),
|
||||
scalar: concretized.to_wgsl(),
|
||||
expr_type: self.type_resolution_to_string(expr_type),
|
||||
scalar: concretized.to_wgsl_for_diagnostics(),
|
||||
inner: err,
|
||||
}))
|
||||
})?;
|
||||
@@ -319,7 +318,7 @@ impl<'source> super::ExpressionContext<'source, '_, '_> {
|
||||
"wgsl automatic_conversion_consensus: {:?}",
|
||||
inners
|
||||
.clone()
|
||||
.map(|inner| inner.to_wgsl(&self.module.to_ctx()))
|
||||
.map(|inner| self.type_inner_to_string(inner))
|
||||
.collect::<Vec<String>>()
|
||||
);
|
||||
let mut best = inners.next().unwrap().scalar().ok_or(0_usize)?;
|
||||
@@ -333,7 +332,7 @@ impl<'source> super::ExpressionContext<'source, '_, '_> {
|
||||
}
|
||||
}
|
||||
|
||||
log::debug!(" consensus: {:?}", best.to_wgsl());
|
||||
log::debug!(" consensus: {:?}", best.to_wgsl_for_diagnostics());
|
||||
Ok(best)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use alloc::{
|
||||
};
|
||||
use core::num::NonZeroU32;
|
||||
|
||||
use crate::common::wgsl::TypeContext;
|
||||
use crate::front::wgsl::error::{Error, ExpectedToken, InvalidAssignmentType};
|
||||
use crate::front::wgsl::index::Index;
|
||||
use crate::front::wgsl::parse::number::Number;
|
||||
@@ -388,6 +389,30 @@ pub struct ExpressionContext<'source, 'temp, 'out> {
|
||||
expr_type: ExpressionContextType<'temp, 'out>,
|
||||
}
|
||||
|
||||
impl TypeContext for ExpressionContext<'_, '_, '_> {
|
||||
fn lookup_type(&self, handle: Handle<crate::Type>) -> &crate::Type {
|
||||
&self.module.types[handle]
|
||||
}
|
||||
|
||||
fn type_name(&self, handle: Handle<crate::Type>) -> &str {
|
||||
self.module.types[handle]
|
||||
.name
|
||||
.as_deref()
|
||||
.unwrap_or("{anonymous type}")
|
||||
}
|
||||
|
||||
fn write_override<W: core::fmt::Write>(
|
||||
&self,
|
||||
handle: Handle<crate::Override>,
|
||||
out: &mut W,
|
||||
) -> core::fmt::Result {
|
||||
match self.module.overrides[handle].name {
|
||||
Some(ref name) => out.write_str(name),
|
||||
None => write!(out, "{{anonymous override {handle:?}}}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> {
|
||||
#[allow(dead_code)]
|
||||
fn as_const(&mut self) -> ExpressionContext<'source, '_, '_> {
|
||||
@@ -1256,8 +1281,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
|
||||
if !explicit_inner.equivalent(init_inner, &ectx.module.types) {
|
||||
return Err(Box::new(Error::InitializationTypeMismatch {
|
||||
name: name.span,
|
||||
expected: explicit_inner.to_wgsl(&ectx.module.to_ctx()),
|
||||
got: init_inner.to_wgsl(&ectx.module.to_ctx()),
|
||||
expected: ectx.type_inner_to_string(explicit_inner),
|
||||
got: ectx.type_inner_to_string(init_inner),
|
||||
}));
|
||||
}
|
||||
ty = explicit_ty;
|
||||
@@ -1487,11 +1512,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
|
||||
.inner
|
||||
.equivalent(&ctx.module.types[init_ty].inner, &ctx.module.types)
|
||||
{
|
||||
let gctx = &ctx.module.to_ctx();
|
||||
return Err(Box::new(Error::InitializationTypeMismatch {
|
||||
name: l.name.span,
|
||||
expected: ty.to_wgsl(gctx),
|
||||
got: init_ty.to_wgsl(gctx),
|
||||
expected: ctx.type_to_string(ty),
|
||||
got: ctx.type_to_string(init_ty),
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -2192,11 +2216,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
|
||||
crate::TypeInner::Vector { scalar, .. } => scalar,
|
||||
_ => {
|
||||
let ty = resolve!(ctx, expr);
|
||||
let gctx = &ctx.module.to_ctx();
|
||||
return Err(Box::new(Error::BadTypeCast {
|
||||
from_type: ty.to_wgsl(gctx),
|
||||
from_type: ctx.type_resolution_to_string(ty),
|
||||
span: ty_span,
|
||||
to_type: to_resolved.to_wgsl(gctx),
|
||||
to_type: ctx.type_to_string(to_resolved),
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -10,7 +10,6 @@ mod lower;
|
||||
mod parse;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod to_wgsl;
|
||||
|
||||
pub use crate::front::wgsl::error::ParseError;
|
||||
pub use crate::front::wgsl::parse::directive::language_extension::{
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
//! Producing the WGSL forms of types, for use in error messages.
|
||||
|
||||
use crate::common::wgsl::ToWgsl;
|
||||
|
||||
use alloc::{
|
||||
format,
|
||||
string::{String, ToString},
|
||||
};
|
||||
|
||||
use crate::proc::GlobalCtx;
|
||||
use crate::Handle;
|
||||
|
||||
impl crate::proc::TypeResolution {
|
||||
pub fn to_wgsl(&self, gctx: &GlobalCtx) -> String {
|
||||
match *self {
|
||||
crate::proc::TypeResolution::Handle(handle) => handle.to_wgsl(gctx),
|
||||
crate::proc::TypeResolution::Value(ref inner) => inner.to_wgsl(gctx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handle<crate::Type> {
|
||||
/// Formats the type as it is written in wgsl.
|
||||
///
|
||||
/// For example `vec3<f32>`.
|
||||
pub fn to_wgsl(self, gctx: &GlobalCtx) -> String {
|
||||
let ty = &gctx.types[self];
|
||||
match ty.name {
|
||||
Some(ref name) => name.clone(),
|
||||
None => ty.inner.to_wgsl(gctx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::TypeInner {
|
||||
/// Formats the type as it is written in wgsl.
|
||||
///
|
||||
/// For example `vec3<f32>`.
|
||||
///
|
||||
/// Note: `TypeInner::Struct` doesn't include the name of the
|
||||
/// struct type. Therefore this method will simply return "struct"
|
||||
/// for them.
|
||||
pub fn to_wgsl(&self, gctx: &GlobalCtx) -> String {
|
||||
use crate::TypeInner as Ti;
|
||||
|
||||
match *self {
|
||||
Ti::Scalar(scalar) => scalar.to_wgsl(),
|
||||
Ti::Vector { size, scalar } => {
|
||||
format!("vec{}<{}>", size as u32, scalar.to_wgsl())
|
||||
}
|
||||
Ti::Matrix {
|
||||
columns,
|
||||
rows,
|
||||
scalar,
|
||||
} => {
|
||||
format!(
|
||||
"mat{}x{}<{}>",
|
||||
columns as u32,
|
||||
rows as u32,
|
||||
scalar.to_wgsl(),
|
||||
)
|
||||
}
|
||||
Ti::Atomic(scalar) => {
|
||||
format!("atomic<{}>", scalar.to_wgsl())
|
||||
}
|
||||
Ti::Pointer { base, .. } => {
|
||||
let name = base.to_wgsl(gctx);
|
||||
format!("ptr<{name}>")
|
||||
}
|
||||
Ti::ValuePointer { scalar, .. } => {
|
||||
format!("ptr<{}>", scalar.to_wgsl())
|
||||
}
|
||||
Ti::Array { base, size, .. } => {
|
||||
let base = base.to_wgsl(gctx);
|
||||
match size {
|
||||
crate::ArraySize::Constant(size) => format!("array<{base}, {size}>"),
|
||||
crate::ArraySize::Pending(_) => unreachable!(),
|
||||
crate::ArraySize::Dynamic => format!("array<{base}>"),
|
||||
}
|
||||
}
|
||||
Ti::Struct { .. } => {
|
||||
// TODO: Actually output the struct?
|
||||
"struct".to_string()
|
||||
}
|
||||
Ti::Image {
|
||||
dim,
|
||||
arrayed,
|
||||
class,
|
||||
} => {
|
||||
let dim_suffix = match dim {
|
||||
crate::ImageDimension::D1 => "_1d",
|
||||
crate::ImageDimension::D2 => "_2d",
|
||||
crate::ImageDimension::D3 => "_3d",
|
||||
crate::ImageDimension::Cube => "_cube",
|
||||
};
|
||||
let array_suffix = if arrayed { "_array" } else { "" };
|
||||
|
||||
let class_suffix = match class {
|
||||
crate::ImageClass::Sampled { multi: true, .. } => "_multisampled",
|
||||
crate::ImageClass::Depth { multi: false } => "_depth",
|
||||
crate::ImageClass::Depth { multi: true } => "_depth_multisampled",
|
||||
crate::ImageClass::Sampled { multi: false, .. }
|
||||
| crate::ImageClass::Storage { .. } => "",
|
||||
};
|
||||
|
||||
let type_in_brackets = match class {
|
||||
crate::ImageClass::Sampled { kind, .. } => {
|
||||
// Note: The only valid widths are 4 bytes wide.
|
||||
// The lexer has already verified this, so we can safely assume it here.
|
||||
// https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type
|
||||
let element_type = crate::Scalar { kind, width: 4 }.to_wgsl();
|
||||
format!("<{element_type}>")
|
||||
}
|
||||
crate::ImageClass::Depth { multi: _ } => String::new(),
|
||||
crate::ImageClass::Storage { format, access } => {
|
||||
if access.contains(crate::StorageAccess::STORE) {
|
||||
format!("<{},write>", format.to_wgsl())
|
||||
} else {
|
||||
format!("<{}>", format.to_wgsl())
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
format!("texture{class_suffix}{dim_suffix}{array_suffix}{type_in_brackets}")
|
||||
}
|
||||
Ti::Sampler { .. } => "sampler".to_string(),
|
||||
Ti::AccelerationStructure { vertex_return } => {
|
||||
let caps = if vertex_return { "<vertex_return>" } else { "" };
|
||||
format!("acceleration_structure{}", caps)
|
||||
}
|
||||
Ti::RayQuery { vertex_return } => {
|
||||
let caps = if vertex_return { "<vertex_return>" } else { "" };
|
||||
format!("ray_query{}", caps)
|
||||
}
|
||||
Ti::BindingArray { base, size, .. } => {
|
||||
let member_type = &gctx.types[base];
|
||||
let base = member_type.name.as_deref().unwrap_or("unknown");
|
||||
match size {
|
||||
crate::ArraySize::Constant(size) => format!("binding_array<{base}, {size}>"),
|
||||
crate::ArraySize::Pending(_) => unreachable!(),
|
||||
crate::ArraySize::Dynamic => format!("binding_array<{base}>"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Scalar {
|
||||
/// Format a scalar kind+width as a type is written in wgsl.
|
||||
///
|
||||
/// Examples: `f32`, `u64`, `bool`.
|
||||
pub fn to_wgsl(self) -> String {
|
||||
let prefix = match self.kind {
|
||||
crate::ScalarKind::Sint => "i",
|
||||
crate::ScalarKind::Uint => "u",
|
||||
crate::ScalarKind::Float => "f",
|
||||
crate::ScalarKind::Bool => return "bool".to_string(),
|
||||
crate::ScalarKind::AbstractInt => return "{AbstractInt}".to_string(),
|
||||
crate::ScalarKind::AbstractFloat => return "{AbstractFloat}".to_string(),
|
||||
};
|
||||
format!("{}{}", prefix, self.width * 8)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use alloc::{string::ToString, vec};
|
||||
|
||||
#[test]
|
||||
fn to_wgsl() {
|
||||
use core::num::NonZeroU32;
|
||||
|
||||
let mut types = crate::UniqueArena::new();
|
||||
|
||||
let mytype1 = types.insert(
|
||||
crate::Type {
|
||||
name: Some("MyType1".to_string()),
|
||||
inner: crate::TypeInner::Struct {
|
||||
members: vec![],
|
||||
span: 0,
|
||||
},
|
||||
},
|
||||
Default::default(),
|
||||
);
|
||||
let mytype2 = types.insert(
|
||||
crate::Type {
|
||||
name: Some("MyType2".to_string()),
|
||||
inner: crate::TypeInner::Struct {
|
||||
members: vec![],
|
||||
span: 0,
|
||||
},
|
||||
},
|
||||
Default::default(),
|
||||
);
|
||||
|
||||
let gctx = crate::proc::GlobalCtx {
|
||||
types: &types,
|
||||
constants: &crate::Arena::new(),
|
||||
overrides: &crate::Arena::new(),
|
||||
global_expressions: &crate::Arena::new(),
|
||||
};
|
||||
let array = crate::TypeInner::Array {
|
||||
base: mytype1,
|
||||
stride: 4,
|
||||
size: crate::ArraySize::Constant(unsafe { NonZeroU32::new_unchecked(32) }),
|
||||
};
|
||||
assert_eq!(array.to_wgsl(&gctx), "array<MyType1, 32>");
|
||||
|
||||
let mat = crate::TypeInner::Matrix {
|
||||
rows: crate::VectorSize::Quad,
|
||||
columns: crate::VectorSize::Bi,
|
||||
scalar: crate::Scalar::F64,
|
||||
};
|
||||
assert_eq!(mat.to_wgsl(&gctx), "mat2x4<f64>");
|
||||
|
||||
let ptr = crate::TypeInner::Pointer {
|
||||
base: mytype2,
|
||||
space: crate::AddressSpace::Storage {
|
||||
access: crate::StorageAccess::default(),
|
||||
},
|
||||
};
|
||||
assert_eq!(ptr.to_wgsl(&gctx), "ptr<MyType2>");
|
||||
|
||||
let img1 = crate::TypeInner::Image {
|
||||
dim: crate::ImageDimension::D2,
|
||||
arrayed: false,
|
||||
class: crate::ImageClass::Sampled {
|
||||
kind: crate::ScalarKind::Float,
|
||||
multi: true,
|
||||
},
|
||||
};
|
||||
assert_eq!(img1.to_wgsl(&gctx), "texture_multisampled_2d<f32>");
|
||||
|
||||
let img2 = crate::TypeInner::Image {
|
||||
dim: crate::ImageDimension::Cube,
|
||||
arrayed: true,
|
||||
class: crate::ImageClass::Depth { multi: false },
|
||||
};
|
||||
assert_eq!(img2.to_wgsl(&gctx), "texture_depth_cube_array");
|
||||
|
||||
let img3 = crate::TypeInner::Image {
|
||||
dim: crate::ImageDimension::D2,
|
||||
arrayed: false,
|
||||
class: crate::ImageClass::Depth { multi: true },
|
||||
};
|
||||
assert_eq!(img3.to_wgsl(&gctx), "texture_depth_multisampled_2d");
|
||||
|
||||
let array = crate::TypeInner::BindingArray {
|
||||
base: mytype1,
|
||||
size: crate::ArraySize::Constant(unsafe { NonZeroU32::new_unchecked(32) }),
|
||||
};
|
||||
assert_eq!(array.to_wgsl(&gctx), "binding_array<MyType1, 32>");
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,9 @@ use crate::{
|
||||
ScalarKind, Span, Type, TypeInner, UnaryOperator,
|
||||
};
|
||||
|
||||
#[cfg(feature = "wgsl-in")]
|
||||
use crate::common::wgsl::TryToWgsl;
|
||||
|
||||
/// A macro that allows dollar signs (`$`) to be emitted by other macros. Useful for generating
|
||||
/// `macro_rules!` items that, in turn, emit their own `macro_rules!` items.
|
||||
///
|
||||
@@ -1554,7 +1557,7 @@ impl<'a> ConstantEvaluator<'a> {
|
||||
let from = format!("{:?} {:?}", expr, self.expressions[expr]);
|
||||
|
||||
#[cfg(feature = "wgsl-in")]
|
||||
let to = target.to_wgsl();
|
||||
let to = target.to_wgsl_for_diagnostics();
|
||||
|
||||
#[cfg(not(feature = "wgsl-in"))]
|
||||
let to = format!("{target:?}");
|
||||
|
||||
Reference in new issue
Block a user