handle bitcast, coopLoad and construction exprs in the lowerer

This commit is contained in:
teoxoy authored and Teodor Tanasoaia committed 2026-01-28 12:00:35 +01:00
1 parent 514d0e743d
commit cb401cef90
12 files changed
+1097 -948

No files matched your search

+39
View File
@@ -200,6 +200,7 @@ pub(crate) enum Error<'a> {
ReservedIdentifierPrefix(Span),
UnknownAddressSpace(Span),
InvalidLocalVariableAddressSpace(Span),
UnknownRayFlag(Span),
RepeatedAttribute(Span),
UnknownAttribute(Span),
UnknownBuiltin(Span),
@@ -276,6 +277,7 @@ pub(crate) enum Error<'a> {
span: Span,
},
CalledEntryPoint(Span),
CalledLocalDecl(Span),
WrongArgumentCount {
span: Span,
expected: Range<u32>,
@@ -422,6 +424,12 @@ pub(crate) enum Error<'a> {
UnexpectedIdentForEnumerant(Span),
UnexpectedExprForEnumerant(Span),
UnusedArgsForTemplate(Vec<Span>),
UnexpectedTemplate(Span),
MissingTemplateArg {
span: Span,
arg: &'static str,
},
UnexpectedExprForTypeExpression(Span),
}
impl From<ConflictingDiagnosticRuleError> for Error<'_> {
@@ -667,6 +675,11 @@ impl<'a> Error<'a> {
labels: vec![(bad_span, "local variables can only use 'function' address space".into())],
notes: vec![],
},
Error::UnknownRayFlag(bad_span) => ParseError {
message: format!("unknown ray flag: `{}`", &source[bad_span]),
labels: vec![(bad_span, "unknown ray flag".into())],
notes: vec![],
},
Error::RepeatedAttribute(bad_span) => ParseError {
message: format!("repeated attribute: `{}`", &source[bad_span]),
labels: vec![(bad_span, "repeated attribute".into())],
@@ -926,6 +939,11 @@ impl<'a> Error<'a> {
labels: vec![(span, "entry point cannot be called".into())],
notes: vec![],
},
Error::CalledLocalDecl(span) => ParseError {
message: "local declaration cannot be called".to_string(),
labels: vec![(span, "local declaration cannot be called".into())],
notes: vec![],
},
Error::WrongArgumentCount {
span,
ref expected,
@@ -1434,6 +1452,27 @@ impl<'a> Error<'a> {
labels: expr_spans.iter().cloned().map(|span| -> (_, _){ (span, "unused".into()) }).collect(),
notes: vec![],
},
Error::UnexpectedTemplate(span) => ParseError {
message: "unexpected template".to_string(),
labels: vec![(span, "expected identifier".into())],
notes: vec![],
},
Error::MissingTemplateArg {
span,
arg,
} => ParseError {
message: format!(
"`{}` needs a template argument specified: {arg}",
&source[span]
),
labels: vec![(span, "is missing a template argument".into())],
notes: vec![],
},
Error::UnexpectedExprForTypeExpression(expr_span) => ParseError {
message: "unexpected expression".to_string(),
labels: vec![(expr_span, "needs to be an identifier resolving to a type declaration (alias or struct) or predeclared type(-generator)".into())],
notes: vec![],
}
}
}
}
+28 -131
View File
@@ -1,10 +1,4 @@
use alloc::{
boxed::Box,
format,
string::{String, ToString},
vec,
vec::Vec,
};
use alloc::{boxed::Box, vec, vec::Vec};
use core::num::NonZeroU32;
use crate::common::wgsl::{TryToWgsl, TypeContext};
@@ -13,9 +7,22 @@ use crate::front::wgsl::parse::ast;
use crate::front::wgsl::{Error, Result};
use crate::{Handle, Span};
/// A cooked form of `ast::ConstructorType` that uses Naga types whenever
/// possible.
enum Constructor<T> {
/// A [`constructor built-in function`].
///
/// WGSL has two types of such functions:
///
/// - Those that fully specify the type being constructed, like
/// `vec3<f32>(x,y,z)`, which obviously constructs a `vec3<f32>`.
///
/// - Those that leave the component type of the composite being constructed
/// implicit, to be inferred from the argument types, like `vec3(x,y,z)`,
/// which constructs a `vec3<T>` where `T` is the type of `x`, `y`, and `z`.
///
/// This enum represents both cases. The `PartialFoo` variants
/// represent the second case, where the component type is implicit.
///
/// [`constructor built-in function`]: https://gpuweb.github.io/gpuweb/wgsl/#constructor-builtin-function
pub enum Constructor<T> {
/// A vector construction whose component type is inferred from the
/// argument: `vec3(1.0)`.
PartialVector { size: crate::VectorSize },
@@ -62,21 +69,6 @@ impl Constructor<Handle<crate::Type>> {
}
}
impl Constructor<(Handle<crate::Type>, &crate::TypeInner)> {
fn to_error_string(&self, ctx: &ExpressionContext) -> String {
match *self {
Self::PartialVector { size } => {
format!("vec{}<?>", size as u32,)
}
Self::PartialMatrix { columns, rows } => {
format!("mat{}x{}<?>", columns as u32, rows as u32,)
}
Self::PartialArray => "array<?, ?>".to_string(),
Self::Type((handle, _inner)) => ctx.type_to_string(handle),
}
}
}
enum Components<'a> {
None,
One {
@@ -108,24 +100,20 @@ impl<'source> Lowerer<'source, '_> {
/// it's one of the `Partial` variants, we need to consider the argument
/// types as well.
///
/// This is used for [`Construct`] expressions, but also for [`Call`]
/// expressions, once we've determined that the "callable" (in WGSL spec
/// terms) is actually a type.
/// This is used for [`Call`] expressions, once we've determined that
/// the "callable" (in WGSL spec terms) is actually a type.
///
/// [`Construct`]: ast::Expression::Construct
/// [`Call`]: ast::Expression::Call
pub fn construct(
&mut self,
span: Span,
constructor: &ast::ConstructorType<'source>,
constructor: Constructor<Handle<crate::Type>>,
ty_span: Span,
components: &[Handle<ast::Expression<'source>>],
ctx: &mut ExpressionContext<'source, '_, '_>,
) -> Result<'source, Handle<crate::Expression>> {
use crate::proc::TypeResolution as Tr;
let constructor_h = self.constructor(constructor, ctx)?;
let components = match *components {
[] => Components::None,
[component] => {
@@ -160,7 +148,7 @@ impl<'source> Lowerer<'source, '_> {
// Even though we computed `constructor` above, wait until now to borrow
// a reference to the `TypeInner`, so that the component-handling code
// above can have mutable access to the type arena.
let constructor = constructor_h.borrow_inner(ctx.module);
let constructor = constructor.borrow_inner(ctx.module);
let expr;
match (components, constructor) {
@@ -573,14 +561,19 @@ impl<'source> Lowerer<'source, '_> {
Components::One {
span, component, ..
},
constructor,
Constructor::Type((
ty,
&(crate::TypeInner::Scalar { .. }
| crate::TypeInner::Vector { .. }
| crate::TypeInner::Matrix { .. }),
)),
) => {
let component_ty = &ctx.typifier()[component];
let from_type = ctx.type_resolution_to_string(component_ty);
return Err(Box::new(Error::BadTypeCast {
span,
from_type,
to_type: constructor.to_error_string(ctx),
to_type: ctx.type_to_string(ty),
}));
}
@@ -600,100 +593,4 @@ impl<'source> Lowerer<'source, '_> {
let expr = ctx.append_expression(expr, span)?;
Ok(expr)
}
/// Build a [`Constructor`] for a WGSL construction expression.
///
/// If `constructor` conveys enough information to determine which Naga [`Type`]
/// we're actually building (i.e., it's not a partial constructor), then
/// ensure the `Type` exists in [`ctx.module`], and return
/// [`Constructor::Type`].
///
/// Otherwise, return the [`Constructor`] partial variant corresponding to
/// `constructor`.
///
/// [`Type`]: crate::Type
/// [`ctx.module`]: ExpressionContext::module
fn constructor<'out>(
&mut self,
constructor: &ast::ConstructorType<'source>,
ctx: &mut ExpressionContext<'source, '_, 'out>,
) -> Result<'source, Constructor<Handle<crate::Type>>> {
let handle = match *constructor {
ast::ConstructorType::Scalar(scalar) => {
let ty = ctx.ensure_type_exists(scalar.to_inner_scalar());
Constructor::Type(ty)
}
ast::ConstructorType::PartialVector { size } => Constructor::PartialVector { size },
ast::ConstructorType::Vector { size, ty, ty_span } => {
let ty = self.resolve_ast_type(ty, &mut ctx.as_const())?;
let scalar = match ctx.module.types[ty].inner {
crate::TypeInner::Scalar(sc) => sc,
_ => return Err(Box::new(Error::UnknownScalarType(ty_span))),
};
let ty = ctx.ensure_type_exists(crate::TypeInner::Vector { size, scalar });
Constructor::Type(ty)
}
ast::ConstructorType::PartialMatrix { columns, rows } => {
Constructor::PartialMatrix { columns, rows }
}
ast::ConstructorType::Matrix {
rows,
columns,
ty,
ty_span,
} => {
let ty = self.resolve_ast_type(ty, &mut ctx.as_const())?;
let scalar = match ctx.module.types[ty].inner {
crate::TypeInner::Scalar(sc) => sc,
_ => return Err(Box::new(Error::UnknownScalarType(ty_span))),
};
let ty = match scalar.kind {
crate::ScalarKind::Float => ctx.ensure_type_exists(crate::TypeInner::Matrix {
columns,
rows,
scalar,
}),
_ => return Err(Box::new(Error::BadMatrixScalarKind(ty_span, scalar))),
};
Constructor::Type(ty)
}
ast::ConstructorType::PartialCooperativeMatrix { .. } => {
return Err(Box::new(Error::UnderspecifiedCooperativeMatrix));
}
ast::ConstructorType::CooperativeMatrix {
rows,
columns,
ty,
ty_span,
role,
} => {
let ty = self.resolve_ast_type(ty, &mut ctx.as_const())?;
let scalar = match ctx.module.types[ty].inner {
crate::TypeInner::Scalar(s) => s,
_ => return Err(Box::new(Error::UnsupportedCooperativeScalar(ty_span))),
};
let ty = ctx.ensure_type_exists(crate::TypeInner::CooperativeMatrix {
columns,
rows,
scalar,
role,
});
Constructor::Type(ty)
}
ast::ConstructorType::PartialArray => Constructor::PartialArray,
ast::ConstructorType::Array { base, size } => {
let base = self.resolve_ast_type(base, &mut ctx.as_const())?;
let size = self.array_size(size, &mut ctx.as_const())?;
ctx.layouter.update(ctx.module.to_ctx()).unwrap();
let stride = ctx.layouter[base].to_stride();
let ty = ctx.ensure_type_exists(crate::TypeInner::Array { base, size, stride });
Constructor::Type(ty)
}
ast::ConstructorType::Type(ty) => Constructor::Type(ty),
};
Ok(handle)
}
}
+424 -166
View File
@@ -7,14 +7,12 @@ use alloc::{
};
use core::num::NonZeroU32;
use crate::front::wgsl::error::{Error, ExpectedToken, InvalidAssignmentType};
use crate::front::wgsl::index::Index;
use crate::front::wgsl::parse::directive::enable_extension::EnableExtensions;
use crate::front::wgsl::parse::number::Number;
use crate::front::wgsl::parse::{ast, conv};
use crate::front::wgsl::Result;
use crate::front::wgsl::{
error::{Error, ExpectedToken, InvalidAssignmentType},
parse::directive::enable_extension::EnableExtensions,
};
use crate::front::Typifier;
use crate::{
common::wgsl::{TryToWgsl, TypeContext},
@@ -24,8 +22,12 @@ use crate::{common::ForDebugWithTypes, proc::LayoutErrorInner};
use crate::{ir, proc};
use crate::{Arena, FastHashMap, FastIndexMap, Handle, Span};
use construction::Constructor;
use template_list::TemplateListIter;
mod construction;
mod conversion;
mod template_list;
/// Resolves the inner type of a given expression.
///
@@ -86,6 +88,8 @@ pub(super) use resolve;
/// State for constructing a `ir::Module`.
pub struct GlobalContext<'source, 'temp, 'out> {
enable_extensions: EnableExtensions,
/// The `TranslationUnit`'s expressions arena.
ast_expressions: &'temp Arena<ast::Expression<'source>>,
@@ -110,6 +114,7 @@ pub struct GlobalContext<'source, 'temp, 'out> {
impl<'source> GlobalContext<'source, '_, '_> {
const fn as_const(&mut self) -> ExpressionContext<'source, '_, '_> {
ExpressionContext {
enable_extensions: self.enable_extensions,
ast_expressions: self.ast_expressions,
globals: self.globals,
types: self.types,
@@ -123,6 +128,7 @@ impl<'source> GlobalContext<'source, '_, '_> {
const fn as_override(&mut self) -> ExpressionContext<'source, '_, '_> {
ExpressionContext {
enable_extensions: self.enable_extensions,
ast_expressions: self.ast_expressions,
globals: self.globals,
types: self.types,
@@ -147,6 +153,8 @@ impl<'source> GlobalContext<'source, '_, '_> {
/// State for lowering a statement within a function.
pub struct StatementContext<'source, 'temp, 'out> {
enable_extensions: EnableExtensions,
// WGSL AST values.
/// A reference to [`TranslationUnit::expressions`] for the translation unit
/// we're lowering.
@@ -214,6 +222,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> {
'temp: 't,
{
ExpressionContext {
enable_extensions: self.enable_extensions,
globals: self.globals,
types: self.types,
ast_expressions: self.ast_expressions,
@@ -241,6 +250,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> {
'temp: 't,
{
ExpressionContext {
enable_extensions: self.enable_extensions,
globals: self.globals,
types: self.types,
ast_expressions: self.ast_expressions,
@@ -262,6 +272,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> {
#[allow(dead_code)]
const fn as_global(&mut self) -> GlobalContext<'a, '_, '_> {
GlobalContext {
enable_extensions: self.enable_extensions,
ast_expressions: self.ast_expressions,
globals: self.globals,
types: self.types,
@@ -370,6 +381,8 @@ pub enum ExpressionContextType<'temp, 'out> {
/// [`as_const`]: ExpressionContext::as_const
/// [`Expression::Constant`]: ir::Expression::Constant
pub struct ExpressionContext<'source, 'temp, 'out> {
enable_extensions: EnableExtensions,
// WGSL AST values.
ast_expressions: &'temp Arena<ast::Expression<'source>>,
types: &'temp Arena<ast::Type<'source>>,
@@ -439,6 +452,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> {
#[allow(dead_code)]
const fn as_const(&mut self) -> ExpressionContext<'source, '_, '_> {
ExpressionContext {
enable_extensions: self.enable_extensions,
globals: self.globals,
types: self.types,
ast_expressions: self.ast_expressions,
@@ -466,6 +480,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> {
const fn as_global(&mut self) -> GlobalContext<'source, '_, '_> {
GlobalContext {
enable_extensions: self.enable_extensions,
ast_expressions: self.ast_expressions,
globals: self.globals,
types: self.types,
@@ -663,6 +678,7 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> {
local_expression_kind_tracker: rctx.local_expression_kind_tracker,
};
let mut nested_ctx = ExpressionContext {
enable_extensions: self.enable_extensions,
expr_type: ExpressionContextType::Runtime(nested_rctx),
ast_expressions: self.ast_expressions,
types: self.types,
@@ -1202,6 +1218,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
};
let mut ctx = GlobalContext {
enable_extensions: tu.enable_extensions,
ast_expressions: &tu.expressions,
globals: &mut FastHashMap::default(),
types: &tu.types,
@@ -1269,11 +1286,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
None
};
let space = Self::var_address_space(
&v.template_list,
&ctx.as_const(),
&tu.enable_extensions,
)?;
let space = Self::var_address_space(&v.template_list, &ctx.as_const())?;
let handle = ctx.module.global_variables.append(
ir::GlobalVariable {
@@ -1540,6 +1553,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
let mut typifier = Typifier::default();
let mut stmt_ctx = StatementContext {
enable_extensions: ctx.enable_extensions,
local_table: &mut local_table,
globals: ctx.globals,
ast_expressions: ctx.ast_expressions,
@@ -2005,18 +2019,13 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
ir::Statement::Return { value }
}
ast::StatementKind::Kill => ir::Statement::Kill,
ast::StatementKind::Call {
ref function,
ref arguments,
} => {
ast::StatementKind::Call(ref call_phrase) => {
let mut emitter = proc::Emitter::default();
emitter.start(&ctx.function.expressions);
let _ = self.call(
call_phrase,
stmt.span,
function,
arguments,
None,
&mut ctx.as_expression(block, &mut emitter),
true,
)?;
@@ -2250,10 +2259,21 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
let handle = ctx.interrupt_emitter(ir::Expression::Literal(literal), span)?;
return Ok(Typed::Plain(handle));
}
ast::Expression::Ident(ast::IdentExpr::Local(local)) => {
ast::Expression::Ident(ast::TemplateElaboratedIdent {
ref template_list, ..
}) if !template_list.is_empty() => {
return Err(Box::new(Error::UnexpectedTemplate(span)))
}
ast::Expression::Ident(ast::TemplateElaboratedIdent {
ident: ast::IdentExpr::Local(local),
..
}) => {
return ctx.local(&local, span);
}
ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => {
ast::Expression::Ident(ast::TemplateElaboratedIdent {
ident: ast::IdentExpr::Unresolved(name),
..
}) => {
let global = ctx
.globals
.get(name)
@@ -2282,14 +2302,6 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
return expr.try_map(|handle| ctx.interrupt_emitter(handle, span));
}
ast::Expression::Construct {
ref ty,
ty_span,
ref components,
} => {
let handle = self.construct(span, ty, ty_span, components, ctx)?;
return Ok(Typed::Plain(handle));
}
ast::Expression::Unary { op, expr } => {
let expr = self.expression_for_abstract(expr, ctx)?;
Typed::Plain(ir::Expression::Unary { op, expr })
@@ -2339,14 +2351,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
ast::Expression::Binary { op, left, right } => {
self.binary(op, left, right, span, ctx)?
}
ast::Expression::Call {
ref function,
ref arguments,
result_ty,
} => {
ast::Expression::Call(ref call_phrase) => {
let handle = self
.call(span, function, arguments, result_ty, ctx, false)?
.ok_or(Error::FunctionReturnsVoid(function.span))?;
.call(call_phrase, span, ctx, false)?
.ok_or(Error::FunctionReturnsVoid(span))?;
return Ok(Typed::Plain(handle));
}
ast::Expression::Index { base, index } => {
@@ -2428,29 +2436,6 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
access
}
ast::Expression::Bitcast { expr, to, ty_span } => {
let expr = self.expression(expr, ctx)?;
let to_resolved = self.resolve_ast_type(to, &mut ctx.as_const())?;
let element_scalar = match ctx.module.types[to_resolved].inner {
ir::TypeInner::Scalar(scalar) => scalar,
ir::TypeInner::Vector { scalar, .. } => scalar,
_ => {
let ty = resolve!(ctx, expr);
return Err(Box::new(Error::BadTypeCast {
from_type: ctx.type_resolution_to_string(ty),
span: ty_span,
to_type: ctx.type_to_string(to_resolved),
}));
}
};
Typed::Plain(ir::Expression::As {
expr,
kind: element_scalar.kind,
convert: None,
})
}
};
expr.try_map(|handle| ctx.append_expression(handle, span))
@@ -2593,10 +2578,14 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
let expr = &ctx.ast_expressions[expr];
match *expr {
ast::Expression::Ident(ast::IdentExpr::Local(_)) => {
Err(Box::new(Error::UnexpectedIdentForEnumerant(span)))
}
ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => {
ast::Expression::Ident(ast::TemplateElaboratedIdent {
ident: ast::IdentExpr::Local(_),
..
}) => Err(Box::new(Error::UnexpectedIdentForEnumerant(span))),
ast::Expression::Ident(ast::TemplateElaboratedIdent {
ident: ast::IdentExpr::Unresolved(name),
..
}) => {
if ctx.globals.get(name).is_some() {
Err(Box::new(Error::UnexpectedIdentForEnumerant(span)))
} else {
@@ -2608,41 +2597,196 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
}
fn var_address_space(
template_list: &Option<Vec<Handle<ast::Expression<'source>>>>,
template_list: &[Handle<ast::Expression<'source>>],
ctx: &ExpressionContext<'source, '_, '_>,
enable_extensions: &EnableExtensions,
) -> Result<'source, ir::AddressSpace> {
let mut address_space = ir::AddressSpace::Handle;
let mut tl = TemplateListIter::new(Span::UNDEFINED, template_list);
let mut address_space = tl.maybe_address_space(ctx)?;
if let Some(ref mut address_space) = address_space {
tl.maybe_access_mode(address_space, ctx)?;
}
tl.finish(ctx)?;
Ok(address_space.unwrap_or(ir::AddressSpace::Handle))
}
if let &Some(ref template_list) = template_list {
let mut template_list_args = template_list.iter();
let address_space_expr = template_list_args.next().unwrap();
fn type_expression(
&mut self,
expr: Handle<ast::Expression<'source>>,
ctx: &mut ExpressionContext<'source, '_, '_>,
) -> Result<'source, Handle<ir::Type>> {
let span = ctx.ast_expressions.get_span(expr);
let expr = &ctx.ast_expressions[expr];
let (enumerant, span) = Self::enumerant(*address_space_expr, ctx)?;
address_space = conv::map_address_space(enumerant, span, enable_extensions)?;
let (ident, ident_span, template_list) = match expr {
&ast::Expression::Ident(ast::TemplateElaboratedIdent {
ident: ast::IdentExpr::Unresolved(ident),
ident_span,
ref template_list,
..
}) => (ident, ident_span, template_list),
_ => return Err(Box::new(Error::UnexpectedExprForTypeExpression(span))),
};
match address_space {
ir::AddressSpace::Storage { ref mut access } => {
if let Some(access_mode_expr) = template_list_args.next() {
let (enumerant, span) = Self::enumerant(*access_mode_expr, ctx)?;
let access_mode = conv::map_access_mode(enumerant, span)?;
*access = access_mode;
} else {
// defaulting to `read`
*access = ir::StorageAccess::LOAD
}
let mut tl = TemplateListIter::new(ident_span, template_list);
if let Some(global) = ctx.globals.get(ident) {
match global {
&LoweredGlobalDecl::Type(handle) => {
tl.finish(ctx)?;
return Ok(handle);
}
_ => {}
}
let unused_args: Vec<Span> = template_list_args
.map(|expr| ctx.ast_expressions.get_span(*expr))
.collect();
if !unused_args.is_empty() {
return Err(Box::new(Error::UnusedArgsForTemplate(unused_args)));
_ => return Err(Box::new(Error::UnexpectedExprForTypeExpression(span))),
}
}
Ok(address_space)
let ty = conv::map_predeclared_type(&ctx.enable_extensions, ident_span, ident)?;
let Some(ty) = ty else {
return Err(Box::new(Error::UnknownIdent(ident_span, ident)));
};
let ty = self.finalize_type(ctx, ty, &mut tl)?;
tl.finish(ctx)?;
Ok(ty)
}
fn finalize_type(
&mut self,
ctx: &mut ExpressionContext<'source, '_, '_>,
ty: conv::PredeclaredType,
tl: &mut TemplateListIter<'_, 'source>,
) -> Result<'source, Handle<ir::Type>> {
let ty = match ty {
conv::PredeclaredType::TypeInner(ty_inner) => {
match ty_inner {
ir::TypeInner::Image {
class: ir::ImageClass::External,
..
} => {
// Other than the WGSL backend, every backend that supports
// external textures does so by lowering them to a set of
// ordinary textures and some parameters saying how to
// sample from them. We don't know which backend will
// consume the `Module` we're building, but in case it's not
// WGSL, populate `SpecialTypes::external_texture_params`
// and `SpecialTypes::external_texture_transfer_function`
// with the types the backend will use for the parameter
// buffer.
//
// Neither of these are the type we are lowering here:
// that's an ordinary `TypeInner::Image`. But the fact we
// are lowering a `texture_external` implies the backends
// may need these additional types too.
ctx.module.generate_external_texture_types();
}
_ => {}
}
ctx.as_global().ensure_type_exists(None, ty_inner)
}
conv::PredeclaredType::RayDesc => ctx.module.generate_ray_desc_type(),
conv::PredeclaredType::RayIntersection => ctx.module.generate_ray_intersection_type(),
conv::PredeclaredType::TypeGenerator(type_generator) => {
let ty_inner = match type_generator {
conv::TypeGenerator::Vector { size } => {
let (scalar, _) = tl.scalar(self, ctx)?;
ir::TypeInner::Vector { size, scalar }
}
conv::TypeGenerator::Matrix { columns, rows } => {
let (scalar, span) = tl.scalar(self, ctx)?;
if scalar.kind != ir::ScalarKind::Float {
return Err(Box::new(Error::BadMatrixScalarKind(span, scalar)));
}
ir::TypeInner::Matrix {
columns,
rows,
scalar,
}
}
conv::TypeGenerator::Array => {
let base = tl.ty(self, ctx)?;
let size = tl.maybe_array_size(self, ctx)?;
// Determine the size of the base type, if needed.
ctx.layouter.update(ctx.module.to_ctx()).map_err(|err| {
let LayoutErrorInner::TooLarge = err.inner else {
unreachable!("unexpected layout error: {err:?}");
};
// Lots of type definitions don't get spans, so this error
// message may not be very useful.
Box::new(Error::TypeTooLarge {
span: ctx.module.types.get_span(err.ty),
})
})?;
let stride = ctx.layouter[base].to_stride();
ir::TypeInner::Array { base, size, stride }
}
conv::TypeGenerator::Atomic => {
let (scalar, _) = tl.scalar(self, ctx)?;
ir::TypeInner::Atomic(scalar)
}
conv::TypeGenerator::Pointer => {
let mut space = tl.address_space(ctx)?;
let base = tl.ty(self, ctx)?;
tl.maybe_access_mode(&mut space, ctx)?;
ir::TypeInner::Pointer { base, space }
}
conv::TypeGenerator::SampledTexture {
dim,
arrayed,
multi,
} => {
let (scalar, span) = tl.scalar(self, ctx)?;
let ir::Scalar { kind, width } = scalar;
if width != 4 {
return Err(Box::new(Error::BadTextureSampleType { span, scalar }));
}
ir::TypeInner::Image {
dim,
arrayed,
class: ir::ImageClass::Sampled { kind, multi },
}
}
conv::TypeGenerator::StorageTexture { dim, arrayed } => {
let format = tl.storage_format(ctx)?;
let access = tl.access_mode(ctx)?;
ir::TypeInner::Image {
dim,
arrayed,
class: ir::ImageClass::Storage { format, access },
}
}
conv::TypeGenerator::BindingArray => {
let base = tl.ty(self, ctx)?;
let size = tl.maybe_array_size(self, ctx)?;
ir::TypeInner::BindingArray { base, size }
}
conv::TypeGenerator::AccelerationStructure => {
let vertex_return = tl.maybe_vertex_return(ctx)?;
ir::TypeInner::AccelerationStructure { vertex_return }
}
conv::TypeGenerator::RayQuery => {
let vertex_return = tl.maybe_vertex_return(ctx)?;
ir::TypeInner::RayQuery { vertex_return }
}
conv::TypeGenerator::CooperativeMatrix { columns, rows } => {
let (ty, span) = tl.ty_with_span(self, ctx)?;
let ir::TypeInner::Scalar(scalar) = ctx.module.types[ty].inner else {
return Err(Box::new(Error::UnsupportedCooperativeScalar(span)));
};
let role = tl.cooperative_role(ctx)?;
ir::TypeInner::CooperativeMatrix {
columns,
rows,
scalar,
role,
}
}
};
ctx.as_global().ensure_type_exists(None, ty_inner)
}
};
Ok(ty)
}
fn binary(
@@ -2743,23 +2887,32 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
/// [`Call`]: ir::Statement::Call
fn call(
&mut self,
call_phrase: &ast::CallPhrase<'source>,
span: Span,
function: &ast::Ident<'source>,
arguments: &[Handle<ast::Expression<'source>>],
result_ty: Option<(Handle<ast::Type<'source>>, Span)>,
ctx: &mut ExpressionContext<'source, '_, '_>,
is_statement: bool,
) -> Result<'source, Option<Handle<ir::Expression>>> {
let function_span = function.span;
match ctx.globals.get(function.name) {
let function_name = match call_phrase.function.ident {
ast::IdentExpr::Unresolved(name) => name,
ast::IdentExpr::Local(_) => {
return Err(Box::new(Error::CalledLocalDecl(
call_phrase.function.ident_span,
)))
}
};
let mut function_span = call_phrase.function.ident_span;
function_span.subsume(call_phrase.function.template_list_span);
let arguments = call_phrase.arguments.as_slice();
let mut tl = TemplateListIter::new(function_span, &call_phrase.function.template_list);
match ctx.globals.get(function_name) {
Some(&LoweredGlobalDecl::Type(ty)) => {
let handle = self.construct(
span,
&ast::ConstructorType::Type(ty),
function_span,
arguments,
ctx,
)?;
// user-declared types can't make use of template lists
tl.finish(ctx)?;
let handle =
self.construct(span, Constructor::Type(ty), function_span, arguments, ctx)?;
Ok(Some(handle))
}
Some(
@@ -2777,6 +2930,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
handle: function,
must_use,
}) => {
// user-declared functions can't make use of template lists
tl.finish(ctx)?;
let arguments = arguments
.iter()
.enumerate()
@@ -2832,8 +2988,126 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
Ok(result)
}
None => {
match function_name {
"bitcast" => {
let ty = tl.ty(self, ctx)?;
tl.finish(ctx)?;
let mut args = ctx.prepare_args(arguments, 1, function_span);
let expr = self.expression(args.next()?, ctx)?;
args.finish()?;
let element_scalar = match ctx.module.types[ty].inner {
ir::TypeInner::Scalar(scalar) => scalar,
ir::TypeInner::Vector { scalar, .. } => scalar,
_ => {
let ty_resolution = resolve!(ctx, expr);
return Err(Box::new(Error::BadTypeCast {
from_type: ctx.type_resolution_to_string(ty_resolution),
span: function_span,
to_type: ctx.type_to_string(ty),
}));
}
};
let expr = ir::Expression::As {
expr,
kind: element_scalar.kind,
convert: None,
};
let expr = ctx.append_expression(expr, function_span)?;
return Ok(Some(expr));
}
"coopLoad" | "coopLoadT" => {
let row_major = function_name.ends_with("T");
let (matrix_ty, matrix_span) = tl.ty_with_span(self, ctx)?;
tl.finish(ctx)?;
let mut args = ctx.prepare_args(arguments, 1, span);
let pointer = self.expression(args.next()?, ctx)?;
let (columns, rows, role) = match ctx.module.types[matrix_ty].inner {
ir::TypeInner::CooperativeMatrix {
columns,
rows,
role,
..
} => (columns, rows, role),
_ => {
return Err(Box::new(Error::InvalidCooperativeLoadType(
matrix_span,
)))
}
};
let stride = if args.total_args > 1 {
self.expression(args.next()?, ctx)?
} else {
// Infer the stride from the matrix type
let stride = if row_major {
columns as u32
} else {
rows as u32
};
ctx.append_expression(
ir::Expression::Literal(ir::Literal::U32(stride)),
Span::UNDEFINED,
)?
};
args.finish()?;
let expr = crate::Expression::CooperativeLoad {
columns,
rows,
role,
data: crate::CooperativeData {
pointer,
stride,
row_major,
},
};
let expr = ctx.append_expression(expr, function_span)?;
return Ok(Some(expr));
}
_ => {}
}
let ty = conv::map_predeclared_type(
&ctx.enable_extensions,
function_span,
function_name,
)?;
if let Some(ty) = ty {
let empty_template_list = call_phrase.function.template_list.is_empty();
let constructor_ty = match ty {
conv::PredeclaredType::TypeGenerator(conv::TypeGenerator::Vector {
size,
}) if empty_template_list => Constructor::PartialVector { size },
conv::PredeclaredType::TypeGenerator(conv::TypeGenerator::Matrix {
columns,
rows,
}) if empty_template_list => Constructor::PartialMatrix { columns, rows },
conv::PredeclaredType::TypeGenerator(conv::TypeGenerator::Array)
if empty_template_list =>
{
Constructor::PartialArray
}
conv::PredeclaredType::TypeGenerator(
conv::TypeGenerator::CooperativeMatrix { .. },
) if empty_template_list => {
return Err(Box::new(Error::UnderspecifiedCooperativeMatrix));
}
_ => Constructor::Type(self.finalize_type(ctx, ty, &mut tl)?),
};
tl.finish(ctx)?;
let handle =
self.construct(span, constructor_ty, function_span, arguments, ctx)?;
return Ok(Some(handle));
};
tl.finish(ctx)?;
let span = function_span;
let expr = if let Some(fun) = conv::map_relational_fun(function.name) {
let expr = if let Some(fun) = conv::map_relational_fun(function_name) {
let mut args = ctx.prepare_args(arguments, 1, span);
let argument = self.expression(args.next()?, ctx)?;
args.finish()?;
@@ -2857,28 +3131,28 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
} else {
ir::Expression::Relational { fun, argument }
}
} else if let Some((axis, ctrl)) = conv::map_derivative(function.name) {
} else if let Some((axis, ctrl)) = conv::map_derivative(function_name) {
let mut args = ctx.prepare_args(arguments, 1, span);
let expr = self.expression(args.next()?, ctx)?;
args.finish()?;
ir::Expression::Derivative { axis, ctrl, expr }
} else if let Some(fun) = conv::map_standard_fun(function.name) {
} else if let Some(fun) = conv::map_standard_fun(function_name) {
self.math_function_helper(span, fun, arguments, ctx)?
} else if let Some(fun) = Texture::map(function.name) {
} else if let Some(fun) = Texture::map(function_name) {
self.texture_sample_helper(fun, arguments, span, ctx)?
} else if let Some((op, cop)) = conv::map_subgroup_operation(function.name) {
} else if let Some((op, cop)) = conv::map_subgroup_operation(function_name) {
return Ok(Some(
self.subgroup_operation_helper(span, op, cop, arguments, ctx)?,
));
} else if let Some(mode) = SubgroupGather::map(function.name) {
} else if let Some(mode) = SubgroupGather::map(function_name) {
return Ok(Some(
self.subgroup_gather_helper(span, mode, arguments, ctx)?,
));
} else if let Some(fun) = ir::AtomicFunction::map(function.name) {
} else if let Some(fun) = ir::AtomicFunction::map(function_name) {
return self.atomic_helper(span, fun, arguments, is_statement, ctx);
} else {
match function.name {
match function_name {
"select" => {
let mut args = ctx.prepare_args(arguments, 3, span);
@@ -3054,7 +3328,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
image,
coordinate,
array_index,
fun: match function.name {
fun: match function_name {
"textureAtomicMin" => ir::AtomicFunction::Min,
"textureAtomicMax" => ir::AtomicFunction::Max,
"textureAtomicAdd" => ir::AtomicFunction::Add,
@@ -3392,17 +3666,6 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
committed: false,
}
}
"RayDesc" => {
let ty = ctx.module.generate_ray_desc_type();
let handle = self.construct(
span,
&ast::ConstructorType::Type(ty),
function.span,
arguments,
ctx,
)?;
return Ok(Some(handle));
}
"subgroupBallot" => {
let mut args = ctx.prepare_args(arguments, 0, span);
let predicate = if arguments.len() == 1 {
@@ -3488,53 +3751,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
);
return Ok(Some(result));
}
"coopLoad" | "coopLoadT" => {
let row_major = function.name.ends_with("T");
let mut args = ctx.prepare_args(arguments, 1, span);
let pointer = self.expression(args.next()?, ctx)?;
let (matrix_ty, matrix_span) = result_ty.expect("generic argument");
let (columns, rows, role) = match ctx.types[matrix_ty] {
ast::Type::CooperativeMatrix {
columns,
rows,
role,
..
} => (columns, rows, role),
_ => {
return Err(Box::new(Error::InvalidCooperativeLoadType(
matrix_span,
)))
}
};
let stride = if args.total_args > 1 {
self.expression(args.next()?, ctx)?
} else {
// Infer the stride from the matrix type
let stride = if row_major {
columns as u32
} else {
rows as u32
};
ctx.append_expression(
ir::Expression::Literal(ir::Literal::U32(stride)),
Span::UNDEFINED,
)?
};
args.finish()?;
crate::Expression::CooperativeLoad {
columns,
rows,
role,
data: crate::CooperativeData {
pointer,
stride,
row_major,
},
}
}
"coopStore" | "coopStoreT" => {
let row_major = function.name.ends_with("T");
let row_major = function_name.ends_with("T");
let mut args = ctx.prepare_args(arguments, 2, span);
let target = self.expression(args.next()?, ctx)?;
@@ -3584,7 +3802,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
ir::Expression::CooperativeMultiplyAdd { a, b, c }
}
_ => {
return Err(Box::new(Error::UnknownIdent(function.span, function.name)))
return Err(Box::new(Error::UnknownIdent(function_span, function_name)))
}
}
};
@@ -4336,6 +4554,46 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
})
}
fn array_size2(
&mut self,
expr: Handle<ast::Expression<'source>>,
ctx: &mut ExpressionContext<'source, '_, '_>,
) -> Result<'source, ir::ArraySize> {
let span = ctx.ast_expressions.get_span(expr);
let const_ctx = &mut ctx.as_const();
let const_expr = self.expression(expr, const_ctx);
match const_expr {
Ok(value) => {
let len = const_ctx.get_const_val(value).map_err(|err| {
Box::new(match err {
proc::ConstValueError::NonConst | proc::ConstValueError::InvalidType => {
Error::ExpectedConstExprConcreteIntegerScalar(span)
}
proc::ConstValueError::Negative => Error::ExpectedPositiveArrayLength(span),
})
})?;
let size = NonZeroU32::new(len).ok_or(Error::ExpectedPositiveArrayLength(span))?;
Ok(ir::ArraySize::Constant(size))
}
Err(err) => {
if let Error::ConstantEvaluatorError(ref ty, _) = *err {
match **ty {
proc::ConstantEvaluatorError::OverrideExpr => {
Ok(ir::ArraySize::Pending(self.array_size_override(
expr,
&mut ctx.as_global().as_override(),
span,
)?))
}
_ => Err(err),
}
} else {
Err(err)
}
}
}
}
fn array_size_override(
&mut self,
size_expr: Handle<ast::Expression<'source>>,
+184
View File
@@ -0,0 +1,184 @@
use alloc::{boxed::Box, vec::Vec};
use crate::{
front::wgsl::{
error::Error,
lower::{ExpressionContext, Lowerer, Result},
parse::{ast, conv},
},
ir, Handle, Span,
};
/// Iterator over a template list.
///
/// All functions will attempt to consume an element in the list.
///
/// Function variants prefixed with "maybe" will not return an error if there
/// are no more elements left in the list.
pub struct TemplateListIter<'iter, 'source> {
ident_span: Span,
template_list: core::slice::Iter<'iter, Handle<ast::Expression<'source>>>,
}
impl<'iter, 'source> TemplateListIter<'iter, 'source> {
pub fn new(ident_span: Span, template_list: &'iter [Handle<ast::Expression<'source>>]) -> Self {
Self {
ident_span,
template_list: template_list.iter(),
}
}
pub fn finish(self, ctx: &ExpressionContext<'source, '_, '_>) -> Result<'source, ()> {
let unused_args: Vec<Span> = self
.template_list
.map(|expr| ctx.ast_expressions.get_span(*expr))
.collect();
if unused_args.is_empty() {
Ok(())
} else {
Err(Box::new(Error::UnusedArgsForTemplate(unused_args)))
}
}
fn expect_next(
&mut self,
arg: &'static str,
) -> Result<'source, Handle<ast::Expression<'source>>> {
if let Some(expr) = self.template_list.next() {
Ok(*expr)
} else {
Err(Box::new(Error::MissingTemplateArg {
span: self.ident_span,
arg,
}))
}
}
pub fn ty(
&mut self,
lowerer: &mut Lowerer<'source, '_>,
ctx: &mut ExpressionContext<'source, '_, '_>,
) -> Result<'source, Handle<ir::Type>> {
let expr = self.expect_next("`T`, a type")?;
lowerer.type_expression(expr, ctx)
}
pub fn ty_with_span(
&mut self,
lowerer: &mut Lowerer<'source, '_>,
ctx: &mut ExpressionContext<'source, '_, '_>,
) -> Result<'source, (Handle<ir::Type>, Span)> {
let expr = self.expect_next("`T`, a type")?;
let span = ctx.ast_expressions.get_span(expr);
let ty = lowerer.type_expression(expr, ctx)?;
Ok((ty, span))
}
pub fn scalar(
&mut self,
lowerer: &mut Lowerer<'source, '_>,
ctx: &mut ExpressionContext<'source, '_, '_>,
) -> Result<'source, (ir::Scalar, Span)> {
let expr = self.expect_next("`T`, a scalar type")?;
let ty = lowerer.type_expression(expr, ctx)?;
let span = ctx.ast_expressions.get_span(expr);
match ctx.module.types[ty].inner {
ir::TypeInner::Scalar(scalar) => Ok((scalar, span)),
_ => Err(Box::new(Error::UnknownScalarType(span))),
}
}
pub fn maybe_array_size(
&mut self,
lowerer: &mut Lowerer<'source, '_>,
ctx: &mut ExpressionContext<'source, '_, '_>,
) -> Result<'source, ir::ArraySize> {
if let Some(expr) = self.template_list.next() {
lowerer.array_size2(*expr, ctx)
} else {
Ok(ir::ArraySize::Dynamic)
}
}
pub fn address_space(
&mut self,
ctx: &ExpressionContext<'source, '_, '_>,
) -> Result<'source, ir::AddressSpace> {
let expr = self.expect_next("`AS`, an address space")?;
let (enumerant, span) = Lowerer::enumerant(expr, ctx)?;
conv::map_address_space(enumerant, span, &ctx.enable_extensions)
}
pub fn maybe_address_space(
&mut self,
ctx: &ExpressionContext<'source, '_, '_>,
) -> Result<'source, Option<ir::AddressSpace>> {
if let Some(expr) = self.template_list.next() {
let (enumerant, span) = Lowerer::enumerant(*expr, ctx)?;
Ok(Some(conv::map_address_space(
enumerant,
span,
&ctx.enable_extensions,
)?))
} else {
Ok(None)
}
}
pub fn access_mode(
&mut self,
ctx: &ExpressionContext<'source, '_, '_>,
) -> Result<'source, ir::StorageAccess> {
let expr = self.expect_next("`Access`, an access mode")?;
let (enumerant, span) = Lowerer::enumerant(expr, ctx)?;
conv::map_access_mode(enumerant, span)
}
pub fn maybe_access_mode(
&mut self,
space: &mut ir::AddressSpace,
ctx: &ExpressionContext<'source, '_, '_>,
) -> Result<'source, ()> {
if let &mut ir::AddressSpace::Storage { ref mut access } = space {
if let Some(expr) = self.template_list.next() {
let (enumerant, span) = Lowerer::enumerant(*expr, ctx)?;
let access_mode = conv::map_access_mode(enumerant, span)?;
*access = access_mode;
} else {
// defaulting to `read`
*access = ir::StorageAccess::LOAD
}
}
Ok(())
}
pub fn storage_format(
&mut self,
ctx: &ExpressionContext<'source, '_, '_>,
) -> Result<'source, ir::StorageFormat> {
let expr = self.expect_next("`Format`, a texel format")?;
let (enumerant, span) = Lowerer::enumerant(expr, ctx)?;
conv::map_storage_format(enumerant, span)
}
pub fn maybe_vertex_return(
&mut self,
ctx: &ExpressionContext<'source, '_, '_>,
) -> Result<'source, bool> {
if let Some(expr) = self.template_list.next() {
let (enumerant, span) = Lowerer::enumerant(*expr, ctx)?;
conv::map_ray_flag(enumerant, span)?;
Ok(true)
} else {
Ok(false)
}
}
pub fn cooperative_role(
&mut self,
ctx: &ExpressionContext<'source, '_, '_>,
) -> Result<'source, crate::CooperativeRole> {
let role_expr = self.expect_next("`Role`, a cooperative matrix role")?;
let (enumerant, span) = Lowerer::enumerant(role_expr, ctx)?;
let role = conv::map_cooperative_role(enumerant, span)?;
Ok(role)
}
}
+32 -137
View File
@@ -58,6 +58,34 @@ pub enum IdentExpr<'a> {
Local(Handle<Local>),
}
#[derive(Debug)]
pub struct TemplateElaboratedIdent<'a> {
pub ident: IdentExpr<'a>,
pub ident_span: Span,
pub template_list: Vec<Handle<Expression<'a>>>,
pub template_list_span: Span,
}
/// A function call or type constructor expression.
///
/// We can't tell whether an expression like `IDENTIFIER(EXPR, ...)` is a
/// construction expression or a function call until we know `IDENTIFIER`'s
/// definition, so we represent everything of that form as one of these
/// expressions until lowering. At that point, [`Lowerer::call`] has
/// everything's definition in hand, and can decide whether to emit a Naga
/// [`Constant`], [`As`], [`Splat`], or [`Compose`] expression.
///
/// [`Lowerer::call`]: Lowerer::call
/// [`Constant`]: crate::Expression::Constant
/// [`As`]: crate::Expression::As
/// [`Splat`]: crate::Expression::Splat
/// [`Compose`]: crate::Expression::Compose
#[derive(Debug)]
pub struct CallPhrase<'a> {
pub function: TemplateElaboratedIdent<'a>,
pub arguments: Vec<Handle<Expression<'a>>>,
}
/// A reference to a module-scope definition or predeclared object.
///
/// Each [`GlobalDecl`] holds a set of these values, to be resolved to
@@ -167,7 +195,7 @@ pub struct ResourceBinding<'a> {
#[derive(Debug)]
pub struct GlobalVariable<'a> {
pub name: Ident<'a>,
pub template_list: Option<Vec<Handle<Expression<'a>>>>,
pub template_list: Vec<Handle<Expression<'a>>>,
pub binding: Option<ResourceBinding<'a>>,
pub ty: Option<Handle<Type<'a>>>,
pub init: Option<Handle<Expression<'a>>>,
@@ -314,10 +342,7 @@ pub enum StatementKind<'a> {
value: Option<Handle<Expression<'a>>>,
},
Kill,
Call {
function: Ident<'a>,
arguments: Vec<Handle<Expression<'a>>>,
},
Call(CallPhrase<'a>),
Assign {
target: Handle<Expression<'a>>,
op: Option<crate::BinaryOperator>,
@@ -342,92 +367,6 @@ pub struct SwitchCase<'a> {
pub fall_through: bool,
}
/// A type at the head of a [`Construct`] expression.
///
/// WGSL has two types of [`type constructor expressions`]:
///
/// - Those that fully specify the type being constructed, like
/// `vec3<f32>(x,y,z)`, which obviously constructs a `vec3<f32>`.
///
/// - Those that leave the component type of the composite being constructed
/// implicit, to be inferred from the argument types, like `vec3(x,y,z)`,
/// which constructs a `vec3<T>` where `T` is the type of `x`, `y`, and `z`.
///
/// This enum represents the head type of both cases. The `PartialFoo` variants
/// represent the second case, where the component type is implicit.
///
/// This does not cover structs or types referred to by type aliases. See the
/// documentation for [`Construct`] and [`Call`] expressions for details.
///
/// [`Construct`]: Expression::Construct
/// [`type constructor expressions`]: https://gpuweb.github.io/gpuweb/wgsl/#type-constructor-expr
/// [`Call`]: Expression::Call
#[derive(Debug)]
pub enum ConstructorType<'a> {
/// A scalar type or conversion: `f32(1)`.
Scalar(Scalar),
/// A vector construction whose component type is inferred from the
/// argument: `vec3(1.0)`.
PartialVector { size: crate::VectorSize },
/// A vector construction whose component type is written out:
/// `vec3<f32>(1.0)`.
Vector {
size: crate::VectorSize,
ty: Handle<Type<'a>>,
ty_span: Span,
},
/// A matrix construction whose component type is inferred from the
/// argument: `mat2x2(1,2,3,4)`.
PartialMatrix {
columns: crate::VectorSize,
rows: crate::VectorSize,
},
/// A matrix construction whose component type is written out:
/// `mat2x2<f32>(1,2,3,4)`.
Matrix {
columns: crate::VectorSize,
rows: crate::VectorSize,
ty: Handle<Type<'a>>,
ty_span: Span,
},
/// A cooperative matrix construction base `coop_mat8x8(...)`.
PartialCooperativeMatrix {
columns: crate::CooperativeSize,
rows: crate::CooperativeSize,
},
/// A full cooperative matrix construction `coop_mat8x8<f32,A>(...)`.
CooperativeMatrix {
columns: crate::CooperativeSize,
rows: crate::CooperativeSize,
ty: Handle<Type<'a>>,
ty_span: Span,
role: crate::CooperativeRole,
},
/// An array whose component type and size are inferred from the arguments:
/// `array(3,4,5)`.
PartialArray,
/// An array whose component type and size are written out:
/// `array<u32, 4>(3,4,5)`.
Array {
base: Handle<Type<'a>>,
size: ArraySize<'a>,
},
/// Constructing a value of a known Naga IR type.
///
/// This variant is produced only during lowering, when we have Naga types
/// available, never during parsing.
Type(Handle<crate::Type>),
}
#[derive(Debug, Copy, Clone)]
pub enum Literal {
Bool(bool),
@@ -440,27 +379,7 @@ use crate::front::wgsl::lower::Lowerer;
#[derive(Debug)]
pub enum Expression<'a> {
Literal(Literal),
Ident(IdentExpr<'a>),
/// A type constructor expression.
///
/// This is only used for expressions like `KEYWORD(EXPR...)` and
/// `KEYWORD<PARAM>(EXPR...)`, where `KEYWORD` is a [type-defining keyword] like
/// `vec3`. These keywords cannot be shadowed by user definitions, so we can
/// tell that such an expression is a construction immediately.
///
/// For ordinary identifiers, we can't tell whether an expression like
/// `IDENTIFIER(EXPR, ...)` is a construction expression or a function call
/// until we know `IDENTIFIER`'s definition, so we represent those as
/// [`Call`] expressions.
///
/// [type-defining keyword]: https://gpuweb.github.io/gpuweb/wgsl/#type-defining-keywords
/// [`Call`]: Expression::Call
Construct {
ty: ConstructorType<'a>,
ty_span: Span,
components: Vec<Handle<Expression<'a>>>,
},
Ident(TemplateElaboratedIdent<'a>),
Unary {
op: crate::UnaryOperator,
expr: Handle<Expression<'a>>,
@@ -472,26 +391,7 @@ pub enum Expression<'a> {
left: Handle<Expression<'a>>,
right: Handle<Expression<'a>>,
},
/// A function call or type constructor expression.
///
/// We can't tell whether an expression like `IDENTIFIER(EXPR, ...)` is a
/// construction expression or a function call until we know `IDENTIFIER`'s
/// definition, so we represent everything of that form as one of these
/// expressions until lowering. At that point, [`Lowerer::call`] has
/// everything's definition in hand, and can decide whether to emit a Naga
/// [`Constant`], [`As`], [`Splat`], or [`Compose`] expression.
///
/// [`Lowerer::call`]: Lowerer::call
/// [`Constant`]: crate::Expression::Constant
/// [`As`]: crate::Expression::As
/// [`Splat`]: crate::Expression::Splat
/// [`Compose`]: crate::Expression::Compose
Call {
function: Ident<'a>,
arguments: Vec<Handle<Expression<'a>>>,
result_ty: Option<(Handle<Type<'a>>, Span)>,
},
Call(CallPhrase<'a>),
Index {
base: Handle<Expression<'a>>,
index: Handle<Expression<'a>>,
@@ -500,11 +400,6 @@ pub enum Expression<'a> {
base: Handle<Expression<'a>>,
field: Ident<'a>,
},
Bitcast {
expr: Handle<Expression<'a>>,
to: Handle<Type<'a>>,
ty_span: Span,
},
}
#[derive(Debug)]
+204 -1
View File
@@ -2,7 +2,7 @@ use crate::front::wgsl::parse::directive::enable_extension::{
EnableExtensions, ImplementedEnableExtension,
};
use crate::front::wgsl::{Error, Result, Scalar};
use crate::Span;
use crate::{ImageClass, ImageDimension, Span, TypeInner, VectorSize};
use alloc::boxed::Box;
@@ -46,6 +46,22 @@ pub fn map_access_mode(word: &str, span: Span) -> Result<'_, crate::StorageAcces
}
}
pub fn map_ray_flag(word: &str, span: Span) -> Result<'_, ()> {
match word {
"vertex_return" => Ok(()),
_ => Err(Box::new(Error::UnknownRayFlag(span))),
}
}
pub fn map_cooperative_role(word: &str, span: Span) -> Result<'_, crate::CooperativeRole> {
match word {
"A" => Ok(crate::CooperativeRole::A),
"B" => Ok(crate::CooperativeRole::B),
"C" => Ok(crate::CooperativeRole::C),
_ => Err(Box::new(Error::UnknownAccess(span))),
}
}
pub fn map_built_in(
enable_extensions: &EnableExtensions,
word: &str,
@@ -391,3 +407,190 @@ pub fn map_subgroup_operation(
_ => return None,
})
}
pub enum TypeGenerator {
Vector {
size: VectorSize,
},
Matrix {
columns: VectorSize,
rows: VectorSize,
},
Array,
Atomic,
Pointer,
SampledTexture {
dim: ImageDimension,
arrayed: bool,
multi: bool,
},
StorageTexture {
dim: ImageDimension,
arrayed: bool,
},
BindingArray,
AccelerationStructure,
RayQuery,
CooperativeMatrix {
columns: crate::CooperativeSize,
rows: crate::CooperativeSize,
},
}
pub enum PredeclaredType {
TypeInner(TypeInner),
RayDesc,
RayIntersection,
TypeGenerator(TypeGenerator),
}
impl From<TypeInner> for PredeclaredType {
fn from(value: TypeInner) -> Self {
Self::TypeInner(value)
}
}
impl From<TypeGenerator> for PredeclaredType {
fn from(value: TypeGenerator) -> Self {
Self::TypeGenerator(value)
}
}
pub fn map_predeclared_type(
enable_extensions: &EnableExtensions,
span: Span,
word: &str,
) -> Result<'static, Option<PredeclaredType>> {
#[rustfmt::skip]
let ty = match word {
// predeclared types
// scalars
"bool" => TypeInner::Scalar(Scalar::BOOL).into(),
"i32" => TypeInner::Scalar(Scalar::I32).into(),
"u32" => TypeInner::Scalar(Scalar::U32).into(),
"f32" => TypeInner::Scalar(Scalar::F32).into(),
"f16" => TypeInner::Scalar(Scalar::F16).into(),
"i64" => TypeInner::Scalar(Scalar::I64).into(),
"u64" => TypeInner::Scalar(Scalar::U64).into(),
"f64" => TypeInner::Scalar(Scalar::F64).into(),
// vector aliases
"vec2i" => TypeInner::Vector { size: VectorSize::Bi, scalar: Scalar::I32 }.into(),
"vec3i" => TypeInner::Vector { size: VectorSize::Tri, scalar: Scalar::I32 }.into(),
"vec4i" => TypeInner::Vector { size: VectorSize::Quad, scalar: Scalar::I32 }.into(),
"vec2u" => TypeInner::Vector { size: VectorSize::Bi, scalar: Scalar::U32 }.into(),
"vec3u" => TypeInner::Vector { size: VectorSize::Tri, scalar: Scalar::U32 }.into(),
"vec4u" => TypeInner::Vector { size: VectorSize::Quad, scalar: Scalar::U32 }.into(),
"vec2f" => TypeInner::Vector { size: VectorSize::Bi, scalar: Scalar::F32 }.into(),
"vec3f" => TypeInner::Vector { size: VectorSize::Tri, scalar: Scalar::F32 }.into(),
"vec4f" => TypeInner::Vector { size: VectorSize::Quad, scalar: Scalar::F32 }.into(),
"vec2h" => TypeInner::Vector { size: VectorSize::Bi, scalar: Scalar::F16 }.into(),
"vec3h" => TypeInner::Vector { size: VectorSize::Tri, scalar: Scalar::F16 }.into(),
"vec4h" => TypeInner::Vector { size: VectorSize::Quad, scalar: Scalar::F16 }.into(),
// matrix aliases
"mat2x2f" => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Bi, scalar: Scalar::F32 }.into(),
"mat2x3f" => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Tri, scalar: Scalar::F32 }.into(),
"mat2x4f" => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Quad, scalar: Scalar::F32 }.into(),
"mat3x2f" => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Bi, scalar: Scalar::F32 }.into(),
"mat3x3f" => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Tri, scalar: Scalar::F32 }.into(),
"mat3x4f" => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Quad, scalar: Scalar::F32 }.into(),
"mat4x2f" => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Bi, scalar: Scalar::F32 }.into(),
"mat4x3f" => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Tri, scalar: Scalar::F32 }.into(),
"mat4x4f" => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Quad, scalar: Scalar::F32 }.into(),
"mat2x2h" => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Bi, scalar: Scalar::F16 }.into(),
"mat2x3h" => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Tri, scalar: Scalar::F16 }.into(),
"mat2x4h" => TypeInner::Matrix { columns: VectorSize::Bi, rows: VectorSize::Quad, scalar: Scalar::F16 }.into(),
"mat3x2h" => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Bi, scalar: Scalar::F16 }.into(),
"mat3x3h" => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Tri, scalar: Scalar::F16 }.into(),
"mat3x4h" => TypeInner::Matrix { columns: VectorSize::Tri, rows: VectorSize::Quad, scalar: Scalar::F16 }.into(),
"mat4x2h" => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Bi, scalar: Scalar::F16 }.into(),
"mat4x3h" => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Tri, scalar: Scalar::F16 }.into(),
"mat4x4h" => TypeInner::Matrix { columns: VectorSize::Quad, rows: VectorSize::Quad, scalar: Scalar::F16 }.into(),
// samplers
"sampler" => TypeInner::Sampler { comparison: false }.into(),
"sampler_comparison" => TypeInner::Sampler { comparison: true }.into(),
// depth textures
"texture_depth_2d" => TypeInner::Image { dim: ImageDimension::D2, arrayed: false, class: ImageClass::Depth { multi: false } }.into(),
"texture_depth_2d_array" => TypeInner::Image { dim: ImageDimension::D2, arrayed: true, class: ImageClass::Depth { multi: false } }.into(),
"texture_depth_cube" => TypeInner::Image { dim: ImageDimension::Cube, arrayed: false, class: ImageClass::Depth { multi: false } }.into(),
"texture_depth_cube_array" => TypeInner::Image { dim: ImageDimension::Cube, arrayed: true, class: ImageClass::Depth { multi: false } }.into(),
"texture_depth_multisampled_2d" => TypeInner::Image { dim: ImageDimension::D2, arrayed: false, class: ImageClass::Depth { multi: true } }.into(),
// external texture
"texture_external" => TypeInner::Image { dim: ImageDimension::D2, arrayed: false, class: ImageClass::External }.into(),
// ray desc
"RayDesc" => PredeclaredType::RayDesc,
// ray intersection
"RayIntersection" => PredeclaredType::RayIntersection,
// predeclared type generators
// vector
"vec2" => TypeGenerator::Vector { size: VectorSize::Bi }.into(),
"vec3" => TypeGenerator::Vector { size: VectorSize::Tri }.into(),
"vec4" => TypeGenerator::Vector { size: VectorSize::Quad }.into(),
// matrix
"mat2x2" => TypeGenerator::Matrix { columns: VectorSize::Bi, rows: VectorSize::Bi }.into(),
"mat2x3" => TypeGenerator::Matrix { columns: VectorSize::Bi, rows: VectorSize::Tri }.into(),
"mat2x4" => TypeGenerator::Matrix { columns: VectorSize::Bi, rows: VectorSize::Quad }.into(),
"mat3x2" => TypeGenerator::Matrix { columns: VectorSize::Tri, rows: VectorSize::Bi }.into(),
"mat3x3" => TypeGenerator::Matrix { columns: VectorSize::Tri, rows: VectorSize::Tri }.into(),
"mat3x4" => TypeGenerator::Matrix { columns: VectorSize::Tri, rows: VectorSize::Quad }.into(),
"mat4x2" => TypeGenerator::Matrix { columns: VectorSize::Quad, rows: VectorSize::Bi }.into(),
"mat4x3" => TypeGenerator::Matrix { columns: VectorSize::Quad, rows: VectorSize::Tri }.into(),
"mat4x4" => TypeGenerator::Matrix { columns: VectorSize::Quad, rows: VectorSize::Quad }.into(),
// array
"array" => TypeGenerator::Array.into(),
// atomic
"atomic" => TypeGenerator::Atomic.into(),
// pointer
"ptr" => TypeGenerator::Pointer.into(),
// sampled textures
"texture_1d" => TypeGenerator::SampledTexture { dim: ImageDimension::D1, arrayed: false, multi: false }.into(),
"texture_2d" => TypeGenerator::SampledTexture { dim: ImageDimension::D2, arrayed: false, multi: false }.into(),
"texture_2d_array" => TypeGenerator::SampledTexture { dim: ImageDimension::D2, arrayed: true, multi: false }.into(),
"texture_3d" => TypeGenerator::SampledTexture { dim: ImageDimension::D3, arrayed: false, multi: false }.into(),
"texture_cube" => TypeGenerator::SampledTexture { dim: ImageDimension::Cube, arrayed: false, multi: false }.into(),
"texture_cube_array" => TypeGenerator::SampledTexture { dim: ImageDimension::Cube, arrayed: true, multi: false }.into(),
"texture_multisampled_2d" => TypeGenerator::SampledTexture { dim: ImageDimension::D2, arrayed: false, multi: true }.into(),
// storage textures
"texture_storage_1d" => TypeGenerator::StorageTexture { dim: ImageDimension::D1, arrayed: false }.into(),
"texture_storage_2d" => TypeGenerator::StorageTexture { dim: ImageDimension::D2, arrayed: false }.into(),
"texture_storage_2d_array" => TypeGenerator::StorageTexture { dim: ImageDimension::D2, arrayed: true }.into(),
"texture_storage_3d" => TypeGenerator::StorageTexture { dim: ImageDimension::D3, arrayed: false }.into(),
// binding array
"binding_array" => TypeGenerator::BindingArray.into(),
// acceleration structure
"acceleration_structure" => TypeGenerator::AccelerationStructure.into(),
// ray query
"ray_query" => TypeGenerator::RayQuery.into(),
// cooperative matrix
"coop_mat8x8" => TypeGenerator::CooperativeMatrix {
columns: crate::CooperativeSize::Eight,
rows: crate::CooperativeSize::Eight,
}.into(),
"coop_mat16x16" => TypeGenerator::CooperativeMatrix {
columns: crate::CooperativeSize::Sixteen,
rows: crate::CooperativeSize::Sixteen,
}.into(),
_ => return Ok(None),
};
// Check for the enable extension required to use this type, if any.
let extension_needed = match ty {
PredeclaredType::TypeInner(ref ty) if ty.scalar() == Some(Scalar::F16) => {
Some(ImplementedEnableExtension::F16)
}
PredeclaredType::TypeGenerator(TypeGenerator::CooperativeMatrix { .. }) => {
Some(ImplementedEnableExtension::WgpuCooperativeMatrix)
}
_ => None,
};
if let Some(extension_needed) = extension_needed {
if !enable_extensions.contains(extension_needed) {
return Err(Box::new(Error::EnableExtensionNotEnabled {
span,
kind: extension_needed.into(),
}));
}
}
Ok(Some(ty))
}
@@ -8,7 +8,7 @@ use crate::Span;
use alloc::boxed::Box;
/// Tracks the status of every enable-extension known to Naga.
#[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EnableExtensions {
wgpu_mesh_shader: bool,
wgpu_ray_query: bool,
+1 -11
View File
@@ -644,23 +644,13 @@ impl<'a> Lexer<'a> {
&mut self,
) -> Result<'a, crate::CooperativeRole> {
let (ident, span) = self.next_ident_with_span()?;
match ident {
"A" => Ok(crate::CooperativeRole::A),
"B" => Ok(crate::CooperativeRole::B),
"C" => Ok(crate::CooperativeRole::C),
_ => Err(Box::new(Error::UnknownAccess(span))),
}
conv::map_cooperative_role(ident, span)
}
pub(in crate::front::wgsl) fn open_arguments(&mut self) -> Result<'a, ()> {
self.expect(Token::Paren('('))
}
pub(in crate::front::wgsl) fn close_arguments(&mut self) -> Result<'a, ()> {
let _ = self.next_if(Token::Separator(','));
self.expect(Token::Paren(')'))
}
pub(in crate::front::wgsl) fn next_argument(&mut self) -> Result<'a, bool> {
let paren = Token::Paren(')');
if self.next_if(Token::Separator(',')) {
+66 -481
View File
@@ -366,396 +366,6 @@ impl Parser {
Ok(ast::SwitchValue::Expr(expr))
}
/// Decide if we're looking at a construction expression, and return its
/// type if so.
///
/// If the identifier `word` is a [type-defining keyword], then return a
/// [`ConstructorType`] value describing the type to build. Return an error
/// if the type is not constructible (like `sampler`).
///
/// If `word` isn't a type name, then return `None`.
///
/// [type-defining keyword]: https://gpuweb.github.io/gpuweb/wgsl/#type-defining-keywords
/// [`ConstructorType`]: ast::ConstructorType
fn constructor_type<'a>(
&mut self,
lexer: &mut Lexer<'a>,
word: &'a str,
span: Span,
ctx: &mut ExpressionContext<'a, '_, '_>,
) -> Result<'a, Option<ast::ConstructorType<'a>>> {
if let Some(scalar) = conv::get_scalar_type(&lexer.enable_extensions, span, word)? {
return Ok(Some(ast::ConstructorType::Scalar(scalar)));
}
let partial = match word {
"vec2" => ast::ConstructorType::PartialVector {
size: crate::VectorSize::Bi,
},
"vec2i" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Bi,
ty: ctx.new_scalar(Scalar::I32),
ty_span: Span::UNDEFINED,
}))
}
"vec2u" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Bi,
ty: ctx.new_scalar(Scalar::U32),
ty_span: Span::UNDEFINED,
}))
}
"vec2f" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Bi,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"vec2h" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Bi,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"vec3" => ast::ConstructorType::PartialVector {
size: crate::VectorSize::Tri,
},
"vec3i" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Tri,
ty: ctx.new_scalar(Scalar::I32),
ty_span: Span::UNDEFINED,
}))
}
"vec3u" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Tri,
ty: ctx.new_scalar(Scalar::U32),
ty_span: Span::UNDEFINED,
}))
}
"vec3f" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Tri,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"vec3h" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Tri,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"vec4" => ast::ConstructorType::PartialVector {
size: crate::VectorSize::Quad,
},
"vec4i" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Quad,
ty: ctx.new_scalar(Scalar::I32),
ty_span: Span::UNDEFINED,
}))
}
"vec4u" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Quad,
ty: ctx.new_scalar(Scalar::U32),
ty_span: Span::UNDEFINED,
}))
}
"vec4f" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Quad,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"vec4h" => {
return Ok(Some(ast::ConstructorType::Vector {
size: crate::VectorSize::Quad,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"mat2x2" => ast::ConstructorType::PartialMatrix {
columns: crate::VectorSize::Bi,
rows: crate::VectorSize::Bi,
},
"mat2x2f" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Bi,
rows: crate::VectorSize::Bi,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"mat2x2h" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Bi,
rows: crate::VectorSize::Bi,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"mat2x3" => ast::ConstructorType::PartialMatrix {
columns: crate::VectorSize::Bi,
rows: crate::VectorSize::Tri,
},
"mat2x3f" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Bi,
rows: crate::VectorSize::Tri,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"mat2x3h" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Bi,
rows: crate::VectorSize::Tri,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"mat2x4" => ast::ConstructorType::PartialMatrix {
columns: crate::VectorSize::Bi,
rows: crate::VectorSize::Quad,
},
"mat2x4f" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Bi,
rows: crate::VectorSize::Quad,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"mat2x4h" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Bi,
rows: crate::VectorSize::Quad,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"mat3x2" => ast::ConstructorType::PartialMatrix {
columns: crate::VectorSize::Tri,
rows: crate::VectorSize::Bi,
},
"mat3x2f" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Tri,
rows: crate::VectorSize::Bi,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"mat3x2h" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Tri,
rows: crate::VectorSize::Bi,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"mat3x3" => ast::ConstructorType::PartialMatrix {
columns: crate::VectorSize::Tri,
rows: crate::VectorSize::Tri,
},
"mat3x3f" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Tri,
rows: crate::VectorSize::Tri,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"mat3x3h" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Tri,
rows: crate::VectorSize::Tri,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"mat3x4" => ast::ConstructorType::PartialMatrix {
columns: crate::VectorSize::Tri,
rows: crate::VectorSize::Quad,
},
"mat3x4f" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Tri,
rows: crate::VectorSize::Quad,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"mat3x4h" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Tri,
rows: crate::VectorSize::Quad,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"mat4x2" => ast::ConstructorType::PartialMatrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Bi,
},
"mat4x2f" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Bi,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"mat4x2h" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Bi,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"mat4x3" => ast::ConstructorType::PartialMatrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Tri,
},
"mat4x3f" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Tri,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"mat4x3h" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Tri,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"mat4x4" => ast::ConstructorType::PartialMatrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Quad,
},
"mat4x4f" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Quad,
ty: ctx.new_scalar(Scalar::F32),
ty_span: Span::UNDEFINED,
}))
}
"mat4x4h" => {
return Ok(Some(ast::ConstructorType::Matrix {
columns: crate::VectorSize::Quad,
rows: crate::VectorSize::Quad,
ty: ctx.new_scalar(Scalar::F16),
ty_span: Span::UNDEFINED,
}))
}
"coop_mat8x8" => {
lexer.require_enable_extension(
ImplementedEnableExtension::WgpuCooperativeMatrix,
span,
)?;
ast::ConstructorType::PartialCooperativeMatrix {
columns: crate::CooperativeSize::Eight,
rows: crate::CooperativeSize::Eight,
}
}
"coop_mat16x16" => {
lexer.require_enable_extension(
ImplementedEnableExtension::WgpuCooperativeMatrix,
span,
)?;
ast::ConstructorType::PartialCooperativeMatrix {
columns: crate::CooperativeSize::Sixteen,
rows: crate::CooperativeSize::Sixteen,
}
}
"array" => ast::ConstructorType::PartialArray,
"atomic"
| "binding_array"
| "sampler"
| "sampler_comparison"
| "texture_1d"
| "texture_1d_array"
| "texture_2d"
| "texture_2d_array"
| "texture_3d"
| "texture_cube"
| "texture_cube_array"
| "texture_multisampled_2d"
| "texture_multisampled_2d_array"
| "texture_depth_2d"
| "texture_depth_2d_array"
| "texture_depth_cube"
| "texture_depth_cube_array"
| "texture_depth_multisampled_2d"
| "texture_external"
| "texture_storage_1d"
| "texture_storage_1d_array"
| "texture_storage_2d"
| "texture_storage_2d_array"
| "texture_storage_3d" => return Err(Box::new(Error::TypeNotConstructible(span))),
_ => return Ok(None),
};
// parse component type if present
match (lexer.peek().0, partial) {
(Token::TemplateArgsStart, ast::ConstructorType::PartialVector { size }) => {
let (ty, ty_span) = self.singular_generic(lexer, ctx)?;
Ok(Some(ast::ConstructorType::Vector { size, ty, ty_span }))
}
(Token::TemplateArgsStart, ast::ConstructorType::PartialMatrix { columns, rows }) => {
let (ty, ty_span) = self.singular_generic(lexer, ctx)?;
Ok(Some(ast::ConstructorType::Matrix {
columns,
rows,
ty,
ty_span,
}))
}
(
Token::TemplateArgsStart,
ast::ConstructorType::PartialCooperativeMatrix { columns, rows },
) => {
let (ty, ty_span, role) = self.cooperative_scalar_and_role(lexer, ctx)?;
Ok(Some(ast::ConstructorType::CooperativeMatrix {
columns,
rows,
ty,
ty_span,
role,
}))
}
(Token::TemplateArgsStart, ast::ConstructorType::PartialArray) => {
lexer.expect(Token::TemplateArgsStart)?;
let base = self.type_specifier(lexer, ctx)?;
let size = if lexer.end_of_generic_arguments() {
let expr = self.const_generic_expression(lexer, ctx)?;
lexer.next_if(Token::Separator(','));
ast::ArraySize::Constant(expr)
} else {
ast::ArraySize::Dynamic
};
lexer.expect(Token::TemplateArgsEnd)?;
Ok(Some(ast::ConstructorType::Array { base, size }))
}
(_, partial) => Ok(Some(partial)),
}
}
/// Expects `name` to be consumed (not in lexer).
fn arguments<'a>(
&mut self,
@@ -792,57 +402,6 @@ impl Parser {
Ok(expr)
}
/// Expects `name` to be consumed (not in lexer).
fn call_expression<'a>(
&mut self,
lexer: &mut Lexer<'a>,
name: &'a str,
name_span: Span,
ctx: &mut ExpressionContext<'a, '_, '_>,
) -> Result<'a, Handle<ast::Expression<'a>>> {
let expr = match name {
// bitcast looks like a function call, but it's an operator and must be handled differently.
"bitcast" => {
let (to, span) = self.singular_generic(lexer, ctx)?;
lexer.open_arguments()?;
let expr = self.expression(lexer, ctx)?;
lexer.close_arguments()?;
ast::Expression::Bitcast {
expr,
to,
ty_span: span,
}
}
// everything else must be handled later, since they can be hidden by user-defined functions.
_ => {
let result_ty = if lexer.peek().0 == Token::TemplateArgsStart {
Some(self.singular_generic(lexer, ctx)?)
} else {
None
};
let arguments = self.arguments(lexer, ctx)?;
ctx.unresolved.insert(ast::Dependency {
ident: name,
usage: name_span,
});
ast::Expression::Call {
function: ast::Ident {
name,
span: name_span,
},
arguments,
result_ty,
}
}
};
let span = lexer.span_with_start(name_span);
let expr = ctx.expressions.append(expr, span);
Ok(expr)
}
fn ident_expr<'a>(
&mut self,
name: &'a str,
@@ -938,22 +497,19 @@ impl Parser {
literal_ray_intersection(crate::RayQueryIntersection::Aabb)
}
(Token::Word(word), span) => {
if let Some(ty) = self.constructor_type(lexer, word, span, ctx)? {
let ty_span = lexer.span_with_start(span);
let components = self.arguments(lexer, ctx)?;
ast::Expression::Construct {
ty,
ty_span,
components,
}
} else if let Token::Paren('(') = lexer.peek().0 {
self.pop_rule_span(lexer);
return self.call_expression(lexer, word, span, ctx);
} else if ["bitcast", "coopLoad"].contains(&word) {
self.pop_rule_span(lexer);
return self.call_expression(lexer, word, span, ctx);
let ident = self.template_elaborated_ident(word, span, lexer, ctx)?;
if let Token::Paren('(') = lexer.peek().0 {
let arguments = self.arguments(lexer, ctx)?;
ctx.unresolved.insert(ast::Dependency {
ident: word,
usage: span,
});
ast::Expression::Call(ast::CallPhrase {
function: ident,
arguments,
})
} else {
let ident = self.ident_expr(word, span, ctx);
ast::Expression::Ident(ident)
}
}
@@ -1117,6 +673,12 @@ impl Parser {
}
(Token::Word(word), span) => {
let ident = this.ident_expr(word, span, ctx);
let ident = ast::TemplateElaboratedIdent {
ident,
ident_span: span,
template_list: Vec::new(),
template_list_span: Span::UNDEFINED,
};
let ident = ctx.expressions.append(ast::Expression::Ident(ident), span);
this.component_or_swizzle_specifier(span, lexer, ctx, ident)?
}
@@ -1330,7 +892,7 @@ impl Parser {
ctx: &mut ExpressionContext<'a, '_, '_>,
) -> Result<'a, ast::GlobalVariable<'a>> {
self.push_rule_span(Rule::VariableDecl, lexer);
let template_list = self.maybe_template_list(lexer, ctx)?;
let (template_list, _) = self.maybe_template_list(lexer, ctx)?;
let (name, ty) = self.optionally_typed_ident(lexer, ctx)?;
let init = if lexer.next_if(Token::Operation('=')) {
@@ -1429,7 +991,8 @@ impl Parser {
&mut self,
lexer: &mut Lexer<'a>,
ctx: &mut ExpressionContext<'a, '_, '_>,
) -> Result<'a, Option<Vec<Handle<ast::Expression<'a>>>>> {
) -> Result<'a, (Vec<Handle<ast::Expression<'a>>>, Span)> {
let start = lexer.start_byte_offset();
if lexer.next_if(Token::TemplateArgsStart) {
let mut args = Vec::new();
args.push(self.expression(lexer, ctx)?);
@@ -1437,12 +1000,30 @@ impl Parser {
args.push(self.expression(lexer, ctx)?);
}
lexer.expect(Token::TemplateArgsEnd)?;
Ok(Some(args))
let span = lexer.span_from(start);
Ok((args, span))
} else {
Ok(None)
Ok((Vec::new(), Span::UNDEFINED))
}
}
fn template_elaborated_ident<'a>(
&mut self,
word: &'a str,
span: Span,
lexer: &mut Lexer<'a>,
ctx: &mut ExpressionContext<'a, '_, '_>,
) -> Result<'a, ast::TemplateElaboratedIdent<'a>> {
let ident = self.ident_expr(word, span, ctx);
let (template_list, template_list_span) = self.maybe_template_list(lexer, ctx)?;
Ok(ast::TemplateElaboratedIdent {
ident,
ident_span: span,
template_list,
template_list_span,
})
}
/// Parses `<T>`, returning T and span of T
fn singular_generic<'a>(
&mut self,
@@ -2145,38 +1726,44 @@ impl Parser {
}
/// Parse a function call statement.
/// Expects `ident` to be consumed (not in the lexer).
fn func_call_statement<'a>(
/// Expects `token` to be consumed (not in the lexer).
fn maybe_func_call_statement<'a>(
&mut self,
lexer: &mut Lexer<'a>,
ident: &'a str,
ident_span: Span,
context: &mut ExpressionContext<'a, '_, '_>,
block: &mut ast::Block<'a>,
) -> Result<'a, ()> {
token: TokenSpan<'a>,
) -> Result<'a, bool> {
let (name, name_span) = match token {
(Token::Word(name), span) => (name, span),
_ => return Ok(false),
};
let ident = self.template_elaborated_ident(name, name_span, lexer, context)?;
if ident.template_list.is_empty() && !matches!(lexer.peek(), (Token::Paren('('), _)) {
return Ok(false);
}
self.push_rule_span(Rule::SingularExpr, lexer);
context.unresolved.insert(ast::Dependency {
ident,
usage: ident_span,
ident: name,
usage: name_span,
});
let arguments = self.arguments(lexer, context)?;
let span = lexer.span_with_start(ident_span);
let span = lexer.span_with_start(name_span);
block.stmts.push(ast::Statement {
kind: ast::StatementKind::Call {
function: ast::Ident {
name: ident,
span: ident_span,
},
kind: ast::StatementKind::Call(ast::CallPhrase {
function: ident,
arguments,
},
}),
span,
});
self.pop_rule_span(lexer);
Ok(())
Ok(true)
}
/// Parses func_call_statement and variable_updating_statement
@@ -2187,12 +1774,10 @@ impl Parser {
block: &mut ast::Block<'a>,
token: TokenSpan<'a>,
) -> Result<'a, ()> {
match token {
(Token::Word(name), span) if matches!(lexer.peek(), (Token::Paren('('), _)) => {
self.func_call_statement(lexer, name, span, context, block)
}
token => self.variable_updating_statement(lexer, context, block, token),
if !self.maybe_func_call_statement(lexer, context, block, token)? {
self.variable_updating_statement(lexer, context, block, token)?;
}
Ok(())
}
/// Parses variable_or_value_statement, func_call_statement and variable_updating_statement.
@@ -3239,7 +2824,7 @@ impl Parser {
}
}
lexer.enable_extensions = enable_extensions.clone();
lexer.enable_extensions = enable_extensions;
tu.enable_extensions = enable_extensions;
tu.diagnostic_filter_leaf =
Self::write_diagnostic_filters(&mut tu.diagnostic_filters, diagnostic_filters, None);
+98
View File
@@ -972,6 +972,104 @@ error: unused expressions for template
│ │\x20\x20\x20\x20\x20\x20\x20\x20
│ unused
",
);
}
#[test]
fn unused_template_list_for_fn() {
assert_parse_err(
"
fn inner_test() {}
fn test() {
inner_test<unused_template_arg>();
}
",
"\
error: unused expressions for template
┌─ wgsl:4:16
│
4 │ inner_test<unused_template_arg>();
│ ^^^^^^^^^^^^^^^^^^^ unused
",
);
}
#[test]
fn unused_template_list_for_struct() {
assert_parse_err(
"
struct test_struct {}
fn test() {
_ = test_struct<unused_template_arg>();
}
",
"\
error: unused expressions for template
┌─ wgsl:4:21
│
4 │ _ = test_struct<unused_template_arg>();
│ ^^^^^^^^^^^^^^^^^^^ unused
",
);
}
#[test]
fn unused_template_list_for_alias() {
assert_parse_err(
"
alias test_alias = f32;
fn test() {
_ = test_alias<unused_template_arg>();
}
",
"\
error: unused expressions for template
┌─ wgsl:4:20
│
4 │ _ = test_alias<unused_template_arg>();
│ ^^^^^^^^^^^^^^^^^^^ unused
",
);
}
#[test]
fn unexpected_template() {
assert_parse_err(
"
fn vertex() -> vec4<f32> {
return vec4<f32>;
}
",
"\
error: unexpected template
┌─ wgsl:3:12
│
3 │ return vec4<f32>;
│ ^^^^^^^^^ expected identifier
",
);
}
#[test]
fn expected_template_arg() {
assert_parse_err(
"
fn test() {
bitcast(8);
}
",
"\
error: `bitcast` needs a template argument specified: `T`, a type
┌─ wgsl:3:5
│
3 │ bitcast(8);
│ ^^^^^^^ is missing a template argument
",
);
}
+4 -4
View File
@@ -248,11 +248,11 @@ fn type_not_constructible() {
_ = atomic<i32>(0);
}
"#,
r#"error: type `atomic` is not constructible
r#"error: type `atomic<i32>` is not constructible
┌─ wgsl:3:21
│
3 │ _ = atomic<i32>(0);
│ ^^^^^^ type is not constructible
│ ^^^^^^^^^^^ type is not constructible
"#,
);
@@ -2883,7 +2883,7 @@ fn function_returns_void() {
┌─ wgsl:7:18
│
7 │ let a = x();
│ ^
│ ^^^
│
= note: perhaps you meant to call the function in a separate statement?
@@ -4582,7 +4582,7 @@ fn cooperative_matrix_enable_extension() {
┌─ wgsl:2:13
│
2 │ let a = {ty}<f32, A>();
│ {carets} the `wgpu_cooperative_matrix` "Enable Extension" is needed for this functionality, but it is not currently enabled.
│ {carets}^^^^^^^^ the `wgpu_cooperative_matrix` "Enable Extension" is needed for this functionality, but it is not currently enabled.
│
= note: You can enable this extension by adding `enable wgpu_cooperative_matrix;` at the top of the shader, before any other items.
+16 -16
View File
@@ -14,15 +14,15 @@ OpDecorate %13 ArrayStride 4
%4 = OpTypeInt 32 1
%5 = OpTypeBool
%6 = OpTypeVector %4 4
%7 = OpTypeFloat 32
%8 = OpTypeVector %7 4
%8 = OpTypeFloat 32
%7 = OpTypeVector %8 4
%10 = OpConstant %3 2
%9 = OpTypeArray %7 %10
%9 = OpTypeArray %8 %10
%11 = OpTypeVector %4 3
%12 = OpTypeVector %5 2
%14 = OpConstant %3 9
%13 = OpTypeArray %4 %14
%15 = OpTypeVector %7 2
%15 = OpTypeVector %8 2
%16 = OpConstant %4 3
%17 = OpConstantTrue %5
%18 = OpConstantFalse %5
@@ -31,13 +31,13 @@ OpDecorate %13 ArrayStride 4
%21 = OpConstant %4 1
%22 = OpConstant %4 2
%23 = OpConstant %4 8
%24 = OpConstant %7 3.141
%25 = OpConstant %7 6.282
%26 = OpConstant %7 0.44444445
%27 = OpConstant %7 0
%28 = OpConstantComposite %8 %26 %27 %27 %27
%29 = OpConstant %7 4
%30 = OpConstant %7 5
%24 = OpConstant %8 3.141
%25 = OpConstant %8 6.282
%26 = OpConstant %8 0.44444445
%27 = OpConstant %8 0
%28 = OpConstantComposite %7 %26 %27 %27 %27
%29 = OpConstant %8 4
%30 = OpConstant %8 5
%31 = OpConstantComposite %15 %29 %30
%32 = OpConstantComposite %12 %17 %18
%35 = OpTypeFunction %2
@@ -58,10 +58,10 @@ OpDecorate %13 ArrayStride 4
%86 = OpConstant %3 30
%87 = OpConstant %3 0
%94 = OpConstantNull %3
%97 = OpConstant %7 1
%98 = OpConstant %7 2
%99 = OpConstantComposite %8 %98 %97 %97 %97
%101 = OpTypePointer Function %8
%97 = OpConstant %8 1
%98 = OpConstant %8 2
%99 = OpConstantComposite %7 %98 %97 %97 %97
%101 = OpTypePointer Function %7
%106 = OpTypePointer Function %9
%107 = OpConstantNull %9
%111 = OpConstantComposite %11 %21 %21 %21
@@ -81,7 +81,7 @@ OpDecorate %13 ArrayStride 4
%153 = OpConstant %4 9
%154 = OpConstantComposite %13 %21 %22 %16 %19 %151 %47 %152 %23 %153
%155 = OpConstantComposite %6 %21 %22 %16 %19
%157 = OpTypePointer Function %7
%157 = OpTypePointer Function %8
%160 = OpConstantNull %4
%162 = OpConstantNull %4
%164 = OpTypePointer Function %13