handle var decl template list in the lowerer

This commit is contained in:
teoxoy authored and Teodor Tanasoaia committed 2026-01-28 12:00:35 +01:00
1 parent cfd3434f83
commit 514d0e743d
7 files changed
+206 -40

No files matched your search

+21
View File
@@ -419,6 +419,9 @@ pub(crate) enum Error<'a> {
UnderspecifiedCooperativeMatrix,
InvalidCooperativeLoadType(Span),
UnsupportedCooperativeScalar(Span),
UnexpectedIdentForEnumerant(Span),
UnexpectedExprForEnumerant(Span),
UnusedArgsForTemplate(Vec<Span>),
}
impl From<ConflictingDiagnosticRuleError> for Error<'_> {
@@ -1413,6 +1416,24 @@ impl<'a> Error<'a> {
labels: vec![(span, "type needs the scalar type specified".into())],
notes: vec![format!("must be F32")],
},
Error::UnexpectedIdentForEnumerant(ident_span) => ParseError {
message: format!(
"identifier `{}` resolves to a declaration",
&source[ident_span]
),
labels: vec![(ident_span, "needs to resolve to a predeclared enumerant".into())],
notes: vec![],
},
Error::UnexpectedExprForEnumerant(expr_span) => ParseError {
message: "unexpected expression".to_string(),
labels: vec![(expr_span, "needs to be an identifier resolving to a predeclared enumerant".into())],
notes: vec![],
},
Error::UnusedArgsForTemplate(ref expr_spans) => ParseError {
message: "unused expressions for template".to_string(),
labels: expr_spans.iter().cloned().map(|span| -> (_, _){ (span, "unused".into()) }).collect(),
notes: vec![],
},
}
}
}
+71 -2
View File
@@ -7,11 +7,14 @@ 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::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},
@@ -1266,10 +1269,16 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
None
};
let space = Self::var_address_space(
&v.template_list,
&ctx.as_const(),
&tu.enable_extensions,
)?;
let handle = ctx.module.global_variables.append(
ir::GlobalVariable {
name: Some(v.name.name.to_string()),
space: v.space,
space,
binding,
ty,
init: initializer,
@@ -2576,6 +2585,66 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
}
}
fn enumerant(
expr: Handle<ast::Expression<'source>>,
ctx: &ExpressionContext<'source, '_, '_>,
) -> Result<'source, (&'source str, Span)> {
let span = ctx.ast_expressions.get_span(expr);
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)) => {
if ctx.globals.get(name).is_some() {
Err(Box::new(Error::UnexpectedIdentForEnumerant(span)))
} else {
Ok((name, span))
}
}
_ => Err(Box::new(Error::UnexpectedExprForEnumerant(span))),
}
}
fn var_address_space(
template_list: &Option<Vec<Handle<ast::Expression<'source>>>>,
ctx: &ExpressionContext<'source, '_, '_>,
enable_extensions: &EnableExtensions,
) -> Result<'source, ir::AddressSpace> {
let mut address_space = 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();
let (enumerant, span) = Self::enumerant(*address_space_expr, ctx)?;
address_space = conv::map_address_space(enumerant, span, enable_extensions)?;
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 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)));
}
}
Ok(address_space)
}
fn binary(
&mut self,
op: ir::BinaryOperator,
+1 -1
View File
@@ -167,7 +167,7 @@ pub struct ResourceBinding<'a> {
#[derive(Debug)]
pub struct GlobalVariable<'a> {
pub name: Ident<'a>,
pub space: crate::AddressSpace,
pub template_list: Option<Vec<Handle<Expression<'a>>>>,
pub binding: Option<ResourceBinding<'a>>,
pub ty: Option<Handle<Type<'a>>>,
pub init: Option<Handle<Expression<'a>>>,
+12
View File
@@ -34,6 +34,18 @@ pub fn map_address_space<'a>(
}
}
pub fn map_access_mode(word: &str, span: Span) -> Result<'_, crate::StorageAccess> {
match word {
"read" => Ok(crate::StorageAccess::LOAD),
"write" => Ok(crate::StorageAccess::STORE),
"read_write" => Ok(crate::StorageAccess::LOAD | crate::StorageAccess::STORE),
"atomic" => Ok(crate::StorageAccess::ATOMIC
| crate::StorageAccess::LOAD
| crate::StorageAccess::STORE),
_ => Err(Box::new(Error::UnknownAccess(span))),
}
}
pub fn map_built_in(
enable_extensions: &EnableExtensions,
word: &str,
+2 -16
View File
@@ -607,21 +607,6 @@ impl<'a> Lexer<'a> {
Ok((scalar, span))
}
pub(in crate::front::wgsl) fn next_storage_access(
&mut self,
) -> Result<'a, crate::StorageAccess> {
let (ident, span) = self.next_ident_with_span()?;
match ident {
"read" => Ok(crate::StorageAccess::LOAD),
"write" => Ok(crate::StorageAccess::STORE),
"read_write" => Ok(crate::StorageAccess::LOAD | crate::StorageAccess::STORE),
"atomic" => Ok(crate::StorageAccess::ATOMIC
| crate::StorageAccess::LOAD
| crate::StorageAccess::STORE),
_ => Err(Box::new(Error::UnknownAccess(span))),
}
}
pub(in crate::front::wgsl) fn next_format_generic(
&mut self,
) -> Result<'a, (crate::StorageFormat, crate::StorageAccess)> {
@@ -629,7 +614,8 @@ impl<'a> Lexer<'a> {
let (ident, ident_span) = self.next_ident_with_span()?;
let format = conv::map_storage_format(ident, ident_span)?;
self.expect(Token::Separator(','))?;
let access = self.next_storage_access()?;
let (ident, ident_span) = self.next_ident_with_span()?;
let access = conv::map_access_mode(ident, ident_span)?;
self.expect(Token::TemplateArgsEnd)?;
Ok((format, access))
}
+23 -21
View File
@@ -1330,24 +1330,7 @@ impl Parser {
ctx: &mut ExpressionContext<'a, '_, '_>,
) -> Result<'a, ast::GlobalVariable<'a>> {
self.push_rule_span(Rule::VariableDecl, lexer);
let mut space = crate::AddressSpace::Handle;
if lexer.next_if(Token::TemplateArgsStart) {
let (class_str, span) = lexer.next_ident_with_span()?;
space = match class_str {
"storage" => {
let access = if lexer.next_if(Token::Separator(',')) {
lexer.next_storage_access()?
} else {
// defaulting to `read`
crate::StorageAccess::LOAD
};
crate::AddressSpace::Storage { access }
}
_ => conv::map_address_space(class_str, span, &lexer.enable_extensions)?,
};
lexer.expect(Token::TemplateArgsEnd)?;
}
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('=')) {
@@ -1361,7 +1344,7 @@ impl Parser {
Ok(ast::GlobalVariable {
name,
space,
template_list,
binding: None,
ty,
init,
@@ -1442,6 +1425,24 @@ impl Parser {
Ok(members)
}
fn maybe_template_list<'a>(
&mut self,
lexer: &mut Lexer<'a>,
ctx: &mut ExpressionContext<'a, '_, '_>,
) -> Result<'a, Option<Vec<Handle<ast::Expression<'a>>>>> {
if lexer.next_if(Token::TemplateArgsStart) {
let mut args = Vec::new();
args.push(self.expression(lexer, ctx)?);
while lexer.next_if(Token::Separator(',')) && lexer.peek().0 != Token::TemplateArgsEnd {
args.push(self.expression(lexer, ctx)?);
}
lexer.expect(Token::TemplateArgsEnd)?;
Ok(Some(args))
} else {
Ok(None)
}
}
/// Parses `<T>`, returning T and span of T
fn singular_generic<'a>(
&mut self,
@@ -1773,9 +1774,10 @@ impl Parser {
let base = self.type_specifier(lexer, ctx)?;
if let crate::AddressSpace::Storage { ref mut access } = space {
*access = if lexer.end_of_generic_arguments() {
let result = lexer.next_storage_access()?;
let (ident, span) = lexer.next_ident_with_span()?;
let access = conv::map_access_mode(ident, span)?;
lexer.next_if(Token::Separator(','));
result
access
} else {
crate::StorageAccess::LOAD
};
+76
View File
@@ -900,3 +900,79 @@ error: found conflicting `diagnostic(…)` rule(s)
}
}
}
mod template {
use crate::front::wgsl::assert_parse_err;
#[test]
fn missing_template_end() {
assert_parse_err(
"
fn storage() {}
var<storage
",
"\
error: expected identifier, found \"<\"
┌─ wgsl:3:4
│
3 │ var<storage
│ ^ expected identifier
",
);
}
#[test]
fn enumerant_shadowing() {
assert_parse_err(
"
fn storage() {}
var<storage> s: u32;
",
"\
error: identifier `storage` resolves to a declaration
┌─ wgsl:3:5
│
3 │ var<storage> s: u32;
│ ^^^^^^^ needs to resolve to a predeclared enumerant
",
);
}
#[test]
fn unexpected_expr_as_enumerant() {
assert_parse_err(
"
var<1 + 1> s: u32;
",
"\
error: unexpected expression
┌─ wgsl:2:5
│
2 │ var<1 + 1> s: u32;
│ ^^^^^ needs to be an identifier resolving to a predeclared enumerant
",
);
}
#[test]
fn unused_exprs_for_template() {
assert_parse_err(
"
var<storage, read_write, extra0, extra1> s: u32;
",
"\
error: unused expressions for template
┌─ wgsl:2:26
│
2 │ var<storage, read_write, extra0, extra1> s: u32;
│ ^^^^^^ ^^^^^^ unused
│ │\x20\x20\x20\x20\x20\x20\x20\x20
│ unused
",
);
}
}