diff --git a/benches/criterion.rs b/benches/criterion.rs index 5093ab045..ad00cb59e 100644 --- a/benches/criterion.rs +++ b/benches/criterion.rs @@ -28,7 +28,7 @@ fn gather_inputs(folder: &str, extension: &str) -> Vec> { } fn parse_glsl(stage: naga::ShaderStage, inputs: &[Box<[u8]>]) { - let mut parser = naga::front::glsl::Parser::default(); + let mut parser = naga::front::glsl::Frontend::default(); let options = naga::front::glsl::Options { stage, defines: Default::default(), @@ -44,12 +44,12 @@ fn frontends(c: &mut Criterion) { #[cfg(all(feature = "wgsl-in", feature = "serialize", feature = "deserialize"))] group.bench_function("bin", |b| { let inputs_wgsl = gather_inputs("tests/in", "wgsl"); - let mut parser = naga::front::wgsl::Parser::new(); + let mut frontend = naga::front::wgsl::Frontend::new(); let inputs_bin = inputs_wgsl .iter() .map(|input| { let string = std::str::from_utf8(input).unwrap(); - let module = parser.parse(string).unwrap(); + let module = frontend.parse(string).unwrap(); bincode::serialize(&module).unwrap() }) .collect::>(); @@ -66,10 +66,10 @@ fn frontends(c: &mut Criterion) { .iter() .map(|input| std::str::from_utf8(input).unwrap()) .collect::>(); - let mut parser = naga::front::wgsl::Parser::new(); + let mut frontend = naga::front::wgsl::Frontend::new(); b.iter(move || { for &input in inputs.iter() { - parser.parse(input).unwrap(); + frontend.parse(input).unwrap(); } }); }); @@ -81,7 +81,7 @@ fn frontends(c: &mut Criterion) { for input in inputs.iter() { let spv = unsafe { slice::from_raw_parts(input.as_ptr() as *const u32, input.len() / 4) }; - let parser = naga::front::spv::Parser::new(spv.iter().cloned(), &options); + let parser = naga::front::spv::Frontend::new(spv.iter().cloned(), &options); parser.parse().unwrap(); } }); @@ -101,12 +101,12 @@ fn frontends(c: &mut Criterion) { #[cfg(feature = "wgsl-in")] fn gather_modules() -> Vec { let inputs = gather_inputs("tests/in", "wgsl"); - let mut parser = naga::front::wgsl::Parser::new(); + let mut frontend = naga::front::wgsl::Frontend::new(); inputs .iter() .map(|input| { let string = std::str::from_utf8(input).unwrap(); - parser.parse(string).unwrap() + frontend.parse(string).unwrap() }) .collect() } diff --git a/cli/src/bin/naga.rs b/cli/src/bin/naga.rs index ddf65f59c..b121dd52d 100644 --- a/cli/src/bin/naga.rs +++ b/cli/src/bin/naga.rs @@ -289,7 +289,7 @@ fn run() -> Result<(), Box> { } ext @ ("vert" | "frag" | "comp") => { let input = String::from_utf8(input)?; - let mut parser = naga::front::glsl::Parser::default(); + let mut parser = naga::front::glsl::Frontend::default(); ( parser diff --git a/src/front/glsl/builtins.rs b/src/front/glsl/builtins.rs index 7206bd2f3..4ff8add9a 100644 --- a/src/front/glsl/builtins.rs +++ b/src/front/glsl/builtins.rs @@ -4,7 +4,7 @@ use super::{ ParameterQualifier, }, context::Context, - Error, ErrorKind, Parser, Result, + Error, ErrorKind, Frontend, Result, }; use crate::{ BinaryOperator, Block, Constant, DerivativeAxis, Expression, Handle, ImageClass, @@ -1676,7 +1676,7 @@ impl MacroCall { /// finally returns the final expression with the correct result pub fn call( &self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, body: &mut Block, args: &mut [Handle], @@ -1688,8 +1688,14 @@ impl MacroCall { args[0] } MacroCall::SamplerShadow => { - sampled_to_depth(&mut parser.module, ctx, args[0], meta, &mut parser.errors); - parser.invalidate_expression(ctx, args[0], meta)?; + sampled_to_depth( + &mut frontend.module, + ctx, + args[0], + meta, + &mut frontend.errors, + ); + frontend.invalidate_expression(ctx, args[0], meta)?; ctx.samplers.insert(args[0], args[1]); args[0] } @@ -1702,7 +1708,7 @@ impl MacroCall { let mut coords = args[1]; if proj { - let size = match *parser.resolve_type(ctx, coords, meta)? { + let size = match *frontend.resolve_type(ctx, coords, meta)? { TypeInner::Vector { size, .. } => size, _ => unreachable!(), }; @@ -1748,7 +1754,7 @@ impl MacroCall { let extra = args.get(2).copied(); let comps = - parser.coordinate_components(ctx, args[0], coords, extra, meta, body)?; + frontend.coordinate_components(ctx, args[0], coords, extra, meta, body)?; let mut num_args = 2; @@ -1795,10 +1801,10 @@ impl MacroCall { true => { let offset_arg = args[num_args]; num_args += 1; - match parser.solve_constant(ctx, offset_arg, meta) { + match frontend.solve_constant(ctx, offset_arg, meta) { Ok(v) => Some(v), Err(e) => { - parser.errors.push(e); + frontend.errors.push(e); None } } @@ -1832,7 +1838,7 @@ impl MacroCall { if arrayed { let mut components = Vec::with_capacity(4); - let size = match *parser.resolve_type(ctx, expr, meta)? { + let size = match *frontend.resolve_type(ctx, expr, meta)? { TypeInner::Vector { size: ori_size, .. } => { for index in 0..(ori_size as u32) { components.push(ctx.add_expression( @@ -1862,7 +1868,7 @@ impl MacroCall { body, )); - let ty = parser.module.types.insert( + let ty = frontend.module.types.insert( Type { name: None, inner: TypeInner::Vector { @@ -1881,7 +1887,7 @@ impl MacroCall { } MacroCall::ImageLoad { multi } => { let comps = - parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; + frontend.coordinate_components(ctx, args[0], args[1], None, meta, body)?; let (sample, level) = match (multi, args.get(2)) { (_, None) => (None, None), (true, Some(&arg)) => (Some(arg), None), @@ -1901,7 +1907,7 @@ impl MacroCall { } MacroCall::ImageStore => { let comps = - parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?; + frontend.coordinate_components(ctx, args[0], args[1], None, meta, body)?; ctx.emit_restart(body); body.push( crate::Statement::ImageStore { @@ -2037,7 +2043,7 @@ impl MacroCall { body, ), MacroCall::Mod(size) => { - ctx.implicit_splat(parser, &mut args[1], meta, size)?; + ctx.implicit_splat(frontend, &mut args[1], meta, size)?; // x - y * floor(x / y) @@ -2081,7 +2087,7 @@ impl MacroCall { ) } MacroCall::Splatted(fun, size, i) => { - ctx.implicit_splat(parser, &mut args[i], meta, size)?; + ctx.implicit_splat(frontend, &mut args[i], meta, size)?; ctx.add_expression( Expression::Math { @@ -2105,8 +2111,8 @@ impl MacroCall { body, ), MacroCall::Clamp(size) => { - ctx.implicit_splat(parser, &mut args[1], meta, size)?; - ctx.implicit_splat(parser, &mut args[2], meta, size)?; + ctx.implicit_splat(frontend, &mut args[1], meta, size)?; + ctx.implicit_splat(frontend, &mut args[2], meta, size)?; ctx.add_expression( Expression::Math { @@ -2143,8 +2149,8 @@ impl MacroCall { return Ok(None); } MacroCall::SmoothStep { splatted } => { - ctx.implicit_splat(parser, &mut args[0], meta, splatted)?; - ctx.implicit_splat(parser, &mut args[1], meta, splatted)?; + ctx.implicit_splat(frontend, &mut args[0], meta, splatted)?; + ctx.implicit_splat(frontend, &mut args[1], meta, splatted)?; ctx.add_expression( Expression::Math { @@ -2202,7 +2208,7 @@ fn texture_call( /// Helper struct for texture calls with the separate components from the vector argument /// -/// Obtained by calling [`coordinate_components`](Parser::coordinate_components) +/// Obtained by calling [`coordinate_components`](Frontend::coordinate_components) #[derive(Debug)] struct CoordComponents { coordinate: Handle, @@ -2211,7 +2217,7 @@ struct CoordComponents { used_extra: bool, } -impl Parser { +impl Frontend { /// Helper function for texture calls, splits the vector argument into it's components fn coordinate_components( &mut self, diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs index 930cd4559..d7a56051b 100644 --- a/src/front/glsl/context.rs +++ b/src/front/glsl/context.rs @@ -5,7 +5,7 @@ use super::{ }, error::{Error, ErrorKind}, types::{scalar_components, type_power}, - Parser, Result, + Frontend, Result, }; use crate::{ front::{Emitter, Typifier}, @@ -61,7 +61,7 @@ pub struct Context { } impl Context { - pub fn new(parser: &Parser, body: &mut Block) -> Self { + pub fn new(frontend: &Frontend, body: &mut Block) -> Self { let mut this = Context { expressions: Arena::new(), locals: Arena::new(), @@ -80,8 +80,8 @@ impl Context { this.emit_start(); - for &(ref name, lookup) in parser.global_variables.iter() { - this.add_global(parser, name, lookup, body) + for &(ref name, lookup) in frontend.global_variables.iter() { + this.add_global(frontend, name, lookup, body) } this @@ -89,7 +89,7 @@ impl Context { pub fn add_global( &mut self, - parser: &Parser, + frontend: &Frontend, name: &str, GlobalLookup { kind, @@ -101,10 +101,10 @@ impl Context { self.emit_end(body); let (expr, load, constant) = match kind { GlobalLookupKind::Variable(v) => { - let span = parser.module.global_variables.get_span(v); + let span = frontend.module.global_variables.get_span(v); let res = ( self.expressions.append(Expression::GlobalVariable(v), span), - parser.module.global_variables[v].space != AddressSpace::Handle, + frontend.module.global_variables[v].space != AddressSpace::Handle, None, ); self.emit_start(); @@ -112,7 +112,7 @@ impl Context { res } GlobalLookupKind::BlockSelect(handle, index) => { - let span = parser.module.global_variables.get_span(handle); + let span = frontend.module.global_variables.get_span(handle); let base = self .expressions .append(Expression::GlobalVariable(handle), span); @@ -124,14 +124,14 @@ impl Context { ( expr, { - let ty = parser.module.global_variables[handle].ty; + let ty = frontend.module.global_variables[handle].ty; - match parser.module.types[ty].inner { + match frontend.module.types[ty].inner { TypeInner::Struct { ref members, .. } => { if let TypeInner::Array { size: crate::ArraySize::Dynamic, .. - } = parser.module.types[members[index as usize].ty].inner + } = frontend.module.types[members[index as usize].ty].inner { false } else { @@ -145,7 +145,7 @@ impl Context { ) } GlobalLookupKind::Constant(v, ty) => { - let span = parser.module.constants.get_span(v); + let span = frontend.module.constants.get_span(v); let res = ( self.expressions.append(Expression::Constant(v), span), false, @@ -241,7 +241,7 @@ impl Context { /// Add function argument to current scope pub fn add_function_arg( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, body: &mut Block, name_meta: Option<(String, Span)>, ty: Handle, @@ -255,14 +255,14 @@ impl Context { }; self.parameters.push(ty); - let opaque = match parser.module.types[ty].inner { + let opaque = match frontend.module.types[ty].inner { TypeInner::Image { .. } | TypeInner::Sampler { .. } => true, _ => false, }; if qualifier.is_lhs() { - let span = parser.module.types.get_span(arg.ty); - arg.ty = parser.module.types.insert( + let span = frontend.module.types.get_span(arg.ty); + arg.ty = frontend.module.types.insert( Type { name: None, inner: TypeInner::Pointer { @@ -345,12 +345,12 @@ impl Context { pub fn lower( &mut self, mut stmt: StmtContext, - parser: &mut Parser, + frontend: &mut Frontend, expr: Handle, pos: ExprPos, body: &mut Block, ) -> Result<(Option>, Span)> { - let res = self.lower_inner(&stmt, parser, expr, pos, body); + let res = self.lower_inner(&stmt, frontend, expr, pos, body); stmt.hir_exprs.clear(); self.stmt_ctx = Some(stmt); @@ -366,12 +366,12 @@ impl Context { pub fn lower_expect( &mut self, mut stmt: StmtContext, - parser: &mut Parser, + frontend: &mut Frontend, expr: Handle, pos: ExprPos, body: &mut Block, ) -> Result<(Handle, Span)> { - let res = self.lower_expect_inner(&stmt, parser, expr, pos, body); + let res = self.lower_expect_inner(&stmt, frontend, expr, pos, body); stmt.hir_exprs.clear(); self.stmt_ctx = Some(stmt); @@ -382,17 +382,17 @@ impl Context { /// internal implementation of [`lower_expect`](Self::lower_expect) /// /// this method is only public because it's used in - /// [`function_call`](Parser::function_call), unless you know what + /// [`function_call`](Frontend::function_call), unless you know what /// you're doing use [`lower_expect`](Self::lower_expect) pub fn lower_expect_inner( &mut self, stmt: &StmtContext, - parser: &mut Parser, + frontend: &mut Frontend, expr: Handle, pos: ExprPos, body: &mut Block, ) -> Result<(Handle, Span)> { - let (maybe_expr, meta) = self.lower_inner(stmt, parser, expr, pos, body)?; + let (maybe_expr, meta) = self.lower_inner(stmt, frontend, expr, pos, body)?; let expr = match maybe_expr { Some(e) => e, @@ -472,7 +472,7 @@ impl Context { fn lower_inner( &mut self, stmt: &StmtContext, - parser: &mut Parser, + frontend: &mut Frontend, expr: Handle, pos: ExprPos, body: &mut Block, @@ -484,18 +484,18 @@ impl Context { let handle = match *kind { HirExprKind::Access { base, index } => { let (index, index_meta) = - self.lower_expect_inner(stmt, parser, index, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, index, ExprPos::Rhs, body)?; let maybe_constant_index = match pos { // Don't try to generate `AccessIndex` if in a LHS position, since it // wouldn't produce a pointer. ExprPos::Lhs => None, - _ => parser.solve_constant(self, index, index_meta).ok(), + _ => frontend.solve_constant(self, index, index_meta).ok(), }; let base = self .lower_expect_inner( stmt, - parser, + frontend, base, pos.maybe_access_base(maybe_constant_index.is_some()), body, @@ -507,7 +507,7 @@ impl Context { Some(self.add_expression( Expression::AccessIndex { base, - index: match parser.module.constants[constant].inner { + index: match frontend.module.constants[constant].inner { crate::ConstantInner::Scalar { value: ScalarValue::Uint(i), .. @@ -528,7 +528,7 @@ impl Context { }); if ExprPos::Rhs == pos { - let resolved = parser.resolve_type(self, pointer, meta)?; + let resolved = frontend.resolve_type(self, pointer, meta)?; if resolved.pointer_space().is_some() { return Ok(( Some(self.add_expression(Expression::Load { pointer }, meta, body)), @@ -540,32 +540,38 @@ impl Context { pointer } HirExprKind::Select { base, ref field } => { - let base = self.lower_expect_inner(stmt, parser, base, pos, body)?.0; + let base = self.lower_expect_inner(stmt, frontend, base, pos, body)?.0; - parser.field_selection(self, pos, body, base, field, meta)? + frontend.field_selection(self, pos, body, base, field, meta)? } HirExprKind::Constant(constant) if pos != ExprPos::Lhs => { self.add_expression(Expression::Constant(constant), meta, body) } HirExprKind::Binary { left, op, right } if pos != ExprPos::Lhs => { let (mut left, left_meta) = - self.lower_expect_inner(stmt, parser, left, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, left, ExprPos::Rhs, body)?; let (mut right, right_meta) = - self.lower_expect_inner(stmt, parser, right, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, right, ExprPos::Rhs, body)?; match op { BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self - .implicit_conversion(parser, &mut right, right_meta, ScalarKind::Uint, 4)?, + .implicit_conversion( + frontend, + &mut right, + right_meta, + ScalarKind::Uint, + 4, + )?, _ => self.binary_implicit_conversion( - parser, &mut left, left_meta, &mut right, right_meta, + frontend, &mut left, left_meta, &mut right, right_meta, )?, } - parser.typifier_grow(self, left, left_meta)?; - parser.typifier_grow(self, right, right_meta)?; + frontend.typifier_grow(self, left, left_meta)?; + frontend.typifier_grow(self, right, right_meta)?; - let left_inner = self.typifier.get(left, &parser.module.types); - let right_inner = self.typifier.get(right, &parser.module.types); + let left_inner = self.typifier.get(left, &frontend.module.types); + let right_inner = self.typifier.get(right, &frontend.module.types); match (left_inner, right_inner) { ( @@ -588,7 +594,7 @@ impl Context { // Check that the two arguments have the same dimensions if !dimensions_ok || left_width != right_width { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( format!( "Cannot apply operation to {left_inner:?} and {right_inner:?}" @@ -634,7 +640,7 @@ impl Context { // Rebuild the matrix from the divided vectors self.expressions.append( Expression::Compose { - ty: parser.module.types.insert( + ty: frontend.module.types.insert( Type { name: None, inner: TypeInner::Matrix { @@ -819,7 +825,7 @@ impl Context { ) => { // Check that the two arguments have the same width if left_width != right_width { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( format!( "Cannot apply operation to {left_inner:?} and {right_inner:?}" @@ -874,7 +880,7 @@ impl Context { // Rebuild the matrix from the operation result vectors self.expressions.append( Expression::Compose { - ty: parser.module.types.insert( + ty: frontend.module.types.insert( Type { name: None, inner: TypeInner::Matrix { @@ -909,7 +915,7 @@ impl Context { ) => { // Check that the two arguments have the same width if left_width != right_width { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( format!( "Cannot apply operation to {left_inner:?} and {right_inner:?}" @@ -965,7 +971,7 @@ impl Context { // Rebuild the matrix from the operation result vectors self.expressions.append( Expression::Compose { - ty: parser.module.types.insert( + ty: frontend.module.types.insert( Type { name: None, inner: TypeInner::Matrix { @@ -993,7 +999,7 @@ impl Context { } HirExprKind::Unary { op, expr } if pos != ExprPos::Lhs => { let expr = self - .lower_expect_inner(stmt, parser, expr, ExprPos::Rhs, body)? + .lower_expect_inner(stmt, frontend, expr, ExprPos::Rhs, body)? .0; self.add_expression(Expression::Unary { op, expr }, meta, body) @@ -1001,7 +1007,7 @@ impl Context { HirExprKind::Variable(ref var) => match pos { ExprPos::Lhs => { if !var.mutable { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Variable cannot be used in LHS position".into(), ), @@ -1044,7 +1050,7 @@ impl Context { _ => var.expr, }, HirExprKind::Call(ref call) if pos != ExprPos::Lhs => { - let maybe_expr = parser.function_or_constructor_call( + let maybe_expr = frontend.function_or_constructor_call( self, stmt, body, @@ -1080,7 +1086,7 @@ impl Context { // Lower the condition first to the current bodyy let condition = self - .lower_expect_inner(stmt, parser, condition, ExprPos::Rhs, body)? + .lower_expect_inner(stmt, frontend, condition, ExprPos::Rhs, body)? .0; // Emit all expressions since we will be adding statements to @@ -1093,7 +1099,7 @@ impl Context { // Lower the `true` branch let (mut accept, accept_meta) = - self.lower_expect_inner(stmt, parser, accept, pos, &mut accept_body)?; + self.lower_expect_inner(stmt, frontend, accept, pos, &mut accept_body)?; // Flush the body of the `true` branch, to start emitting on the // `false` branch @@ -1101,7 +1107,7 @@ impl Context { // Lower the `false` branch let (mut reject, reject_meta) = - self.lower_expect_inner(stmt, parser, reject, pos, &mut reject_body)?; + self.lower_expect_inner(stmt, frontend, reject, pos, &mut reject_body)?; // Flush the body of the `false` branch self.emit_restart(&mut reject_body); @@ -1113,9 +1119,9 @@ impl Context { Some((reject_power, reject_width, reject_kind)), ) = ( // Get the components of both branches and calculate the type power - self.expr_scalar_components(parser, accept, accept_meta)? + self.expr_scalar_components(frontend, accept, accept_meta)? .and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))), - self.expr_scalar_components(parser, reject, reject_meta)? + self.expr_scalar_components(frontend, reject, reject_meta)? .and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))), ) { match accept_power.cmp(&reject_power) { @@ -1146,7 +1152,7 @@ impl Context { // We need to get the type of the resulting expression to create the local, // this must be done after implicit conversions to ensure both branches have // the same type. - let ty = parser.resolve_type_handle(self, accept, accept_meta)?; + let ty = frontend.resolve_type_handle(self, accept, accept_meta)?; // Add the local that will hold the result of our conditional let local = self.locals.append( @@ -1205,17 +1211,17 @@ impl Context { } HirExprKind::Assign { tgt, value } if ExprPos::Lhs != pos => { let (pointer, ptr_meta) = - self.lower_expect_inner(stmt, parser, tgt, ExprPos::Lhs, body)?; + self.lower_expect_inner(stmt, frontend, tgt, ExprPos::Lhs, body)?; let (mut value, value_meta) = - self.lower_expect_inner(stmt, parser, value, ExprPos::Rhs, body)?; + self.lower_expect_inner(stmt, frontend, value, ExprPos::Rhs, body)?; - let ty = match *parser.resolve_type(self, pointer, ptr_meta)? { - TypeInner::Pointer { base, .. } => &parser.module.types[base].inner, + let ty = match *frontend.resolve_type(self, pointer, ptr_meta)? { + TypeInner::Pointer { base, .. } => &frontend.module.types[base].inner, ref ty => ty, }; if let Some((kind, width)) = scalar_components(ty) { - self.implicit_conversion(parser, &mut value, value_meta, kind, width)?; + self.implicit_conversion(frontend, &mut value, value_meta, kind, width)?; } self.lower_store(pointer, value, meta, body); @@ -1224,7 +1230,7 @@ impl Context { } HirExprKind::PrePostfix { op, postfix, expr } if ExprPos::Lhs != pos => { let (pointer, _) = - self.lower_expect_inner(stmt, parser, expr, ExprPos::Lhs, body)?; + self.lower_expect_inner(stmt, frontend, expr, ExprPos::Lhs, body)?; let left = if let Expression::Swizzle { .. } = self.expressions[pointer] { pointer } else { @@ -1241,7 +1247,7 @@ impl Context { Some(crate::ConstantInner::Scalar { width, value }) }; - let res = match *parser.resolve_type(self, left, meta)? { + let res = match *frontend.resolve_type(self, left, meta)? { TypeInner::Scalar { kind, width } => { let ty = TypeInner::Scalar { kind, width }; make_constant_inner(kind, width).map(|i| (ty, i, None, None)) @@ -1268,7 +1274,7 @@ impl Context { let (ty_inner, inner, rows, columns) = match res { Some(res) => res, None => { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Increment/decrement only works on scalar/vector/matrix".into(), ), @@ -1278,7 +1284,7 @@ impl Context { } }; - let constant_1 = parser.module.constants.append( + let constant_1 = frontend.module.constants.append( Constant { name: None, specialization: None, @@ -1297,7 +1303,7 @@ impl Context { self.add_expression(Expression::Splat { size, value: right }, meta, body); if let Some(cols) = columns { - let ty = parser.module.types.insert( + let ty = frontend.module.types.insert( Type { name: None, inner: ty_inner, @@ -1333,21 +1339,22 @@ impl Context { } if ExprPos::Lhs != pos => { let args = args .iter() - .map(|e| self.lower_expect_inner(stmt, parser, *e, ExprPos::Rhs, body)) + .map(|e| self.lower_expect_inner(stmt, frontend, *e, ExprPos::Rhs, body)) .collect::>>()?; match name.as_ref() { "length" => { if !args.is_empty() { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( ".length() doesn't take any arguments".into(), ), meta, }); } - let lowered_array = - self.lower_expect_inner(stmt, parser, object, pos, body)?.0; - let array_type = parser.resolve_type(self, lowered_array, meta)?; + let lowered_array = self + .lower_expect_inner(stmt, frontend, object, pos, body)? + .0; + let array_type = frontend.resolve_type(self, lowered_array, meta)?; match *array_type { TypeInner::Array { @@ -1357,7 +1364,7 @@ impl Context { let mut array_length = self.add_expression(Expression::Constant(size), meta, body); self.forced_conversion( - parser, + frontend, &mut array_length, meta, ScalarKind::Sint, @@ -1411,22 +1418,22 @@ impl Context { pub fn expr_scalar_components( &mut self, - parser: &Parser, + frontend: &Frontend, expr: Handle, meta: Span, ) -> Result> { - let ty = parser.resolve_type(self, expr, meta)?; + let ty = frontend.resolve_type(self, expr, meta)?; Ok(scalar_components(ty)) } pub fn expr_power( &mut self, - parser: &Parser, + frontend: &Frontend, expr: Handle, meta: Span, ) -> Result> { Ok(self - .expr_scalar_components(parser, expr, meta)? + .expr_scalar_components(frontend, expr, meta)? .and_then(|(kind, width)| type_power(kind, width))) } @@ -1451,7 +1458,7 @@ impl Context { pub fn implicit_conversion( &mut self, - parser: &Parser, + frontend: &Frontend, expr: &mut Handle, meta: Span, kind: ScalarKind, @@ -1459,7 +1466,7 @@ impl Context { ) -> Result<()> { if let (Some(tgt_power), Some(expr_power)) = ( type_power(kind, width), - self.expr_power(parser, *expr, meta)?, + self.expr_power(frontend, *expr, meta)?, ) { if tgt_power > expr_power { self.conversion(expr, meta, kind, width)?; @@ -1471,14 +1478,14 @@ impl Context { pub fn forced_conversion( &mut self, - parser: &Parser, + frontend: &Frontend, expr: &mut Handle, meta: Span, kind: ScalarKind, width: crate::Bytes, ) -> Result<()> { if let Some((expr_scalar_kind, expr_width)) = - self.expr_scalar_components(parser, *expr, meta)? + self.expr_scalar_components(frontend, *expr, meta)? { if expr_scalar_kind != kind || expr_width != width { self.conversion(expr, meta, kind, width)?; @@ -1490,14 +1497,14 @@ impl Context { pub fn binary_implicit_conversion( &mut self, - parser: &Parser, + frontend: &Frontend, left: &mut Handle, left_meta: Span, right: &mut Handle, right_meta: Span, ) -> Result<()> { - let left_components = self.expr_scalar_components(parser, *left, left_meta)?; - let right_components = self.expr_scalar_components(parser, *right, right_meta)?; + let left_components = self.expr_scalar_components(frontend, *left, left_meta)?; + let right_components = self.expr_scalar_components(frontend, *right, right_meta)?; if let ( Some((left_power, left_width, left_kind)), @@ -1523,12 +1530,12 @@ impl Context { pub fn implicit_splat( &mut self, - parser: &Parser, + frontend: &Frontend, expr: &mut Handle, meta: Span, vector_size: Option, ) -> Result<()> { - let expr_type = parser.resolve_type(self, *expr, meta)?; + let expr_type = frontend.resolve_type(self, *expr, meta)?; if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { *expr = self diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs index 806008e5b..3718fc7ab 100644 --- a/src/front/glsl/functions.rs +++ b/src/front/glsl/functions.rs @@ -4,7 +4,7 @@ use super::{ context::{Context, ExprPos, StmtContext}, error::{Error, ErrorKind}, types::scalar_components, - Parser, Result, + Frontend, Result, }; use crate::{ front::glsl::types::type_power, proc::ensure_block_returns, AddressSpace, Arena, Block, @@ -14,7 +14,7 @@ use crate::{ }; use std::iter; -impl Parser { +impl Frontend { fn add_constant_value( &mut self, scalar_kind: ScalarKind, @@ -1032,7 +1032,7 @@ impl Parser { let void = result.is_none(); - let &mut Parser { + let &mut Frontend { ref mut lookup_function, ref mut module, .. @@ -1121,7 +1121,7 @@ impl Parser { ) { let void = result.is_none(); - let &mut Parser { + let &mut Frontend { ref mut lookup_function, ref mut module, .. diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 0e0b503d3..b799293e5 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -1,7 +1,7 @@ /*! Frontend for [GLSL][glsl] (OpenGL Shading Language). -To begin, take a look at the documentation for the [`Parser`](Parser). +To begin, take a look at the documentation for the [`Frontend`]. # Supported versions ## Vulkan @@ -37,7 +37,7 @@ mod variables; type Result = std::result::Result; -/// Per-shader options passed to [`parse`](Parser::parse). +/// Per-shader options passed to [`parse`](Frontend::parse). /// /// The [`From`](From) trait is implemented for [`ShaderStage`](ShaderStage) to /// provide a quick way to create a Options instance. @@ -79,7 +79,7 @@ pub struct ShaderMetadata { /// The GLSL profile specified in the shader trough the use of the /// `#version` preprocessor directive. pub profile: Profile, - /// The shader stage in the pipeline, passed to the [`parse`](Parser::parse) + /// The shader stage in the pipeline, passed to the [`parse`](Frontend::parse) /// method via the [`Options`](Options) struct. pub stage: ShaderStage, @@ -124,16 +124,16 @@ impl Default for ShaderMetadata { } } -/// The `Parser` is the central structure of the GLSL frontend. +/// The `Frontend` is the central structure of the GLSL frontend. /// -/// To instantiate a new `Parser` the [`Default`](Default) trait is used, so a -/// call to the associated function [`Parser::default`](Parser::default) will -/// return a new `Parser` instance. +/// To instantiate a new `Frontend` the [`Default`](Default) trait is used, so a +/// call to the associated function [`Frontend::default`](Frontend::default) will +/// return a new `Frontend` instance. /// -/// To parse a shader simply call the [`parse`](Parser::parse) method with a +/// To parse a shader simply call the [`parse`](Frontend::parse) method with a /// [`Options`](Options) struct and a [`&str`](str) holding the glsl code. /// -/// The `Parser` also provides the [`metadata`](Parser::metadata) to get some +/// The `Frontend` also provides the [`metadata`](Frontend::metadata) to get some /// further information about the previously parsed shader, like version and /// extensions used (see the documentation for /// [`ShaderMetadata`](ShaderMetadata) to see all the returned information) @@ -141,7 +141,7 @@ impl Default for ShaderMetadata { /// # Example usage /// ```rust /// use naga::ShaderStage; -/// use naga::front::glsl::{Parser, Options}; +/// use naga::front::glsl::{Frontend, Options}; /// /// let glsl = r#" /// #version 450 core @@ -149,20 +149,20 @@ impl Default for ShaderMetadata { /// void main() {} /// "#; /// -/// let mut parser = Parser::default(); +/// let mut frontend = Frontend::default(); /// let options = Options::from(ShaderStage::Vertex); -/// parser.parse(&options, glsl); +/// frontend.parse(&options, glsl); /// ``` /// /// # Reusability /// -/// If there's a need to parse more than one shader reusing the same `Parser` +/// If there's a need to parse more than one shader reusing the same `Frontend` /// instance may be beneficial since internal allocations will be reused. /// -/// Calling the [`parse`](Parser::parse) method multiple times will reset the -/// `Parser` so no extra care is needed when reusing. +/// Calling the [`parse`](Frontend::parse) method multiple times will reset the +/// `Frontend` so no extra care is needed when reusing. #[derive(Debug, Default)] -pub struct Parser { +pub struct Frontend { meta: ShaderMetadata, lookup_function: FastHashMap, @@ -179,7 +179,7 @@ pub struct Parser { module: Module, } -impl Parser { +impl Frontend { fn reset(&mut self, stage: ShaderStage) { self.meta.reset(stage); @@ -197,7 +197,7 @@ impl Parser { /// Parses a shader either outputting a shader [`Module`](Module) or a list /// of [`Error`](Error)s. /// - /// Multiple calls using the same `Parser` and different shaders are supported. + /// Multiple calls using the same `Frontend` and different shaders are supported. pub fn parse( &mut self, options: &Options, diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs index 2705fd904..ebcfc2fec 100644 --- a/src/front/glsl/parser.rs +++ b/src/front/glsl/parser.rs @@ -7,7 +7,7 @@ use super::{ token::{Directive, DirectiveKind}, token::{Token, TokenValue}, variables::{GlobalOrConstant, VarDeclaration}, - Parser, Result, + Frontend, Result, }; use crate::{arena::Handle, Block, Constant, ConstantInner, Expression, ScalarValue, Span, Type}; use core::convert::TryFrom; @@ -56,8 +56,8 @@ impl<'source> ParsingContext<'source> { Ok(()) } - pub fn expect_ident(&mut self, parser: &mut Parser) -> Result<(String, Span)> { - let token = self.bump(parser)?; + pub fn expect_ident(&mut self, frontend: &mut Frontend) -> Result<(String, Span)> { + let token = self.bump(frontend)?; match token.value { TokenValue::Identifier(name) => Ok((name, token.meta)), @@ -68,8 +68,8 @@ impl<'source> ParsingContext<'source> { } } - pub fn expect(&mut self, parser: &mut Parser, value: TokenValue) -> Result { - let token = self.bump(parser)?; + pub fn expect(&mut self, frontend: &mut Frontend, value: TokenValue) -> Result { + let token = self.bump(frontend)?; if token.value != value { Err(Error { @@ -81,7 +81,7 @@ impl<'source> ParsingContext<'source> { } } - pub fn next(&mut self, parser: &mut Parser) -> Option { + pub fn next(&mut self, frontend: &mut Frontend) -> Option { loop { if let Some(token) = self.backtracked_token.take() { self.last_meta = token.meta; @@ -96,9 +96,9 @@ impl<'source> ParsingContext<'source> { break Some(token); } LexerResultKind::Directive(directive) => { - parser.handle_directive(directive, res.meta) + frontend.handle_directive(directive, res.meta) } - LexerResultKind::Error(error) => parser.errors.push(Error { + LexerResultKind::Error(error) => frontend.errors.push(Error { kind: ErrorKind::PreprocessorError(error), meta: res.meta, }), @@ -106,23 +106,23 @@ impl<'source> ParsingContext<'source> { } } - pub fn bump(&mut self, parser: &mut Parser) -> Result { - self.next(parser).ok_or(Error { + pub fn bump(&mut self, frontend: &mut Frontend) -> Result { + self.next(frontend).ok_or(Error { kind: ErrorKind::EndOfFile, meta: self.last_meta, }) } /// Returns None on the end of the file rather than an error like other methods - pub fn bump_if(&mut self, parser: &mut Parser, value: TokenValue) -> Option { - if self.peek(parser).filter(|t| t.value == value).is_some() { - self.bump(parser).ok() + pub fn bump_if(&mut self, frontend: &mut Frontend, value: TokenValue) -> Option { + if self.peek(frontend).filter(|t| t.value == value).is_some() { + self.bump(frontend).ok() } else { None } } - pub fn peek(&mut self, parser: &mut Parser) -> Option<&Token> { + pub fn peek(&mut self, frontend: &mut Frontend) -> Option<&Token> { loop { if let Some(ref token) = self.backtracked_token { break Some(token); @@ -142,9 +142,9 @@ impl<'source> ParsingContext<'source> { match res.kind { LexerResultKind::Directive(directive) => { - parser.handle_directive(directive, res.meta) + frontend.handle_directive(directive, res.meta) } - LexerResultKind::Error(error) => parser.errors.push(Error { + LexerResultKind::Error(error) => frontend.errors.push(Error { kind: ErrorKind::PreprocessorError(error), meta: res.meta, }), @@ -155,30 +155,30 @@ impl<'source> ParsingContext<'source> { } } - pub fn expect_peek(&mut self, parser: &mut Parser) -> Result<&Token> { + pub fn expect_peek(&mut self, frontend: &mut Frontend) -> Result<&Token> { let meta = self.last_meta; - self.peek(parser).ok_or(Error { + self.peek(frontend).ok_or(Error { kind: ErrorKind::EndOfFile, meta, }) } - pub fn parse(&mut self, parser: &mut Parser) -> Result<()> { + pub fn parse(&mut self, frontend: &mut Frontend) -> Result<()> { // Body and expression arena for global initialization let mut body = Block::new(); - let mut ctx = Context::new(parser, &mut body); + let mut ctx = Context::new(frontend, &mut body); - while self.peek(parser).is_some() { - self.parse_external_declaration(parser, &mut ctx, &mut body)?; + while self.peek(frontend).is_some() { + self.parse_external_declaration(frontend, &mut ctx, &mut body)?; } // Add an `EntryPoint` to `parser.module` for `main`, if a // suitable overload exists. Error out if we can't find one. - if let Some(declaration) = parser.lookup_function.get("main") { + if let Some(declaration) = frontend.lookup_function.get("main") { for decl in declaration.overloads.iter() { if let FunctionKind::Call(handle) = decl.kind { if decl.defined && decl.parameters.is_empty() { - parser.add_entry_point(handle, body, ctx.expressions); + frontend.add_entry_point(handle, body, ctx.expressions); return Ok(()); } } @@ -191,10 +191,10 @@ impl<'source> ParsingContext<'source> { }) } - fn parse_uint_constant(&mut self, parser: &mut Parser) -> Result<(u32, Span)> { - let (value, meta) = self.parse_constant_expression(parser)?; + fn parse_uint_constant(&mut self, frontend: &mut Frontend) -> Result<(u32, Span)> { + let (value, meta) = self.parse_constant_expression(frontend)?; - let int = match parser.module.constants[value].inner { + let int = match frontend.module.constants[value].inner { ConstantInner::Scalar { value: ScalarValue::Uint(int), .. @@ -222,21 +222,21 @@ impl<'source> ParsingContext<'source> { fn parse_constant_expression( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ) -> Result<(Handle, Span)> { let mut block = Block::new(); - let mut ctx = Context::new(parser, &mut block); + let mut ctx = Context::new(frontend, &mut block); let mut stmt_ctx = ctx.stmt_ctx(); - let expr = self.parse_conditional(parser, &mut ctx, &mut stmt_ctx, &mut block, None)?; - let (root, meta) = ctx.lower_expect(stmt_ctx, parser, expr, ExprPos::Rhs, &mut block)?; + let expr = self.parse_conditional(frontend, &mut ctx, &mut stmt_ctx, &mut block, None)?; + let (root, meta) = ctx.lower_expect(stmt_ctx, frontend, expr, ExprPos::Rhs, &mut block)?; - Ok((parser.solve_constant(&ctx, root, meta)?, meta)) + Ok((frontend.solve_constant(&ctx, root, meta)?, meta)) } } -impl Parser { +impl Frontend { fn handle_directive(&mut self, directive: Directive, meta: Span) { let mut tokens = directive.tokens.into_iter(); @@ -409,7 +409,7 @@ pub struct DeclarationContext<'ctx, 'qualifiers> { impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> { fn add_var( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ty: Handle, name: String, init: Option>, @@ -425,14 +425,14 @@ impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> { match self.external { true => { - let global = parser.add_global_var(self.ctx, self.body, decl)?; + let global = frontend.add_global_var(self.ctx, self.body, decl)?; let expr = match global { GlobalOrConstant::Global(handle) => Expression::GlobalVariable(handle), GlobalOrConstant::Constant(handle) => Expression::Constant(handle), }; Ok(self.ctx.add_expression(expr, meta, self.body)) } - false => parser.add_local_var(self.ctx, self.body, decl), + false => frontend.add_local_var(self.ctx, self.body, decl), } } diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs index fe1c66e8f..3ae22559a 100644 --- a/src/front/glsl/parser/declarations.rs +++ b/src/front/glsl/parser/declarations.rs @@ -10,7 +10,7 @@ use crate::{ token::{Token, TokenValue}, types::scalar_components, variables::{GlobalOrConstant, VarDeclaration}, - Error, ErrorKind, Parser, Span, + Error, ErrorKind, Frontend, Span, }, proc::Alignment, AddressSpace, Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StructMember, @@ -71,19 +71,19 @@ fn element_or_member_type( impl<'source> ParsingContext<'source> { pub fn parse_external_declaration( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, global_ctx: &mut Context, global_body: &mut Block, ) -> Result<()> { if self - .parse_declaration(parser, global_ctx, global_body, true)? + .parse_declaration(frontend, global_ctx, global_body, true)? .is_none() { - let token = self.bump(parser)?; + let token = self.bump(frontend)?; match token.value { - TokenValue::Semicolon if parser.meta.version == 460 => Ok(()), + TokenValue::Semicolon if frontend.meta.version == 460 => Ok(()), _ => { - let expected = match parser.meta.version { + let expected = match frontend.meta.version { 460 => vec![TokenValue::Semicolon.into(), ExpectedToken::Eof], _ => vec![ExpectedToken::Eof], }; @@ -100,7 +100,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_initializer( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ty: Handle, ctx: &mut Context, body: &mut Block, @@ -113,20 +113,21 @@ impl<'source> ParsingContext<'source> { // initializer_list: // initializer // initializer_list COMMA initializer - if let Some(Token { mut meta, .. }) = self.bump_if(parser, TokenValue::LeftBrace) { + if let Some(Token { mut meta, .. }) = self.bump_if(frontend, TokenValue::LeftBrace) { // initializer_list let mut components = Vec::new(); loop { // The type expected to be parsed inside the initializer list - let new_ty = element_or_member_type(ty, components.len(), &mut parser.module.types); + let new_ty = + element_or_member_type(ty, components.len(), &mut frontend.module.types); - components.push(self.parse_initializer(parser, new_ty, ctx, body)?.0); + components.push(self.parse_initializer(frontend, new_ty, ctx, body)?.0); - let token = self.bump(parser)?; + let token = self.bump(frontend)?; match token.value { TokenValue::Comma => { if let Some(Token { meta: end_meta, .. }) = - self.bump_if(parser, TokenValue::RightBrace) + self.bump_if(frontend, TokenValue::RightBrace) { meta.subsume(end_meta); break; @@ -154,12 +155,13 @@ impl<'source> ParsingContext<'source> { )) } else { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_assignment(parser, ctx, &mut stmt, body)?; - let (mut init, init_meta) = ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; + let expr = self.parse_assignment(frontend, ctx, &mut stmt, body)?; + let (mut init, init_meta) = + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; - let scalar_components = scalar_components(&parser.module.types[ty].inner); + let scalar_components = scalar_components(&frontend.module.types[ty].inner); if let Some((kind, width)) = scalar_components { - ctx.implicit_conversion(parser, &mut init, init_meta, kind, width)?; + ctx.implicit_conversion(frontend, &mut init, init_meta, kind, width)?; } Ok((init, init_meta)) @@ -171,7 +173,7 @@ impl<'source> ParsingContext<'source> { // produced Error::InvalidToken if it isn't consumed pub fn parse_init_declarator_list( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, mut ty: Handle, ctx: &mut DeclarationContext, ) -> Result<()> { @@ -191,14 +193,14 @@ impl<'source> ParsingContext<'source> { // Consume any leading comma, e.g. this is valid: `float, a=1;` if self - .peek(parser) + .peek(frontend) .map_or(false, |t| t.value == TokenValue::Comma) { - self.next(parser); + self.next(frontend); } loop { - let token = self.bump(parser)?; + let token = self.bump(frontend)?; let name = match token.value { TokenValue::Semicolon => break, TokenValue::Identifier(name) => name, @@ -221,18 +223,18 @@ impl<'source> ParsingContext<'source> { // parse an array specifier if it exists // NOTE: unlike other parse methods this one doesn't expect an array specifier and // returns Ok(None) rather than an error if there is not one - self.parse_array_specifier(parser, &mut meta, &mut ty)?; + self.parse_array_specifier(frontend, &mut meta, &mut ty)?; let init = self - .bump_if(parser, TokenValue::Assign) + .bump_if(frontend, TokenValue::Assign) .map::, _>(|_| { let (mut expr, init_meta) = - self.parse_initializer(parser, ty, ctx.ctx, ctx.body)?; + self.parse_initializer(frontend, ty, ctx.ctx, ctx.body)?; - let scalar_components = scalar_components(&parser.module.types[ty].inner); + let scalar_components = scalar_components(&frontend.module.types[ty].inner); if let Some((kind, width)) = scalar_components { ctx.ctx - .implicit_conversion(parser, &mut expr, init_meta, kind, width)?; + .implicit_conversion(frontend, &mut expr, init_meta, kind, width)?; } meta.subsume(init_meta); @@ -244,7 +246,7 @@ impl<'source> ParsingContext<'source> { let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const; let maybe_constant = if ctx.external { if let Some((root, meta)) = init { - match parser.solve_constant(ctx.ctx, root, meta) { + match frontend.solve_constant(ctx.ctx, root, meta) { Ok(res) => Some(res), // If the declaration is external (global scope) and is constant qualified // then the initializer must be a constant expression @@ -258,14 +260,14 @@ impl<'source> ParsingContext<'source> { None }; - let pointer = ctx.add_var(parser, ty, name, maybe_constant, meta)?; + let pointer = ctx.add_var(frontend, ty, name, maybe_constant, meta)?; if let Some((value, _)) = init.filter(|_| maybe_constant.is_none()) { ctx.flush_expressions(); ctx.body.push(Statement::Store { pointer, value }, meta); } - let token = self.bump(parser)?; + let token = self.bump(frontend)?; match token.value { TokenValue::Semicolon => break, TokenValue::Comma => {} @@ -287,7 +289,7 @@ impl<'source> ParsingContext<'source> { /// `external` whether or not we are in a global or local context pub fn parse_declaration( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, body: &mut Block, external: bool, @@ -304,36 +306,36 @@ impl<'source> ParsingContext<'source> { // type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON // type_qualifier IDENTIFIER identifier_list SEMICOLON - if self.peek_type_qualifier(parser) || self.peek_type_name(parser) { - let mut qualifiers = self.parse_type_qualifiers(parser)?; + if self.peek_type_qualifier(frontend) || self.peek_type_name(frontend) { + let mut qualifiers = self.parse_type_qualifiers(frontend)?; - if self.peek_type_name(parser) { + if self.peek_type_name(frontend) { // This branch handles variables and function prototypes and if // external is true also function definitions - let (ty, mut meta) = self.parse_type(parser)?; + let (ty, mut meta) = self.parse_type(frontend)?; - let token = self.bump(parser)?; + let token = self.bump(frontend)?; let token_fallthrough = match token.value { - TokenValue::Identifier(name) => match self.expect_peek(parser)?.value { + TokenValue::Identifier(name) => match self.expect_peek(frontend)?.value { TokenValue::LeftParen => { // This branch handles function definition and prototypes - self.bump(parser)?; + self.bump(frontend)?; let result = ty.map(|ty| FunctionResult { ty, binding: None }); let mut body = Block::new(); - let mut context = Context::new(parser, &mut body); + let mut context = Context::new(frontend, &mut body); - self.parse_function_args(parser, &mut context, &mut body)?; + self.parse_function_args(frontend, &mut context, &mut body)?; - let end_meta = self.expect(parser, TokenValue::RightParen)?.meta; + let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta; meta.subsume(end_meta); - let token = self.bump(parser)?; + let token = self.bump(frontend)?; return match token.value { TokenValue::Semicolon => { // This branch handles function prototypes - parser.add_prototype(context, name, result, meta); + frontend.add_prototype(context, name, result, meta); Ok(Some(meta)) } @@ -345,13 +347,13 @@ impl<'source> ParsingContext<'source> { // parse the body self.parse_compound_statement( token.meta, - parser, + frontend, &mut context, &mut body, &mut None, )?; - parser.add_function(context, name, result, body, meta); + frontend.add_function(context, name, result, body, meta); Ok(Some(meta)) } @@ -396,9 +398,9 @@ impl<'source> ParsingContext<'source> { }; self.backtrack(token_fallthrough)?; - self.parse_init_declarator_list(parser, ty, &mut ctx)?; + self.parse_init_declarator_list(frontend, ty, &mut ctx)?; } else { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError("Declaration cannot have void type".into()), meta, }) @@ -410,12 +412,12 @@ impl<'source> ParsingContext<'source> { // ```glsl // layout(early_fragment_tests); // ``` - let token = self.bump(parser)?; + let token = self.bump(frontend)?; match token.value { TokenValue::Identifier(ty_name) => { - if self.bump_if(parser, TokenValue::LeftBrace).is_some() { + if self.bump_if(frontend, TokenValue::LeftBrace).is_some() { self.parse_block_declaration( - parser, + frontend, ctx, body, &mut qualifiers, @@ -425,10 +427,10 @@ impl<'source> ParsingContext<'source> { .map(Some) } else { if qualifiers.invariant.take().is_some() { - parser.make_variable_invariant(ctx, body, &ty_name, token.meta); + frontend.make_variable_invariant(ctx, body, &ty_name, token.meta); - qualifiers.unused_errors(&mut parser.errors); - self.expect(parser, TokenValue::Semicolon)?; + qualifiers.unused_errors(&mut frontend.errors); + self.expect(frontend, TokenValue::Semicolon)?; return Ok(Some(qualifiers.span)); } @@ -443,25 +445,25 @@ impl<'source> ParsingContext<'source> { } TokenValue::Semicolon => { if let Some(value) = - qualifiers.uint_layout_qualifier("local_size_x", &mut parser.errors) + qualifiers.uint_layout_qualifier("local_size_x", &mut frontend.errors) { - parser.meta.workgroup_size[0] = value; + frontend.meta.workgroup_size[0] = value; } if let Some(value) = - qualifiers.uint_layout_qualifier("local_size_y", &mut parser.errors) + qualifiers.uint_layout_qualifier("local_size_y", &mut frontend.errors) { - parser.meta.workgroup_size[1] = value; + frontend.meta.workgroup_size[1] = value; } if let Some(value) = - qualifiers.uint_layout_qualifier("local_size_z", &mut parser.errors) + qualifiers.uint_layout_qualifier("local_size_z", &mut frontend.errors) { - parser.meta.workgroup_size[2] = value; + frontend.meta.workgroup_size[2] = value; } - parser.meta.early_fragment_tests |= qualifiers - .none_layout_qualifier("early_fragment_tests", &mut parser.errors); + frontend.meta.early_fragment_tests |= qualifiers + .none_layout_qualifier("early_fragment_tests", &mut frontend.errors); - qualifiers.unused_errors(&mut parser.errors); + qualifiers.unused_errors(&mut frontend.errors); Ok(Some(qualifiers.span)) } @@ -475,12 +477,12 @@ impl<'source> ParsingContext<'source> { } } } else { - match self.peek(parser).map(|t| &t.value) { + match self.peek(frontend).map(|t| &t.value) { Some(&TokenValue::Precision) => { // PRECISION precision_qualifier type_specifier SEMICOLON - self.bump(parser)?; + self.bump(frontend)?; - let token = self.bump(parser)?; + let token = self.bump(frontend)?; let _ = match token.value { TokenValue::PrecisionQualifier(p) => p, _ => { @@ -498,14 +500,14 @@ impl<'source> ParsingContext<'source> { } }; - let (ty, meta) = self.parse_type_non_void(parser)?; + let (ty, meta) = self.parse_type_non_void(frontend)?; - match parser.module.types[ty].inner { + match frontend.module.types[ty].inner { TypeInner::Scalar { kind: ScalarKind::Float | ScalarKind::Sint, .. } => {} - _ => parser.errors.push(Error { + _ => frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Precision statement can only work on floats and ints".into(), ), @@ -513,7 +515,7 @@ impl<'source> ParsingContext<'source> { }), } - self.expect(parser, TokenValue::Semicolon)?; + self.expect(frontend, TokenValue::Semicolon)?; Ok(Some(meta)) } @@ -524,7 +526,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_block_declaration( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, body: &mut Block, qualifiers: &mut TypeQualifiers, @@ -546,10 +548,10 @@ impl<'source> ParsingContext<'source> { }; let mut members = Vec::new(); - let span = self.parse_struct_declaration_list(parser, &mut members, layout)?; - self.expect(parser, TokenValue::RightBrace)?; + let span = self.parse_struct_declaration_list(frontend, &mut members, layout)?; + self.expect(frontend, TokenValue::RightBrace)?; - let mut ty = parser.module.types.insert( + let mut ty = frontend.module.types.insert( Type { name: Some(ty_name), inner: TypeInner::Struct { @@ -560,13 +562,13 @@ impl<'source> ParsingContext<'source> { Default::default(), ); - let token = self.bump(parser)?; + let token = self.bump(frontend)?; let name = match token.value { TokenValue::Semicolon => None, TokenValue::Identifier(name) => { - self.parse_array_specifier(parser, &mut meta, &mut ty)?; + self.parse_array_specifier(frontend, &mut meta, &mut ty)?; - self.expect(parser, TokenValue::Semicolon)?; + self.expect(frontend, TokenValue::Semicolon)?; Some(name) } @@ -581,7 +583,7 @@ impl<'source> ParsingContext<'source> { } }; - let global = parser.add_global_var( + let global = frontend.add_global_var( ctx, body, VarDeclaration { @@ -605,9 +607,9 @@ impl<'source> ParsingContext<'source> { entry_arg: None, mutable: true, }; - ctx.add_global(parser, &k, lookup, body); + ctx.add_global(frontend, &k, lookup, body); - parser.global_variables.push((k, lookup)); + frontend.global_variables.push((k, lookup)); } Ok(meta) @@ -616,7 +618,7 @@ impl<'source> ParsingContext<'source> { // TODO: Accept layout arguments pub fn parse_struct_declaration_list( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, members: &mut Vec, layout: StructLayout, ) -> Result { @@ -626,22 +628,22 @@ impl<'source> ParsingContext<'source> { loop { // TODO: type_qualifier - let (mut ty, mut meta) = self.parse_type_non_void(parser)?; - let (name, end_meta) = self.expect_ident(parser)?; + let (mut ty, mut meta) = self.parse_type_non_void(frontend)?; + let (name, end_meta) = self.expect_ident(frontend)?; meta.subsume(end_meta); - self.parse_array_specifier(parser, &mut meta, &mut ty)?; + self.parse_array_specifier(frontend, &mut meta, &mut ty)?; - self.expect(parser, TokenValue::Semicolon)?; + self.expect(frontend, TokenValue::Semicolon)?; let info = offset::calculate_offset( ty, meta, layout, - &mut parser.module.types, - &parser.module.constants, - &mut parser.errors, + &mut frontend.module.types, + &frontend.module.constants, + &mut frontend.errors, ); let member_alignment = info.align; @@ -657,7 +659,7 @@ impl<'source> ParsingContext<'source> { span += info.span; - if let TokenValue::RightBrace = self.expect_peek(parser)?.value { + if let TokenValue::RightBrace = self.expect_peek(frontend)?.value { break; } } diff --git a/src/front/glsl/parser/expressions.rs b/src/front/glsl/parser/expressions.rs index ad9cf80a0..f09e58b6f 100644 --- a/src/front/glsl/parser/expressions.rs +++ b/src/front/glsl/parser/expressions.rs @@ -5,7 +5,7 @@ use crate::{ error::{ErrorKind, ExpectedToken}, parser::ParsingContext, token::{Token, TokenValue}, - Error, Parser, Result, Span, + Error, Frontend, Result, Span, }, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Handle, ScalarValue, Type, TypeInner, UnaryOperator, @@ -14,12 +14,12 @@ use crate::{ impl<'source> ParsingContext<'source> { pub fn parse_primary( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let mut token = self.bump(parser)?; + let mut token = self.bump(frontend)?; let (width, value) = match token.value { TokenValue::IntConstant(int) => ( @@ -36,8 +36,8 @@ impl<'source> ParsingContext<'source> { ), TokenValue::BoolConstant(value) => (1, ScalarValue::Bool(value)), TokenValue::LeftParen => { - let expr = self.parse_expression(parser, ctx, stmt, body)?; - let meta = self.expect(parser, TokenValue::RightParen)?.meta; + let expr = self.parse_expression(frontend, ctx, stmt, body)?; + let meta = self.expect(frontend, TokenValue::RightParen)?.meta; token.meta.subsume(meta); @@ -59,7 +59,7 @@ impl<'source> ParsingContext<'source> { } }; - let handle = parser.module.constants.fetch_or_append( + let handle = frontend.module.constants.fetch_or_append( Constant { name: None, specialization: None, @@ -79,20 +79,20 @@ impl<'source> ParsingContext<'source> { pub fn parse_function_call_args( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, meta: &mut Span, ) -> Result>> { let mut args = Vec::new(); - if let Some(token) = self.bump_if(parser, TokenValue::RightParen) { + if let Some(token) = self.bump_if(frontend, TokenValue::RightParen) { meta.subsume(token.meta); } else { loop { - args.push(self.parse_assignment(parser, ctx, stmt, body)?); + args.push(self.parse_assignment(frontend, ctx, stmt, body)?); - let token = self.bump(parser)?; + let token = self.bump(frontend)?; match token.value { TokenValue::Comma => {} TokenValue::RightParen => { @@ -117,26 +117,26 @@ impl<'source> ParsingContext<'source> { pub fn parse_postfix( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let mut base = if self.peek_type_name(parser) { - let (mut handle, mut meta) = self.parse_type_non_void(parser)?; + let mut base = if self.peek_type_name(frontend) { + let (mut handle, mut meta) = self.parse_type_non_void(frontend)?; - self.expect(parser, TokenValue::LeftParen)?; - let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; + self.expect(frontend, TokenValue::LeftParen)?; + let args = self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?; if let TypeInner::Array { size: ArraySize::Dynamic, stride, base, - } = parser.module.types[handle].inner + } = frontend.module.types[handle].inner { - let span = parser.module.types.get_span(handle); + let span = frontend.module.types.get_span(handle); - let constant = parser.module.constants.fetch_or_append( + let constant = frontend.module.constants.fetch_or_append( Constant { name: None, specialization: None, @@ -147,7 +147,7 @@ impl<'source> ParsingContext<'source> { }, Span::default(), ); - handle = parser.module.types.insert( + handle = frontend.module.types.insert( Type { name: None, inner: TypeInner::Array { @@ -170,13 +170,13 @@ impl<'source> ParsingContext<'source> { }, Default::default(), ) - } else if let TokenValue::Identifier(_) = self.expect_peek(parser)?.value { - let (name, mut meta) = self.expect_ident(parser)?; + } else if let TokenValue::Identifier(_) = self.expect_peek(frontend)?.value { + let (name, mut meta) = self.expect_ident(frontend)?; - let expr = if self.bump_if(parser, TokenValue::LeftParen).is_some() { - let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; + let expr = if self.bump_if(frontend, TokenValue::LeftParen).is_some() { + let args = self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?; - let kind = match parser.lookup_type.get(&name) { + let kind = match frontend.lookup_type.get(&name) { Some(ty) => FunctionCallKind::TypeConstructor(*ty), None => FunctionCallKind::Function(name), }; @@ -186,7 +186,7 @@ impl<'source> ParsingContext<'source> { meta, } } else { - let var = match parser.lookup_variable(ctx, body, &name, meta) { + let var = match frontend.lookup_variable(ctx, body, &name, meta) { Some(var) => var, None => { return Err(Error { @@ -204,20 +204,20 @@ impl<'source> ParsingContext<'source> { stmt.hir_exprs.append(expr, Default::default()) } else { - self.parse_primary(parser, ctx, stmt, body)? + self.parse_primary(frontend, ctx, stmt, body)? }; while let TokenValue::LeftBracket | TokenValue::Dot | TokenValue::Increment - | TokenValue::Decrement = self.expect_peek(parser)?.value + | TokenValue::Decrement = self.expect_peek(frontend)?.value { - let Token { value, mut meta } = self.bump(parser)?; + let Token { value, mut meta } = self.bump(frontend)?; match value { TokenValue::LeftBracket => { - let index = self.parse_expression(parser, ctx, stmt, body)?; - let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta; + let index = self.parse_expression(frontend, ctx, stmt, body)?; + let end_meta = self.expect(frontend, TokenValue::RightBracket)?.meta; meta.subsume(end_meta); base = stmt.hir_exprs.append( @@ -229,11 +229,11 @@ impl<'source> ParsingContext<'source> { ) } TokenValue::Dot => { - let (field, end_meta) = self.expect_ident(parser)?; + let (field, end_meta) = self.expect_ident(frontend)?; - if self.bump_if(parser, TokenValue::LeftParen).is_some() { + if self.bump_if(frontend, TokenValue::LeftParen).is_some() { let args = - self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?; + self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?; base = stmt.hir_exprs.append( HirExpr { @@ -283,16 +283,16 @@ impl<'source> ParsingContext<'source> { pub fn parse_unary( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - Ok(match self.expect_peek(parser)?.value { + Ok(match self.expect_peek(frontend)?.value { TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => { - let Token { value, mut meta } = self.bump(parser)?; + let Token { value, mut meta } = self.bump(frontend)?; - let expr = self.parse_unary(parser, ctx, stmt, body)?; + let expr = self.parse_unary(frontend, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[expr].meta; let kind = match value { @@ -312,9 +312,9 @@ impl<'source> ParsingContext<'source> { .append(HirExpr { kind, meta }, Default::default()) } TokenValue::Increment | TokenValue::Decrement => { - let Token { value, meta } = self.bump(parser)?; + let Token { value, meta } = self.bump(frontend)?; - let expr = self.parse_unary(parser, ctx, stmt, body)?; + let expr = self.parse_unary(frontend, ctx, stmt, body)?; stmt.hir_exprs.append( HirExpr { @@ -331,32 +331,32 @@ impl<'source> ParsingContext<'source> { Default::default(), ) } - _ => self.parse_postfix(parser, ctx, stmt, body)?, + _ => self.parse_postfix(frontend, ctx, stmt, body)?, }) } pub fn parse_binary( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, - passtrough: Option>, + passthrough: Option>, min_bp: u8, ) -> Result> { - let mut left = passtrough + let mut left = passthrough .ok_or(ErrorKind::EndOfFile /* Dummy error */) - .or_else(|_| self.parse_unary(parser, ctx, stmt, body))?; + .or_else(|_| self.parse_unary(frontend, ctx, stmt, body))?; let mut meta = stmt.hir_exprs[left].meta; - while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(parser)?.value) { + while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(frontend)?.value) { if l_bp < min_bp { break; } - let Token { value, .. } = self.bump(parser)?; + let Token { value, .. } = self.bump(frontend)?; - let right = self.parse_binary(parser, ctx, stmt, body, None, r_bp)?; + let right = self.parse_binary(frontend, ctx, stmt, body, None, r_bp)?; let end_meta = stmt.hir_exprs[right].meta; meta.subsume(end_meta); @@ -399,19 +399,19 @@ impl<'source> ParsingContext<'source> { pub fn parse_conditional( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, - passtrough: Option>, + passthrough: Option>, ) -> Result> { - let mut condition = self.parse_binary(parser, ctx, stmt, body, passtrough, 0)?; + let mut condition = self.parse_binary(frontend, ctx, stmt, body, passthrough, 0)?; let mut meta = stmt.hir_exprs[condition].meta; - if self.bump_if(parser, TokenValue::Question).is_some() { - let accept = self.parse_expression(parser, ctx, stmt, body)?; - self.expect(parser, TokenValue::Colon)?; - let reject = self.parse_assignment(parser, ctx, stmt, body)?; + if self.bump_if(frontend, TokenValue::Question).is_some() { + let accept = self.parse_expression(frontend, ctx, stmt, body)?; + self.expect(frontend, TokenValue::Colon)?; + let reject = self.parse_assignment(frontend, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[reject].meta; meta.subsume(end_meta); @@ -433,18 +433,18 @@ impl<'source> ParsingContext<'source> { pub fn parse_assignment( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let tgt = self.parse_unary(parser, ctx, stmt, body)?; + let tgt = self.parse_unary(frontend, ctx, stmt, body)?; let mut meta = stmt.hir_exprs[tgt].meta; - Ok(match self.expect_peek(parser)?.value { + Ok(match self.expect_peek(frontend)?.value { TokenValue::Assign => { - self.bump(parser)?; - let value = self.parse_assignment(parser, ctx, stmt, body)?; + self.bump(frontend)?; + let value = self.parse_assignment(frontend, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[value].meta; meta.subsume(end_meta); @@ -466,8 +466,8 @@ impl<'source> ParsingContext<'source> { | TokenValue::LeftShiftAssign | TokenValue::RightShiftAssign | TokenValue::XorAssign => { - let token = self.bump(parser)?; - let right = self.parse_assignment(parser, ctx, stmt, body)?; + let token = self.bump(frontend)?; + let right = self.parse_assignment(frontend, ctx, stmt, body)?; let end_meta = stmt.hir_exprs[right].meta; meta.subsume(end_meta); @@ -503,22 +503,22 @@ impl<'source> ParsingContext<'source> { Default::default(), ) } - _ => self.parse_conditional(parser, ctx, stmt, body, Some(tgt))?, + _ => self.parse_conditional(frontend, ctx, stmt, body, Some(tgt))?, }) } pub fn parse_expression( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, stmt: &mut StmtContext, body: &mut Block, ) -> Result> { - let mut expr = self.parse_assignment(parser, ctx, stmt, body)?; + let mut expr = self.parse_assignment(frontend, ctx, stmt, body)?; - while let TokenValue::Comma = self.expect_peek(parser)?.value { - self.bump(parser)?; - expr = self.parse_assignment(parser, ctx, stmt, body)?; + while let TokenValue::Comma = self.expect_peek(frontend)?.value { + self.bump(frontend)?; + expr = self.parse_assignment(frontend, ctx, stmt, body)?; } Ok(expr) diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs index 9ab3400eb..93988f82f 100644 --- a/src/front/glsl/parser/functions.rs +++ b/src/front/glsl/parser/functions.rs @@ -7,23 +7,23 @@ use crate::{ parser::ParsingContext, token::{Token, TokenValue}, variables::VarDeclaration, - Error, ErrorKind, Parser, Result, + Error, ErrorKind, Frontend, Result, }, Block, ConstantInner, Expression, ScalarValue, Statement, SwitchCase, UnaryOperator, }; impl<'source> ParsingContext<'source> { - pub fn peek_parameter_qualifier(&mut self, parser: &mut Parser) -> bool { - self.peek(parser).map_or(false, |t| match t.value { + pub fn peek_parameter_qualifier(&mut self, frontend: &mut Frontend) -> bool { + self.peek(frontend).map_or(false, |t| match t.value { TokenValue::In | TokenValue::Out | TokenValue::InOut | TokenValue::Const => true, _ => false, }) } /// Returns the parsed `ParameterQualifier` or `ParameterQualifier::In` - pub fn parse_parameter_qualifier(&mut self, parser: &mut Parser) -> ParameterQualifier { - if self.peek_parameter_qualifier(parser) { - match self.bump(parser).unwrap().value { + pub fn parse_parameter_qualifier(&mut self, frontend: &mut Frontend) -> ParameterQualifier { + if self.peek_parameter_qualifier(frontend) { + match self.bump(frontend).unwrap().value { TokenValue::In => ParameterQualifier::In, TokenValue::Out => ParameterQualifier::Out, TokenValue::InOut => ParameterQualifier::InOut, @@ -37,30 +37,30 @@ impl<'source> ParsingContext<'source> { pub fn parse_statement( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, body: &mut Block, terminator: &mut Option, ) -> Result> { // Type qualifiers always identify a declaration statement - if self.peek_type_qualifier(parser) { - return self.parse_declaration(parser, ctx, body, false); + if self.peek_type_qualifier(frontend) { + return self.parse_declaration(frontend, ctx, body, false); } // Type names can identify either declaration statements or type constructors // depending on wether the token following the type name is a `(` (LeftParen) - if self.peek_type_name(parser) { + if self.peek_type_name(frontend) { // Start by consuming the type name so that we can peek the token after it - let token = self.bump(parser)?; + let token = self.bump(frontend)?; // Peek the next token and check if it's a `(` (LeftParen) if so the statement // is a constructor, otherwise it's a declaration. We need to do the check // beforehand and not in the if since we will backtrack before the if - let declaration = TokenValue::LeftParen != self.expect_peek(parser)?.value; + let declaration = TokenValue::LeftParen != self.expect_peek(frontend)?.value; self.backtrack(token)?; if declaration { - return self.parse_declaration(parser, ctx, body, false); + return self.parse_declaration(frontend, ctx, body, false); } } @@ -73,32 +73,32 @@ impl<'source> ParsingContext<'source> { let &Token { ref value, mut meta, - } = self.expect_peek(parser)?; + } = self.expect_peek(frontend)?; let meta_rest = match *value { TokenValue::Continue => { - let meta = self.bump(parser)?.meta; + let meta = self.bump(frontend)?.meta; body.push(Statement::Continue, meta); terminator.get_or_insert(body.len()); - self.expect(parser, TokenValue::Semicolon)?.meta + self.expect(frontend, TokenValue::Semicolon)?.meta } TokenValue::Break => { - let meta = self.bump(parser)?.meta; + let meta = self.bump(frontend)?.meta; body.push(Statement::Break, meta); terminator.get_or_insert(body.len()); - self.expect(parser, TokenValue::Semicolon)?.meta + self.expect(frontend, TokenValue::Semicolon)?.meta } TokenValue::Return => { - self.bump(parser)?; - let (value, meta) = match self.expect_peek(parser)?.value { - TokenValue::Semicolon => (None, self.bump(parser)?.meta), + self.bump(frontend)?; + let (value, meta) = match self.expect_peek(frontend)?.value { + TokenValue::Semicolon => (None, self.bump(frontend)?.meta), _ => { // TODO: Implicit conversions let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - self.expect(parser, TokenValue::Semicolon)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + self.expect(frontend, TokenValue::Semicolon)?; let (handle, meta) = - ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; (Some(handle), meta) } }; @@ -111,39 +111,39 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::Discard => { - let meta = self.bump(parser)?.meta; + let meta = self.bump(frontend)?.meta; body.push(Statement::Kill, meta); terminator.get_or_insert(body.len()); - self.expect(parser, TokenValue::Semicolon)?.meta + self.expect(frontend, TokenValue::Semicolon)?.meta } TokenValue::If => { - let mut meta = self.bump(parser)?.meta; + let mut meta = self.bump(frontend)?.meta; - self.expect(parser, TokenValue::LeftParen)?; + self.expect(frontend, TokenValue::LeftParen)?; let condition = { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; let (handle, more_meta) = - ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; meta.subsume(more_meta); handle }; - self.expect(parser, TokenValue::RightParen)?; + self.expect(frontend, TokenValue::RightParen)?; ctx.emit_restart(body); let mut accept = Block::new(); if let Some(more_meta) = - self.parse_statement(parser, ctx, &mut accept, &mut None)? + self.parse_statement(frontend, ctx, &mut accept, &mut None)? { meta.subsume(more_meta) } let mut reject = Block::new(); - if self.bump_if(parser, TokenValue::Else).is_some() { + if self.bump_if(frontend, TokenValue::Else).is_some() { if let Some(more_meta) = - self.parse_statement(parser, ctx, &mut reject, &mut None)? + self.parse_statement(frontend, ctx, &mut reject, &mut None)? { meta.subsume(more_meta); } @@ -161,18 +161,19 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::Switch => { - let mut meta = self.bump(parser)?.meta; + let mut meta = self.bump(frontend)?.meta; let end_meta; - self.expect(parser, TokenValue::LeftParen)?; + self.expect(frontend, TokenValue::LeftParen)?; let selector = { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?.0 + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)? + .0 }; - self.expect(parser, TokenValue::RightParen)?; + self.expect(frontend, TokenValue::RightParen)?; ctx.emit_restart(body); @@ -180,19 +181,19 @@ impl<'source> ParsingContext<'source> { // Track if any default case is present in the switch statement. let mut default_present = false; - self.expect(parser, TokenValue::LeftBrace)?; + self.expect(frontend, TokenValue::LeftBrace)?; loop { - let value = match self.expect_peek(parser)?.value { + let value = match self.expect_peek(frontend)?.value { TokenValue::Case => { - self.bump(parser)?; + self.bump(frontend)?; let value = { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; let (root, meta) = - ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?; - let constant = parser.solve_constant(ctx, root, meta)?; + ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?; + let constant = frontend.solve_constant(ctx, root, meta)?; - match parser.module.constants[constant].inner { + match frontend.module.constants[constant].inner { ConstantInner::Scalar { value: ScalarValue::Sint(int), .. @@ -202,7 +203,7 @@ impl<'source> ParsingContext<'source> { .. } => int as i32, _ => { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Case values can only be integers".into(), ), @@ -216,16 +217,16 @@ impl<'source> ParsingContext<'source> { crate::SwitchValue::Integer(value) } TokenValue::Default => { - self.bump(parser)?; + self.bump(frontend)?; default_present = true; crate::SwitchValue::Default } TokenValue::RightBrace => { - end_meta = self.bump(parser)?.meta; + end_meta = self.bump(frontend)?.meta; break; } _ => { - let Token { value, meta } = self.bump(parser)?; + let Token { value, meta } = self.bump(frontend)?; return Err(Error { kind: ErrorKind::InvalidToken( value, @@ -240,18 +241,23 @@ impl<'source> ParsingContext<'source> { } }; - self.expect(parser, TokenValue::Colon)?; + self.expect(frontend, TokenValue::Colon)?; let mut body = Block::new(); let mut case_terminator = None; loop { - match self.expect_peek(parser)?.value { + match self.expect_peek(frontend)?.value { TokenValue::Case | TokenValue::Default | TokenValue::RightBrace => { break } _ => { - self.parse_statement(parser, ctx, &mut body, &mut case_terminator)?; + self.parse_statement( + frontend, + ctx, + &mut body, + &mut case_terminator, + )?; } } } @@ -284,7 +290,7 @@ impl<'source> ParsingContext<'source> { // also be checked because `break`s count as statements but // they aren't added to the body) if case.body.is_empty() && case.fall_through { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "last case/default label must be followed by statements".into(), ), @@ -315,17 +321,17 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::While => { - let mut meta = self.bump(parser)?.meta; + let mut meta = self.bump(frontend)?.meta; let mut loop_body = Block::new(); let mut stmt = ctx.stmt_ctx(); - self.expect(parser, TokenValue::LeftParen)?; - let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?; - meta.subsume(self.expect(parser, TokenValue::RightParen)?.meta); + self.expect(frontend, TokenValue::LeftParen)?; + let root = self.parse_expression(frontend, ctx, &mut stmt, &mut loop_body)?; + meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta); let (expr, expr_meta) = - ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?; + ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut loop_body)?; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -349,7 +355,7 @@ impl<'source> ParsingContext<'source> { meta.subsume(expr_meta); if let Some(body_meta) = - self.parse_statement(parser, ctx, &mut loop_body, &mut None)? + self.parse_statement(frontend, ctx, &mut loop_body, &mut None)? { meta.subsume(body_meta); } @@ -366,24 +372,24 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::Do => { - let mut meta = self.bump(parser)?.meta; + let mut meta = self.bump(frontend)?.meta; let mut loop_body = Block::new(); let mut terminator = None; - self.parse_statement(parser, ctx, &mut loop_body, &mut terminator)?; + self.parse_statement(frontend, ctx, &mut loop_body, &mut terminator)?; let mut stmt = ctx.stmt_ctx(); - self.expect(parser, TokenValue::While)?; - self.expect(parser, TokenValue::LeftParen)?; - let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?; - let end_meta = self.expect(parser, TokenValue::RightParen)?.meta; + self.expect(frontend, TokenValue::While)?; + self.expect(frontend, TokenValue::LeftParen)?; + let root = self.parse_expression(frontend, ctx, &mut stmt, &mut loop_body)?; + let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta; meta.subsume(end_meta); let (expr, expr_meta) = - ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?; + ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut loop_body)?; let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -420,58 +426,59 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::For => { - let mut meta = self.bump(parser)?.meta; + let mut meta = self.bump(frontend)?.meta; ctx.symbol_table.push_scope(); - self.expect(parser, TokenValue::LeftParen)?; + self.expect(frontend, TokenValue::LeftParen)?; - if self.bump_if(parser, TokenValue::Semicolon).is_none() { - if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { - self.parse_declaration(parser, ctx, body, false)?; + if self.bump_if(frontend, TokenValue::Semicolon).is_none() { + if self.peek_type_name(frontend) || self.peek_type_qualifier(frontend) { + self.parse_declaration(frontend, ctx, body, false)?; } else { let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?; - self.expect(parser, TokenValue::Semicolon)?; + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + ctx.lower(stmt, frontend, expr, ExprPos::Rhs, body)?; + self.expect(frontend, TokenValue::Semicolon)?; } } let (mut block, mut continuing) = (Block::new(), Block::new()); - if self.bump_if(parser, TokenValue::Semicolon).is_none() { - let (expr, expr_meta) = - if self.peek_type_name(parser) || self.peek_type_qualifier(parser) { - let mut qualifiers = self.parse_type_qualifiers(parser)?; - let (ty, mut meta) = self.parse_type_non_void(parser)?; - let name = self.expect_ident(parser)?.0; + if self.bump_if(frontend, TokenValue::Semicolon).is_none() { + let (expr, expr_meta) = if self.peek_type_name(frontend) + || self.peek_type_qualifier(frontend) + { + let mut qualifiers = self.parse_type_qualifiers(frontend)?; + let (ty, mut meta) = self.parse_type_non_void(frontend)?; + let name = self.expect_ident(frontend)?.0; - self.expect(parser, TokenValue::Assign)?; + self.expect(frontend, TokenValue::Assign)?; - let (value, end_meta) = - self.parse_initializer(parser, ty, ctx, &mut block)?; - meta.subsume(end_meta); + let (value, end_meta) = + self.parse_initializer(frontend, ty, ctx, &mut block)?; + meta.subsume(end_meta); - let decl = VarDeclaration { - qualifiers: &mut qualifiers, - ty, - name: Some(name), - init: None, - meta, - }; - - let pointer = parser.add_local_var(ctx, &mut block, decl)?; - - ctx.emit_restart(&mut block); - - block.push(Statement::Store { pointer, value }, meta); - - (value, end_meta) - } else { - let mut stmt = ctx.stmt_ctx(); - let root = self.parse_expression(parser, ctx, &mut stmt, &mut block)?; - ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut block)? + let decl = VarDeclaration { + qualifiers: &mut qualifiers, + ty, + name: Some(name), + init: None, + meta, }; + let pointer = frontend.add_local_var(ctx, &mut block, decl)?; + + ctx.emit_restart(&mut block); + + block.push(Statement::Store { pointer, value }, meta); + + (value, end_meta) + } else { + let mut stmt = ctx.stmt_ctx(); + let root = self.parse_expression(frontend, ctx, &mut stmt, &mut block)?; + ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut block)? + }; + let condition = ctx.add_expression( Expression::Unary { op: UnaryOperator::Not, @@ -492,22 +499,24 @@ impl<'source> ParsingContext<'source> { crate::Span::default(), ); - self.expect(parser, TokenValue::Semicolon)?; + self.expect(frontend, TokenValue::Semicolon)?; } - match self.expect_peek(parser)?.value { + match self.expect_peek(frontend)?.value { TokenValue::RightParen => {} _ => { let mut stmt = ctx.stmt_ctx(); let rest = - self.parse_expression(parser, ctx, &mut stmt, &mut continuing)?; - ctx.lower(stmt, parser, rest, ExprPos::Rhs, &mut continuing)?; + self.parse_expression(frontend, ctx, &mut stmt, &mut continuing)?; + ctx.lower(stmt, frontend, rest, ExprPos::Rhs, &mut continuing)?; } } - meta.subsume(self.expect(parser, TokenValue::RightParen)?.meta); + meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta); - if let Some(stmt_meta) = self.parse_statement(parser, ctx, &mut block, &mut None)? { + if let Some(stmt_meta) = + self.parse_statement(frontend, ctx, &mut block, &mut None)? + { meta.subsume(stmt_meta); } @@ -525,14 +534,14 @@ impl<'source> ParsingContext<'source> { meta } TokenValue::LeftBrace => { - let meta = self.bump(parser)?.meta; + let meta = self.bump(frontend)?.meta; let mut block = Block::new(); let mut block_terminator = None; let meta = self.parse_compound_statement( meta, - parser, + frontend, ctx, &mut block, &mut block_terminator, @@ -545,15 +554,15 @@ impl<'source> ParsingContext<'source> { meta } - TokenValue::Semicolon => self.bump(parser)?.meta, + TokenValue::Semicolon => self.bump(frontend)?.meta, _ => { // Attempt to force expression parsing for remainder of the // tokens. Unknown or invalid tokens will be caught there and // turned into an error. let mut stmt = ctx.stmt_ctx(); - let expr = self.parse_expression(parser, ctx, &mut stmt, body)?; - ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?; - self.expect(parser, TokenValue::Semicolon)?.meta + let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?; + ctx.lower(stmt, frontend, expr, ExprPos::Rhs, body)?; + self.expect(frontend, TokenValue::Semicolon)?.meta } }; @@ -564,7 +573,7 @@ impl<'source> ParsingContext<'source> { pub fn parse_compound_statement( &mut self, mut meta: Span, - parser: &mut Parser, + frontend: &mut Frontend, ctx: &mut Context, body: &mut Block, terminator: &mut Option, @@ -574,13 +583,13 @@ impl<'source> ParsingContext<'source> { loop { if let Some(Token { meta: brace_meta, .. - }) = self.bump_if(parser, TokenValue::RightBrace) + }) = self.bump_if(frontend, TokenValue::RightBrace) { meta.subsume(brace_meta); break; } - let stmt = self.parse_statement(parser, ctx, body, terminator)?; + let stmt = self.parse_statement(frontend, ctx, body, terminator)?; if let Some(stmt_meta) = stmt { meta.subsume(stmt_meta); @@ -598,32 +607,32 @@ impl<'source> ParsingContext<'source> { pub fn parse_function_args( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, context: &mut Context, body: &mut Block, ) -> Result<()> { - if self.bump_if(parser, TokenValue::Void).is_some() { + if self.bump_if(frontend, TokenValue::Void).is_some() { return Ok(()); } loop { - if self.peek_type_name(parser) || self.peek_parameter_qualifier(parser) { - let qualifier = self.parse_parameter_qualifier(parser); - let mut ty = self.parse_type_non_void(parser)?.0; + if self.peek_type_name(frontend) || self.peek_parameter_qualifier(frontend) { + let qualifier = self.parse_parameter_qualifier(frontend); + let mut ty = self.parse_type_non_void(frontend)?.0; - match self.expect_peek(parser)?.value { + match self.expect_peek(frontend)?.value { TokenValue::Comma => { - self.bump(parser)?; - context.add_function_arg(parser, body, None, ty, qualifier); + self.bump(frontend)?; + context.add_function_arg(frontend, body, None, ty, qualifier); continue; } TokenValue::Identifier(_) => { - let mut name = self.expect_ident(parser)?; - self.parse_array_specifier(parser, &mut name.1, &mut ty)?; + let mut name = self.expect_ident(frontend)?; + self.parse_array_specifier(frontend, &mut name.1, &mut ty)?; - context.add_function_arg(parser, body, Some(name), ty, qualifier); + context.add_function_arg(frontend, body, Some(name), ty, qualifier); - if self.bump_if(parser, TokenValue::Comma).is_some() { + if self.bump_if(frontend, TokenValue::Comma).is_some() { continue; } diff --git a/src/front/glsl/parser/types.rs b/src/front/glsl/parser/types.rs index 93396823e..08a70669a 100644 --- a/src/front/glsl/parser/types.rs +++ b/src/front/glsl/parser/types.rs @@ -4,7 +4,7 @@ use crate::{ error::ExpectedToken, parser::ParsingContext, token::{Token, TokenValue}, - Error, ErrorKind, Parser, Result, + Error, ErrorKind, Frontend, Result, }, AddressSpace, ArraySize, Handle, Span, Type, TypeInner, }; @@ -14,50 +14,51 @@ impl<'source> ParsingContext<'source> { /// and modifying the type handle if it exists pub fn parse_array_specifier( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, span: &mut Span, ty: &mut Handle, ) -> Result<()> { - while self.parse_array_specifier_single(parser, span, ty)? {} + while self.parse_array_specifier_single(frontend, span, ty)? {} Ok(()) } /// Implementation of [`Self::parse_array_specifier`] for a single array_specifier fn parse_array_specifier_single( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, span: &mut Span, ty: &mut Handle, ) -> Result { - if self.bump_if(parser, TokenValue::LeftBracket).is_some() { - let size = - if let Some(Token { meta, .. }) = self.bump_if(parser, TokenValue::RightBracket) { - span.subsume(meta); - ArraySize::Dynamic - } else { - let (value, constant_span) = self.parse_uint_constant(parser)?; - let constant = parser.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(value as u64), - }, + if self.bump_if(frontend, TokenValue::LeftBracket).is_some() { + let size = if let Some(Token { meta, .. }) = + self.bump_if(frontend, TokenValue::RightBracket) + { + span.subsume(meta); + ArraySize::Dynamic + } else { + let (value, constant_span) = self.parse_uint_constant(frontend)?; + let constant = frontend.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(value as u64), }, - constant_span, - ); - let end_span = self.expect(parser, TokenValue::RightBracket)?.meta; - span.subsume(end_span); - ArraySize::Constant(constant) - }; + }, + constant_span, + ); + let end_span = self.expect(frontend, TokenValue::RightBracket)?.meta; + span.subsume(end_span); + ArraySize::Constant(constant) + }; - parser + frontend .layouter - .update(&parser.module.types, &parser.module.constants) + .update(&frontend.module.types, &frontend.module.constants) .unwrap(); - let stride = parser.layouter[*ty].to_stride(); - *ty = parser.module.types.insert( + let stride = frontend.layouter[*ty].to_stride(); + *ty = frontend.module.types.insert( Type { name: None, inner: TypeInner::Array { @@ -75,31 +76,34 @@ impl<'source> ParsingContext<'source> { } } - pub fn parse_type(&mut self, parser: &mut Parser) -> Result<(Option>, Span)> { - let token = self.bump(parser)?; + pub fn parse_type(&mut self, frontend: &mut Frontend) -> Result<(Option>, Span)> { + let token = self.bump(frontend)?; let mut handle = match token.value { TokenValue::Void => return Ok((None, token.meta)), - TokenValue::TypeName(ty) => parser.module.types.insert(ty, token.meta), + TokenValue::TypeName(ty) => frontend.module.types.insert(ty, token.meta), TokenValue::Struct => { let mut meta = token.meta; - let ty_name = self.expect_ident(parser)?.0; - self.expect(parser, TokenValue::LeftBrace)?; + let ty_name = self.expect_ident(frontend)?.0; + self.expect(frontend, TokenValue::LeftBrace)?; let mut members = Vec::new(); - let span = - self.parse_struct_declaration_list(parser, &mut members, StructLayout::Std140)?; - let end_meta = self.expect(parser, TokenValue::RightBrace)?.meta; + let span = self.parse_struct_declaration_list( + frontend, + &mut members, + StructLayout::Std140, + )?; + let end_meta = self.expect(frontend, TokenValue::RightBrace)?.meta; meta.subsume(end_meta); - let ty = parser.module.types.insert( + let ty = frontend.module.types.insert( Type { name: Some(ty_name.clone()), inner: TypeInner::Struct { members, span }, }, meta, ); - parser.lookup_type.insert(ty_name, ty); + frontend.lookup_type.insert(ty_name, ty); ty } - TokenValue::Identifier(ident) => match parser.lookup_type.get(&ident) { + TokenValue::Identifier(ident) => match frontend.lookup_type.get(&ident) { Some(ty) => *ty, None => { return Err(Error { @@ -124,12 +128,12 @@ impl<'source> ParsingContext<'source> { }; let mut span = token.meta; - self.parse_array_specifier(parser, &mut span, &mut handle)?; + self.parse_array_specifier(frontend, &mut span, &mut handle)?; Ok((Some(handle), span)) } - pub fn parse_type_non_void(&mut self, parser: &mut Parser) -> Result<(Handle, Span)> { - let (maybe_ty, meta) = self.parse_type(parser)?; + pub fn parse_type_non_void(&mut self, frontend: &mut Frontend) -> Result<(Handle, Span)> { + let (maybe_ty, meta) = self.parse_type(frontend)?; let ty = maybe_ty.ok_or_else(|| Error { kind: ErrorKind::SemanticError("Type can't be void".into()), meta, @@ -138,8 +142,8 @@ impl<'source> ParsingContext<'source> { Ok((ty, meta)) } - pub fn peek_type_qualifier(&mut self, parser: &mut Parser) -> bool { - self.peek(parser).map_or(false, |t| match t.value { + pub fn peek_type_qualifier(&mut self, frontend: &mut Frontend) -> bool { + self.peek(frontend).map_or(false, |t| match t.value { TokenValue::Invariant | TokenValue::Interpolation(_) | TokenValue::Sampling(_) @@ -157,15 +161,18 @@ impl<'source> ParsingContext<'source> { }) } - pub fn parse_type_qualifiers<'a>(&mut self, parser: &mut Parser) -> Result> { + pub fn parse_type_qualifiers<'a>( + &mut self, + frontend: &mut Frontend, + ) -> Result> { let mut qualifiers = TypeQualifiers::default(); - while self.peek_type_qualifier(parser) { - let token = self.bump(parser)?; + while self.peek_type_qualifier(frontend) { + let token = self.bump(frontend)?; // Handle layout qualifiers outside the match since this can push multiple values if token.value == TokenValue::Layout { - self.parse_layout_qualifier_id_list(parser, &mut qualifiers)?; + self.parse_layout_qualifier_id_list(frontend, &mut qualifiers)?; continue; } @@ -174,7 +181,7 @@ impl<'source> ParsingContext<'source> { match token.value { TokenValue::Invariant => { if qualifiers.invariant.is_some() { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one invariant qualifier per declaration" .into(), @@ -187,7 +194,7 @@ impl<'source> ParsingContext<'source> { } TokenValue::Interpolation(i) => { if qualifiers.interpolation.is_some() { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one interpolation qualifier per declaration" .into(), @@ -225,7 +232,7 @@ impl<'source> ParsingContext<'source> { if StorageQualifier::AddressSpace(AddressSpace::Function) != qualifiers.storage.0 { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one storage qualifier per declaration".into(), ), @@ -237,7 +244,7 @@ impl<'source> ParsingContext<'source> { } TokenValue::Sampling(s) => { if qualifiers.sampling.is_some() { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one sampling qualifier per declaration" .into(), @@ -250,7 +257,7 @@ impl<'source> ParsingContext<'source> { } TokenValue::PrecisionQualifier(p) => { if qualifiers.precision.is_some() { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "Cannot use more than one precision qualifier per declaration" .into(), @@ -266,7 +273,7 @@ impl<'source> ParsingContext<'source> { .storage_access .get_or_insert((crate::StorageAccess::all(), Span::default())); if !storage_access.0.contains(!access) { - parser.errors.push(Error { + frontend.errors.push(Error { kind: ErrorKind::SemanticError( "The same memory qualifier can only be used once".into(), ), @@ -287,20 +294,20 @@ impl<'source> ParsingContext<'source> { pub fn parse_layout_qualifier_id_list( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, qualifiers: &mut TypeQualifiers, ) -> Result<()> { - self.expect(parser, TokenValue::LeftParen)?; + self.expect(frontend, TokenValue::LeftParen)?; loop { - self.parse_layout_qualifier_id(parser, &mut qualifiers.layout_qualifiers)?; + self.parse_layout_qualifier_id(frontend, &mut qualifiers.layout_qualifiers)?; - if self.bump_if(parser, TokenValue::Comma).is_some() { + if self.bump_if(frontend, TokenValue::Comma).is_some() { continue; } break; } - let token = self.expect(parser, TokenValue::RightParen)?; + let token = self.expect(frontend, TokenValue::RightParen)?; qualifiers.span.subsume(token.meta); Ok(()) @@ -308,14 +315,14 @@ impl<'source> ParsingContext<'source> { pub fn parse_layout_qualifier_id( &mut self, - parser: &mut Parser, + frontend: &mut Frontend, qualifiers: &mut crate::FastHashMap, ) -> Result<()> { // layout_qualifier_id: // IDENTIFIER // IDENTIFIER EQUAL constant_expression // SHARED - let mut token = self.bump(parser)?; + let mut token = self.bump(frontend)?; match token.value { TokenValue::Identifier(name) => { let (key, value) = match name.as_str() { @@ -332,11 +339,11 @@ impl<'source> ParsingContext<'source> { (QualifierKey::Format, QualifierValue::Format(format)) } else { let key = QualifierKey::String(name.into()); - let value = if self.bump_if(parser, TokenValue::Assign).is_some() { - let (value, end_meta) = match self.parse_uint_constant(parser) { + let value = if self.bump_if(frontend, TokenValue::Assign).is_some() { + let (value, end_meta) = match self.parse_uint_constant(frontend) { Ok(v) => v, Err(e) => { - parser.errors.push(e); + frontend.errors.push(e); (0, Span::default()) } }; @@ -354,7 +361,7 @@ impl<'source> ParsingContext<'source> { qualifiers.insert(key, (value, token.meta)); } - _ => parser.errors.push(Error { + _ => frontend.errors.push(Error { kind: ErrorKind::InvalidToken(token.value, vec![ExpectedToken::Identifier]), meta: token.meta, }), @@ -363,11 +370,11 @@ impl<'source> ParsingContext<'source> { Ok(()) } - pub fn peek_type_name(&mut self, parser: &mut Parser) -> bool { - self.peek(parser).map_or(false, |t| match t.value { + pub fn peek_type_name(&mut self, frontend: &mut Frontend) -> bool { + self.peek(frontend).map_or(false, |t| match t.value { TokenValue::TypeName(_) | TokenValue::Void => true, TokenValue::Struct => true, - TokenValue::Identifier(ref ident) => parser.lookup_type.contains_key(ident), + TokenValue::Identifier(ref ident) => frontend.lookup_type.contains_key(ident), _ => false, }) } diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs index df6edd21d..ae529a6fb 100644 --- a/src/front/glsl/parser_tests.rs +++ b/src/front/glsl/parser_tests.rs @@ -3,18 +3,18 @@ use super::{ error::ExpectedToken, error::{Error, ErrorKind}, token::TokenValue, - Options, Parser, Span, + Frontend, Options, Span, }; use crate::ShaderStage; use pp_rs::token::PreprocessorError; #[test] fn version() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); // invalid versions assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 99000\n void main(){}", @@ -28,7 +28,7 @@ fn version() { ); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 449\n void main(){}", @@ -42,7 +42,7 @@ fn version() { ); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 450 smart\n void main(){}", @@ -56,7 +56,7 @@ fn version() { ); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 450\nvoid main(){} #version 450", @@ -79,45 +79,45 @@ fn version() { ); // valid versions - parser + frontend .parse( &Options::from(ShaderStage::Vertex), " # version 450\nvoid main() {}", ) .unwrap(); assert_eq!( - (parser.metadata().version, parser.metadata().profile), + (frontend.metadata().version, frontend.metadata().profile), (450, Profile::Core) ); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 450\nvoid main() {}", ) .unwrap(); assert_eq!( - (parser.metadata().version, parser.metadata().profile), + (frontend.metadata().version, frontend.metadata().profile), (450, Profile::Core) ); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), "#version 450 core\nvoid main(void) {}", ) .unwrap(); assert_eq!( - (parser.metadata().version, parser.metadata().profile), + (frontend.metadata().version, frontend.metadata().profile), (450, Profile::Core) ); } #[test] fn control_flow() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -133,7 +133,7 @@ fn control_flow() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -147,7 +147,7 @@ fn control_flow() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -170,7 +170,7 @@ fn control_flow() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -188,7 +188,7 @@ fn control_flow() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -208,9 +208,9 @@ fn control_flow() { #[test] fn declarations() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -227,7 +227,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -244,7 +244,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -261,7 +261,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -278,7 +278,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -297,7 +297,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -309,7 +309,7 @@ fn declarations() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -324,9 +324,9 @@ fn declarations() { #[test] fn textures() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -346,9 +346,9 @@ fn textures() { #[test] fn functions() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -361,7 +361,7 @@ fn functions() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -375,7 +375,7 @@ fn functions() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -387,7 +387,7 @@ fn functions() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -402,7 +402,7 @@ fn functions() { .unwrap(); // Function overloading - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -429,7 +429,7 @@ fn functions() { .unwrap(); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -455,7 +455,7 @@ fn functions() { println!(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -474,7 +474,7 @@ fn functions() { .unwrap(); // Nested function call - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -489,7 +489,7 @@ fn functions() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -510,9 +510,9 @@ fn functions() { #[test] fn constants() { use crate::{Constant, ConstantInner, ScalarValue}; - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - let module = parser + let module = frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -556,9 +556,9 @@ fn constants() { #[test] fn function_overloading() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -582,9 +582,9 @@ fn function_overloading() { #[test] fn implicit_conversions() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -599,7 +599,7 @@ fn implicit_conversions() { .unwrap(); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -621,7 +621,7 @@ fn implicit_conversions() { ); assert_eq!( - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -645,9 +645,9 @@ fn implicit_conversions() { #[test] fn structs() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -661,7 +661,7 @@ fn structs() { ) .unwrap_err(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -675,7 +675,7 @@ fn structs() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -690,7 +690,7 @@ fn structs() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -706,7 +706,7 @@ fn structs() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -718,7 +718,7 @@ fn structs() { ) .unwrap_err(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -735,9 +735,9 @@ fn structs() { #[test] fn swizzles() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -752,7 +752,7 @@ fn swizzles() { ) .unwrap(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -765,7 +765,7 @@ fn swizzles() { ) .unwrap_err(); - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -781,10 +781,10 @@ fn swizzles() { #[test] fn expressions() { - let mut parser = Parser::default(); + let mut frontend = Frontend::default(); // Vector indexing - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -800,7 +800,7 @@ fn expressions() { .unwrap(); // Prefix increment/decrement - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" @@ -816,7 +816,7 @@ fn expressions() { .unwrap(); // Dynamic indexing of array - parser + frontend .parse( &Options::from(ShaderStage::Vertex), r#" diff --git a/src/front/glsl/types.rs b/src/front/glsl/types.rs index 29d6e692b..632378c60 100644 --- a/src/front/glsl/types.rs +++ b/src/front/glsl/types.rs @@ -1,4 +1,6 @@ -use super::{constants::ConstantSolver, context::Context, Error, ErrorKind, Parser, Result, Span}; +use super::{ + constants::ConstantSolver, context::Context, Error, ErrorKind, Frontend, Result, Span, +}; use crate::{ proc::ResolveContext, Bytes, Constant, Expression, Handle, ImageClass, ImageDimension, ScalarKind, Type, TypeInner, VectorSize, @@ -224,7 +226,7 @@ pub const fn type_power(kind: ScalarKind, width: Bytes) -> Option { }) } -impl Parser { +impl Frontend { /// Resolves the types of the expressions until `expr` (inclusive) /// /// This needs to be done before the [`typifier`] can be queried for diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs index e3fba754d..73fcb6e5e 100644 --- a/src/front/glsl/variables.rs +++ b/src/front/glsl/variables.rs @@ -2,7 +2,7 @@ use super::{ ast::*, context::{Context, ExprPos}, error::{Error, ErrorKind}, - Parser, Result, Span, + Frontend, Result, Span, }; use crate::{ AddressSpace, Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, @@ -18,7 +18,7 @@ pub struct VarDeclaration<'a, 'key> { pub meta: Span, } -/// Information about a builtin used in [`add_builtin`](Parser::add_builtin). +/// Information about a builtin used in [`add_builtin`](Frontend::add_builtin). struct BuiltInData { /// The type of the builtin. inner: TypeInner, @@ -35,7 +35,7 @@ pub enum GlobalOrConstant { Constant(Handle), } -impl Parser { +impl Frontend { /// Adds a builtin and returns a variable reference to it fn add_builtin( &mut self, diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs index 39987e62d..b43abcac3 100644 --- a/src/front/spv/function.rs +++ b/src/front/spv/function.rs @@ -14,7 +14,7 @@ pub struct MergeInstruction { pub continue_block_id: Option, } -impl> super::Parser { +impl> super::Frontend { // Registers a function call. It will generate a dummy handle to call, which // gets resolved after all the functions are processed. pub(super) fn add_call( diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs index 07681917b..7a70b3339 100644 --- a/src/front/spv/image.rs +++ b/src/front/spv/image.rs @@ -218,7 +218,7 @@ pub(super) fn patch_comparison_type( true } -impl> super::Parser { +impl> super::Frontend { pub(super) fn parse_image_couple(&mut self) -> Result<(), Error> { let _result_type_id = self.next()?; let result_id = self.next()?; diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 93a76178b..8b24a8e88 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -514,7 +514,7 @@ enum SignAnchor { Operand, } -pub struct Parser { +pub struct Frontend { data: I, data_offset: usize, state: ModuleState, @@ -565,9 +565,9 @@ pub struct Parser { builtin_usage: FastHashSet, } -impl> Parser { +impl> Frontend { pub fn new(data: I, options: &Options) -> Self { - Parser { + Frontend { data, data_offset: 0, state: ModuleState::Empty, @@ -5095,7 +5095,7 @@ pub fn parse_u8_slice(data: &[u8], options: &Options) -> Result)>, + notes: Vec, +} + +impl ParseError { + pub fn labels(&self) -> impl Iterator + ExactSizeIterator + '_ { + self.labels + .iter() + .map(|&(span, ref msg)| (span, msg.as_ref())) + } + + pub fn message(&self) -> &str { + &self.message + } + + fn diagnostic(&self) -> Diagnostic<()> { + let diagnostic = Diagnostic::error() + .with_message(self.message.to_string()) + .with_labels( + self.labels + .iter() + .map(|label| { + Label::primary((), label.0.to_range().unwrap()) + .with_message(label.1.to_string()) + }) + .collect(), + ) + .with_notes( + self.notes + .iter() + .map(|note| format!("note: {note}")) + .collect(), + ); + diagnostic + } + + /// Emits a summary of the error to standard error stream. + pub fn emit_to_stderr(&self, source: &str) { + self.emit_to_stderr_with_path(source, "wgsl") + } + + /// Emits a summary of the error to standard error stream. + pub fn emit_to_stderr_with_path(&self, source: &str, path: &str) { + let files = SimpleFile::new(path, source); + let config = codespan_reporting::term::Config::default(); + let writer = StandardStream::stderr(ColorChoice::Auto); + term::emit(&mut writer.lock(), &config, &files, &self.diagnostic()) + .expect("cannot write error"); + } + + /// Emits a summary of the error to a string. + pub fn emit_to_string(&self, source: &str) -> String { + self.emit_to_string_with_path(source, "wgsl") + } + + /// Emits a summary of the error to a string. + pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String { + let files = SimpleFile::new(path, source); + let config = codespan_reporting::term::Config::default(); + let mut writer = NoColor::new(Vec::new()); + term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error"); + String::from_utf8(writer.into_inner()).unwrap() + } + + /// Returns a [`SourceLocation`] for the first label in the error message. + pub fn location(&self, source: &str) -> Option { + self.labels.get(0).map(|label| label.0.location(source)) + } +} + +impl std::fmt::Display for ParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.message) + } +} + +impl std::error::Error for ParseError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + None + } +} + +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum ExpectedToken<'a> { + Token(Token<'a>), + Identifier, + Number, + Integer, + /// A compile-time constant expression. + Constant, + /// Expected: constant, parenthesized expression, identifier + PrimaryExpression, + /// Expected: assignment, increment/decrement expression + Assignment, + /// Expected: 'case', 'default', '}' + SwitchItem, + /// Expected: ',', ')' + WorkgroupSizeSeparator, + /// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof + GlobalItem, + /// Expected a type. + Type, + /// Access of `var`, `let`, `const`. + Variable, + /// Access of a function + Function, +} + +#[derive(Clone, Copy, Debug, Error, PartialEq)] +pub enum NumberError { + #[error("invalid numeric literal format")] + Invalid, + #[error("numeric literal not representable by target type")] + NotRepresentable, + #[error("unimplemented f16 type")] + UnimplementedF16, +} + +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum InvalidAssignmentType { + Other, + Swizzle, + ImmutableBinding, +} + +#[derive(Clone, Debug)] +pub enum Error<'a> { + Unexpected(Span, ExpectedToken<'a>), + UnexpectedComponents(Span), + BadNumber(Span, NumberError), + /// A negative signed integer literal where both signed and unsigned, + /// but only non-negative literals are allowed. + NegativeInt(Span), + BadU32Constant(Span), + BadMatrixScalarKind(Span, crate::ScalarKind, u8), + BadAccessor(Span), + BadTexture(Span), + BadTypeCast { + span: Span, + from_type: String, + to_type: String, + }, + BadTextureSampleType { + span: Span, + kind: crate::ScalarKind, + width: u8, + }, + BadIncrDecrReferenceType(Span), + InvalidResolve(ResolveError), + InvalidForInitializer(Span), + /// A break if appeared outside of a continuing block + InvalidBreakIf(Span), + InvalidGatherComponent(Span), + InvalidConstructorComponentType(Span, i32), + InvalidIdentifierUnderscore(Span), + ReservedIdentifierPrefix(Span), + UnknownAddressSpace(Span), + UnknownAttribute(Span), + UnknownBuiltin(Span), + UnknownAccess(Span), + UnknownIdent(Span, &'a str), + UnknownScalarType(Span), + UnknownType(Span), + UnknownStorageFormat(Span), + UnknownConservativeDepth(Span), + SizeAttributeTooLow(Span, u32), + AlignAttributeTooLow(Span, Alignment), + NonPowerOfTwoAlignAttribute(Span), + InconsistentBinding(Span), + TypeNotConstructible(Span), + TypeNotInferrable(Span), + InitializationTypeMismatch(Span, String, String), + MissingType(Span), + MissingAttribute(&'static str, Span), + InvalidAtomicPointer(Span), + InvalidAtomicOperandType(Span), + Pointer(&'static str, Span), + NotPointer(Span), + NotReference(&'static str, Span), + InvalidAssignment { + span: Span, + ty: InvalidAssignmentType, + }, + ReservedKeyword(Span), + /// Redefinition of an identifier (used for both module-scope and local redefinitions). + Redefinition { + /// Span of the identifier in the previous definition. + previous: Span, + + /// Span of the identifier in the new definition. + current: Span, + }, + /// A declaration refers to itself directly. + RecursiveDeclaration { + /// The location of the name of the declaration. + ident: Span, + + /// The point at which it is used. + usage: Span, + }, + /// A declaration refers to itself indirectly, through one or more other + /// definitions. + CyclicDeclaration { + /// The location of the name of some declaration in the cycle. + ident: Span, + + /// The edges of the cycle of references. + /// + /// Each `(decl, reference)` pair indicates that the declaration whose + /// name is `decl` has an identifier at `reference` whose definition is + /// the next declaration in the cycle. The last pair's `reference` is + /// the same identifier as `ident`, above. + path: Vec<(Span, Span)>, + }, + ConstExprUnsupported(Span), + InvalidSwitchValue { + uint: bool, + span: Span, + }, + CalledEntryPoint(Span), + WrongArgumentCount { + span: Span, + expected: Range, + found: u32, + }, + FunctionReturnsVoid(Span), + Other, +} + +impl<'a> Error<'a> { + pub(crate) fn as_parse_error(&self, source: &'a str) -> ParseError { + match *self { + Error::Unexpected(unexpected_span, expected) => { + let expected_str = match expected { + ExpectedToken::Token(token) => { + match token { + Token::Separator(c) => format!("'{c}'"), + Token::Paren(c) => format!("'{c}'"), + Token::Attribute => "@".to_string(), + Token::Number(_) => "number".to_string(), + Token::Word(s) => s.to_string(), + Token::Operation(c) => format!("operation ('{c}')"), + Token::LogicalOperation(c) => format!("logical operation ('{c}')"), + Token::ShiftOperation(c) => format!("bitshift ('{c}{c}')"), + Token::AssignmentOperation(c) if c=='<' || c=='>' => format!("bitshift ('{c}{c}=')"), + Token::AssignmentOperation(c) => format!("operation ('{c}=')"), + Token::IncrementOperation => "increment operation".to_string(), + Token::DecrementOperation => "decrement operation".to_string(), + Token::Arrow => "->".to_string(), + Token::Unknown(c) => format!("unknown ('{c}')"), + Token::Trivia => "trivia".to_string(), + Token::End => "end".to_string(), + } + } + ExpectedToken::Identifier => "identifier".to_string(), + ExpectedToken::Number => "32-bit signed integer literal".to_string(), + ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), + ExpectedToken::Constant => "compile-time constant".to_string(), + ExpectedToken::PrimaryExpression => "expression".to_string(), + ExpectedToken::Assignment => "assignment or increment/decrement".to_string(), + ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), + ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), + ExpectedToken::GlobalItem => "global item ('struct', 'const', 'var', 'type', ';', 'fn') or the end of the file".to_string(), + ExpectedToken::Type => "type".to_string(), + ExpectedToken::Variable => "variable access".to_string(), + ExpectedToken::Function => "function name".to_string(), + }; + ParseError { + message: format!( + "expected {}, found '{}'", + expected_str, &source[unexpected_span], + ), + labels: vec![(unexpected_span, format!("expected {expected_str}").into())], + notes: vec![], + } + } + Error::UnexpectedComponents(bad_span) => ParseError { + message: "unexpected components".to_string(), + labels: vec![(bad_span, "unexpected components".into())], + notes: vec![], + }, + Error::BadNumber(bad_span, ref err) => ParseError { + message: format!("{}: `{}`", err, &source[bad_span],), + labels: vec![(bad_span, err.to_string().into())], + notes: vec![], + }, + Error::NegativeInt(bad_span) => ParseError { + message: format!( + "expected non-negative integer literal, found `{}`", + &source[bad_span], + ), + labels: vec![(bad_span, "expected non-negative integer".into())], + notes: vec![], + }, + Error::BadU32Constant(bad_span) => ParseError { + message: format!( + "expected unsigned integer constant expression, found `{}`", + &source[bad_span], + ), + labels: vec![(bad_span, "expected unsigned integer".into())], + notes: vec![], + }, + Error::BadMatrixScalarKind(span, kind, width) => ParseError { + message: format!( + "matrix scalar type must be floating-point, but found `{}`", + kind.to_wgsl(width) + ), + labels: vec![(span, "must be floating-point (e.g. `f32`)".into())], + notes: vec![], + }, + Error::BadAccessor(accessor_span) => ParseError { + message: format!("invalid field accessor `{}`", &source[accessor_span],), + labels: vec![(accessor_span, "invalid accessor".into())], + notes: vec![], + }, + Error::UnknownIdent(ident_span, ident) => ParseError { + message: format!("no definition in scope for identifier: '{ident}'"), + labels: vec![(ident_span, "unknown identifier".into())], + notes: vec![], + }, + Error::UnknownScalarType(bad_span) => ParseError { + message: format!("unknown scalar type: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown scalar type".into())], + notes: vec!["Valid scalar types are f32, f64, i32, u32, bool".into()], + }, + Error::BadTextureSampleType { span, kind, width } => ParseError { + message: format!( + "texture sample type must be one of f32, i32 or u32, but found {}", + kind.to_wgsl(width) + ), + labels: vec![(span, "must be one of f32, i32 or u32".into())], + notes: vec![], + }, + Error::BadIncrDecrReferenceType(span) => ParseError { + message: + "increment/decrement operation requires reference type to be one of i32 or u32" + .to_string(), + labels: vec![(span, "must be a reference type of i32 or u32".into())], + notes: vec![], + }, + Error::BadTexture(bad_span) => ParseError { + message: format!( + "expected an image, but found '{}' which is not an image", + &source[bad_span] + ), + labels: vec![(bad_span, "not an image".into())], + notes: vec![], + }, + Error::BadTypeCast { + span, + ref from_type, + ref to_type, + } => { + let msg = format!("cannot cast a {from_type} to a {to_type}"); + ParseError { + message: msg.clone(), + labels: vec![(span, msg.into())], + notes: vec![], + } + } + Error::InvalidResolve(ref resolve_error) => ParseError { + message: resolve_error.to_string(), + labels: vec![], + notes: vec![], + }, + Error::InvalidForInitializer(bad_span) => ParseError { + message: format!( + "for(;;) initializer is not an assignment or a function call: '{}'", + &source[bad_span] + ), + labels: vec![(bad_span, "not an assignment or function call".into())], + notes: vec![], + }, + Error::InvalidBreakIf(bad_span) => ParseError { + message: "A break if is only allowed in a continuing block".to_string(), + labels: vec![(bad_span, "not in a continuing block".into())], + notes: vec![], + }, + Error::InvalidGatherComponent(bad_span) => ParseError { + message: format!( + "textureGather component '{}' doesn't exist, must be 0, 1, 2, or 3", + &source[bad_span] + ), + labels: vec![(bad_span, "invalid component".into())], + notes: vec![], + }, + Error::InvalidConstructorComponentType(bad_span, component) => ParseError { + message: format!("invalid type for constructor component at index [{component}]"), + labels: vec![(bad_span, "invalid component type".into())], + notes: vec![], + }, + Error::InvalidIdentifierUnderscore(bad_span) => ParseError { + message: "Identifier can't be '_'".to_string(), + labels: vec![(bad_span, "invalid identifier".into())], + notes: vec![ + "Use phony assignment instead ('_ =' notice the absence of 'let' or 'var')" + .to_string(), + ], + }, + Error::ReservedIdentifierPrefix(bad_span) => ParseError { + message: format!( + "Identifier starts with a reserved prefix: '{}'", + &source[bad_span] + ), + labels: vec![(bad_span, "invalid identifier".into())], + notes: vec![], + }, + Error::UnknownAddressSpace(bad_span) => ParseError { + message: format!("unknown address space: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown address space".into())], + notes: vec![], + }, + Error::UnknownAttribute(bad_span) => ParseError { + message: format!("unknown attribute: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown attribute".into())], + notes: vec![], + }, + Error::UnknownBuiltin(bad_span) => ParseError { + message: format!("unknown builtin: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown builtin".into())], + notes: vec![], + }, + Error::UnknownAccess(bad_span) => ParseError { + message: format!("unknown access: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown access".into())], + notes: vec![], + }, + Error::UnknownStorageFormat(bad_span) => ParseError { + message: format!("unknown storage format: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown storage format".into())], + notes: vec![], + }, + Error::UnknownConservativeDepth(bad_span) => ParseError { + message: format!("unknown conservative depth: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown conservative depth".into())], + notes: vec![], + }, + Error::UnknownType(bad_span) => ParseError { + message: format!("unknown type: '{}'", &source[bad_span]), + labels: vec![(bad_span, "unknown type".into())], + notes: vec![], + }, + Error::SizeAttributeTooLow(bad_span, min_size) => ParseError { + message: format!("struct member size must be at least {min_size}"), + labels: vec![(bad_span, format!("must be at least {min_size}").into())], + notes: vec![], + }, + Error::AlignAttributeTooLow(bad_span, min_align) => ParseError { + message: format!("struct member alignment must be at least {min_align}"), + labels: vec![(bad_span, format!("must be at least {min_align}").into())], + notes: vec![], + }, + Error::NonPowerOfTwoAlignAttribute(bad_span) => ParseError { + message: "struct member alignment must be a power of 2".to_string(), + labels: vec![(bad_span, "must be a power of 2".into())], + notes: vec![], + }, + Error::InconsistentBinding(span) => ParseError { + message: "input/output binding is not consistent".to_string(), + labels: vec![(span, "input/output binding is not consistent".into())], + notes: vec![], + }, + Error::TypeNotConstructible(span) => ParseError { + message: format!("type `{}` is not constructible", &source[span]), + labels: vec![(span, "type is not constructible".into())], + notes: vec![], + }, + Error::TypeNotInferrable(span) => ParseError { + message: "type can't be inferred".to_string(), + labels: vec![(span, "type can't be inferred".into())], + notes: vec![], + }, + Error::InitializationTypeMismatch(name_span, ref expected_ty, ref got_ty) => { + ParseError { + message: format!( + "the type of `{}` is expected to be `{}`, but got `{}`", + &source[name_span], expected_ty, got_ty, + ), + labels: vec![( + name_span, + format!("definition of `{}`", &source[name_span]).into(), + )], + notes: vec![], + } + } + Error::MissingType(name_span) => ParseError { + message: format!("variable `{}` needs a type", &source[name_span]), + labels: vec![( + name_span, + format!("definition of `{}`", &source[name_span]).into(), + )], + notes: vec![], + }, + Error::MissingAttribute(name, name_span) => ParseError { + message: format!( + "variable `{}` needs a '{}' attribute", + &source[name_span], name + ), + labels: vec![( + name_span, + format!("definition of `{}`", &source[name_span]).into(), + )], + notes: vec![], + }, + Error::InvalidAtomicPointer(span) => ParseError { + message: "atomic operation is done on a pointer to a non-atomic".to_string(), + labels: vec![(span, "atomic pointer is invalid".into())], + notes: vec![], + }, + Error::InvalidAtomicOperandType(span) => ParseError { + message: "atomic operand type is inconsistent with the operation".to_string(), + labels: vec![(span, "atomic operand type is invalid".into())], + notes: vec![], + }, + Error::NotPointer(span) => ParseError { + message: "the operand of the `*` operator must be a pointer".to_string(), + labels: vec![(span, "expression is not a pointer".into())], + notes: vec![], + }, + Error::NotReference(what, span) => ParseError { + message: format!("{what} must be a reference"), + labels: vec![(span, "expression is not a reference".into())], + notes: vec![], + }, + Error::InvalidAssignment { span, ty } => ParseError { + message: "invalid left-hand side of assignment".into(), + labels: vec![(span, "cannot assign to this expression".into())], + notes: match ty { + InvalidAssignmentType::Swizzle => vec![ + "WGSL does not support assignments to swizzles".into(), + "consider assigning each component individually".into(), + ], + InvalidAssignmentType::ImmutableBinding => vec![ + format!("'{}' is an immutable binding", &source[span]), + "consider declaring it with `var` instead of `let`".into(), + ], + InvalidAssignmentType::Other => vec![], + }, + }, + Error::Pointer(what, span) => ParseError { + message: format!("{what} must not be a pointer"), + labels: vec![(span, "expression is a pointer".into())], + notes: vec![], + }, + Error::ReservedKeyword(name_span) => ParseError { + message: format!("name `{}` is a reserved keyword", &source[name_span]), + labels: vec![( + name_span, + format!("definition of `{}`", &source[name_span]).into(), + )], + notes: vec![], + }, + Error::Redefinition { previous, current } => ParseError { + message: format!("redefinition of `{}`", &source[current]), + labels: vec![ + ( + current, + format!("redefinition of `{}`", &source[current]).into(), + ), + ( + previous, + format!("previous definition of `{}`", &source[previous]).into(), + ), + ], + notes: vec![], + }, + Error::RecursiveDeclaration { ident, usage } => ParseError { + message: format!("declaration of `{}` is recursive", &source[ident]), + labels: vec![(ident, "".into()), (usage, "uses itself here".into())], + notes: vec![], + }, + Error::CyclicDeclaration { ident, ref path } => ParseError { + message: format!("declaration of `{}` is cyclic", &source[ident]), + labels: path + .iter() + .enumerate() + .flat_map(|(i, &(ident, usage))| { + [ + (ident, "".into()), + ( + usage, + if i == path.len() - 1 { + "ending the cycle".into() + } else { + format!("uses `{}`", &source[ident]).into() + }, + ), + ] + }) + .collect(), + notes: vec![], + }, + Error::ConstExprUnsupported(span) => ParseError { + message: "this constant expression is not supported".to_string(), + labels: vec![(span, "expression is not supported".into())], + notes: vec![ + "this should be fixed in a future version of Naga".into(), + "https://github.com/gfx-rs/naga/issues/1829".into(), + ], + }, + Error::InvalidSwitchValue { uint, span } => ParseError { + message: "invalid switch value".to_string(), + labels: vec![( + span, + if uint { + "expected unsigned integer" + } else { + "expected signed integer" + } + .into(), + )], + notes: vec![if uint { + format!("suffix the integer with a `u`: '{}u'", &source[span]) + } else { + let span = span.to_range().unwrap(); + format!( + "remove the `u` suffix: '{}'", + &source[span.start..span.end - 1] + ) + }], + }, + Error::CalledEntryPoint(span) => ParseError { + message: "entry point cannot be called".to_string(), + labels: vec![(span, "entry point cannot be called".into())], + notes: vec![], + }, + Error::WrongArgumentCount { + span, + ref expected, + found, + } => ParseError { + message: format!( + "wrong number of arguments: expected {}, found {}", + if expected.len() < 2 { + format!("{}", expected.start) + } else { + format!("{}..{}", expected.start, expected.end) + }, + found + ), + labels: vec![(span, "wrong number of arguments".into())], + notes: vec![], + }, + Error::FunctionReturnsVoid(span) => ParseError { + message: "function does not return any value".to_string(), + labels: vec![(span, "".into())], + notes: vec![ + "perhaps you meant to call the function in a separate statement?".into(), + ], + }, + Error::Other => ParseError { + message: "other error".to_string(), + labels: vec![], + notes: vec![], + }, + } + } +} diff --git a/src/front/wgsl/index.rs b/src/front/wgsl/index.rs index a36273572..a5524fe8f 100644 --- a/src/front/wgsl/index.rs +++ b/src/front/wgsl/index.rs @@ -1,4 +1,5 @@ -use super::{ast, Error}; +use super::Error; +use crate::front::wgsl::parse::ast; use crate::{FastHashMap, Handle, Span}; /// A `GlobalDecl` list in which each definition occurs before all its uses. diff --git a/src/front/wgsl/construction.rs b/src/front/wgsl/lower/construction.rs similarity index 99% rename from src/front/wgsl/construction.rs rename to src/front/wgsl/lower/construction.rs index 2fae293c1..723d4441f 100644 --- a/src/front/wgsl/construction.rs +++ b/src/front/wgsl/lower/construction.rs @@ -1,6 +1,8 @@ +use crate::front::wgsl::parse::ast; use crate::{Handle, Span}; -use super::{ast, Error, ExpressionContext, Lowerer, OutputContext}; +use crate::front::wgsl::error::Error; +use crate::front::wgsl::lower::{ExpressionContext, Lowerer, OutputContext}; use crate::proc::TypeResolution; enum ConcreteConstructorHandle { @@ -133,7 +135,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { /// /// [`Construct`]: ast::Expression::Construct /// [`Call`]: ast::Expression::Call - pub(super) fn construct( + pub fn construct( &mut self, span: Span, constructor: &ast::ConstructorType<'source>, @@ -561,7 +563,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { /// [`Type`]: crate::Type /// [`Constant`]: crate::Constant /// [`ctx.module`]: OutputContext::module - pub(super) fn const_construct( + pub fn const_construct( &mut self, span: Span, constructor: &ast::ConstructorType<'source>, diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs new file mode 100644 index 000000000..7d03c7fb7 --- /dev/null +++ b/src/front/wgsl/lower/mod.rs @@ -0,0 +1,2371 @@ +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::{Emitter, Typifier}; +use crate::proc::{ensure_block_returns, Alignment, Layouter, ResolveContext, TypeResolution}; +use crate::{Arena, FastHashMap, Handle, Span}; + +mod construction; + +/// State for constructing a `crate::Module`. +pub struct OutputContext<'source, 'temp, 'out> { + /// The `TranslationUnit`'s expressions arena. + ast_expressions: &'temp Arena>, + + /// The `TranslationUnit`'s types arena. + types: &'temp Arena>, + + // Naga IR values. + /// The map from the names of module-scope declarations to the Naga IR + /// `Handle`s we have built for them, owned by `Lowerer::lower`. + globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, + + /// The module we're constructing. + module: &'out mut crate::Module, +} + +impl<'source> OutputContext<'source, '_, '_> { + fn reborrow(&mut self) -> OutputContext<'source, '_, '_> { + OutputContext { + ast_expressions: self.ast_expressions, + globals: self.globals, + types: self.types, + module: self.module, + } + } + + fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { + self.module + .types + .insert(crate::Type { inner, name: None }, Span::UNDEFINED) + } +} + +/// State for lowering a statement within a function. +pub struct StatementContext<'source, 'temp, 'out> { + // WGSL AST values. + /// A reference to [`TranslationUnit::expressions`] for the translation unit + /// we're lowering. + /// + /// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions + ast_expressions: &'temp Arena>, + + /// A reference to [`TranslationUnit::types`] for the translation unit + /// we're lowering. + /// + /// [`TranslationUnit::types`]: ast::TranslationUnit::types + types: &'temp Arena>, + + // Naga IR values. + /// The map from the names of module-scope declarations to the Naga IR + /// `Handle`s we have built for them, owned by `Lowerer::lower`. + globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, + + /// A map from `ast::Local` handles to the Naga expressions we've built for them. + /// + /// The Naga expressions are either [`LocalVariable`] or + /// [`FunctionArgument`] expressions. + /// + /// [`LocalVariable`]: crate::Expression::LocalVariable + /// [`FunctionArgument`]: crate::Expression::FunctionArgument + local_table: &'temp mut FastHashMap, TypedExpression>, + + typifier: &'temp mut Typifier, + variables: &'out mut Arena, + naga_expressions: &'out mut Arena, + named_expressions: &'out mut FastHashMap, String>, + arguments: &'out [crate::FunctionArgument], + module: &'out mut crate::Module, +} + +impl<'a, 'temp> StatementContext<'a, 'temp, '_> { + fn reborrow(&mut self) -> StatementContext<'a, '_, '_> { + StatementContext { + local_table: self.local_table, + globals: self.globals, + types: self.types, + ast_expressions: self.ast_expressions, + typifier: self.typifier, + variables: self.variables, + naga_expressions: self.naga_expressions, + named_expressions: self.named_expressions, + arguments: self.arguments, + module: self.module, + } + } + + fn as_expression<'t>( + &'t mut self, + block: &'t mut crate::Block, + emitter: &'t mut Emitter, + ) -> ExpressionContext<'a, 't, '_> + where + 'temp: 't, + { + ExpressionContext { + local_table: self.local_table, + globals: self.globals, + types: self.types, + ast_expressions: self.ast_expressions, + typifier: self.typifier, + naga_expressions: self.naga_expressions, + module: self.module, + local_vars: self.variables, + arguments: self.arguments, + block, + emitter, + } + } + + fn as_output(&mut self) -> OutputContext<'a, '_, '_> { + OutputContext { + ast_expressions: self.ast_expressions, + globals: self.globals, + types: self.types, + module: self.module, + } + } +} + +/// State for lowering an `ast::Expression` to Naga IR. +/// +/// Not to be confused with `parser::ExpressionContext`. +pub struct ExpressionContext<'source, 'temp, 'out> { + // WGSL AST values. + local_table: &'temp mut FastHashMap, TypedExpression>, + ast_expressions: &'temp Arena>, + types: &'temp Arena>, + + // Naga IR values. + /// The map from the names of module-scope declarations to the Naga IR + /// `Handle`s we have built for them, owned by `Lowerer::lower`. + globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, + + typifier: &'temp mut Typifier, + naga_expressions: &'out mut Arena, + local_vars: &'out Arena, + arguments: &'out [crate::FunctionArgument], + module: &'out mut crate::Module, + block: &'temp mut crate::Block, + emitter: &'temp mut Emitter, +} + +impl<'a> ExpressionContext<'a, '_, '_> { + fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { + ExpressionContext { + local_table: self.local_table, + globals: self.globals, + types: self.types, + ast_expressions: self.ast_expressions, + typifier: self.typifier, + naga_expressions: self.naga_expressions, + module: self.module, + local_vars: self.local_vars, + arguments: self.arguments, + block: self.block, + emitter: self.emitter, + } + } + + fn as_output(&mut self) -> OutputContext<'a, '_, '_> { + OutputContext { + ast_expressions: self.ast_expressions, + globals: self.globals, + types: self.types, + module: self.module, + } + } + + /// Determine the type of `handle`, and add it to the module's arena. + /// + /// If you just need a `TypeInner` for `handle`'s type, use + /// [`grow_types`] and [`resolved_inner`] instead. This function + /// should only be used when the type of `handle` needs to appear + /// in the module's final `Arena`, for example, if you're + /// creating a [`LocalVariable`] whose type is inferred from its + /// initializer. + /// + /// [`grow_types`]: Self::grow_types + /// [`resolved_inner`]: Self::resolved_inner + /// [`LocalVariable`]: crate::LocalVariable + fn register_type( + &mut self, + handle: Handle, + ) -> Result, Error<'a>> { + self.grow_types(handle)?; + Ok(self.typifier.register_type(handle, &mut self.module.types)) + } + + /// Resolve the types of all expressions up through `handle`. + /// + /// Ensure that [`self.typifier`] has a [`TypeResolution`] for + /// every expression in [`self.naga_expressions`]. + /// + /// This does not add types to any arena. The [`Typifier`] + /// documentation explains the steps we take to avoid filling + /// arenas with intermediate types. + /// + /// This function takes `&mut self`, so it can't conveniently + /// return a shared reference to the resulting `TypeResolution`: + /// the shared reference would extend the mutable borrow, and you + /// wouldn't be able to use `self` for anything else. Instead, you + /// should call `grow_types` to cover the handles you need, and + /// then use `self.typifier[handle]` or + /// [`self.resolved_inner(handle)`] to get at their resolutions. + /// + /// [`self.typifier`]: ExpressionContext::typifier + /// [`self.resolved_inner(handle)`]: ExpressionContext::resolved_inner + /// [`Typifier`]: Typifier + fn grow_types(&mut self, handle: Handle) -> Result<&mut Self, Error<'a>> { + let resolve_ctx = ResolveContext { + constants: &self.module.constants, + types: &self.module.types, + global_vars: &self.module.global_variables, + local_vars: self.local_vars, + functions: &self.module.functions, + arguments: self.arguments, + }; + self.typifier + .grow(handle, self.naga_expressions, &resolve_ctx) + .map_err(Error::InvalidResolve)?; + Ok(self) + } + + fn resolved_inner(&self, handle: Handle) -> &crate::TypeInner { + self.typifier[handle].inner_with(&self.module.types) + } + + fn image_data( + &mut self, + image: Handle, + span: Span, + ) -> Result<(crate::ImageClass, bool), Error<'a>> { + self.grow_types(image)?; + match *self.resolved_inner(image) { + crate::TypeInner::Image { class, arrayed, .. } => Ok((class, arrayed)), + _ => Err(Error::BadTexture(span)), + } + } + + fn prepare_args<'b>( + &mut self, + args: &'b [Handle>], + min_args: u32, + span: Span, + ) -> ArgumentContext<'b, 'a> { + ArgumentContext { + args: args.iter(), + min_args, + args_used: 0, + total_args: args.len() as u32, + span, + } + } + + /// Insert splats, if needed by the non-'*' operations. + fn binary_op_splat( + &mut self, + op: crate::BinaryOperator, + left: &mut Handle, + right: &mut Handle, + ) -> Result<(), Error<'a>> { + if op != crate::BinaryOperator::Multiply { + self.grow_types(*left)?.grow_types(*right)?; + + let left_size = match *self.resolved_inner(*left) { + crate::TypeInner::Vector { size, .. } => Some(size), + _ => None, + }; + + match (left_size, self.resolved_inner(*right)) { + (Some(size), &crate::TypeInner::Scalar { .. }) => { + *right = self.naga_expressions.append( + crate::Expression::Splat { + size, + value: *right, + }, + self.naga_expressions.get_span(*right), + ); + } + (None, &crate::TypeInner::Vector { size, .. }) => { + *left = self.naga_expressions.append( + crate::Expression::Splat { size, value: *left }, + self.naga_expressions.get_span(*left), + ); + } + _ => {} + } + } + + Ok(()) + } + + /// Add a single expression to the expression table that is not covered by `self.emitter`. + /// + /// This is useful for `CallResult` and `AtomicResult` expressions, which should not be covered by + /// `Emit` statements. + fn interrupt_emitter( + &mut self, + expression: crate::Expression, + span: Span, + ) -> Handle { + self.block + .extend(self.emitter.finish(self.naga_expressions)); + let result = self.naga_expressions.append(expression, span); + self.emitter.start(self.naga_expressions); + result + } + + /// Apply the WGSL Load Rule to `expr`. + /// + /// If `expr` is has type `ref`, perform a load to produce a value of type + /// `T`. Otherwise, return `expr` unchanged. + fn apply_load_rule(&mut self, expr: TypedExpression) -> Handle { + if expr.is_reference { + let load = crate::Expression::Load { + pointer: expr.handle, + }; + let span = self.naga_expressions.get_span(expr.handle); + self.naga_expressions.append(load, span) + } else { + expr.handle + } + } + + /// Creates a zero value constant of type `ty` + /// + /// Returns `None` if the given `ty` is not a constructible type + fn create_zero_value_constant( + &mut self, + ty: Handle, + ) -> Option> { + let inner = match self.module.types[ty].inner { + crate::TypeInner::Scalar { kind, width } => { + let value = match kind { + crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), + crate::ScalarKind::Uint => crate::ScalarValue::Uint(0), + crate::ScalarKind::Float => crate::ScalarValue::Float(0.), + crate::ScalarKind::Bool => crate::ScalarValue::Bool(false), + }; + crate::ConstantInner::Scalar { width, value } + } + crate::TypeInner::Vector { size, kind, width } => { + let scalar_ty = self.ensure_type_exists(crate::TypeInner::Scalar { width, kind }); + let component = self.create_zero_value_constant(scalar_ty); + crate::ConstantInner::Composite { + ty, + components: (0..size as u8).map(|_| component).collect::>()?, + } + } + crate::TypeInner::Matrix { + columns, + rows, + width, + } => { + let vec_ty = self.ensure_type_exists(crate::TypeInner::Vector { + width, + kind: crate::ScalarKind::Float, + size: rows, + }); + let component = self.create_zero_value_constant(vec_ty); + crate::ConstantInner::Composite { + ty, + components: (0..columns as u8) + .map(|_| component) + .collect::>()?, + } + } + crate::TypeInner::Array { + base, + size: crate::ArraySize::Constant(size), + .. + } => { + let component = self.create_zero_value_constant(base); + crate::ConstantInner::Composite { + ty, + components: (0..self.module.constants[size].to_array_length().unwrap()) + .map(|_| component) + .collect::>()?, + } + } + crate::TypeInner::Struct { ref members, .. } => { + let members = members.clone(); + crate::ConstantInner::Composite { + ty, + components: members + .iter() + .map(|member| self.create_zero_value_constant(member.ty)) + .collect::>()?, + } + } + _ => return None, + }; + + let constant = self.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + Span::UNDEFINED, + ); + Some(constant) + } + + fn format_typeinner(&self, inner: &crate::TypeInner) -> String { + inner.to_wgsl(&self.module.types, &self.module.constants) + } + + fn format_type(&self, handle: Handle) -> String { + let ty = &self.module.types[handle]; + match ty.name { + Some(ref name) => name.clone(), + None => self.format_typeinner(&ty.inner), + } + } + + fn format_type_resolution(&self, resolution: &TypeResolution) -> String { + match *resolution { + TypeResolution::Handle(handle) => self.format_type(handle), + TypeResolution::Value(ref inner) => self.format_typeinner(inner), + } + } + + fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { + self.as_output().ensure_type_exists(inner) + } +} + +struct ArgumentContext<'ctx, 'source> { + args: std::slice::Iter<'ctx, Handle>>, + min_args: u32, + args_used: u32, + total_args: u32, + span: Span, +} + +impl<'source> ArgumentContext<'_, 'source> { + pub fn finish(self) -> Result<(), Error<'source>> { + if self.args.len() == 0 { + Ok(()) + } else { + Err(Error::WrongArgumentCount { + found: self.total_args, + expected: self.min_args..self.args_used + 1, + span: self.span, + }) + } + } + + pub fn next(&mut self) -> Result>, Error<'source>> { + match self.args.next().copied() { + Some(arg) => { + self.args_used += 1; + Ok(arg) + } + None => Err(Error::WrongArgumentCount { + found: self.total_args, + expected: self.min_args..self.args_used + 1, + span: self.span, + }), + } + } +} + +/// A Naga [`Expression`] handle, with WGSL type information. +/// +/// Naga and WGSL types are very close, but Naga lacks WGSL's 'reference' types, +/// which we need to know to apply the Load Rule. This struct carries a Naga +/// `Handle` along with enough information to determine its WGSL type. +/// +/// [`Expression`]: crate::Expression +#[derive(Debug, Copy, Clone)] +struct TypedExpression { + /// The handle of the Naga expression. + handle: Handle, + + /// True if this expression's WGSL type is a reference. + /// + /// When this is true, `handle` must be a pointer. + is_reference: bool, +} + +impl TypedExpression { + const fn non_reference(handle: Handle) -> TypedExpression { + TypedExpression { + handle, + is_reference: false, + } + } +} + +enum Composition { + Single(u32), + Multi(crate::VectorSize, [crate::SwizzleComponent; 4]), +} + +impl Composition { + const fn letter_component(letter: char) -> Option { + use crate::SwizzleComponent as Sc; + match letter { + 'x' | 'r' => Some(Sc::X), + 'y' | 'g' => Some(Sc::Y), + 'z' | 'b' => Some(Sc::Z), + 'w' | 'a' => Some(Sc::W), + _ => None, + } + } + + fn extract_impl(name: &str, name_span: Span) -> Result { + let ch = name.chars().next().ok_or(Error::BadAccessor(name_span))?; + match Self::letter_component(ch) { + Some(sc) => Ok(sc as u32), + None => Err(Error::BadAccessor(name_span)), + } + } + + fn make(name: &str, name_span: Span) -> Result { + if name.len() > 1 { + let mut components = [crate::SwizzleComponent::X; 4]; + for (comp, ch) in components.iter_mut().zip(name.chars()) { + *comp = Self::letter_component(ch).ok_or(Error::BadAccessor(name_span))?; + } + + let size = match name.len() { + 2 => crate::VectorSize::Bi, + 3 => crate::VectorSize::Tri, + 4 => crate::VectorSize::Quad, + _ => return Err(Error::BadAccessor(name_span)), + }; + Ok(Composition::Multi(size, components)) + } else { + Self::extract_impl(name, name_span).map(Composition::Single) + } + } +} + +/// An `ast::GlobalDecl` for which we have built the Naga IR equivalent. +enum LoweredGlobalDecl { + Function(Handle), + Var(Handle), + Const(Handle), + Type(Handle), + EntryPoint, +} + +enum ConstantOrInner { + Constant(Handle), + Inner(crate::ConstantInner), +} + +enum Texture { + Gather, + GatherCompare, + + Sample, + SampleBias, + SampleCompare, + SampleCompareLevel, + SampleGrad, + SampleLevel, + // SampleBaseClampToEdge, +} + +impl Texture { + pub fn map(word: &str) -> Option { + Some(match word { + "textureGather" => Self::Gather, + "textureGatherCompare" => Self::GatherCompare, + + "textureSample" => Self::Sample, + "textureSampleBias" => Self::SampleBias, + "textureSampleCompare" => Self::SampleCompare, + "textureSampleCompareLevel" => Self::SampleCompareLevel, + "textureSampleGrad" => Self::SampleGrad, + "textureSampleLevel" => Self::SampleLevel, + // "textureSampleBaseClampToEdge" => Some(Self::SampleBaseClampToEdge), + _ => return None, + }) + } + + pub const fn min_argument_count(&self) -> u32 { + match *self { + Self::Gather => 3, + Self::GatherCompare => 4, + + Self::Sample => 3, + Self::SampleBias => 5, + Self::SampleCompare => 5, + Self::SampleCompareLevel => 5, + Self::SampleGrad => 6, + Self::SampleLevel => 5, + // Self::SampleBaseClampToEdge => 3, + } + } +} + +pub struct Lowerer<'source, 'temp> { + index: &'temp Index<'source>, + layouter: Layouter, +} + +impl<'source, 'temp> Lowerer<'source, 'temp> { + pub fn new(index: &'temp Index<'source>) -> Self { + Self { + index, + layouter: Layouter::default(), + } + } + + pub fn lower( + &mut self, + tu: &'temp ast::TranslationUnit<'source>, + ) -> Result> { + let mut module = crate::Module::default(); + + let mut ctx = OutputContext { + ast_expressions: &tu.expressions, + globals: &mut FastHashMap::default(), + types: &tu.types, + module: &mut module, + }; + + for decl in self.index.visit_ordered() { + let span = tu.decls.get_span(decl); + let decl = &tu.decls[decl]; + + match decl.kind { + ast::GlobalDeclKind::Fn(ref f) => { + let decl = self.function(f, span, ctx.reborrow())?; + ctx.globals.insert(f.name.name, decl); + } + ast::GlobalDeclKind::Var(ref v) => { + let ty = self.resolve_ast_type(v.ty, ctx.reborrow())?; + + let init = v + .init + .map(|init| self.constant(init, ctx.reborrow())) + .transpose()?; + + let handle = ctx.module.global_variables.append( + crate::GlobalVariable { + name: Some(v.name.name.to_string()), + space: v.space, + binding: v.binding.clone(), + ty, + init, + }, + span, + ); + + ctx.globals + .insert(v.name.name, LoweredGlobalDecl::Var(handle)); + } + ast::GlobalDeclKind::Const(ref c) => { + let inner = self.constant_inner(c.init, ctx.reborrow())?; + let inner = match inner { + ConstantOrInner::Constant(c) => ctx.module.constants[c].inner.clone(), + ConstantOrInner::Inner(inner) => inner, + }; + + let inferred_type = match inner { + crate::ConstantInner::Scalar { width, value } => { + ctx.ensure_type_exists(crate::TypeInner::Scalar { + width, + kind: value.scalar_kind(), + }) + } + crate::ConstantInner::Composite { ty, .. } => ty, + }; + + let handle = ctx.module.constants.append( + crate::Constant { + name: Some(c.name.name.to_string()), + specialization: None, + inner, + }, + span, + ); + + let explicit_ty = + c.ty.map(|ty| self.resolve_ast_type(ty, ctx.reborrow())) + .transpose()?; + + if let Some(explicit) = explicit_ty { + if explicit != inferred_type { + let ty = &ctx.module.types[explicit]; + let explicit = ty.name.clone().unwrap_or_else(|| { + ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) + }); + + let ty = &ctx.module.types[inferred_type]; + let inferred = ty.name.clone().unwrap_or_else(|| { + ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) + }); + + return Err(Error::InitializationTypeMismatch( + c.name.span, + explicit, + inferred, + )); + } + } + + ctx.globals + .insert(c.name.name, LoweredGlobalDecl::Const(handle)); + } + ast::GlobalDeclKind::Struct(ref s) => { + let handle = self.r#struct(s, span, ctx.reborrow())?; + ctx.globals + .insert(s.name.name, LoweredGlobalDecl::Type(handle)); + } + ast::GlobalDeclKind::Type(ref alias) => { + let ty = self.resolve_ast_type(alias.ty, ctx.reborrow())?; + ctx.globals + .insert(alias.name.name, LoweredGlobalDecl::Type(ty)); + } + } + } + + Ok(module) + } + + fn function( + &mut self, + f: &ast::Function<'source>, + span: Span, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result> { + let mut local_table = FastHashMap::default(); + let mut local_variables = Arena::new(); + let mut expressions = Arena::new(); + let mut named_expressions = crate::NamedExpressions::default(); + + let arguments = f + .arguments + .iter() + .enumerate() + .map(|(i, arg)| { + let ty = self.resolve_ast_type(arg.ty, ctx.reborrow())?; + let expr = expressions + .append(crate::Expression::FunctionArgument(i as u32), arg.name.span); + local_table.insert(arg.handle, TypedExpression::non_reference(expr)); + named_expressions.insert(expr, arg.name.name.to_string()); + + Ok(crate::FunctionArgument { + name: Some(arg.name.name.to_string()), + ty, + binding: self.interpolate_default(&arg.binding, ty, ctx.reborrow()), + }) + }) + .collect::, _>>()?; + + let result = f + .result + .as_ref() + .map(|res| { + self.resolve_ast_type(res.ty, ctx.reborrow()) + .map(|ty| crate::FunctionResult { + ty, + binding: self.interpolate_default(&res.binding, ty, ctx.reborrow()), + }) + }) + .transpose()?; + + let mut typifier = Typifier::default(); + let mut body = self.block( + &f.body, + StatementContext { + local_table: &mut local_table, + globals: ctx.globals, + ast_expressions: ctx.ast_expressions, + typifier: &mut typifier, + variables: &mut local_variables, + naga_expressions: &mut expressions, + named_expressions: &mut named_expressions, + types: ctx.types, + module: ctx.module, + arguments: &arguments, + }, + )?; + ensure_block_returns(&mut body); + + let function = crate::Function { + name: Some(f.name.name.to_string()), + arguments, + result, + local_variables, + expressions, + named_expressions, + body, + }; + + if let Some(ref entry) = f.entry_point { + ctx.module.entry_points.push(crate::EntryPoint { + name: f.name.name.to_string(), + stage: entry.stage, + early_depth_test: entry.early_depth_test, + workgroup_size: entry.workgroup_size, + function, + }); + Ok(LoweredGlobalDecl::EntryPoint) + } else { + let handle = ctx.module.functions.append(function, span); + Ok(LoweredGlobalDecl::Function(handle)) + } + } + + fn block( + &mut self, + b: &ast::Block<'source>, + mut ctx: StatementContext<'source, '_, '_>, + ) -> Result> { + let mut block = crate::Block::default(); + + for stmt in b.stmts.iter() { + self.statement(stmt, &mut block, ctx.reborrow())?; + } + + Ok(block) + } + + fn statement( + &mut self, + stmt: &ast::Statement<'source>, + block: &mut crate::Block, + mut ctx: StatementContext<'source, '_, '_>, + ) -> Result<(), Error<'source>> { + let out = match stmt.kind { + ast::StatementKind::Block(ref block) => { + let block = self.block(block, ctx.reborrow())?; + crate::Statement::Block(block) + } + ast::StatementKind::LocalDecl(ref decl) => match *decl { + ast::LocalDecl::Let(ref l) => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let value = self.expression(l.init, ctx.as_expression(block, &mut emitter))?; + + let explicit_ty = + l.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) + .transpose()?; + + if let Some(ty) = explicit_ty { + let mut ctx = ctx.as_expression(block, &mut emitter); + let init_ty = ctx.register_type(value)?; + if !ctx.module.types[ty] + .inner + .equivalent(&ctx.module.types[init_ty].inner, &ctx.module.types) + { + return Err(Error::InitializationTypeMismatch( + l.name.span, + ctx.format_type(ty), + ctx.format_type(init_ty), + )); + } + } + + block.extend(emitter.finish(ctx.naga_expressions)); + ctx.local_table + .insert(l.handle, TypedExpression::non_reference(value)); + ctx.named_expressions.insert(value, l.name.name.to_string()); + + return Ok(()); + } + ast::LocalDecl::Var(ref v) => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let initializer = match v.init { + Some(init) => { + let initializer = + self.expression(init, ctx.as_expression(block, &mut emitter))?; + ctx.as_expression(block, &mut emitter) + .grow_types(initializer)?; + Some(initializer) + } + None => None, + }; + + let explicit_ty = + v.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) + .transpose()?; + + let ty = match (explicit_ty, initializer) { + (Some(explicit), Some(initializer)) => { + let ctx = ctx.as_expression(block, &mut emitter); + let initializer_ty = ctx.resolved_inner(initializer); + if !ctx.module.types[explicit] + .inner + .equivalent(initializer_ty, &ctx.module.types) + { + return Err(Error::InitializationTypeMismatch( + v.name.span, + ctx.format_type(explicit), + ctx.format_typeinner(initializer_ty), + )); + } + explicit + } + (Some(explicit), None) => explicit, + (None, Some(initializer)) => ctx + .as_expression(block, &mut emitter) + .register_type(initializer)?, + (None, None) => { + return Err(Error::MissingType(v.name.span)); + } + }; + + let var = ctx.variables.append( + crate::LocalVariable { + name: Some(v.name.name.to_string()), + ty, + init: None, + }, + stmt.span, + ); + + let handle = ctx + .as_expression(block, &mut emitter) + .interrupt_emitter(crate::Expression::LocalVariable(var), Span::UNDEFINED); + block.extend(emitter.finish(ctx.naga_expressions)); + ctx.local_table.insert( + v.handle, + TypedExpression { + handle, + is_reference: true, + }, + ); + + match initializer { + Some(initializer) => crate::Statement::Store { + pointer: handle, + value: initializer, + }, + None => return Ok(()), + } + } + }, + ast::StatementKind::If { + condition, + ref accept, + ref reject, + } => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let condition = + self.expression(condition, ctx.as_expression(block, &mut emitter))?; + block.extend(emitter.finish(ctx.naga_expressions)); + + let accept = self.block(accept, ctx.reborrow())?; + let reject = self.block(reject, ctx.reborrow())?; + + crate::Statement::If { + condition, + accept, + reject, + } + } + ast::StatementKind::Switch { + selector, + ref cases, + } => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let mut ectx = ctx.as_expression(block, &mut emitter); + let selector = self.expression(selector, ectx.reborrow())?; + + ectx.grow_types(selector)?; + let uint = + ectx.resolved_inner(selector).scalar_kind() == Some(crate::ScalarKind::Uint); + block.extend(emitter.finish(ctx.naga_expressions)); + + let cases = cases + .iter() + .map(|case| { + Ok(crate::SwitchCase { + value: match case.value { + ast::SwitchValue::I32(num) if !uint => { + crate::SwitchValue::Integer(num) + } + ast::SwitchValue::U32(num) if uint => { + crate::SwitchValue::Integer(num as i32) + } + ast::SwitchValue::Default => crate::SwitchValue::Default, + _ => { + return Err(Error::InvalidSwitchValue { + uint, + span: case.value_span, + }); + } + }, + body: self.block(&case.body, ctx.reborrow())?, + fall_through: case.fall_through, + }) + }) + .collect::>()?; + + crate::Statement::Switch { selector, cases } + } + ast::StatementKind::Loop { + ref body, + ref continuing, + break_if, + } => { + let body = self.block(body, ctx.reborrow())?; + let mut continuing = self.block(continuing, ctx.reborrow())?; + + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + let break_if = break_if + .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) + .transpose()?; + continuing.extend(emitter.finish(ctx.naga_expressions)); + + crate::Statement::Loop { + body, + continuing, + break_if, + } + } + ast::StatementKind::Break => crate::Statement::Break, + ast::StatementKind::Continue => crate::Statement::Continue, + ast::StatementKind::Return { value } => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let value = value + .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) + .transpose()?; + block.extend(emitter.finish(ctx.naga_expressions)); + + crate::Statement::Return { value } + } + ast::StatementKind::Kill => crate::Statement::Kill, + ast::StatementKind::Call { + ref function, + ref arguments, + } => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let _ = self.call( + stmt.span, + function, + arguments, + ctx.as_expression(block, &mut emitter), + )?; + block.extend(emitter.finish(ctx.naga_expressions)); + return Ok(()); + } + ast::StatementKind::Assign { target, op, value } => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let expr = + self.expression_for_reference(target, ctx.as_expression(block, &mut emitter))?; + let mut value = self.expression(value, ctx.as_expression(block, &mut emitter))?; + + if !expr.is_reference { + let ty = if ctx.named_expressions.contains_key(&expr.handle) { + InvalidAssignmentType::ImmutableBinding + } else { + match ctx.naga_expressions[expr.handle] { + crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, + _ => InvalidAssignmentType::Other, + } + }; + + return Err(Error::InvalidAssignment { + span: ctx.ast_expressions.get_span(target), + ty, + }); + } + + let value = match op { + Some(op) => { + let mut ctx = ctx.as_expression(block, &mut emitter); + let mut left = ctx.apply_load_rule(expr); + ctx.binary_op_splat(op, &mut left, &mut value)?; + ctx.naga_expressions.append( + crate::Expression::Binary { + op, + left, + right: value, + }, + stmt.span, + ) + } + None => value, + }; + block.extend(emitter.finish(ctx.naga_expressions)); + + crate::Statement::Store { + pointer: expr.handle, + value, + } + } + ast::StatementKind::Increment(value) | ast::StatementKind::Decrement(value) => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let op = match stmt.kind { + ast::StatementKind::Increment(_) => crate::BinaryOperator::Add, + ast::StatementKind::Decrement(_) => crate::BinaryOperator::Subtract, + _ => unreachable!(), + }; + + let value_span = ctx.ast_expressions.get_span(value); + let reference = + self.expression_for_reference(value, ctx.as_expression(block, &mut emitter))?; + let mut ectx = ctx.as_expression(block, &mut emitter); + + ectx.grow_types(reference.handle)?; + let (kind, width) = match *ectx.resolved_inner(reference.handle) { + crate::TypeInner::ValuePointer { + size: None, + kind, + width, + .. + } => (kind, width), + crate::TypeInner::Pointer { base, .. } => match ectx.module.types[base].inner { + crate::TypeInner::Scalar { kind, width } => (kind, width), + _ => return Err(Error::BadIncrDecrReferenceType(value_span)), + }, + _ => return Err(Error::BadIncrDecrReferenceType(value_span)), + }; + let constant_inner = crate::ConstantInner::Scalar { + width, + value: match kind { + crate::ScalarKind::Sint => crate::ScalarValue::Sint(1), + crate::ScalarKind::Uint => crate::ScalarValue::Uint(1), + _ => return Err(Error::BadIncrDecrReferenceType(value_span)), + }, + }; + let constant = ectx.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner: constant_inner, + }, + Span::UNDEFINED, + ); + + let left = ectx.naga_expressions.append( + crate::Expression::Load { + pointer: reference.handle, + }, + value_span, + ); + let right = + ectx.interrupt_emitter(crate::Expression::Constant(constant), Span::UNDEFINED); + let value = ectx + .naga_expressions + .append(crate::Expression::Binary { op, left, right }, stmt.span); + + block.extend(emitter.finish(ctx.naga_expressions)); + crate::Statement::Store { + pointer: reference.handle, + value, + } + } + ast::StatementKind::Ignore(expr) => { + let mut emitter = Emitter::default(); + emitter.start(ctx.naga_expressions); + + let _ = self.expression(expr, ctx.as_expression(block, &mut emitter))?; + block.extend(emitter.finish(ctx.naga_expressions)); + return Ok(()); + } + }; + + block.push(out, stmt.span); + + Ok(()) + } + + fn expression( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let expr = self.expression_for_reference(expr, ctx.reborrow())?; + Ok(ctx.apply_load_rule(expr)) + } + + fn expression_for_reference( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result> { + let span = ctx.ast_expressions.get_span(expr); + let expr = &ctx.ast_expressions[expr]; + + let (expr, is_reference) = match *expr { + ast::Expression::Literal(literal) => { + let inner = match literal { + ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Float(f as _), + }, + ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Sint(i as _), + }, + ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(u as _), + }, + ast::Literal::Number(_) => { + unreachable!("got abstract numeric type when not expected"); + } + ast::Literal::Bool(b) => crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(b), + }, + }; + let handle = ctx.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + Span::UNDEFINED, + ); + let handle = ctx.interrupt_emitter(crate::Expression::Constant(handle), span); + return Ok(TypedExpression::non_reference(handle)); + } + ast::Expression::Ident(ast::IdentExpr::Local(local)) => { + return Ok(ctx.local_table[&local]) + } + ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { + return if let Some(global) = ctx.globals.get(name) { + let (expr, is_reference) = match *global { + LoweredGlobalDecl::Var(handle) => ( + crate::Expression::GlobalVariable(handle), + ctx.module.global_variables[handle].space + != crate::AddressSpace::Handle, + ), + LoweredGlobalDecl::Const(handle) => { + (crate::Expression::Constant(handle), false) + } + _ => { + return Err(Error::Unexpected(span, ExpectedToken::Variable)); + } + }; + + let handle = ctx.interrupt_emitter(expr, span); + Ok(TypedExpression { + handle, + is_reference, + }) + } else { + Err(Error::UnknownIdent(span, name)) + } + } + ast::Expression::Construct { + ref ty, + ty_span, + ref components, + } => { + let handle = self.construct(span, ty, ty_span, components, ctx.reborrow())?; + return Ok(TypedExpression::non_reference(handle)); + } + ast::Expression::Unary { op, expr } => { + let expr = self.expression(expr, ctx.reborrow())?; + (crate::Expression::Unary { op, expr }, false) + } + ast::Expression::AddrOf(expr) => { + // The `&` operator simply converts a reference to a pointer. And since a + // reference is required, the Load Rule is not applied. + let expr = self.expression_for_reference(expr, ctx.reborrow())?; + if !expr.is_reference { + return Err(Error::NotReference("the operand of the `&` operator", span)); + } + + // No code is generated. We just declare the pointer a reference now. + return Ok(TypedExpression { + is_reference: false, + ..expr + }); + } + ast::Expression::Deref(expr) => { + // The pointer we dereference must be loaded. + let pointer = self.expression(expr, ctx.reborrow())?; + + ctx.grow_types(pointer)?; + if ctx.resolved_inner(pointer).pointer_space().is_none() { + return Err(Error::NotPointer(span)); + } + + return Ok(TypedExpression { + handle: pointer, + is_reference: true, + }); + } + ast::Expression::Binary { op, left, right } => { + // Load both operands. + let mut left = self.expression(left, ctx.reborrow())?; + let mut right = self.expression(right, ctx.reborrow())?; + ctx.binary_op_splat(op, &mut left, &mut right)?; + (crate::Expression::Binary { op, left, right }, false) + } + ast::Expression::Call { + ref function, + ref arguments, + } => { + let handle = self + .call(span, function, arguments, ctx.reborrow())? + .ok_or(Error::FunctionReturnsVoid(function.span))?; + return Ok(TypedExpression::non_reference(handle)); + } + ast::Expression::Index { base, index } => { + let expr = self.expression_for_reference(base, ctx.reborrow())?; + let index = self.expression(index, ctx.reborrow())?; + + ctx.grow_types(expr.handle)?; + let wgsl_pointer = + ctx.resolved_inner(expr.handle).pointer_space().is_some() && !expr.is_reference; + + if wgsl_pointer { + return Err(Error::Pointer( + "the value indexed by a `[]` subscripting expression", + ctx.ast_expressions.get_span(base), + )); + } + + if let crate::Expression::Constant(constant) = ctx.naga_expressions[index] { + let span = ctx.naga_expressions.get_span(index); + let index = match ctx.module.constants[constant].inner { + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(int), + .. + } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Sint(int), + .. + } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), + _ => Err(Error::BadU32Constant(span)), + }?; + + ( + crate::Expression::AccessIndex { + base: expr.handle, + index, + }, + expr.is_reference, + ) + } else { + ( + crate::Expression::Access { + base: expr.handle, + index, + }, + expr.is_reference, + ) + } + } + ast::Expression::Member { base, ref field } => { + let TypedExpression { + handle, + is_reference, + } = self.expression_for_reference(base, ctx.reborrow())?; + + ctx.grow_types(handle)?; + let temp_inner; + let (composite, wgsl_pointer) = match *ctx.resolved_inner(handle) { + crate::TypeInner::Pointer { base, .. } => { + (&ctx.module.types[base].inner, !is_reference) + } + crate::TypeInner::ValuePointer { + size: None, + kind, + width, + .. + } => { + temp_inner = crate::TypeInner::Scalar { kind, width }; + (&temp_inner, !is_reference) + } + crate::TypeInner::ValuePointer { + size: Some(size), + kind, + width, + .. + } => { + temp_inner = crate::TypeInner::Vector { size, kind, width }; + (&temp_inner, !is_reference) + } + ref other => (other, false), + }; + + if wgsl_pointer { + return Err(Error::Pointer( + "the value accessed by a `.member` expression", + ctx.ast_expressions.get_span(base), + )); + } + + let access = match *composite { + crate::TypeInner::Struct { ref members, .. } => { + let index = members + .iter() + .position(|m| m.name.as_deref() == Some(field.name)) + .ok_or(Error::BadAccessor(field.span))? + as u32; + + ( + crate::Expression::AccessIndex { + base: handle, + index, + }, + is_reference, + ) + } + crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { + match Composition::make(field.name, field.span)? { + Composition::Multi(size, pattern) => { + let vector = ctx.apply_load_rule(TypedExpression { + handle, + is_reference, + }); + + ( + crate::Expression::Swizzle { + size, + vector, + pattern, + }, + false, + ) + } + Composition::Single(index) => ( + crate::Expression::AccessIndex { + base: handle, + index, + }, + is_reference, + ), + } + } + _ => return Err(Error::BadAccessor(field.span)), + }; + + access + } + ast::Expression::Bitcast { expr, to, ty_span } => { + let expr = self.expression(expr, ctx.reborrow())?; + let to_resolved = self.resolve_ast_type(to, ctx.as_output())?; + + let kind = match ctx.module.types[to_resolved].inner { + crate::TypeInner::Scalar { kind, .. } => kind, + crate::TypeInner::Vector { kind, .. } => kind, + _ => { + let ty = &ctx.typifier[expr]; + return Err(Error::BadTypeCast { + from_type: ctx.format_type_resolution(ty), + span: ty_span, + to_type: ctx.format_type(to_resolved), + }); + } + }; + + ( + crate::Expression::As { + expr, + kind, + convert: None, + }, + false, + ) + } + }; + + let handle = ctx.naga_expressions.append(expr, span); + Ok(TypedExpression { + handle, + is_reference, + }) + } + + /// Generate Naga IR for call expressions and statements, and type + /// constructor expressions. + /// + /// The "function" being called is simply an `Ident` that we know refers to + /// some module-scope definition. + /// + /// - If it is the name of a type, then the expression is a type constructor + /// expression: either constructing a value from components, a conversion + /// expression, or a zero value expression. + /// + /// - If it is the name of a function, then we're generating a [`Call`] + /// statement. We may be in the midst of generating code for an + /// expression, in which case we must generate an `Emit` statement to + /// force evaluation of the IR expressions we've generated so far, add the + /// `Call` statement to the current block, and then resume generating + /// expressions. + /// + /// [`Call`]: crate::Statement::Call + fn call( + &mut self, + span: Span, + function: &ast::Ident<'source>, + arguments: &[Handle>], + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result>, Error<'source>> { + match ctx.globals.get(function.name) { + Some(&LoweredGlobalDecl::Type(ty)) => { + let handle = self.construct( + span, + &ast::ConstructorType::Type(ty), + function.span, + arguments, + ctx.reborrow(), + )?; + Ok(Some(handle)) + } + Some(&LoweredGlobalDecl::Const(_) | &LoweredGlobalDecl::Var(_)) => { + Err(Error::Unexpected(function.span, ExpectedToken::Function)) + } + Some(&LoweredGlobalDecl::EntryPoint) => Err(Error::CalledEntryPoint(function.span)), + Some(&LoweredGlobalDecl::Function(function)) => { + let arguments = arguments + .iter() + .map(|&arg| self.expression(arg, ctx.reborrow())) + .collect::, _>>()?; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + let result = ctx.module.functions[function].result.is_some().then(|| { + ctx.naga_expressions + .append(crate::Expression::CallResult(function), span) + }); + ctx.emitter.start(ctx.naga_expressions); + ctx.block.push( + crate::Statement::Call { + function, + arguments, + result, + }, + span, + ); + + Ok(result) + } + None => { + let span = function.span; + 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.reborrow())?; + args.finish()?; + + crate::Expression::Relational { fun, argument } + } else if let Some(axis) = conv::map_derivative_axis(function.name) { + let mut args = ctx.prepare_args(arguments, 1, span); + let expr = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::Derivative { axis, expr } + } else if let Some(fun) = conv::map_standard_fun(function.name) { + let expected = fun.argument_count() as _; + let mut args = ctx.prepare_args(arguments, expected, span); + + let arg = self.expression(args.next()?, ctx.reborrow())?; + let arg1 = args + .next() + .map(|x| self.expression(x, ctx.reborrow())) + .ok() + .transpose()?; + let arg2 = args + .next() + .map(|x| self.expression(x, ctx.reborrow())) + .ok() + .transpose()?; + let arg3 = args + .next() + .map(|x| self.expression(x, ctx.reborrow())) + .ok() + .transpose()?; + + args.finish()?; + + crate::Expression::Math { + fun, + arg, + arg1, + arg2, + arg3, + } + } else if let Some(fun) = Texture::map(function.name) { + self.texture_sample_helper(fun, arguments, span, ctx.reborrow())? + } else { + match function.name { + "select" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let reject = self.expression(args.next()?, ctx.reborrow())?; + let accept = self.expression(args.next()?, ctx.reborrow())?; + let condition = self.expression(args.next()?, ctx.reborrow())?; + + args.finish()?; + + crate::Expression::Select { + reject, + accept, + condition, + } + } + "arrayLength" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let expr = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ArrayLength(expr) + } + "atomicLoad" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::Load { pointer } + } + "atomicStore" => { + let mut args = ctx.prepare_args(arguments, 2, span); + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + let value = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + ctx.emitter.start(ctx.naga_expressions); + ctx.block + .push(crate::Statement::Store { pointer, value }, span); + return Ok(None); + } + "atomicAdd" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Add, + arguments, + ctx.reborrow(), + )?)) + } + "atomicSub" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Subtract, + arguments, + ctx.reborrow(), + )?)) + } + "atomicAnd" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::And, + arguments, + ctx.reborrow(), + )?)) + } + "atomicOr" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::InclusiveOr, + arguments, + ctx.reborrow(), + )?)) + } + "atomicXor" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::ExclusiveOr, + arguments, + ctx.reborrow(), + )?)) + } + "atomicMin" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Min, + arguments, + ctx.reborrow(), + )?)) + } + "atomicMax" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Max, + arguments, + ctx.reborrow(), + )?)) + } + "atomicExchange" => { + return Ok(Some(self.atomic_helper( + span, + crate::AtomicFunction::Exchange { compare: None }, + arguments, + ctx.reborrow(), + )?)) + } + "atomicCompareExchangeWeak" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + + let compare = self.expression(args.next()?, ctx.reborrow())?; + + let value = args.next()?; + let value_span = ctx.ast_expressions.get_span(value); + let value = self.expression(value, ctx.reborrow())?; + ctx.grow_types(value)?; + + args.finish()?; + + let expression = match *ctx.resolved_inner(value) { + crate::TypeInner::Scalar { kind, width } => { + let bool_ty = ctx.module.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { + kind: crate::ScalarKind::Bool, + width: crate::BOOL_WIDTH, + }, + }, + Span::UNDEFINED, + ); + let scalar_ty = ctx.module.types.insert( + crate::Type { + name: None, + inner: crate::TypeInner::Scalar { kind, width }, + }, + Span::UNDEFINED, + ); + let struct_ty = ctx.module.types.insert( + crate::Type { + name: Some( + "__atomic_compare_exchange_result".to_string(), + ), + inner: crate::TypeInner::Struct { + members: vec![ + crate::StructMember { + name: Some("old_value".to_string()), + ty: scalar_ty, + binding: None, + offset: 0, + }, + crate::StructMember { + name: Some("exchanged".to_string()), + ty: bool_ty, + binding: None, + offset: 4, + }, + ], + span: 8, + }, + }, + Span::UNDEFINED, + ); + crate::Expression::AtomicResult { + ty: struct_ty, + comparison: true, + } + } + _ => return Err(Error::InvalidAtomicOperandType(value_span)), + }; + + let result = ctx.interrupt_emitter(expression, span); + ctx.block.push( + crate::Statement::Atomic { + pointer, + fun: crate::AtomicFunction::Exchange { + compare: Some(compare), + }, + value, + result, + }, + span, + ); + return Ok(Some(result)); + } + "storageBarrier" => { + ctx.prepare_args(arguments, 0, span).finish()?; + + ctx.block + .push(crate::Statement::Barrier(crate::Barrier::STORAGE), span); + return Ok(None); + } + "workgroupBarrier" => { + ctx.prepare_args(arguments, 0, span).finish()?; + + ctx.block + .push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP), span); + return Ok(None); + } + "textureStore" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let image = args.next()?; + let image_span = ctx.ast_expressions.get_span(image); + let image = self.expression(image, ctx.reborrow())?; + + let coordinate = self.expression(args.next()?, ctx.reborrow())?; + + let (_, arrayed) = ctx.image_data(image, image_span)?; + let array_index = arrayed + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let value = self.expression(args.next()?, ctx.reborrow())?; + + args.finish()?; + + ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); + ctx.emitter.start(ctx.naga_expressions); + let stmt = crate::Statement::ImageStore { + image, + coordinate, + array_index, + value, + }; + ctx.block.push(stmt, span); + return Ok(None); + } + "textureLoad" => { + let mut args = ctx.prepare_args(arguments, 3, span); + + let image = args.next()?; + let image_span = ctx.ast_expressions.get_span(image); + let image = self.expression(image, ctx.reborrow())?; + + let coordinate = self.expression(args.next()?, ctx.reborrow())?; + + let (class, arrayed) = ctx.image_data(image, image_span)?; + let array_index = arrayed + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let level = class + .is_mipmapped() + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let sample = class + .is_multisampled() + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + args.finish()?; + + crate::Expression::ImageLoad { + image, + coordinate, + array_index, + level, + sample, + } + } + "textureDimensions" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + let level = args + .next() + .map(|arg| self.expression(arg, ctx.reborrow())) + .ok() + .transpose()?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::Size { level }, + } + } + "textureNumLevels" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumLevels, + } + } + "textureNumLayers" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumLayers, + } + } + "textureNumSamples" => { + let mut args = ctx.prepare_args(arguments, 1, span); + let image = self.expression(args.next()?, ctx.reborrow())?; + args.finish()?; + + crate::Expression::ImageQuery { + image, + query: crate::ImageQuery::NumSamples, + } + } + _ => return Err(Error::UnknownIdent(function.span, function.name)), + } + }; + + let expr = ctx.naga_expressions.append(expr, span); + Ok(Some(expr)) + } + } + } + + fn atomic_pointer( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let span = ctx.ast_expressions.get_span(expr); + let pointer = self.expression(expr, ctx.reborrow())?; + + ctx.grow_types(pointer)?; + match *ctx.resolved_inner(pointer) { + crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { + crate::TypeInner::Atomic { .. } => Ok(pointer), + ref other => { + log::error!("Pointer type to {:?} passed to atomic op", other); + Err(Error::InvalidAtomicPointer(span)) + } + }, + ref other => { + log::error!("Type {:?} passed to atomic op", other); + Err(Error::InvalidAtomicPointer(span)) + } + } + } + + fn atomic_helper( + &mut self, + span: Span, + fun: crate::AtomicFunction, + args: &[Handle>], + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let mut args = ctx.prepare_args(args, 2, span); + + let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; + + let value = args.next()?; + let value = self.expression(value, ctx.reborrow())?; + let ty = ctx.register_type(value)?; + + args.finish()?; + + let result = ctx.interrupt_emitter( + crate::Expression::AtomicResult { + ty, + comparison: false, + }, + span, + ); + ctx.block.push( + crate::Statement::Atomic { + pointer, + fun, + value, + result, + }, + span, + ); + Ok(result) + } + + fn texture_sample_helper( + &mut self, + fun: Texture, + args: &[Handle>], + span: Span, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result> { + let mut args = ctx.prepare_args(args, fun.min_argument_count(), span); + + let (image, gather) = match fun { + Texture::Gather => { + let image_or_component = args.next()?; + match self.gather_component(image_or_component, ctx.reborrow())? { + Some(component) => { + let image = args.next()?; + (image, Some(component)) + } + None => (image_or_component, Some(crate::SwizzleComponent::X)), + } + } + Texture::GatherCompare => { + let image = args.next()?; + (image, Some(crate::SwizzleComponent::X)) + } + + _ => { + let image = args.next()?; + (image, None) + } + }; + + let image_span = ctx.ast_expressions.get_span(image); + let image = self.expression(image, ctx.reborrow())?; + + let sampler = self.expression(args.next()?, ctx.reborrow())?; + + let coordinate = self.expression(args.next()?, ctx.reborrow())?; + + let (_, arrayed) = ctx.image_data(image, image_span)?; + let array_index = arrayed + .then(|| self.expression(args.next()?, ctx.reborrow())) + .transpose()?; + + let (level, depth_ref) = match fun { + Texture::Gather => (crate::SampleLevel::Zero, None), + Texture::GatherCompare => { + let reference = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Zero, Some(reference)) + } + + Texture::Sample => (crate::SampleLevel::Auto, None), + Texture::SampleBias => { + let bias = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Bias(bias), None) + } + Texture::SampleCompare => { + let reference = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Auto, Some(reference)) + } + Texture::SampleCompareLevel => { + let reference = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Zero, Some(reference)) + } + Texture::SampleGrad => { + let x = self.expression(args.next()?, ctx.reborrow())?; + let y = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Gradient { x, y }, None) + } + Texture::SampleLevel => { + let level = self.expression(args.next()?, ctx.reborrow())?; + (crate::SampleLevel::Exact(level), None) + } + }; + + let offset = args + .next() + .map(|arg| self.constant(arg, ctx.as_output())) + .ok() + .transpose()?; + + args.finish()?; + + Ok(crate::Expression::ImageSample { + image, + sampler, + gather, + coordinate, + array_index, + offset, + level, + depth_ref, + }) + } + + fn gather_component( + &mut self, + expr: Handle>, + mut ctx: ExpressionContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let span = ctx.ast_expressions.get_span(expr); + + let constant = match self.constant_inner(expr, ctx.as_output()).ok() { + Some(ConstantOrInner::Constant(c)) => ctx.module.constants[c].inner.clone(), + Some(ConstantOrInner::Inner(inner)) => inner, + None => return Ok(None), + }; + + let int = match constant { + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Sint(i), + .. + } if i >= 0 => i as u64, + crate::ConstantInner::Scalar { + value: crate::ScalarValue::Uint(i), + .. + } => i, + _ => { + return Err(Error::InvalidGatherComponent(span)); + } + }; + + crate::SwizzleComponent::XYZW + .get(int as usize) + .copied() + .map(Some) + .ok_or(Error::InvalidGatherComponent(span)) + } + + fn r#struct( + &mut self, + s: &ast::Struct<'source>, + span: Span, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let mut offset = 0; + let mut struct_alignment = Alignment::ONE; + let mut members = Vec::with_capacity(s.members.len()); + + for member in s.members.iter() { + let ty = self.resolve_ast_type(member.ty, ctx.reborrow())?; + + self.layouter + .update(&ctx.module.types, &ctx.module.constants) + .unwrap(); + + let member_min_size = self.layouter[ty].size; + let member_min_alignment = self.layouter[ty].alignment; + + let member_size = if let Some((size, span)) = member.size { + if size < member_min_size { + return Err(Error::SizeAttributeTooLow(span, member_min_size)); + } else { + size + } + } else { + member_min_size + }; + + let member_alignment = if let Some((align, span)) = member.align { + if let Some(alignment) = Alignment::new(align) { + if alignment < member_min_alignment { + return Err(Error::AlignAttributeTooLow(span, member_min_alignment)); + } else { + alignment + } + } else { + return Err(Error::NonPowerOfTwoAlignAttribute(span)); + } + } else { + member_min_alignment + }; + + let binding = self.interpolate_default(&member.binding, ty, ctx.reborrow()); + + offset = member_alignment.round_up(offset); + struct_alignment = struct_alignment.max(member_alignment); + + members.push(crate::StructMember { + name: Some(member.name.name.to_owned()), + ty, + binding, + offset, + }); + + offset += member_size; + } + + let size = struct_alignment.round_up(offset); + let inner = crate::TypeInner::Struct { + members, + span: size, + }; + + let handle = ctx.module.types.insert( + crate::Type { + name: Some(s.name.name.to_string()), + inner, + }, + span, + ); + Ok(handle) + } + + /// Return a Naga `Handle` representing the front-end type `handle`. + fn resolve_ast_type( + &mut self, + handle: Handle>, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let inner = match ctx.types[handle] { + ast::Type::Scalar { kind, width } => crate::TypeInner::Scalar { kind, width }, + ast::Type::Vector { size, kind, width } => { + crate::TypeInner::Vector { size, kind, width } + } + ast::Type::Matrix { + rows, + columns, + width, + } => crate::TypeInner::Matrix { + columns, + rows, + width, + }, + ast::Type::Atomic { kind, width } => crate::TypeInner::Atomic { kind, width }, + ast::Type::Pointer { base, space } => { + let base = self.resolve_ast_type(base, ctx.reborrow())?; + crate::TypeInner::Pointer { base, space } + } + ast::Type::Array { base, size } => { + let base = self.resolve_ast_type(base, ctx.reborrow())?; + self.layouter + .update(&ctx.module.types, &ctx.module.constants) + .unwrap(); + + crate::TypeInner::Array { + base, + size: match size { + ast::ArraySize::Constant(constant) => { + let constant = self.constant(constant, ctx.reborrow())?; + crate::ArraySize::Constant(constant) + } + ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, + }, + stride: self.layouter[base].to_stride(), + } + } + ast::Type::Image { + dim, + arrayed, + class, + } => crate::TypeInner::Image { + dim, + arrayed, + class, + }, + ast::Type::Sampler { comparison } => crate::TypeInner::Sampler { comparison }, + ast::Type::BindingArray { base, size } => { + let base = self.resolve_ast_type(base, ctx.reborrow())?; + + crate::TypeInner::BindingArray { + base, + size: match size { + ast::ArraySize::Constant(constant) => { + let constant = self.constant(constant, ctx.reborrow())?; + crate::ArraySize::Constant(constant) + } + ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, + }, + } + } + ast::Type::User(ref ident) => { + return match ctx.globals.get(ident.name) { + Some(&LoweredGlobalDecl::Type(handle)) => Ok(handle), + Some(_) => Err(Error::Unexpected(ident.span, ExpectedToken::Type)), + None => Err(Error::UnknownType(ident.span)), + } + } + }; + + Ok(ctx.ensure_type_exists(inner)) + } + + /// Find or construct a Naga [`Constant`] whose value is `expr`. + /// + /// The `ctx` indicates the Naga [`Module`] to which we should add + /// new `Constant`s or [`Type`]s as needed. + /// + /// [`Module`]: crate::Module + /// [`Constant`]: crate::Constant + /// [`Type`]: crate::Type + fn constant( + &mut self, + expr: Handle>, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result, Error<'source>> { + let inner = match self.constant_inner(expr, ctx.reborrow())? { + ConstantOrInner::Constant(c) => return Ok(c), + ConstantOrInner::Inner(inner) => inner, + }; + + let c = ctx.module.constants.fetch_or_append( + crate::Constant { + name: None, + specialization: None, + inner, + }, + Span::UNDEFINED, + ); + Ok(c) + } + + fn constant_inner( + &mut self, + expr: Handle>, + mut ctx: OutputContext<'source, '_, '_>, + ) -> Result> { + let span = ctx.ast_expressions.get_span(expr); + let inner = match ctx.ast_expressions[expr] { + ast::Expression::Literal(literal) => match literal { + ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Float(f as _), + }, + ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Sint(i as _), + }, + ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { + width: 4, + value: crate::ScalarValue::Uint(u as _), + }, + ast::Literal::Number(_) => { + unreachable!("got abstract numeric type when not expected"); + } + ast::Literal::Bool(b) => crate::ConstantInner::Scalar { + width: 1, + value: crate::ScalarValue::Bool(b), + }, + }, + ast::Expression::Ident(ast::IdentExpr::Local(_)) => { + return Err(Error::Unexpected(span, ExpectedToken::Constant)) + } + ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { + return if let Some(global) = ctx.globals.get(name) { + match *global { + LoweredGlobalDecl::Const(handle) => Ok(ConstantOrInner::Constant(handle)), + _ => Err(Error::Unexpected(span, ExpectedToken::Constant)), + } + } else { + Err(Error::UnknownIdent(span, name)) + } + } + ast::Expression::Construct { + ref ty, + ref components, + .. + } => self.const_construct(span, ty, components, ctx.reborrow())?, + ast::Expression::Call { + ref function, + ref arguments, + } => match ctx.globals.get(function.name) { + Some(&LoweredGlobalDecl::Type(ty)) => self.const_construct( + span, + &ast::ConstructorType::Type(ty), + arguments, + ctx.reborrow(), + )?, + Some(_) => return Err(Error::ConstExprUnsupported(span)), + None => return Err(Error::UnknownIdent(function.span, function.name)), + }, + _ => return Err(Error::ConstExprUnsupported(span)), + }; + + Ok(ConstantOrInner::Inner(inner)) + } + + fn interpolate_default( + &mut self, + binding: &Option, + ty: Handle, + ctx: OutputContext<'source, '_, '_>, + ) -> Option { + let mut binding = binding.clone(); + if let Some(ref mut binding) = binding { + binding.apply_default_interpolation(&ctx.module.types[ty].inner); + } + + binding + } +} diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index 7e2826845..8ac82fe45 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -4,648 +4,48 @@ Frontend for [WGSL][wgsl] (WebGPU Shading Language). [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html */ -mod ast; -mod construction; -mod conv; +mod error; mod index; -mod lexer; -mod number; +mod lower; +mod parse; #[cfg(test)] mod tests; -use crate::{ - arena::{Arena, Handle, UniqueArena}, - proc::{ - ensure_block_returns, Alignment, Layouter, ResolveContext, ResolveError, TypeResolution, - }, - span::SourceLocation, - FastHashMap, FastHashSet, Span, -}; +use crate::arena::{Arena, UniqueArena}; -use self::{lexer::Lexer, number::Number}; -use codespan_reporting::{ - diagnostic::{Diagnostic, Label}, - files::SimpleFile, - term::{ - self, - termcolor::{ColorChoice, NoColor, StandardStream}, - }, -}; -use std::{borrow::Cow, convert::TryFrom, ops::Range}; +use crate::front::wgsl::error::Error; +use crate::front::wgsl::parse::Parser; use thiserror::Error; -type TokenSpan<'a> = (Token<'a>, Span); +pub use crate::front::wgsl::error::ParseError; +use crate::front::wgsl::lower::Lowerer; -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum Token<'a> { - Separator(char), - Paren(char), - Attribute, - Number(Result), - Word(&'a str), - Operation(char), - LogicalOperation(char), - ShiftOperation(char), - AssignmentOperation(char), - IncrementOperation, - DecrementOperation, - Arrow, - Unknown(char), - Trivia, - End, +pub struct Frontend { + parser: Parser, } -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum NumberType { - I32, - U32, - F32, -} - -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum ExpectedToken<'a> { - Token(Token<'a>), - Identifier, - Number(NumberType), - Integer, - /// A compile-time constant expression. - Constant, - /// Expected: constant, parenthesized expression, identifier - PrimaryExpression, - /// Expected: assignment, increment/decrement expression - Assignment, - /// Expected: '}', identifier - FieldName, - /// Expected: 'case', 'default', '}' - SwitchItem, - /// Expected: ',', ')' - WorkgroupSizeSeparator, - /// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof - GlobalItem, - /// Expected a type. - Type, - /// Access of `var`, `let`, `const`. - Variable, - /// Access of a function - Function, -} - -#[derive(Clone, Copy, Debug, Error, PartialEq)] -pub enum NumberError { - #[error("invalid numeric literal format")] - Invalid, - #[error("numeric literal not representable by target type")] - NotRepresentable, - #[error("unimplemented f16 type")] - UnimplementedF16, -} - -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum InvalidAssignmentType { - Other, - Swizzle, - ImmutableBinding, -} - -#[derive(Clone, Debug)] -pub enum Error<'a> { - Unexpected(Span, ExpectedToken<'a>), - UnexpectedComponents(Span), - BadNumber(Span, NumberError), - /// A negative signed integer literal where both signed and unsigned, - /// but only non-negative literals are allowed. - NegativeInt(Span), - BadU32Constant(Span), - BadMatrixScalarKind(Span, crate::ScalarKind, u8), - BadAccessor(Span), - BadTexture(Span), - BadTypeCast { - span: Span, - from_type: String, - to_type: String, - }, - BadTextureSampleType { - span: Span, - kind: crate::ScalarKind, - width: u8, - }, - BadIncrDecrReferenceType(Span), - InvalidResolve(ResolveError), - InvalidForInitializer(Span), - /// A break if appeared outside of a continuing block - InvalidBreakIf(Span), - InvalidGatherComponent(Span), - InvalidConstructorComponentType(Span, i32), - InvalidIdentifierUnderscore(Span), - ReservedIdentifierPrefix(Span), - UnknownAddressSpace(Span), - UnknownAttribute(Span), - UnknownBuiltin(Span), - UnknownAccess(Span), - UnknownIdent(Span, &'a str), - UnknownScalarType(Span), - UnknownType(Span), - UnknownStorageFormat(Span), - UnknownConservativeDepth(Span), - SizeAttributeTooLow(Span, u32), - AlignAttributeTooLow(Span, Alignment), - NonPowerOfTwoAlignAttribute(Span), - InconsistentBinding(Span), - TypeNotConstructible(Span), - TypeNotInferrable(Span), - InitializationTypeMismatch(Span, String, String), - MissingType(Span), - MissingAttribute(&'static str, Span), - InvalidAtomicPointer(Span), - InvalidAtomicOperandType(Span), - Pointer(&'static str, Span), - NotPointer(Span), - NotReference(&'static str, Span), - InvalidAssignment { - span: Span, - ty: InvalidAssignmentType, - }, - ReservedKeyword(Span), - /// Redefinition of an identifier (used for both module-scope and local redefinitions). - Redefinition { - /// Span of the identifier in the previous definition. - previous: Span, - - /// Span of the identifier in the new definition. - current: Span, - }, - /// A declaration refers to itself directly. - RecursiveDeclaration { - /// The location of the name of the declaration. - ident: Span, - - /// The point at which it is used. - usage: Span, - }, - /// A declaration refers to itself indirectly, through one or more other - /// definitions. - CyclicDeclaration { - /// The location of the name of some declaration in the cycle. - ident: Span, - - /// The edges of the cycle of references. - /// - /// Each `(decl, reference)` pair indicates that the declaration whose - /// name is `decl` has an identifier at `reference` whose definition is - /// the next declaration in the cycle. The last pair's `reference` is - /// the same identifier as `ident`, above. - path: Vec<(Span, Span)>, - }, - ConstExprUnsupported(Span), - InvalidSwitchValue { - uint: bool, - span: Span, - }, - CalledEntryPoint(Span), - WrongArgumentCount { - span: Span, - expected: Range, - found: u32, - }, - FunctionReturnsVoid(Span), - Other, -} - -impl<'a> Error<'a> { - fn as_parse_error(&self, source: &'a str) -> ParseError { - match *self { - Error::Unexpected(unexpected_span, expected) => { - let expected_str = match expected { - ExpectedToken::Token(token) => { - match token { - Token::Separator(c) => format!("'{c}'"), - Token::Paren(c) => format!("'{c}'"), - Token::Attribute => "@".to_string(), - Token::Number(_) => "number".to_string(), - Token::Word(s) => s.to_string(), - Token::Operation(c) => format!("operation ('{c}')"), - Token::LogicalOperation(c) => format!("logical operation ('{c}')"), - Token::ShiftOperation(c) => format!("bitshift ('{c}{c}')"), - Token::AssignmentOperation(c) if c=='<' || c=='>' => format!("bitshift ('{c}{c}=')"), - Token::AssignmentOperation(c) => format!("operation ('{c}=')"), - Token::IncrementOperation => "increment operation".to_string(), - Token::DecrementOperation => "decrement operation".to_string(), - Token::Arrow => "->".to_string(), - Token::Unknown(c) => format!("unknown ('{c}')"), - Token::Trivia => "trivia".to_string(), - Token::End => "end".to_string(), - } - } - ExpectedToken::Identifier => "identifier".to_string(), - ExpectedToken::Number(ty) => { - match ty { - NumberType::I32 => "32-bit signed integer literal", - NumberType::U32 => "32-bit unsigned integer literal", - NumberType::F32 => "32-bit floating-point literal", - }.to_string() - }, - ExpectedToken::Integer => "unsigned/signed integer literal".to_string(), - ExpectedToken::Constant => "compile-time constant".to_string(), - ExpectedToken::PrimaryExpression => "expression".to_string(), - ExpectedToken::Assignment => "assignment or increment/decrement".to_string(), - ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(), - ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(), - ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(), - ExpectedToken::GlobalItem => "global item ('struct', 'const', 'var', 'type', ';', 'fn') or the end of the file".to_string(), - ExpectedToken::Type => "type".to_string(), - ExpectedToken::Variable => "variable access".to_string(), - ExpectedToken::Function => "function name".to_string(), - }; - ParseError { - message: format!( - "expected {}, found '{}'", - expected_str, &source[unexpected_span], - ), - labels: vec![(unexpected_span, format!("expected {expected_str}").into())], - notes: vec![], - } - } - Error::UnexpectedComponents(bad_span) => ParseError { - message: "unexpected components".to_string(), - labels: vec![(bad_span, "unexpected components".into())], - notes: vec![], - }, - Error::BadNumber(bad_span, ref err) => ParseError { - message: format!("{}: `{}`", err, &source[bad_span],), - labels: vec![(bad_span, err.to_string().into())], - notes: vec![], - }, - Error::NegativeInt(bad_span) => ParseError { - message: format!( - "expected non-negative integer literal, found `{}`", - &source[bad_span], - ), - labels: vec![(bad_span, "expected non-negative integer".into())], - notes: vec![], - }, - Error::BadU32Constant(bad_span) => ParseError { - message: format!( - "expected unsigned integer constant expression, found `{}`", - &source[bad_span], - ), - labels: vec![(bad_span, "expected unsigned integer".into())], - notes: vec![], - }, - Error::BadMatrixScalarKind(span, kind, width) => ParseError { - message: format!( - "matrix scalar type must be floating-point, but found `{}`", - kind.to_wgsl(width) - ), - labels: vec![(span, "must be floating-point (e.g. `f32`)".into())], - notes: vec![], - }, - Error::BadAccessor(accessor_span) => ParseError { - message: format!("invalid field accessor `{}`", &source[accessor_span],), - labels: vec![(accessor_span, "invalid accessor".into())], - notes: vec![], - }, - Error::UnknownIdent(ident_span, ident) => ParseError { - message: format!("no definition in scope for identifier: '{ident}'"), - labels: vec![(ident_span, "unknown identifier".into())], - notes: vec![], - }, - Error::UnknownScalarType(bad_span) => ParseError { - message: format!("unknown scalar type: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown scalar type".into())], - notes: vec!["Valid scalar types are f32, f64, i32, u32, bool".into()], - }, - Error::BadTextureSampleType { span, kind, width } => ParseError { - message: format!( - "texture sample type must be one of f32, i32 or u32, but found {}", - kind.to_wgsl(width) - ), - labels: vec![(span, "must be one of f32, i32 or u32".into())], - notes: vec![], - }, - Error::BadIncrDecrReferenceType(span) => ParseError { - message: - "increment/decrement operation requires reference type to be one of i32 or u32" - .to_string(), - labels: vec![(span, "must be a reference type of i32 or u32".into())], - notes: vec![], - }, - Error::BadTexture(bad_span) => ParseError { - message: format!( - "expected an image, but found '{}' which is not an image", - &source[bad_span] - ), - labels: vec![(bad_span, "not an image".into())], - notes: vec![], - }, - Error::BadTypeCast { - span, - ref from_type, - ref to_type, - } => { - let msg = format!("cannot cast a {from_type} to a {to_type}"); - ParseError { - message: msg.clone(), - labels: vec![(span, msg.into())], - notes: vec![], - } - } - Error::InvalidResolve(ref resolve_error) => ParseError { - message: resolve_error.to_string(), - labels: vec![], - notes: vec![], - }, - Error::InvalidForInitializer(bad_span) => ParseError { - message: format!( - "for(;;) initializer is not an assignment or a function call: '{}'", - &source[bad_span] - ), - labels: vec![(bad_span, "not an assignment or function call".into())], - notes: vec![], - }, - Error::InvalidBreakIf(bad_span) => ParseError { - message: "A break if is only allowed in a continuing block".to_string(), - labels: vec![(bad_span, "not in a continuing block".into())], - notes: vec![], - }, - Error::InvalidGatherComponent(bad_span) => ParseError { - message: format!( - "textureGather component '{}' doesn't exist, must be 0, 1, 2, or 3", - &source[bad_span] - ), - labels: vec![(bad_span, "invalid component".into())], - notes: vec![], - }, - Error::InvalidConstructorComponentType(bad_span, component) => ParseError { - message: format!("invalid type for constructor component at index [{component}]"), - labels: vec![(bad_span, "invalid component type".into())], - notes: vec![], - }, - Error::InvalidIdentifierUnderscore(bad_span) => ParseError { - message: "Identifier can't be '_'".to_string(), - labels: vec![(bad_span, "invalid identifier".into())], - notes: vec![ - "Use phony assignment instead ('_ =' notice the absence of 'let' or 'var')" - .to_string(), - ], - }, - Error::ReservedIdentifierPrefix(bad_span) => ParseError { - message: format!( - "Identifier starts with a reserved prefix: '{}'", - &source[bad_span] - ), - labels: vec![(bad_span, "invalid identifier".into())], - notes: vec![], - }, - Error::UnknownAddressSpace(bad_span) => ParseError { - message: format!("unknown address space: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown address space".into())], - notes: vec![], - }, - Error::UnknownAttribute(bad_span) => ParseError { - message: format!("unknown attribute: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown attribute".into())], - notes: vec![], - }, - Error::UnknownBuiltin(bad_span) => ParseError { - message: format!("unknown builtin: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown builtin".into())], - notes: vec![], - }, - Error::UnknownAccess(bad_span) => ParseError { - message: format!("unknown access: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown access".into())], - notes: vec![], - }, - Error::UnknownStorageFormat(bad_span) => ParseError { - message: format!("unknown storage format: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown storage format".into())], - notes: vec![], - }, - Error::UnknownConservativeDepth(bad_span) => ParseError { - message: format!("unknown conservative depth: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown conservative depth".into())], - notes: vec![], - }, - Error::UnknownType(bad_span) => ParseError { - message: format!("unknown type: '{}'", &source[bad_span]), - labels: vec![(bad_span, "unknown type".into())], - notes: vec![], - }, - Error::SizeAttributeTooLow(bad_span, min_size) => ParseError { - message: format!("struct member size must be at least {min_size}"), - labels: vec![(bad_span, format!("must be at least {min_size}").into())], - notes: vec![], - }, - Error::AlignAttributeTooLow(bad_span, min_align) => ParseError { - message: format!("struct member alignment must be at least {min_align}"), - labels: vec![(bad_span, format!("must be at least {min_align}").into())], - notes: vec![], - }, - Error::NonPowerOfTwoAlignAttribute(bad_span) => ParseError { - message: "struct member alignment must be a power of 2".to_string(), - labels: vec![(bad_span, "must be a power of 2".into())], - notes: vec![], - }, - Error::InconsistentBinding(span) => ParseError { - message: "input/output binding is not consistent".to_string(), - labels: vec![(span, "input/output binding is not consistent".into())], - notes: vec![], - }, - Error::TypeNotConstructible(span) => ParseError { - message: format!("type `{}` is not constructible", &source[span]), - labels: vec![(span, "type is not constructible".into())], - notes: vec![], - }, - Error::TypeNotInferrable(span) => ParseError { - message: "type can't be inferred".to_string(), - labels: vec![(span, "type can't be inferred".into())], - notes: vec![], - }, - Error::InitializationTypeMismatch(name_span, ref expected_ty, ref got_ty) => { - ParseError { - message: format!( - "the type of `{}` is expected to be `{}`, but got `{}`", - &source[name_span], expected_ty, got_ty, - ), - labels: vec![( - name_span, - format!("definition of `{}`", &source[name_span]).into(), - )], - notes: vec![], - } - } - Error::MissingType(name_span) => ParseError { - message: format!("variable `{}` needs a type", &source[name_span]), - labels: vec![( - name_span, - format!("definition of `{}`", &source[name_span]).into(), - )], - notes: vec![], - }, - Error::MissingAttribute(name, name_span) => ParseError { - message: format!( - "variable `{}` needs a '{}' attribute", - &source[name_span], name - ), - labels: vec![( - name_span, - format!("definition of `{}`", &source[name_span]).into(), - )], - notes: vec![], - }, - Error::InvalidAtomicPointer(span) => ParseError { - message: "atomic operation is done on a pointer to a non-atomic".to_string(), - labels: vec![(span, "atomic pointer is invalid".into())], - notes: vec![], - }, - Error::InvalidAtomicOperandType(span) => ParseError { - message: "atomic operand type is inconsistent with the operation".to_string(), - labels: vec![(span, "atomic operand type is invalid".into())], - notes: vec![], - }, - Error::NotPointer(span) => ParseError { - message: "the operand of the `*` operator must be a pointer".to_string(), - labels: vec![(span, "expression is not a pointer".into())], - notes: vec![], - }, - Error::NotReference(what, span) => ParseError { - message: format!("{what} must be a reference"), - labels: vec![(span, "expression is not a reference".into())], - notes: vec![], - }, - Error::InvalidAssignment { span, ty } => ParseError { - message: "invalid left-hand side of assignment".into(), - labels: vec![(span, "cannot assign to this expression".into())], - notes: match ty { - InvalidAssignmentType::Swizzle => vec![ - "WGSL does not support assignments to swizzles".into(), - "consider assigning each component individually".into(), - ], - InvalidAssignmentType::ImmutableBinding => vec![ - format!("'{}' is an immutable binding", &source[span]), - "consider declaring it with `var` instead of `let`".into(), - ], - InvalidAssignmentType::Other => vec![], - }, - }, - Error::Pointer(what, span) => ParseError { - message: format!("{what} must not be a pointer"), - labels: vec![(span, "expression is a pointer".into())], - notes: vec![], - }, - Error::ReservedKeyword(name_span) => ParseError { - message: format!("name `{}` is a reserved keyword", &source[name_span]), - labels: vec![( - name_span, - format!("definition of `{}`", &source[name_span]).into(), - )], - notes: vec![], - }, - Error::Redefinition { previous, current } => ParseError { - message: format!("redefinition of `{}`", &source[current]), - labels: vec![ - ( - current, - format!("redefinition of `{}`", &source[current]).into(), - ), - ( - previous, - format!("previous definition of `{}`", &source[previous]).into(), - ), - ], - notes: vec![], - }, - Error::RecursiveDeclaration { ident, usage } => ParseError { - message: format!("declaration of `{}` is recursive", &source[ident]), - labels: vec![(ident, "".into()), (usage, "uses itself here".into())], - notes: vec![], - }, - Error::CyclicDeclaration { ident, ref path } => ParseError { - message: format!("declaration of `{}` is cyclic", &source[ident]), - labels: path - .iter() - .enumerate() - .flat_map(|(i, &(ident, usage))| { - [ - (ident, "".into()), - ( - usage, - if i == path.len() - 1 { - "ending the cycle".into() - } else { - format!("uses `{}`", &source[ident]).into() - }, - ), - ] - }) - .collect(), - notes: vec![], - }, - Error::ConstExprUnsupported(span) => ParseError { - message: "this constant expression is not supported".to_string(), - labels: vec![(span, "expression is not supported".into())], - notes: vec![ - "this should be fixed in a future version of Naga".into(), - "https://github.com/gfx-rs/naga/issues/1829".into(), - ], - }, - Error::InvalidSwitchValue { uint, span } => ParseError { - message: "invalid switch value".to_string(), - labels: vec![( - span, - if uint { - "expected unsigned integer" - } else { - "expected signed integer" - } - .into(), - )], - notes: vec![if uint { - format!("suffix the integer with a `u`: '{}u'", &source[span]) - } else { - let span = span.to_range().unwrap(); - format!( - "remove the `u` suffix: '{}'", - &source[span.start..span.end - 1] - ) - }], - }, - Error::CalledEntryPoint(span) => ParseError { - message: "entry point cannot be called".to_string(), - labels: vec![(span, "entry point cannot be called".into())], - notes: vec![], - }, - Error::WrongArgumentCount { - span, - ref expected, - found, - } => ParseError { - message: format!( - "wrong number of arguments: expected {}, found {}", - if expected.len() < 2 { - format!("{}", expected.start) - } else { - format!("{}..{}", expected.start, expected.end) - }, - found - ), - labels: vec![(span, "wrong number of arguments".into())], - notes: vec![], - }, - Error::FunctionReturnsVoid(span) => ParseError { - message: "function does not return any value".to_string(), - labels: vec![(span, "".into())], - notes: vec![ - "perhaps you meant to call the function in a separate statement?".into(), - ], - }, - Error::Other => ParseError { - message: "other error".to_string(), - labels: vec![], - notes: vec![], - }, +impl Frontend { + pub const fn new() -> Self { + Self { + parser: Parser::new(), } } + + pub fn parse(&mut self, source: &str) -> Result { + self.inner(source).map_err(|x| x.as_parse_error(source)) + } + + fn inner<'a>(&mut self, source: &'a str) -> Result> { + let tu = self.parser.parse(source)?; + let index = index::Index::generate(&tu)?; + let module = Lowerer::new(&index).lower(&tu)?; + + Ok(module) + } +} + +pub fn parse_str(source: &str) -> Result { + Frontend::new().parse(source) } impl crate::StorageFormat { @@ -936,4512 +336,3 @@ impl crate::ScalarKind { format!("{}{}", prefix, width * 8) } } - -/// State for constructing an AST expression. -struct ParseExpressionContext<'input, 'temp, 'out> { - /// The [`TranslationUnit::expressions`] arena to which we should contribute - /// expressions. - /// - /// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions - expressions: &'out mut Arena>, - - /// The [`TranslationUnit::types`] arena to which we should contribute new - /// types. - /// - /// [`TranslationUnit::types`]: ast::TranslationUnit::types - types: &'out mut Arena>, - - /// A map from identifiers in scope to the locals/arguments they represent. - /// - /// The handles refer to the [`Function::locals`] area; see that field's - /// documentation for details. - /// - /// [`Function::locals`]: ast::Function::locals - local_table: &'temp mut super::SymbolTable<&'input str, Handle>, - - /// The [`Function::locals`] arena for the function we're building. - /// - /// [`Function::locals`]: ast::Function::locals - locals: &'out mut Arena, - - /// Identifiers used by the current global declaration that have no local definition. - /// - /// This becomes the [`GlobalDecl`]'s [`dependencies`] set. - /// - /// Note that we don't know at parse time what kind of [`GlobalDecl`] the - /// name refers to. We can't look up names until we've seen the entire - /// translation unit. - /// - /// [`GlobalDecl`]: ast::GlobalDecl - /// [`dependencies`]: ast::GlobalDecl::dependencies - unresolved: &'out mut FastHashSet>, -} - -impl<'a> ParseExpressionContext<'a, '_, '_> { - fn reborrow(&mut self) -> ParseExpressionContext<'a, '_, '_> { - ParseExpressionContext { - expressions: self.expressions, - types: self.types, - local_table: self.local_table, - locals: self.locals, - unresolved: self.unresolved, - } - } - - fn parse_binary_op( - &mut self, - lexer: &mut Lexer<'a>, - classifier: impl Fn(Token<'a>) -> Option, - mut parser: impl FnMut( - &mut Lexer<'a>, - ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>>, - ) -> Result>, Error<'a>> { - let start = lexer.start_byte_offset(); - let mut accumulator = parser(lexer, self.reborrow())?; - while let Some(op) = classifier(lexer.peek().0) { - let _ = lexer.next(); - let left = accumulator; - let right = parser(lexer, self.reborrow())?; - accumulator = self.expressions.append( - ast::Expression::Binary { op, left, right }, - lexer.span_from(start), - ); - } - Ok(accumulator) - } -} - -/// State for constructing a `crate::Module`. -struct OutputContext<'source, 'temp, 'out> { - /// The `TranslationUnit`'s expressions arena. - ast_expressions: &'temp Arena>, - - /// The `TranslationUnit`'s types arena. - types: &'temp Arena>, - - // Naga IR values. - /// The map from the names of module-scope declarations to the Naga IR - /// `Handle`s we have built for them, owned by `Lowerer::lower`. - globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, - - /// The module we're constructing. - module: &'out mut crate::Module, -} - -impl<'source> OutputContext<'source, '_, '_> { - fn reborrow(&mut self) -> OutputContext<'source, '_, '_> { - OutputContext { - ast_expressions: self.ast_expressions, - globals: self.globals, - types: self.types, - module: self.module, - } - } - - fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { - self.module - .types - .insert(crate::Type { inner, name: None }, Span::UNDEFINED) - } -} - -/// State for lowering a statement within a function. -struct StatementContext<'source, 'temp, 'out> { - // WGSL AST values. - /// A reference to [`TranslationUnit::expressions`] for the translation unit - /// we're lowering. - /// - /// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions - ast_expressions: &'temp Arena>, - - /// A reference to [`TranslationUnit::types`] for the translation unit - /// we're lowering. - /// - /// [`TranslationUnit::types`]: ast::TranslationUnit::types - types: &'temp Arena>, - - // Naga IR values. - /// The map from the names of module-scope declarations to the Naga IR - /// `Handle`s we have built for them, owned by `Lowerer::lower`. - globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, - - /// A map from `ast::Local` handles to the Naga expressions we've built for them. - /// - /// The Naga expressions are either [`LocalVariable`] or - /// [`FunctionArgument`] expressions. - /// - /// [`LocalVariable`]: crate::Expression::LocalVariable - /// [`FunctionArgument`]: crate::Expression::FunctionArgument - local_table: &'temp mut FastHashMap, TypedExpression>, - - typifier: &'temp mut super::Typifier, - variables: &'out mut Arena, - naga_expressions: &'out mut Arena, - named_expressions: &'out mut FastHashMap, String>, - arguments: &'out [crate::FunctionArgument], - module: &'out mut crate::Module, -} - -impl<'a, 'temp> StatementContext<'a, 'temp, '_> { - fn reborrow(&mut self) -> StatementContext<'a, '_, '_> { - StatementContext { - local_table: self.local_table, - globals: self.globals, - types: self.types, - ast_expressions: self.ast_expressions, - typifier: self.typifier, - variables: self.variables, - naga_expressions: self.naga_expressions, - named_expressions: self.named_expressions, - arguments: self.arguments, - module: self.module, - } - } - - fn as_expression<'t>( - &'t mut self, - block: &'t mut crate::Block, - emitter: &'t mut super::Emitter, - ) -> ExpressionContext<'a, 't, '_> - where - 'temp: 't, - { - ExpressionContext { - local_table: self.local_table, - globals: self.globals, - types: self.types, - ast_expressions: self.ast_expressions, - typifier: self.typifier, - naga_expressions: self.naga_expressions, - module: self.module, - local_vars: self.variables, - arguments: self.arguments, - block, - emitter, - } - } - - fn as_output(&mut self) -> OutputContext<'a, '_, '_> { - OutputContext { - ast_expressions: self.ast_expressions, - globals: self.globals, - types: self.types, - module: self.module, - } - } -} - -struct ExpressionContext<'source, 'temp, 'out> { - // WGSL AST values. - local_table: &'temp mut FastHashMap, TypedExpression>, - ast_expressions: &'temp Arena>, - types: &'temp Arena>, - - // Naga IR values. - /// The map from the names of module-scope declarations to the Naga IR - /// `Handle`s we have built for them, owned by `Lowerer::lower`. - globals: &'temp mut FastHashMap<&'source str, LoweredGlobalDecl>, - - typifier: &'temp mut super::Typifier, - naga_expressions: &'out mut Arena, - local_vars: &'out Arena, - arguments: &'out [crate::FunctionArgument], - module: &'out mut crate::Module, - block: &'temp mut crate::Block, - emitter: &'temp mut super::Emitter, -} - -impl<'a> ExpressionContext<'a, '_, '_> { - fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { - ExpressionContext { - local_table: self.local_table, - globals: self.globals, - types: self.types, - ast_expressions: self.ast_expressions, - typifier: self.typifier, - naga_expressions: self.naga_expressions, - module: self.module, - local_vars: self.local_vars, - arguments: self.arguments, - block: self.block, - emitter: self.emitter, - } - } - - fn as_output(&mut self) -> OutputContext<'a, '_, '_> { - OutputContext { - ast_expressions: self.ast_expressions, - globals: self.globals, - types: self.types, - module: self.module, - } - } - - /// Determine the type of `handle`, and add it to the module's arena. - /// - /// If you just need a `TypeInner` for `handle`'s type, use - /// [`grow_types`] and [`resolved_inner`] instead. This function - /// should only be used when the type of `handle` needs to appear - /// in the module's final `Arena`, for example, if you're - /// creating a [`LocalVariable`] whose type is inferred from its - /// initializer. - /// - /// [`grow_types`]: Self::grow_types - /// [`resolved_inner`]: Self::resolved_inner - /// [`LocalVariable`]: crate::LocalVariable - fn register_type( - &mut self, - handle: Handle, - ) -> Result, Error<'a>> { - self.grow_types(handle)?; - Ok(self.typifier.register_type(handle, &mut self.module.types)) - } - - /// Resolve the types of all expressions up through `handle`. - /// - /// Ensure that [`self.typifier`] has a [`TypeResolution`] for - /// every expression in [`self.naga_expressions`]. - /// - /// This does not add types to any arena. The [`Typifier`] - /// documentation explains the steps we take to avoid filling - /// arenas with intermediate types. - /// - /// This function takes `&mut self`, so it can't conveniently - /// return a shared reference to the resulting `TypeResolution`: - /// the shared reference would extend the mutable borrow, and you - /// wouldn't be able to use `self` for anything else. Instead, you - /// should call `grow_types` to cover the handles you need, and - /// then use `self.typifier[handle]` or - /// [`self.resolved_inner(handle)`] to get at their resolutions. - /// - /// [`self.typifier`]: ExpressionContext::typifier - /// [`self.resolved_inner(handle)`]: ExpressionContext::resolved_inner - /// [`Typifier`]: super::Typifier - fn grow_types(&mut self, handle: Handle) -> Result<&mut Self, Error<'a>> { - let resolve_ctx = ResolveContext { - constants: &self.module.constants, - types: &self.module.types, - global_vars: &self.module.global_variables, - local_vars: self.local_vars, - functions: &self.module.functions, - arguments: self.arguments, - }; - self.typifier - .grow(handle, self.naga_expressions, &resolve_ctx) - .map_err(Error::InvalidResolve)?; - Ok(self) - } - - fn resolved_inner(&self, handle: Handle) -> &crate::TypeInner { - self.typifier[handle].inner_with(&self.module.types) - } - - fn image_data( - &mut self, - image: Handle, - span: Span, - ) -> Result<(crate::ImageClass, bool), Error<'a>> { - self.grow_types(image)?; - match *self.resolved_inner(image) { - crate::TypeInner::Image { class, arrayed, .. } => Ok((class, arrayed)), - _ => Err(Error::BadTexture(span)), - } - } - - fn prepare_args<'b>( - &mut self, - args: &'b [Handle>], - min_args: u32, - span: Span, - ) -> ArgumentContext<'b, 'a> { - ArgumentContext { - args: args.iter(), - min_args, - args_used: 0, - total_args: args.len() as u32, - span, - } - } - - /// Insert splats, if needed by the non-'*' operations. - fn binary_op_splat( - &mut self, - op: crate::BinaryOperator, - left: &mut Handle, - right: &mut Handle, - ) -> Result<(), Error<'a>> { - if op != crate::BinaryOperator::Multiply { - self.grow_types(*left)?.grow_types(*right)?; - - let left_size = match *self.resolved_inner(*left) { - crate::TypeInner::Vector { size, .. } => Some(size), - _ => None, - }; - - match (left_size, self.resolved_inner(*right)) { - (Some(size), &crate::TypeInner::Scalar { .. }) => { - *right = self.naga_expressions.append( - crate::Expression::Splat { - size, - value: *right, - }, - self.naga_expressions.get_span(*right), - ); - } - (None, &crate::TypeInner::Vector { size, .. }) => { - *left = self.naga_expressions.append( - crate::Expression::Splat { size, value: *left }, - self.naga_expressions.get_span(*left), - ); - } - _ => {} - } - } - - Ok(()) - } - - /// Add a single expression to the expression table that is not covered by `self.emitter`. - /// - /// This is useful for `CallResult` and `AtomicResult` expressions, which should not be covered by - /// `Emit` statements. - fn interrupt_emitter( - &mut self, - expression: crate::Expression, - span: Span, - ) -> Handle { - self.block - .extend(self.emitter.finish(self.naga_expressions)); - let result = self.naga_expressions.append(expression, span); - self.emitter.start(self.naga_expressions); - result - } - - /// Apply the WGSL Load Rule to `expr`. - /// - /// If `expr` is has type `ref`, perform a load to produce a value of type - /// `T`. Otherwise, return `expr` unchanged. - fn apply_load_rule(&mut self, expr: TypedExpression) -> Handle { - if expr.is_reference { - let load = crate::Expression::Load { - pointer: expr.handle, - }; - let span = self.naga_expressions.get_span(expr.handle); - self.naga_expressions.append(load, span) - } else { - expr.handle - } - } - - /// Creates a zero value constant of type `ty` - /// - /// Returns `None` if the given `ty` is not a constructible type - fn create_zero_value_constant( - &mut self, - ty: Handle, - ) -> Option> { - let inner = match self.module.types[ty].inner { - crate::TypeInner::Scalar { kind, width } => { - let value = match kind { - crate::ScalarKind::Sint => crate::ScalarValue::Sint(0), - crate::ScalarKind::Uint => crate::ScalarValue::Uint(0), - crate::ScalarKind::Float => crate::ScalarValue::Float(0.), - crate::ScalarKind::Bool => crate::ScalarValue::Bool(false), - }; - crate::ConstantInner::Scalar { width, value } - } - crate::TypeInner::Vector { size, kind, width } => { - let scalar_ty = self.ensure_type_exists(crate::TypeInner::Scalar { width, kind }); - let component = self.create_zero_value_constant(scalar_ty); - crate::ConstantInner::Composite { - ty, - components: (0..size as u8).map(|_| component).collect::>()?, - } - } - crate::TypeInner::Matrix { - columns, - rows, - width, - } => { - let vec_ty = self.ensure_type_exists(crate::TypeInner::Vector { - width, - kind: crate::ScalarKind::Float, - size: rows, - }); - let component = self.create_zero_value_constant(vec_ty); - crate::ConstantInner::Composite { - ty, - components: (0..columns as u8) - .map(|_| component) - .collect::>()?, - } - } - crate::TypeInner::Array { - base, - size: crate::ArraySize::Constant(size), - .. - } => { - let component = self.create_zero_value_constant(base); - crate::ConstantInner::Composite { - ty, - components: (0..self.module.constants[size].to_array_length().unwrap()) - .map(|_| component) - .collect::>()?, - } - } - crate::TypeInner::Struct { ref members, .. } => { - let members = members.clone(); - crate::ConstantInner::Composite { - ty, - components: members - .iter() - .map(|member| self.create_zero_value_constant(member.ty)) - .collect::>()?, - } - } - _ => return None, - }; - - let constant = self.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - Span::UNDEFINED, - ); - Some(constant) - } - - fn format_typeinner(&self, inner: &crate::TypeInner) -> String { - inner.to_wgsl(&self.module.types, &self.module.constants) - } - - fn format_type(&self, handle: Handle) -> String { - let ty = &self.module.types[handle]; - match ty.name { - Some(ref name) => name.clone(), - None => self.format_typeinner(&ty.inner), - } - } - - fn format_type_resolution(&self, resolution: &TypeResolution) -> String { - match *resolution { - TypeResolution::Handle(handle) => self.format_type(handle), - TypeResolution::Value(ref inner) => self.format_typeinner(inner), - } - } - - fn ensure_type_exists(&mut self, inner: crate::TypeInner) -> Handle { - self.as_output().ensure_type_exists(inner) - } -} - -struct ArgumentContext<'ctx, 'source> { - args: std::slice::Iter<'ctx, Handle>>, - min_args: u32, - args_used: u32, - total_args: u32, - span: Span, -} - -impl<'source> ArgumentContext<'_, 'source> { - pub fn finish(self) -> Result<(), Error<'source>> { - if self.args.len() == 0 { - Ok(()) - } else { - Err(Error::WrongArgumentCount { - found: self.total_args, - expected: self.min_args..self.args_used + 1, - span: self.span, - }) - } - } - - pub fn next(&mut self) -> Result>, Error<'source>> { - match self.args.next().copied() { - Some(arg) => { - self.args_used += 1; - Ok(arg) - } - None => Err(Error::WrongArgumentCount { - found: self.total_args, - expected: self.min_args..self.args_used + 1, - span: self.span, - }), - } - } -} - -/// A Naga [`Expression`] handle, with WGSL type information. -/// -/// Naga and WGSL types are very close, but Naga lacks WGSL's 'reference' types, -/// which we need to know to apply the Load Rule. This struct carries a Naga -/// `Handle` along with enough information to determine its WGSL type. -/// -/// [`Expression`]: crate::Expression -#[derive(Debug, Copy, Clone)] -struct TypedExpression { - /// The handle of the Naga expression. - handle: Handle, - - /// True if this expression's WGSL type is a reference. - /// - /// When this is true, `handle` must be a pointer. - is_reference: bool, -} - -impl TypedExpression { - const fn non_reference(handle: Handle) -> TypedExpression { - TypedExpression { - handle, - is_reference: false, - } - } -} - -enum Composition { - Single(u32), - Multi(crate::VectorSize, [crate::SwizzleComponent; 4]), -} - -impl Composition { - const fn letter_component(letter: char) -> Option { - use crate::SwizzleComponent as Sc; - match letter { - 'x' | 'r' => Some(Sc::X), - 'y' | 'g' => Some(Sc::Y), - 'z' | 'b' => Some(Sc::Z), - 'w' | 'a' => Some(Sc::W), - _ => None, - } - } - - fn extract_impl(name: &str, name_span: Span) -> Result { - let ch = name.chars().next().ok_or(Error::BadAccessor(name_span))?; - match Self::letter_component(ch) { - Some(sc) => Ok(sc as u32), - None => Err(Error::BadAccessor(name_span)), - } - } - - fn make(name: &str, name_span: Span) -> Result { - if name.len() > 1 { - let mut components = [crate::SwizzleComponent::X; 4]; - for (comp, ch) in components.iter_mut().zip(name.chars()) { - *comp = Self::letter_component(ch).ok_or(Error::BadAccessor(name_span))?; - } - - let size = match name.len() { - 2 => crate::VectorSize::Bi, - 3 => crate::VectorSize::Tri, - 4 => crate::VectorSize::Quad, - _ => return Err(Error::BadAccessor(name_span)), - }; - Ok(Composition::Multi(size, components)) - } else { - Self::extract_impl(name, name_span).map(Composition::Single) - } - } -} - -/// Which grammar rule we are in the midst of parsing. -/// -/// This is used for error checking. `Parser` maintains a stack of -/// these and (occasionally) checks that it is being pushed and popped -/// as expected. -#[derive(Clone, Debug, PartialEq)] -enum Rule { - Attribute, - VariableDecl, - TypeDecl, - FunctionDecl, - Block, - Statement, - PrimaryExpr, - SingularExpr, - UnaryExpr, - GeneralExpr, -} - -#[derive(Default)] -struct BindingParser { - location: Option, - built_in: Option, - interpolation: Option, - sampling: Option, - invariant: bool, -} - -impl BindingParser { - fn parse<'a>( - &mut self, - lexer: &mut Lexer<'a>, - name: &'a str, - name_span: Span, - ) -> Result<(), Error<'a>> { - match name { - "location" => { - lexer.expect(Token::Paren('('))?; - self.location = Some(Parser::non_negative_i32_literal(lexer)?); - lexer.expect(Token::Paren(')'))?; - } - "builtin" => { - lexer.expect(Token::Paren('('))?; - let (raw, span) = lexer.next_ident_with_span()?; - self.built_in = Some(conv::map_built_in(raw, span)?); - lexer.expect(Token::Paren(')'))?; - } - "interpolate" => { - lexer.expect(Token::Paren('('))?; - let (raw, span) = lexer.next_ident_with_span()?; - self.interpolation = Some(conv::map_interpolation(raw, span)?); - if lexer.skip(Token::Separator(',')) { - let (raw, span) = lexer.next_ident_with_span()?; - self.sampling = Some(conv::map_sampling(raw, span)?); - } - lexer.expect(Token::Paren(')'))?; - } - "invariant" => self.invariant = true, - _ => return Err(Error::UnknownAttribute(name_span)), - } - Ok(()) - } - - const fn finish<'a>(self, span: Span) -> Result, Error<'a>> { - match ( - self.location, - self.built_in, - self.interpolation, - self.sampling, - self.invariant, - ) { - (None, None, None, None, false) => Ok(None), - (Some(location), None, interpolation, sampling, false) => { - // Before handing over the completed `Module`, we call - // `apply_default_interpolation` to ensure that the interpolation and - // sampling have been explicitly specified on all vertex shader output and fragment - // shader input user bindings, so leaving them potentially `None` here is fine. - Ok(Some(crate::Binding::Location { - location, - interpolation, - sampling, - })) - } - (None, Some(crate::BuiltIn::Position { .. }), None, None, invariant) => { - Ok(Some(crate::Binding::BuiltIn(crate::BuiltIn::Position { - invariant, - }))) - } - (None, Some(built_in), None, None, false) => { - Ok(Some(crate::Binding::BuiltIn(built_in))) - } - (_, _, _, _, _) => Err(Error::InconsistentBinding(span)), - } - } -} - -#[derive(Clone, Debug)] -pub struct ParseError { - message: String, - labels: Vec<(Span, Cow<'static, str>)>, - notes: Vec, -} - -impl ParseError { - pub fn labels(&self) -> impl Iterator + ExactSizeIterator + '_ { - self.labels - .iter() - .map(|&(span, ref msg)| (span, msg.as_ref())) - } - - pub fn message(&self) -> &str { - &self.message - } - - fn diagnostic(&self) -> Diagnostic<()> { - let diagnostic = Diagnostic::error() - .with_message(self.message.to_string()) - .with_labels( - self.labels - .iter() - .map(|label| { - Label::primary((), label.0.to_range().unwrap()) - .with_message(label.1.to_string()) - }) - .collect(), - ) - .with_notes( - self.notes - .iter() - .map(|note| format!("note: {note}")) - .collect(), - ); - diagnostic - } - - /// Emits a summary of the error to standard error stream. - pub fn emit_to_stderr(&self, source: &str) { - self.emit_to_stderr_with_path(source, "wgsl") - } - - /// Emits a summary of the error to standard error stream. - pub fn emit_to_stderr_with_path(&self, source: &str, path: &str) { - let files = SimpleFile::new(path, source); - let config = codespan_reporting::term::Config::default(); - let writer = StandardStream::stderr(ColorChoice::Auto); - term::emit(&mut writer.lock(), &config, &files, &self.diagnostic()) - .expect("cannot write error"); - } - - /// Emits a summary of the error to a string. - pub fn emit_to_string(&self, source: &str) -> String { - self.emit_to_string_with_path(source, "wgsl") - } - - /// Emits a summary of the error to a string. - pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String { - let files = SimpleFile::new(path, source); - let config = codespan_reporting::term::Config::default(); - let mut writer = NoColor::new(Vec::new()); - term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error"); - String::from_utf8(writer.into_inner()).unwrap() - } - - /// Returns a [`SourceLocation`] for the first label in the error message. - pub fn location(&self, source: &str) -> Option { - self.labels.get(0).map(|label| label.0.location(source)) - } -} - -impl std::fmt::Display for ParseError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.message) - } -} - -impl std::error::Error for ParseError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - None - } -} - -pub struct Parser { - rules: Vec<(Rule, usize)>, -} - -impl Parser { - pub const fn new() -> Self { - Parser { rules: Vec::new() } - } - - fn reset(&mut self) { - self.rules.clear(); - } - - fn push_rule_span(&mut self, rule: Rule, lexer: &mut Lexer<'_>) { - self.rules.push((rule, lexer.start_byte_offset())); - } - - fn pop_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { - let (_, initial) = self.rules.pop().unwrap(); - lexer.span_from(initial) - } - - fn peek_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { - let &(_, initial) = self.rules.last().unwrap(); - lexer.span_from(initial) - } - - fn switch_value<'a>(lexer: &mut Lexer<'a>) -> Result<(ast::SwitchValue, Span), Error<'a>> { - let token_span = lexer.next(); - match token_span.0 { - Token::Word("default") => Ok((ast::SwitchValue::Default, token_span.1)), - Token::Number(Ok(Number::U32(num))) => Ok((ast::SwitchValue::U32(num), token_span.1)), - Token::Number(Ok(Number::I32(num))) => Ok((ast::SwitchValue::I32(num), token_span.1)), - Token::Number(Err(e)) => Err(Error::BadNumber(token_span.1, e)), - _ => Err(Error::Unexpected(token_span.1, ExpectedToken::Integer)), - } - } - - /// Parse a non-negative signed integer literal. - /// This is for attributes like `size`, `location` and others. - fn non_negative_i32_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { - match lexer.next() { - (Token::Number(Ok(Number::I32(num))), span) => { - u32::try_from(num).map_err(|_| Error::NegativeInt(span)) - } - (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), - other => Err(Error::Unexpected( - other.1, - ExpectedToken::Number(NumberType::I32), - )), - } - } - - /// Parse a non-negative integer literal that may be either signed or unsigned. - /// This is for the `workgroup_size` attribute and array lengths. - /// Note: these values should be no larger than [`i32::MAX`], but this is not checked here. - fn generic_non_negative_int_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { - match lexer.next() { - (Token::Number(Ok(Number::I32(num))), span) => { - u32::try_from(num).map_err(|_| Error::NegativeInt(span)) - } - (Token::Number(Ok(Number::U32(num))), _) => Ok(num), - (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), - other => Err(Error::Unexpected( - other.1, - ExpectedToken::Number(NumberType::I32), - )), - } - } - - /// 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, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - if let Some((kind, width)) = conv::get_scalar_type(word) { - return Ok(Some(ast::ConstructorType::Scalar { kind, width })); - } - - let partial = match word { - "vec2" => ast::ConstructorType::PartialVector { - size: crate::VectorSize::Bi, - }, - "vec3" => ast::ConstructorType::PartialVector { - size: crate::VectorSize::Tri, - }, - "vec4" => ast::ConstructorType::PartialVector { - size: crate::VectorSize::Quad, - }, - "mat2x2" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Bi, - rows: crate::VectorSize::Bi, - }, - "mat2x3" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Bi, - rows: crate::VectorSize::Tri, - }, - "mat2x4" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Bi, - rows: crate::VectorSize::Quad, - }, - "mat3x2" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Tri, - rows: crate::VectorSize::Bi, - }, - "mat3x3" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Tri, - rows: crate::VectorSize::Tri, - }, - "mat3x4" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Tri, - rows: crate::VectorSize::Quad, - }, - "mat4x2" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Quad, - rows: crate::VectorSize::Bi, - }, - "mat4x3" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Quad, - rows: crate::VectorSize::Tri, - }, - "mat4x4" => ast::ConstructorType::PartialMatrix { - columns: crate::VectorSize::Quad, - rows: crate::VectorSize::Quad, - }, - "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_storage_1d" - | "texture_storage_1d_array" - | "texture_storage_2d" - | "texture_storage_2d_array" - | "texture_storage_3d" => return Err(Error::TypeNotConstructible(span)), - _ => return Ok(None), - }; - - // parse component type if present - match (lexer.peek().0, partial) { - (Token::Paren('<'), ast::ConstructorType::PartialVector { size }) => { - let (kind, width) = lexer.next_scalar_generic()?; - Ok(Some(ast::ConstructorType::Vector { size, kind, width })) - } - (Token::Paren('<'), ast::ConstructorType::PartialMatrix { columns, rows }) => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - match kind { - crate::ScalarKind::Float => Ok(Some(ast::ConstructorType::Matrix { - columns, - rows, - width, - })), - _ => Err(Error::BadMatrixScalarKind(span, kind, width)), - } - } - (Token::Paren('<'), ast::ConstructorType::PartialArray) => { - lexer.expect_generic_paren('<')?; - let base = self.type_decl(lexer, ctx.reborrow())?; - let size = if lexer.skip(Token::Separator(',')) { - let expr = self.unary_expression(lexer, ctx.reborrow())?; - ast::ArraySize::Constant(expr) - } else { - ast::ArraySize::Dynamic - }; - lexer.expect_generic_paren('>')?; - - Ok(Some(ast::ConstructorType::Array { base, size })) - } - (_, partial) => Ok(Some(partial)), - } - } - - /// Expects `name` to be consumed (not in lexer). - fn arguments<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>>, Error<'a>> { - lexer.open_arguments()?; - let mut arguments = Vec::new(); - loop { - if !arguments.is_empty() { - if !lexer.next_argument()? { - break; - } - } else if lexer.skip(Token::Paren(')')) { - break; - } - let arg = self.general_expression(lexer, ctx.reborrow())?; - arguments.push(arg); - } - - Ok(arguments) - } - - /// Expects [`Rule::PrimaryExpr`] or [`Rule::SingularExpr`] on top; does not pop it. - /// Expects `name` to be consumed (not in lexer). - fn function_call<'a>( - &mut self, - lexer: &mut Lexer<'a>, - name: &'a str, - name_span: Span, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - assert!(self.rules.last().is_some()); - - let expr = match name { - // bitcast looks like a function call, but it's an operator and must be handled differently. - "bitcast" => { - lexer.expect_generic_paren('<')?; - let start = lexer.start_byte_offset(); - let to = self.type_decl(lexer, ctx.reborrow())?; - let span = lexer.span_from(start); - lexer.expect_generic_paren('>')?; - - lexer.open_arguments()?; - let expr = self.general_expression(lexer, ctx.reborrow())?; - 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 arguments = self.arguments(lexer, ctx.reborrow())?; - ctx.unresolved.insert(ast::Dependency { - ident: name, - usage: name_span, - }); - ast::Expression::Call { - function: ast::Ident { - name, - span: name_span, - }, - arguments, - } - } - }; - - let span = self.peek_rule_span(lexer); - let expr = ctx.expressions.append(expr, span); - Ok(expr) - } - - fn ident_expr<'a>( - &mut self, - name: &'a str, - name_span: Span, - ctx: ParseExpressionContext<'a, '_, '_>, - ) -> ast::IdentExpr<'a> { - match ctx.local_table.lookup(name) { - Some(&local) => ast::IdentExpr::Local(local), - None => { - ctx.unresolved.insert(ast::Dependency { - ident: name, - usage: name_span, - }); - ast::IdentExpr::Unresolved(name) - } - } - } - - fn primary_expression<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - self.push_rule_span(Rule::PrimaryExpr, lexer); - - let expr = match lexer.peek() { - (Token::Paren('('), _) => { - let _ = lexer.next(); - let expr = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(')'))?; - self.pop_rule_span(lexer); - return Ok(expr); - } - (Token::Word("true"), _) => { - let _ = lexer.next(); - ast::Expression::Literal(ast::Literal::Bool(true)) - } - (Token::Word("false"), _) => { - let _ = lexer.next(); - ast::Expression::Literal(ast::Literal::Bool(false)) - } - (Token::Number(res), span) => { - let _ = lexer.next(); - let num = res.map_err(|err| Error::BadNumber(span, err))?; - ast::Expression::Literal(ast::Literal::Number(num)) - } - (Token::Word(word), span) => { - let start = lexer.start_byte_offset(); - let _ = lexer.next(); - - if let Some(ty) = self.constructor_type(lexer, word, span, ctx.reborrow())? { - let ty_span = lexer.span_from(start); - let components = self.arguments(lexer, ctx.reborrow())?; - ast::Expression::Construct { - ty, - ty_span, - components, - } - } else if let Token::Paren('(') = lexer.peek().0 { - self.pop_rule_span(lexer); - return self.function_call(lexer, word, span, ctx); - } else if word == "bitcast" { - self.pop_rule_span(lexer); - return self.function_call(lexer, word, span, ctx); - } else { - let ident = self.ident_expr(word, span, ctx.reborrow()); - ast::Expression::Ident(ident) - } - } - other => return Err(Error::Unexpected(other.1, ExpectedToken::PrimaryExpression)), - }; - - let span = self.pop_rule_span(lexer); - let expr = ctx.expressions.append(expr, span); - Ok(expr) - } - - fn postfix<'a>( - &mut self, - span_start: usize, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - expr: Handle>, - ) -> Result>, Error<'a>> { - let mut expr = expr; - - loop { - let expression = match lexer.peek().0 { - Token::Separator('.') => { - let _ = lexer.next(); - let field = lexer.next_ident()?; - - ast::Expression::Member { base: expr, field } - } - Token::Paren('[') => { - let _ = lexer.next(); - let index = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren(']'))?; - - ast::Expression::Index { base: expr, index } - } - _ => break, - }; - - let span = lexer.span_from(span_start); - expr = ctx.expressions.append(expression, span); - } - - Ok(expr) - } - - /// Parse a `unary_expression`. - fn unary_expression<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - self.push_rule_span(Rule::UnaryExpr, lexer); - //TODO: refactor this to avoid backing up - let expr = match lexer.peek().0 { - Token::Operation('-') => { - let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; - let expr = ast::Expression::Unary { - op: crate::UnaryOperator::Negate, - expr, - }; - let span = self.peek_rule_span(lexer); - ctx.expressions.append(expr, span) - } - Token::Operation('!' | '~') => { - let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; - let expr = ast::Expression::Unary { - op: crate::UnaryOperator::Not, - expr, - }; - let span = self.peek_rule_span(lexer); - ctx.expressions.append(expr, span) - } - Token::Operation('*') => { - let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; - let expr = ast::Expression::Deref(expr); - let span = self.peek_rule_span(lexer); - ctx.expressions.append(expr, span) - } - Token::Operation('&') => { - let _ = lexer.next(); - let expr = self.unary_expression(lexer, ctx.reborrow())?; - let expr = ast::Expression::AddrOf(expr); - let span = self.peek_rule_span(lexer); - ctx.expressions.append(expr, span) - } - _ => self.singular_expression(lexer, ctx.reborrow())?, - }; - - self.pop_rule_span(lexer); - Ok(expr) - } - - /// Parse a `singular_expression`. - fn singular_expression<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - let start = lexer.start_byte_offset(); - self.push_rule_span(Rule::SingularExpr, lexer); - let primary_expr = self.primary_expression(lexer, ctx.reborrow())?; - let singular_expr = self.postfix(start, lexer, ctx.reborrow(), primary_expr)?; - self.pop_rule_span(lexer); - - Ok(singular_expr) - } - - fn equality_expression<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut context: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - // equality_expression - context.parse_binary_op( - lexer, - |token| match token { - Token::LogicalOperation('=') => Some(crate::BinaryOperator::Equal), - Token::LogicalOperation('!') => Some(crate::BinaryOperator::NotEqual), - _ => None, - }, - // relational_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Paren('<') => Some(crate::BinaryOperator::Less), - Token::Paren('>') => Some(crate::BinaryOperator::Greater), - Token::LogicalOperation('<') => Some(crate::BinaryOperator::LessEqual), - Token::LogicalOperation('>') => Some(crate::BinaryOperator::GreaterEqual), - _ => None, - }, - // shift_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::ShiftOperation('<') => { - Some(crate::BinaryOperator::ShiftLeft) - } - Token::ShiftOperation('>') => { - Some(crate::BinaryOperator::ShiftRight) - } - _ => None, - }, - // additive_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('+') => Some(crate::BinaryOperator::Add), - Token::Operation('-') => { - Some(crate::BinaryOperator::Subtract) - } - _ => None, - }, - // multiplicative_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('*') => { - Some(crate::BinaryOperator::Multiply) - } - Token::Operation('/') => { - Some(crate::BinaryOperator::Divide) - } - Token::Operation('%') => { - Some(crate::BinaryOperator::Modulo) - } - _ => None, - }, - |lexer, context| self.unary_expression(lexer, context), - ) - }, - ) - }, - ) - }, - ) - }, - ) - } - - fn general_expression<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - self.general_expression_with_span(lexer, ctx.reborrow()) - .map(|(expr, _)| expr) - } - - fn general_expression_with_span<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut context: ParseExpressionContext<'a, '_, '_>, - ) -> Result<(Handle>, Span), Error<'a>> { - self.push_rule_span(Rule::GeneralExpr, lexer); - // logical_or_expression - let handle = context.parse_binary_op( - lexer, - |token| match token { - Token::LogicalOperation('|') => Some(crate::BinaryOperator::LogicalOr), - _ => None, - }, - // logical_and_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::LogicalOperation('&') => Some(crate::BinaryOperator::LogicalAnd), - _ => None, - }, - // inclusive_or_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('|') => Some(crate::BinaryOperator::InclusiveOr), - _ => None, - }, - // exclusive_or_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('^') => { - Some(crate::BinaryOperator::ExclusiveOr) - } - _ => None, - }, - // and_expression - |lexer, mut context| { - context.parse_binary_op( - lexer, - |token| match token { - Token::Operation('&') => { - Some(crate::BinaryOperator::And) - } - _ => None, - }, - |lexer, context| { - self.equality_expression(lexer, context) - }, - ) - }, - ) - }, - ) - }, - ) - }, - )?; - Ok((handle, self.pop_rule_span(lexer))) - } - - fn variable_decl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { - self.push_rule_span(Rule::VariableDecl, lexer); - let mut space = crate::AddressSpace::Handle; - - if lexer.skip(Token::Paren('<')) { - let (class_str, span) = lexer.next_ident_with_span()?; - space = match class_str { - "storage" => { - let access = if lexer.skip(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.expect(Token::Paren('>'))?; - } - let name = lexer.next_ident()?; - lexer.expect(Token::Separator(':'))?; - let ty = self.type_decl(lexer, ctx.reborrow())?; - - let init = if lexer.skip(Token::Operation('=')) { - let handle = self.general_expression(lexer, ctx.reborrow())?; - Some(handle) - } else { - None - }; - lexer.expect(Token::Separator(';'))?; - self.pop_rule_span(lexer); - - Ok(ast::GlobalVariable { - name, - space, - binding: None, - ty, - init, - }) - } - - fn struct_body<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - let mut members = Vec::new(); - - lexer.expect(Token::Paren('{'))?; - let mut ready = true; - while !lexer.skip(Token::Paren('}')) { - if !ready { - return Err(Error::Unexpected( - lexer.next().1, - ExpectedToken::Token(Token::Separator(',')), - )); - } - let (mut size, mut align) = (None, None); - self.push_rule_span(Rule::Attribute, lexer); - let mut bind_parser = BindingParser::default(); - while lexer.skip(Token::Attribute) { - match lexer.next_ident_with_span()? { - ("size", _) => { - lexer.expect(Token::Paren('('))?; - let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; - lexer.expect(Token::Paren(')'))?; - size = Some((value, span)); - } - ("align", _) => { - lexer.expect(Token::Paren('('))?; - let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; - lexer.expect(Token::Paren(')'))?; - align = Some((value, span)); - } - (word, word_span) => bind_parser.parse(lexer, word, word_span)?, - } - } - - let bind_span = self.pop_rule_span(lexer); - let binding = bind_parser.finish(bind_span)?; - - let name = lexer.next_ident()?; - lexer.expect(Token::Separator(':'))?; - let ty = self.type_decl(lexer, ctx.reborrow())?; - ready = lexer.skip(Token::Separator(',')); - - members.push(ast::StructMember { - name, - ty, - binding, - size, - align, - }); - } - - Ok(members) - } - - fn matrix_scalar_type<'a>( - &mut self, - lexer: &mut Lexer<'a>, - columns: crate::VectorSize, - rows: crate::VectorSize, - ) -> Result, Error<'a>> { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - match kind { - crate::ScalarKind::Float => Ok(ast::Type::Matrix { - columns, - rows, - width, - }), - _ => Err(Error::BadMatrixScalarKind(span, kind, width)), - } - } - - fn type_decl_impl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - word: &'a str, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - if let Some((kind, width)) = conv::get_scalar_type(word) { - return Ok(Some(ast::Type::Scalar { kind, width })); - } - - Ok(Some(match word { - "vec2" => { - let (kind, width) = lexer.next_scalar_generic()?; - ast::Type::Vector { - size: crate::VectorSize::Bi, - kind, - width, - } - } - "vec3" => { - let (kind, width) = lexer.next_scalar_generic()?; - ast::Type::Vector { - size: crate::VectorSize::Tri, - kind, - width, - } - } - "vec4" => { - let (kind, width) = lexer.next_scalar_generic()?; - ast::Type::Vector { - size: crate::VectorSize::Quad, - kind, - width, - } - } - "mat2x2" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Bi)? - } - "mat2x3" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Tri)? - } - "mat2x4" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Quad)? - } - "mat3x2" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Bi)? - } - "mat3x3" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Tri)? - } - "mat3x4" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Quad)? - } - "mat4x2" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Bi)? - } - "mat4x3" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Tri)? - } - "mat4x4" => { - self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Quad)? - } - "atomic" => { - let (kind, width) = lexer.next_scalar_generic()?; - ast::Type::Atomic { kind, width } - } - "ptr" => { - lexer.expect_generic_paren('<')?; - let (ident, span) = lexer.next_ident_with_span()?; - let mut space = conv::map_address_space(ident, span)?; - lexer.expect(Token::Separator(','))?; - let base = self.type_decl(lexer, ctx)?; - if let crate::AddressSpace::Storage { ref mut access } = space { - *access = if lexer.skip(Token::Separator(',')) { - lexer.next_storage_access()? - } else { - crate::StorageAccess::LOAD - }; - } - lexer.expect_generic_paren('>')?; - ast::Type::Pointer { base, space } - } - "array" => { - lexer.expect_generic_paren('<')?; - let base = self.type_decl(lexer, ctx.reborrow())?; - let size = if lexer.skip(Token::Separator(',')) { - let size = self.unary_expression(lexer, ctx.reborrow())?; - ast::ArraySize::Constant(size) - } else { - ast::ArraySize::Dynamic - }; - lexer.expect_generic_paren('>')?; - - ast::Type::Array { base, size } - } - "binding_array" => { - lexer.expect_generic_paren('<')?; - let base = self.type_decl(lexer, ctx.reborrow())?; - let size = if lexer.skip(Token::Separator(',')) { - let size = self.unary_expression(lexer, ctx.reborrow())?; - ast::ArraySize::Constant(size) - } else { - ast::ArraySize::Dynamic - }; - lexer.expect_generic_paren('>')?; - - ast::Type::BindingArray { base, size } - } - "sampler" => ast::Type::Sampler { comparison: false }, - "sampler_comparison" => ast::Type::Sampler { comparison: true }, - "texture_1d" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D1, - arrayed: false, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_1d_array" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D1, - arrayed: true, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_2d" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_2d_array" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: true, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_3d" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D3, - arrayed: false, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_cube" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::Cube, - arrayed: false, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_cube_array" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::Cube, - arrayed: true, - class: crate::ImageClass::Sampled { kind, multi: false }, - } - } - "texture_multisampled_2d" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Sampled { kind, multi: true }, - } - } - "texture_multisampled_2d_array" => { - let (kind, width, span) = lexer.next_scalar_generic_with_span()?; - Self::check_texture_sample_type(kind, width, span)?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: true, - class: crate::ImageClass::Sampled { kind, multi: true }, - } - } - "texture_depth_2d" => ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Depth { multi: false }, - }, - "texture_depth_2d_array" => ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: true, - class: crate::ImageClass::Depth { multi: false }, - }, - "texture_depth_cube" => ast::Type::Image { - dim: crate::ImageDimension::Cube, - arrayed: false, - class: crate::ImageClass::Depth { multi: false }, - }, - "texture_depth_cube_array" => ast::Type::Image { - dim: crate::ImageDimension::Cube, - arrayed: true, - class: crate::ImageClass::Depth { multi: false }, - }, - "texture_depth_multisampled_2d" => ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Depth { multi: true }, - }, - "texture_storage_1d" => { - let (format, access) = lexer.next_format_generic()?; - ast::Type::Image { - dim: crate::ImageDimension::D1, - arrayed: false, - class: crate::ImageClass::Storage { format, access }, - } - } - "texture_storage_1d_array" => { - let (format, access) = lexer.next_format_generic()?; - ast::Type::Image { - dim: crate::ImageDimension::D1, - arrayed: true, - class: crate::ImageClass::Storage { format, access }, - } - } - "texture_storage_2d" => { - let (format, access) = lexer.next_format_generic()?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: false, - class: crate::ImageClass::Storage { format, access }, - } - } - "texture_storage_2d_array" => { - let (format, access) = lexer.next_format_generic()?; - ast::Type::Image { - dim: crate::ImageDimension::D2, - arrayed: true, - class: crate::ImageClass::Storage { format, access }, - } - } - "texture_storage_3d" => { - let (format, access) = lexer.next_format_generic()?; - ast::Type::Image { - dim: crate::ImageDimension::D3, - arrayed: false, - class: crate::ImageClass::Storage { format, access }, - } - } - _ => return Ok(None), - })) - } - - const fn check_texture_sample_type( - kind: crate::ScalarKind, - width: u8, - span: Span, - ) -> Result<(), Error<'static>> { - use crate::ScalarKind::*; - // Validate according to https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type - match (kind, width) { - (Float | Sint | Uint, 4) => Ok(()), - _ => Err(Error::BadTextureSampleType { span, kind, width }), - } - } - - /// Parse type declaration of a given name. - fn type_decl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result>, Error<'a>> { - self.push_rule_span(Rule::TypeDecl, lexer); - - let (name, span) = lexer.next_ident_with_span()?; - - let ty = match self.type_decl_impl(lexer, name, ctx.reborrow())? { - Some(ty) => ty, - None => { - ctx.unresolved.insert(ast::Dependency { - ident: name, - usage: span, - }); - ast::Type::User(ast::Ident { name, span }) - } - }; - - self.pop_rule_span(lexer); - - let handle = ctx.types.append(ty, Span::UNDEFINED); - Ok(handle) - } - - fn assignment_op_and_rhs<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, - target: Handle>, - span_start: usize, - ) -> Result<(), Error<'a>> { - use crate::BinaryOperator as Bo; - - let op = lexer.next(); - let (op, value) = match op { - (Token::Operation('='), _) => { - let value = self.general_expression(lexer, ctx.reborrow())?; - (None, value) - } - (Token::AssignmentOperation(c), _) => { - let op = match c { - '<' => Bo::ShiftLeft, - '>' => Bo::ShiftRight, - '+' => Bo::Add, - '-' => Bo::Subtract, - '*' => Bo::Multiply, - '/' => Bo::Divide, - '%' => Bo::Modulo, - '&' => Bo::And, - '|' => Bo::InclusiveOr, - '^' => Bo::ExclusiveOr, - // Note: `consume_token` shouldn't produce any other assignment ops - _ => unreachable!(), - }; - - let value = self.general_expression(lexer, ctx.reborrow())?; - (Some(op), value) - } - token @ (Token::IncrementOperation | Token::DecrementOperation, _) => { - let op = match token.0 { - Token::IncrementOperation => ast::StatementKind::Increment, - Token::DecrementOperation => ast::StatementKind::Decrement, - _ => unreachable!(), - }; - - let span = lexer.span_from(span_start); - block.stmts.push(ast::Statement { - kind: op(target), - span, - }); - return Ok(()); - } - _ => return Err(Error::Unexpected(op.1, ExpectedToken::Assignment)), - }; - - let span = lexer.span_from(span_start); - block.stmts.push(ast::Statement { - kind: ast::StatementKind::Assign { target, op, value }, - span, - }); - Ok(()) - } - - /// Parse an assignment statement (will also parse increment and decrement statements) - fn assignment_statement<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, - ) -> Result<(), Error<'a>> { - let span_start = lexer.start_byte_offset(); - let target = self.general_expression(lexer, ctx.reborrow())?; - self.assignment_op_and_rhs(lexer, ctx, block, target, span_start) - } - - /// Parse a function call statement. - /// Expects `ident` to be consumed (not in the lexer). - fn function_statement<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - ident: &'a str, - ident_span: Span, - span_start: usize, - mut context: ParseExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, - ) -> Result<(), Error<'a>> { - self.push_rule_span(Rule::SingularExpr, lexer); - - context.unresolved.insert(ast::Dependency { - ident, - usage: ident_span, - }); - let arguments = self.arguments(lexer, context.reborrow())?; - let span = lexer.span_from(span_start); - - block.stmts.push(ast::Statement { - kind: ast::StatementKind::Call { - function: ast::Ident { - name: ident, - span: ident_span, - }, - arguments, - }, - span, - }); - - self.pop_rule_span(lexer); - - Ok(()) - } - - fn function_call_or_assignment_statement<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - mut context: ParseExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, - ) -> Result<(), Error<'a>> { - let span_start = lexer.start_byte_offset(); - match lexer.peek() { - (Token::Word(name), span) => { - // A little hack for 2 token lookahead. - let cloned = lexer.clone(); - let _ = lexer.next(); - match lexer.peek() { - (Token::Paren('('), _) => self.function_statement( - lexer, - name, - span, - span_start, - context.reborrow(), - block, - ), - _ => { - *lexer = cloned; - self.assignment_statement(lexer, context.reborrow(), block) - } - } - } - _ => self.assignment_statement(lexer, context.reborrow(), block), - } - } - - fn statement<'a, 'out>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, 'out>, - block: &'out mut ast::Block<'a>, - ) -> Result<(), Error<'a>> { - self.push_rule_span(Rule::Statement, lexer); - match lexer.peek() { - (Token::Separator(';'), _) => { - let _ = lexer.next(); - self.pop_rule_span(lexer); - return Ok(()); - } - (Token::Paren('{'), _) => { - let (inner, span) = self.block(lexer, ctx.reborrow())?; - block.stmts.push(ast::Statement { - kind: ast::StatementKind::Block(inner), - span, - }); - self.pop_rule_span(lexer); - return Ok(()); - } - (Token::Word(word), _) => { - let kind = match word { - "_" => { - let _ = lexer.next(); - lexer.expect(Token::Operation('='))?; - let expr = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(';'))?; - - ast::StatementKind::Ignore(expr) - } - "let" => { - let _ = lexer.next(); - let name = lexer.next_ident()?; - - let given_ty = if lexer.skip(Token::Separator(':')) { - let ty = self.type_decl(lexer, ctx.reborrow())?; - Some(ty) - } else { - None - }; - lexer.expect(Token::Operation('='))?; - let expr_id = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(';'))?; - - let handle = ctx.locals.append(ast::Local, name.span); - if let Some(old) = ctx.local_table.add(name.name, handle) { - return Err(Error::Redefinition { - previous: ctx.locals.get_span(old), - current: name.span, - }); - } - - ast::StatementKind::LocalDecl(ast::LocalDecl::Let(ast::Let { - name, - ty: given_ty, - init: expr_id, - handle, - })) - } - "var" => { - let _ = lexer.next(); - - let name = lexer.next_ident()?; - let ty = if lexer.skip(Token::Separator(':')) { - let ty = self.type_decl(lexer, ctx.reborrow())?; - Some(ty) - } else { - None - }; - - let init = if lexer.skip(Token::Operation('=')) { - let init = self.general_expression(lexer, ctx.reborrow())?; - Some(init) - } else { - None - }; - - lexer.expect(Token::Separator(';'))?; - - let handle = ctx.locals.append(ast::Local, name.span); - if let Some(old) = ctx.local_table.add(name.name, handle) { - return Err(Error::Redefinition { - previous: ctx.locals.get_span(old), - current: name.span, - }); - } - - ast::StatementKind::LocalDecl(ast::LocalDecl::Var(ast::LocalVariable { - name, - ty, - init, - handle, - })) - } - "return" => { - let _ = lexer.next(); - let value = if lexer.peek().0 != Token::Separator(';') { - let handle = self.general_expression(lexer, ctx.reborrow())?; - Some(handle) - } else { - None - }; - lexer.expect(Token::Separator(';'))?; - ast::StatementKind::Return { value } - } - "if" => { - let _ = lexer.next(); - let condition = self.general_expression(lexer, ctx.reborrow())?; - - let accept = self.block(lexer, ctx.reborrow())?.0; - - let mut elsif_stack = Vec::new(); - let mut elseif_span_start = lexer.start_byte_offset(); - let mut reject = loop { - if !lexer.skip(Token::Word("else")) { - break ast::Block::default(); - } - - if !lexer.skip(Token::Word("if")) { - // ... else { ... } - break self.block(lexer, ctx.reborrow())?.0; - } - - // ... else if (...) { ... } - let other_condition = self.general_expression(lexer, ctx.reborrow())?; - let other_block = self.block(lexer, ctx.reborrow())?; - elsif_stack.push((elseif_span_start, other_condition, other_block)); - elseif_span_start = lexer.start_byte_offset(); - }; - - // reverse-fold the else-if blocks - //Note: we may consider uplifting this to the IR - for (other_span_start, other_cond, other_block) in - elsif_stack.into_iter().rev() - { - let sub_stmt = ast::StatementKind::If { - condition: other_cond, - accept: other_block.0, - reject, - }; - reject = ast::Block::default(); - let span = lexer.span_from(other_span_start); - reject.stmts.push(ast::Statement { - kind: sub_stmt, - span, - }) - } - - ast::StatementKind::If { - condition, - accept, - reject, - } - } - "switch" => { - let _ = lexer.next(); - let selector = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Paren('{'))?; - let mut cases = Vec::new(); - - loop { - // cases + default - match lexer.next() { - (Token::Word("case"), _) => { - // parse a list of values - let (value, value_span) = loop { - let (value, value_span) = Self::switch_value(lexer)?; - if lexer.skip(Token::Separator(',')) { - if lexer.skip(Token::Separator(':')) { - break (value, value_span); - } - } else { - lexer.skip(Token::Separator(':')); - break (value, value_span); - } - cases.push(ast::SwitchCase { - value, - value_span, - body: ast::Block::default(), - fall_through: true, - }); - }; - - let body = self.block(lexer, ctx.reborrow())?.0; - - cases.push(ast::SwitchCase { - value, - value_span, - body, - fall_through: false, - }); - } - (Token::Word("default"), value_span) => { - lexer.skip(Token::Separator(':')); - let body = self.block(lexer, ctx.reborrow())?.0; - cases.push(ast::SwitchCase { - value: ast::SwitchValue::Default, - value_span, - body, - fall_through: false, - }); - } - (Token::Paren('}'), _) => break, - (_, span) => { - return Err(Error::Unexpected(span, ExpectedToken::SwitchItem)) - } - } - } - - ast::StatementKind::Switch { selector, cases } - } - "loop" => self.r#loop(lexer, ctx.reborrow())?, - "while" => { - let _ = lexer.next(); - let mut body = ast::Block::default(); - - let (condition, span) = lexer.capture_span(|lexer| { - let condition = self.general_expression(lexer, ctx.reborrow())?; - Ok(condition) - })?; - let mut reject = ast::Block::default(); - reject.stmts.push(ast::Statement { - kind: ast::StatementKind::Break, - span, - }); - - body.stmts.push(ast::Statement { - kind: ast::StatementKind::If { - condition, - accept: ast::Block::default(), - reject, - }, - span, - }); - - let (block, span) = self.block(lexer, ctx.reborrow())?; - body.stmts.push(ast::Statement { - kind: ast::StatementKind::Block(block), - span, - }); - - ast::StatementKind::Loop { - body, - continuing: ast::Block::default(), - break_if: None, - } - } - "for" => { - let _ = lexer.next(); - lexer.expect(Token::Paren('('))?; - - ctx.local_table.push_scope(); - - if !lexer.skip(Token::Separator(';')) { - let num_statements = block.stmts.len(); - let (_, span) = lexer.capture_span(|lexer| { - self.statement(lexer, ctx.reborrow(), block) - })?; - - if block.stmts.len() != num_statements { - match block.stmts.last().unwrap().kind { - ast::StatementKind::Call { .. } - | ast::StatementKind::Assign { .. } - | ast::StatementKind::LocalDecl(_) => {} - _ => return Err(Error::InvalidForInitializer(span)), - } - } - }; - - let mut body = ast::Block::default(); - if !lexer.skip(Token::Separator(';')) { - let (condition, span) = lexer.capture_span(|lexer| { - let condition = self.general_expression(lexer, ctx.reborrow())?; - lexer.expect(Token::Separator(';'))?; - Ok(condition) - })?; - let mut reject = ast::Block::default(); - reject.stmts.push(ast::Statement { - kind: ast::StatementKind::Break, - span, - }); - body.stmts.push(ast::Statement { - kind: ast::StatementKind::If { - condition, - accept: ast::Block::default(), - reject, - }, - span, - }); - }; - - let mut continuing = ast::Block::default(); - if !lexer.skip(Token::Paren(')')) { - self.function_call_or_assignment_statement( - lexer, - ctx.reborrow(), - &mut continuing, - )?; - lexer.expect(Token::Paren(')'))?; - } - - let (block, span) = self.block(lexer, ctx.reborrow())?; - body.stmts.push(ast::Statement { - kind: ast::StatementKind::Block(block), - span, - }); - - ctx.local_table.pop_scope(); - - ast::StatementKind::Loop { - body, - continuing, - break_if: None, - } - } - "break" => { - let (_, span) = lexer.next(); - // Check if the next token is an `if`, this indicates - // that the user tried to type out a `break if` which - // is illegal in this position. - let (peeked_token, peeked_span) = lexer.peek(); - if let Token::Word("if") = peeked_token { - let span = span.until(&peeked_span); - return Err(Error::InvalidBreakIf(span)); - } - ast::StatementKind::Break - } - "continue" => { - let _ = lexer.next(); - ast::StatementKind::Continue - } - "discard" => { - let _ = lexer.next(); - ast::StatementKind::Kill - } - // assignment or a function call - _ => { - self.function_call_or_assignment_statement(lexer, ctx.reborrow(), block)?; - lexer.expect(Token::Separator(';'))?; - self.pop_rule_span(lexer); - return Ok(()); - } - }; - - let span = self.pop_rule_span(lexer); - block.stmts.push(ast::Statement { kind, span }); - } - _ => { - self.assignment_statement(lexer, ctx.reborrow(), block)?; - self.pop_rule_span(lexer); - } - } - Ok(()) - } - - fn r#loop<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result, Error<'a>> { - let _ = lexer.next(); - let mut body = ast::Block::default(); - let mut continuing = ast::Block::default(); - let mut break_if = None; - - lexer.expect(Token::Paren('{'))?; - - ctx.local_table.push_scope(); - - loop { - if lexer.skip(Token::Word("continuing")) { - // Branch for the `continuing` block, this must be - // the last thing in the loop body - - // Expect a opening brace to start the continuing block - lexer.expect(Token::Paren('{'))?; - loop { - if lexer.skip(Token::Word("break")) { - // Branch for the `break if` statement, this statement - // has the form `break if ;` and must be the last - // statement in a continuing block - - // The break must be followed by an `if` to form - // the break if - lexer.expect(Token::Word("if"))?; - - let condition = self.general_expression(lexer, ctx.reborrow())?; - // Set the condition of the break if to the newly parsed - // expression - break_if = Some(condition); - - // Expect a semicolon to close the statement - lexer.expect(Token::Separator(';'))?; - // Expect a closing brace to close the continuing block, - // since the break if must be the last statement - lexer.expect(Token::Paren('}'))?; - // Stop parsing the continuing block - break; - } else if lexer.skip(Token::Paren('}')) { - // If we encounter a closing brace it means we have reached - // the end of the continuing block and should stop processing - break; - } else { - // Otherwise try to parse a statement - self.statement(lexer, ctx.reborrow(), &mut continuing)?; - } - } - // Since the continuing block must be the last part of the loop body, - // we expect to see a closing brace to end the loop body - lexer.expect(Token::Paren('}'))?; - break; - } - if lexer.skip(Token::Paren('}')) { - // If we encounter a closing brace it means we have reached - // the end of the loop body and should stop processing - break; - } - // Otherwise try to parse a statement - self.statement(lexer, ctx.reborrow(), &mut body)?; - } - - ctx.local_table.pop_scope(); - - Ok(ast::StatementKind::Loop { - body, - continuing, - break_if, - }) - } - - /// compound_statement - fn block<'a>( - &mut self, - lexer: &mut Lexer<'a>, - mut ctx: ParseExpressionContext<'a, '_, '_>, - ) -> Result<(ast::Block<'a>, Span), Error<'a>> { - self.push_rule_span(Rule::Block, lexer); - - ctx.local_table.push_scope(); - - let _ = lexer.next(); - let mut statements = ast::Block::default(); - while !lexer.skip(Token::Paren('}')) { - self.statement(lexer, ctx.reborrow(), &mut statements)?; - } - - ctx.local_table.pop_scope(); - - let span = self.pop_rule_span(lexer); - Ok((statements, span)) - } - - fn varying_binding<'a>( - &mut self, - lexer: &mut Lexer<'a>, - ) -> Result, Error<'a>> { - let mut bind_parser = BindingParser::default(); - self.push_rule_span(Rule::Attribute, lexer); - - while lexer.skip(Token::Attribute) { - let (word, span) = lexer.next_ident_with_span()?; - bind_parser.parse(lexer, word, span)?; - } - - let span = self.pop_rule_span(lexer); - bind_parser.finish(span) - } - - fn function_decl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - out: &mut ast::TranslationUnit<'a>, - dependencies: &mut FastHashSet>, - ) -> Result, Error<'a>> { - self.push_rule_span(Rule::FunctionDecl, lexer); - // read function name - let fun_name = lexer.next_ident()?; - - let mut locals = Arena::new(); - - let mut ctx = ParseExpressionContext { - expressions: &mut out.expressions, - local_table: &mut super::SymbolTable::default(), - locals: &mut locals, - types: &mut out.types, - unresolved: dependencies, - }; - - // read parameter list - let mut arguments = Vec::new(); - lexer.expect(Token::Paren('('))?; - let mut ready = true; - while !lexer.skip(Token::Paren(')')) { - if !ready { - return Err(Error::Unexpected( - lexer.next().1, - ExpectedToken::Token(Token::Separator(',')), - )); - } - let binding = self.varying_binding(lexer)?; - - let param_name = lexer.next_ident()?; - - lexer.expect(Token::Separator(':'))?; - let param_type = self.type_decl(lexer, ctx.reborrow())?; - - let handle = ctx.locals.append(ast::Local, param_name.span); - ctx.local_table.add(param_name.name, handle); - arguments.push(ast::FunctionArgument { - name: param_name, - ty: param_type, - binding, - handle, - }); - ready = lexer.skip(Token::Separator(',')); - } - // read return type - let result = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { - let binding = self.varying_binding(lexer)?; - let ty = self.type_decl(lexer, ctx.reborrow())?; - Some(ast::FunctionResult { ty, binding }) - } else { - None - }; - - // read body - let body = self.block(lexer, ctx)?.0; - - let fun = ast::Function { - entry_point: None, - name: fun_name, - arguments, - result, - body, - locals, - }; - - // done - self.pop_rule_span(lexer); - - Ok(fun) - } - - fn global_decl<'a>( - &mut self, - lexer: &mut Lexer<'a>, - out: &mut ast::TranslationUnit<'a>, - ) -> Result<(), Error<'a>> { - // read attributes - let mut binding = None; - let mut stage = None; - let mut workgroup_size = [0u32; 3]; - let mut early_depth_test = None; - let (mut bind_index, mut bind_group) = (None, None); - - self.push_rule_span(Rule::Attribute, lexer); - while lexer.skip(Token::Attribute) { - match lexer.next_ident_with_span()? { - ("binding", _) => { - lexer.expect(Token::Paren('('))?; - bind_index = Some(Self::non_negative_i32_literal(lexer)?); - lexer.expect(Token::Paren(')'))?; - } - ("group", _) => { - lexer.expect(Token::Paren('('))?; - bind_group = Some(Self::non_negative_i32_literal(lexer)?); - lexer.expect(Token::Paren(')'))?; - } - ("vertex", _) => { - stage = Some(crate::ShaderStage::Vertex); - } - ("fragment", _) => { - stage = Some(crate::ShaderStage::Fragment); - } - ("compute", _) => { - stage = Some(crate::ShaderStage::Compute); - } - ("workgroup_size", _) => { - lexer.expect(Token::Paren('('))?; - workgroup_size = [1u32; 3]; - for (i, size) in workgroup_size.iter_mut().enumerate() { - *size = Self::generic_non_negative_int_literal(lexer)?; - match lexer.next() { - (Token::Paren(')'), _) => break, - (Token::Separator(','), _) if i != 2 => (), - other => { - return Err(Error::Unexpected( - other.1, - ExpectedToken::WorkgroupSizeSeparator, - )) - } - } - } - } - ("early_depth_test", _) => { - let conservative = if lexer.skip(Token::Paren('(')) { - let (ident, ident_span) = lexer.next_ident_with_span()?; - let value = conv::map_conservative_depth(ident, ident_span)?; - lexer.expect(Token::Paren(')'))?; - Some(value) - } else { - None - }; - early_depth_test = Some(crate::EarlyDepthTest { conservative }); - } - (_, word_span) => return Err(Error::UnknownAttribute(word_span)), - } - } - - let attrib_span = self.pop_rule_span(lexer); - match (bind_group, bind_index) { - (Some(group), Some(index)) => { - binding = Some(crate::ResourceBinding { - group, - binding: index, - }); - } - (Some(_), None) => return Err(Error::MissingAttribute("binding", attrib_span)), - (None, Some(_)) => return Err(Error::MissingAttribute("group", attrib_span)), - (None, None) => {} - } - - let mut dependencies = FastHashSet::default(); - let mut ctx = ParseExpressionContext { - expressions: &mut out.expressions, - local_table: &mut super::SymbolTable::default(), - locals: &mut Arena::new(), - types: &mut out.types, - unresolved: &mut dependencies, - }; - - // read item - let start = lexer.start_byte_offset(); - let kind = match lexer.next() { - (Token::Separator(';'), _) => None, - (Token::Word("struct"), _) => { - let name = lexer.next_ident()?; - - let members = self.struct_body(lexer, ctx)?; - Some(ast::GlobalDeclKind::Struct(ast::Struct { name, members })) - } - (Token::Word("type"), _) => { - let name = lexer.next_ident()?; - - lexer.expect(Token::Operation('='))?; - let ty = self.type_decl(lexer, ctx)?; - lexer.expect(Token::Separator(';'))?; - Some(ast::GlobalDeclKind::Type(ast::TypeAlias { name, ty })) - } - (Token::Word("const"), _) => { - let name = lexer.next_ident()?; - - let ty = if lexer.skip(Token::Separator(':')) { - let ty = self.type_decl(lexer, ctx.reborrow())?; - Some(ty) - } else { - None - }; - - lexer.expect(Token::Operation('='))?; - let init = self.general_expression(lexer, ctx)?; - lexer.expect(Token::Separator(';'))?; - - Some(ast::GlobalDeclKind::Const(ast::Const { name, ty, init })) - } - (Token::Word("var"), _) => { - let mut var = self.variable_decl(lexer, ctx)?; - var.binding = binding.take(); - Some(ast::GlobalDeclKind::Var(var)) - } - (Token::Word("fn"), _) => { - let function = self.function_decl(lexer, out, &mut dependencies)?; - Some(ast::GlobalDeclKind::Fn(ast::Function { - entry_point: stage.map(|stage| ast::EntryPoint { - stage, - early_depth_test, - workgroup_size, - }), - ..function - })) - } - (Token::End, _) => return Ok(()), - other => return Err(Error::Unexpected(other.1, ExpectedToken::GlobalItem)), - }; - - if let Some(kind) = kind { - out.decls.append( - ast::GlobalDecl { kind, dependencies }, - lexer.span_from(start), - ); - } - - if !self.rules.is_empty() { - log::error!("Reached the end of global decl, but rule stack is not empty"); - log::error!("Rules: {:?}", self.rules); - return Err(Error::Other); - }; - - match binding { - None => Ok(()), - // we had the attribute but no var? - Some(_) => Err(Error::Other), - } - } - - pub fn parse(&mut self, source: &str) -> Result { - self.reset(); - - let mut lexer = Lexer::new(source); - let mut tu = ast::TranslationUnit::default(); - loop { - match self.global_decl(&mut lexer, &mut tu) { - Err(error) => return Err(error.as_parse_error(lexer.source)), - Ok(()) => { - if lexer.peek().0 == Token::End { - break; - } - } - } - } - - let index = index::Index::generate(&tu).map_err(|x| x.as_parse_error(source))?; - let module = Lowerer::new(&index) - .lower(&tu) - .map_err(|x| x.as_parse_error(source))?; - - Ok(module) - } -} - -/// An `ast::GlobalDecl` for which we have built the Naga IR equivalent. -enum LoweredGlobalDecl { - Function(Handle), - Var(Handle), - Const(Handle), - Type(Handle), - EntryPoint, -} - -enum ConstantOrInner { - Constant(Handle), - Inner(crate::ConstantInner), -} - -enum Texture { - Gather, - GatherCompare, - - Sample, - SampleBias, - SampleCompare, - SampleCompareLevel, - SampleGrad, - SampleLevel, - // SampleBaseClampToEdge, -} - -impl Texture { - pub fn map(word: &str) -> Option { - Some(match word { - "textureGather" => Self::Gather, - "textureGatherCompare" => Self::GatherCompare, - - "textureSample" => Self::Sample, - "textureSampleBias" => Self::SampleBias, - "textureSampleCompare" => Self::SampleCompare, - "textureSampleCompareLevel" => Self::SampleCompareLevel, - "textureSampleGrad" => Self::SampleGrad, - "textureSampleLevel" => Self::SampleLevel, - // "textureSampleBaseClampToEdge" => Some(Self::SampleBaseClampToEdge), - _ => return None, - }) - } - - pub const fn min_argument_count(&self) -> u32 { - match *self { - Self::Gather => 3, - Self::GatherCompare => 4, - - Self::Sample => 3, - Self::SampleBias => 5, - Self::SampleCompare => 5, - Self::SampleCompareLevel => 5, - Self::SampleGrad => 6, - Self::SampleLevel => 5, - // Self::SampleBaseClampToEdge => 3, - } - } -} - -struct Lowerer<'source, 'temp> { - index: &'temp index::Index<'source>, - layouter: Layouter, -} - -impl<'source, 'temp> Lowerer<'source, 'temp> { - pub fn new(index: &'temp index::Index<'source>) -> Self { - Self { - index, - layouter: Layouter::default(), - } - } - - pub fn lower( - &mut self, - tu: &'temp ast::TranslationUnit<'source>, - ) -> Result> { - let mut module = crate::Module::default(); - - let mut ctx = OutputContext { - ast_expressions: &tu.expressions, - globals: &mut FastHashMap::default(), - types: &tu.types, - module: &mut module, - }; - - for decl in self.index.visit_ordered() { - let span = tu.decls.get_span(decl); - let decl = &tu.decls[decl]; - - match decl.kind { - ast::GlobalDeclKind::Fn(ref f) => { - let decl = self.function(f, span, ctx.reborrow())?; - ctx.globals.insert(f.name.name, decl); - } - ast::GlobalDeclKind::Var(ref v) => { - let ty = self.resolve_ast_type(v.ty, ctx.reborrow())?; - - let init = v - .init - .map(|init| self.constant(init, ctx.reborrow())) - .transpose()?; - - let handle = ctx.module.global_variables.append( - crate::GlobalVariable { - name: Some(v.name.name.to_string()), - space: v.space, - binding: v.binding.clone(), - ty, - init, - }, - span, - ); - - ctx.globals - .insert(v.name.name, LoweredGlobalDecl::Var(handle)); - } - ast::GlobalDeclKind::Const(ref c) => { - let inner = self.constant_inner(c.init, ctx.reborrow())?; - let inner = match inner { - ConstantOrInner::Constant(c) => ctx.module.constants[c].inner.clone(), - ConstantOrInner::Inner(inner) => inner, - }; - - let inferred_type = match inner { - crate::ConstantInner::Scalar { width, value } => { - ctx.ensure_type_exists(crate::TypeInner::Scalar { - width, - kind: value.scalar_kind(), - }) - } - crate::ConstantInner::Composite { ty, .. } => ty, - }; - - let handle = ctx.module.constants.append( - crate::Constant { - name: Some(c.name.name.to_string()), - specialization: None, - inner, - }, - span, - ); - - let explicit_ty = - c.ty.map(|ty| self.resolve_ast_type(ty, ctx.reborrow())) - .transpose()?; - - if let Some(explicit) = explicit_ty { - if explicit != inferred_type { - let ty = &ctx.module.types[explicit]; - let explicit = ty.name.clone().unwrap_or_else(|| { - ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) - }); - - let ty = &ctx.module.types[inferred_type]; - let inferred = ty.name.clone().unwrap_or_else(|| { - ty.inner.to_wgsl(&ctx.module.types, &ctx.module.constants) - }); - - return Err(Error::InitializationTypeMismatch( - c.name.span, - explicit, - inferred, - )); - } - } - - ctx.globals - .insert(c.name.name, LoweredGlobalDecl::Const(handle)); - } - ast::GlobalDeclKind::Struct(ref s) => { - let handle = self.r#struct(s, span, ctx.reborrow())?; - ctx.globals - .insert(s.name.name, LoweredGlobalDecl::Type(handle)); - } - ast::GlobalDeclKind::Type(ref alias) => { - let ty = self.resolve_ast_type(alias.ty, ctx.reborrow())?; - ctx.globals - .insert(alias.name.name, LoweredGlobalDecl::Type(ty)); - } - } - } - - Ok(module) - } - - fn function( - &mut self, - f: &ast::Function<'source>, - span: Span, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result> { - let mut local_table = FastHashMap::default(); - let mut local_variables = Arena::new(); - let mut expressions = Arena::new(); - let mut named_expressions = crate::NamedExpressions::default(); - - let arguments = f - .arguments - .iter() - .enumerate() - .map(|(i, arg)| { - let ty = self.resolve_ast_type(arg.ty, ctx.reborrow())?; - let expr = expressions - .append(crate::Expression::FunctionArgument(i as u32), arg.name.span); - local_table.insert(arg.handle, TypedExpression::non_reference(expr)); - named_expressions.insert(expr, arg.name.name.to_string()); - - Ok(crate::FunctionArgument { - name: Some(arg.name.name.to_string()), - ty, - binding: self.interpolate_default(&arg.binding, ty, ctx.reborrow()), - }) - }) - .collect::, _>>()?; - - let result = f - .result - .as_ref() - .map(|res| { - self.resolve_ast_type(res.ty, ctx.reborrow()) - .map(|ty| crate::FunctionResult { - ty, - binding: self.interpolate_default(&res.binding, ty, ctx.reborrow()), - }) - }) - .transpose()?; - - let mut typifier = super::Typifier::default(); - let mut body = self.block( - &f.body, - StatementContext { - local_table: &mut local_table, - globals: ctx.globals, - ast_expressions: ctx.ast_expressions, - typifier: &mut typifier, - variables: &mut local_variables, - naga_expressions: &mut expressions, - named_expressions: &mut named_expressions, - types: ctx.types, - module: ctx.module, - arguments: &arguments, - }, - )?; - ensure_block_returns(&mut body); - - let function = crate::Function { - name: Some(f.name.name.to_string()), - arguments, - result, - local_variables, - expressions, - named_expressions, - body, - }; - - if let Some(ref entry) = f.entry_point { - ctx.module.entry_points.push(crate::EntryPoint { - name: f.name.name.to_string(), - stage: entry.stage, - early_depth_test: entry.early_depth_test, - workgroup_size: entry.workgroup_size, - function, - }); - Ok(LoweredGlobalDecl::EntryPoint) - } else { - let handle = ctx.module.functions.append(function, span); - Ok(LoweredGlobalDecl::Function(handle)) - } - } - - fn block( - &mut self, - b: &ast::Block<'source>, - mut ctx: StatementContext<'source, '_, '_>, - ) -> Result> { - let mut block = crate::Block::default(); - - for stmt in b.stmts.iter() { - self.statement(stmt, &mut block, ctx.reborrow())?; - } - - Ok(block) - } - - fn statement( - &mut self, - stmt: &ast::Statement<'source>, - block: &mut crate::Block, - mut ctx: StatementContext<'source, '_, '_>, - ) -> Result<(), Error<'source>> { - let out = match stmt.kind { - ast::StatementKind::Block(ref block) => { - let block = self.block(block, ctx.reborrow())?; - crate::Statement::Block(block) - } - ast::StatementKind::LocalDecl(ref decl) => match *decl { - ast::LocalDecl::Let(ref l) => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let value = self.expression(l.init, ctx.as_expression(block, &mut emitter))?; - - let explicit_ty = - l.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) - .transpose()?; - - if let Some(ty) = explicit_ty { - let mut ctx = ctx.as_expression(block, &mut emitter); - let init_ty = ctx.register_type(value)?; - if !ctx.module.types[ty] - .inner - .equivalent(&ctx.module.types[init_ty].inner, &ctx.module.types) - { - return Err(Error::InitializationTypeMismatch( - l.name.span, - ctx.format_type(ty), - ctx.format_type(init_ty), - )); - } - } - - block.extend(emitter.finish(ctx.naga_expressions)); - ctx.local_table - .insert(l.handle, TypedExpression::non_reference(value)); - ctx.named_expressions.insert(value, l.name.name.to_string()); - - return Ok(()); - } - ast::LocalDecl::Var(ref v) => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let initializer = match v.init { - Some(init) => { - let initializer = - self.expression(init, ctx.as_expression(block, &mut emitter))?; - ctx.as_expression(block, &mut emitter) - .grow_types(initializer)?; - Some(initializer) - } - None => None, - }; - - let explicit_ty = - v.ty.map(|ty| self.resolve_ast_type(ty, ctx.as_output())) - .transpose()?; - - let ty = match (explicit_ty, initializer) { - (Some(explicit), Some(initializer)) => { - let ctx = ctx.as_expression(block, &mut emitter); - let initializer_ty = ctx.resolved_inner(initializer); - if !ctx.module.types[explicit] - .inner - .equivalent(initializer_ty, &ctx.module.types) - { - return Err(Error::InitializationTypeMismatch( - v.name.span, - ctx.format_type(explicit), - ctx.format_typeinner(initializer_ty), - )); - } - explicit - } - (Some(explicit), None) => explicit, - (None, Some(initializer)) => ctx - .as_expression(block, &mut emitter) - .register_type(initializer)?, - (None, None) => { - return Err(Error::MissingType(v.name.span)); - } - }; - - let var = ctx.variables.append( - crate::LocalVariable { - name: Some(v.name.name.to_string()), - ty, - init: None, - }, - stmt.span, - ); - - let handle = ctx - .as_expression(block, &mut emitter) - .interrupt_emitter(crate::Expression::LocalVariable(var), Span::UNDEFINED); - block.extend(emitter.finish(ctx.naga_expressions)); - ctx.local_table.insert( - v.handle, - TypedExpression { - handle, - is_reference: true, - }, - ); - - match initializer { - Some(initializer) => crate::Statement::Store { - pointer: handle, - value: initializer, - }, - None => return Ok(()), - } - } - }, - ast::StatementKind::If { - condition, - ref accept, - ref reject, - } => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let condition = - self.expression(condition, ctx.as_expression(block, &mut emitter))?; - block.extend(emitter.finish(ctx.naga_expressions)); - - let accept = self.block(accept, ctx.reborrow())?; - let reject = self.block(reject, ctx.reborrow())?; - - crate::Statement::If { - condition, - accept, - reject, - } - } - ast::StatementKind::Switch { - selector, - ref cases, - } => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let mut ectx = ctx.as_expression(block, &mut emitter); - let selector = self.expression(selector, ectx.reborrow())?; - - ectx.grow_types(selector)?; - let uint = - ectx.resolved_inner(selector).scalar_kind() == Some(crate::ScalarKind::Uint); - block.extend(emitter.finish(ctx.naga_expressions)); - - let cases = cases - .iter() - .map(|case| { - Ok(crate::SwitchCase { - value: match case.value { - ast::SwitchValue::I32(num) if !uint => { - crate::SwitchValue::Integer(num) - } - ast::SwitchValue::U32(num) if uint => { - crate::SwitchValue::Integer(num as i32) - } - ast::SwitchValue::Default => crate::SwitchValue::Default, - _ => { - return Err(Error::InvalidSwitchValue { - uint, - span: case.value_span, - }); - } - }, - body: self.block(&case.body, ctx.reborrow())?, - fall_through: case.fall_through, - }) - }) - .collect::>()?; - - crate::Statement::Switch { selector, cases } - } - ast::StatementKind::Loop { - ref body, - ref continuing, - break_if, - } => { - let body = self.block(body, ctx.reborrow())?; - let mut continuing = self.block(continuing, ctx.reborrow())?; - - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - let break_if = break_if - .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) - .transpose()?; - continuing.extend(emitter.finish(ctx.naga_expressions)); - - crate::Statement::Loop { - body, - continuing, - break_if, - } - } - ast::StatementKind::Break => crate::Statement::Break, - ast::StatementKind::Continue => crate::Statement::Continue, - ast::StatementKind::Return { value } => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let value = value - .map(|expr| self.expression(expr, ctx.as_expression(block, &mut emitter))) - .transpose()?; - block.extend(emitter.finish(ctx.naga_expressions)); - - crate::Statement::Return { value } - } - ast::StatementKind::Kill => crate::Statement::Kill, - ast::StatementKind::Call { - ref function, - ref arguments, - } => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let _ = self.call( - stmt.span, - function, - arguments, - ctx.as_expression(block, &mut emitter), - )?; - block.extend(emitter.finish(ctx.naga_expressions)); - return Ok(()); - } - ast::StatementKind::Assign { target, op, value } => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let expr = - self.expression_for_reference(target, ctx.as_expression(block, &mut emitter))?; - let mut value = self.expression(value, ctx.as_expression(block, &mut emitter))?; - - if !expr.is_reference { - let ty = if ctx.named_expressions.contains_key(&expr.handle) { - InvalidAssignmentType::ImmutableBinding - } else { - match ctx.naga_expressions[expr.handle] { - crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle, - _ => InvalidAssignmentType::Other, - } - }; - - return Err(Error::InvalidAssignment { - span: ctx.ast_expressions.get_span(target), - ty, - }); - } - - let value = match op { - Some(op) => { - let mut ctx = ctx.as_expression(block, &mut emitter); - let mut left = ctx.apply_load_rule(expr); - ctx.binary_op_splat(op, &mut left, &mut value)?; - ctx.naga_expressions.append( - crate::Expression::Binary { - op, - left, - right: value, - }, - stmt.span, - ) - } - None => value, - }; - block.extend(emitter.finish(ctx.naga_expressions)); - - crate::Statement::Store { - pointer: expr.handle, - value, - } - } - ast::StatementKind::Increment(value) | ast::StatementKind::Decrement(value) => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let op = match stmt.kind { - ast::StatementKind::Increment(_) => crate::BinaryOperator::Add, - ast::StatementKind::Decrement(_) => crate::BinaryOperator::Subtract, - _ => unreachable!(), - }; - - let value_span = ctx.ast_expressions.get_span(value); - let reference = - self.expression_for_reference(value, ctx.as_expression(block, &mut emitter))?; - let mut ectx = ctx.as_expression(block, &mut emitter); - - ectx.grow_types(reference.handle)?; - let (kind, width) = match *ectx.resolved_inner(reference.handle) { - crate::TypeInner::ValuePointer { - size: None, - kind, - width, - .. - } => (kind, width), - crate::TypeInner::Pointer { base, .. } => match ectx.module.types[base].inner { - crate::TypeInner::Scalar { kind, width } => (kind, width), - _ => return Err(Error::BadIncrDecrReferenceType(value_span)), - }, - _ => return Err(Error::BadIncrDecrReferenceType(value_span)), - }; - let constant_inner = crate::ConstantInner::Scalar { - width, - value: match kind { - crate::ScalarKind::Sint => crate::ScalarValue::Sint(1), - crate::ScalarKind::Uint => crate::ScalarValue::Uint(1), - _ => return Err(Error::BadIncrDecrReferenceType(value_span)), - }, - }; - let constant = ectx.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner: constant_inner, - }, - Span::UNDEFINED, - ); - - let left = ectx.naga_expressions.append( - crate::Expression::Load { - pointer: reference.handle, - }, - value_span, - ); - let right = - ectx.interrupt_emitter(crate::Expression::Constant(constant), Span::UNDEFINED); - let value = ectx - .naga_expressions - .append(crate::Expression::Binary { op, left, right }, stmt.span); - - block.extend(emitter.finish(ctx.naga_expressions)); - crate::Statement::Store { - pointer: reference.handle, - value, - } - } - ast::StatementKind::Ignore(expr) => { - let mut emitter = super::Emitter::default(); - emitter.start(ctx.naga_expressions); - - let _ = self.expression(expr, ctx.as_expression(block, &mut emitter))?; - block.extend(emitter.finish(ctx.naga_expressions)); - return Ok(()); - } - }; - - block.push(out, stmt.span); - - Ok(()) - } - - fn expression( - &mut self, - expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let expr = self.expression_for_reference(expr, ctx.reborrow())?; - Ok(ctx.apply_load_rule(expr)) - } - - fn expression_for_reference( - &mut self, - expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result> { - let span = ctx.ast_expressions.get_span(expr); - let expr = &ctx.ast_expressions[expr]; - - let (expr, is_reference) = match *expr { - ast::Expression::Literal(literal) => { - let inner = match literal { - ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Float(f as _), - }, - ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Sint(i as _), - }, - ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(u as _), - }, - ast::Literal::Number(_) => { - unreachable!("got abstract numeric type when not expected"); - } - ast::Literal::Bool(b) => crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(b), - }, - }; - let handle = ctx.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - Span::UNDEFINED, - ); - let handle = ctx.interrupt_emitter(crate::Expression::Constant(handle), span); - return Ok(TypedExpression::non_reference(handle)); - } - ast::Expression::Ident(ast::IdentExpr::Local(local)) => { - return Ok(ctx.local_table[&local]) - } - ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { - return if let Some(global) = ctx.globals.get(name) { - let (expr, is_reference) = match *global { - LoweredGlobalDecl::Var(handle) => ( - crate::Expression::GlobalVariable(handle), - ctx.module.global_variables[handle].space - != crate::AddressSpace::Handle, - ), - LoweredGlobalDecl::Const(handle) => { - (crate::Expression::Constant(handle), false) - } - _ => { - return Err(Error::Unexpected(span, ExpectedToken::Variable)); - } - }; - - let handle = ctx.interrupt_emitter(expr, span); - Ok(TypedExpression { - handle, - is_reference, - }) - } else { - Err(Error::UnknownIdent(span, name)) - } - } - ast::Expression::Construct { - ref ty, - ty_span, - ref components, - } => { - let handle = self.construct(span, ty, ty_span, components, ctx.reborrow())?; - return Ok(TypedExpression::non_reference(handle)); - } - ast::Expression::Unary { op, expr } => { - let expr = self.expression(expr, ctx.reborrow())?; - (crate::Expression::Unary { op, expr }, false) - } - ast::Expression::AddrOf(expr) => { - // The `&` operator simply converts a reference to a pointer. And since a - // reference is required, the Load Rule is not applied. - let expr = self.expression_for_reference(expr, ctx.reborrow())?; - if !expr.is_reference { - return Err(Error::NotReference("the operand of the `&` operator", span)); - } - - // No code is generated. We just declare the pointer a reference now. - return Ok(TypedExpression { - is_reference: false, - ..expr - }); - } - ast::Expression::Deref(expr) => { - // The pointer we dereference must be loaded. - let pointer = self.expression(expr, ctx.reborrow())?; - - ctx.grow_types(pointer)?; - if ctx.resolved_inner(pointer).pointer_space().is_none() { - return Err(Error::NotPointer(span)); - } - - return Ok(TypedExpression { - handle: pointer, - is_reference: true, - }); - } - ast::Expression::Binary { op, left, right } => { - // Load both operands. - let mut left = self.expression(left, ctx.reborrow())?; - let mut right = self.expression(right, ctx.reborrow())?; - ctx.binary_op_splat(op, &mut left, &mut right)?; - (crate::Expression::Binary { op, left, right }, false) - } - ast::Expression::Call { - ref function, - ref arguments, - } => { - let handle = self - .call(span, function, arguments, ctx.reborrow())? - .ok_or(Error::FunctionReturnsVoid(function.span))?; - return Ok(TypedExpression::non_reference(handle)); - } - ast::Expression::Index { base, index } => { - let expr = self.expression_for_reference(base, ctx.reborrow())?; - let index = self.expression(index, ctx.reborrow())?; - - ctx.grow_types(expr.handle)?; - let wgsl_pointer = - ctx.resolved_inner(expr.handle).pointer_space().is_some() && !expr.is_reference; - - if wgsl_pointer { - return Err(Error::Pointer( - "the value indexed by a `[]` subscripting expression", - ctx.ast_expressions.get_span(base), - )); - } - - if let crate::Expression::Constant(constant) = ctx.naga_expressions[index] { - let span = ctx.naga_expressions.get_span(index); - let index = match ctx.module.constants[constant].inner { - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(int), - .. - } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Sint(int), - .. - } => u32::try_from(int).map_err(|_| Error::BadU32Constant(span)), - _ => Err(Error::BadU32Constant(span)), - }?; - - ( - crate::Expression::AccessIndex { - base: expr.handle, - index, - }, - expr.is_reference, - ) - } else { - ( - crate::Expression::Access { - base: expr.handle, - index, - }, - expr.is_reference, - ) - } - } - ast::Expression::Member { base, ref field } => { - let TypedExpression { - handle, - is_reference, - } = self.expression_for_reference(base, ctx.reborrow())?; - - ctx.grow_types(handle)?; - let temp_inner; - let (composite, wgsl_pointer) = match *ctx.resolved_inner(handle) { - crate::TypeInner::Pointer { base, .. } => { - (&ctx.module.types[base].inner, !is_reference) - } - crate::TypeInner::ValuePointer { - size: None, - kind, - width, - .. - } => { - temp_inner = crate::TypeInner::Scalar { kind, width }; - (&temp_inner, !is_reference) - } - crate::TypeInner::ValuePointer { - size: Some(size), - kind, - width, - .. - } => { - temp_inner = crate::TypeInner::Vector { size, kind, width }; - (&temp_inner, !is_reference) - } - ref other => (other, false), - }; - - if wgsl_pointer { - return Err(Error::Pointer( - "the value accessed by a `.member` expression", - ctx.ast_expressions.get_span(base), - )); - } - - let access = match *composite { - crate::TypeInner::Struct { ref members, .. } => { - let index = members - .iter() - .position(|m| m.name.as_deref() == Some(field.name)) - .ok_or(Error::BadAccessor(field.span))? - as u32; - - ( - crate::Expression::AccessIndex { - base: handle, - index, - }, - is_reference, - ) - } - crate::TypeInner::Vector { .. } | crate::TypeInner::Matrix { .. } => { - match Composition::make(field.name, field.span)? { - Composition::Multi(size, pattern) => { - let vector = ctx.apply_load_rule(TypedExpression { - handle, - is_reference, - }); - - ( - crate::Expression::Swizzle { - size, - vector, - pattern, - }, - false, - ) - } - Composition::Single(index) => ( - crate::Expression::AccessIndex { - base: handle, - index, - }, - is_reference, - ), - } - } - _ => return Err(Error::BadAccessor(field.span)), - }; - - access - } - ast::Expression::Bitcast { expr, to, ty_span } => { - let expr = self.expression(expr, ctx.reborrow())?; - let to_resolved = self.resolve_ast_type(to, ctx.as_output())?; - - let kind = match ctx.module.types[to_resolved].inner { - crate::TypeInner::Scalar { kind, .. } => kind, - crate::TypeInner::Vector { kind, .. } => kind, - _ => { - let ty = &ctx.typifier[expr]; - return Err(Error::BadTypeCast { - from_type: ctx.format_type_resolution(ty), - span: ty_span, - to_type: ctx.format_type(to_resolved), - }); - } - }; - - ( - crate::Expression::As { - expr, - kind, - convert: None, - }, - false, - ) - } - }; - - let handle = ctx.naga_expressions.append(expr, span); - Ok(TypedExpression { - handle, - is_reference, - }) - } - - /// Generate Naga IR for call expressions and statements, and type - /// constructor expressions. - /// - /// The "function" being called is simply an `Ident` that we know refers to - /// some module-scope definition. - /// - /// - If it is the name of a type, then the expression is a type constructor - /// expression: either constructing a value from components, a conversion - /// expression, or a zero value expression. - /// - /// - If it is the name of a function, then we're generating a [`Call`] - /// statement. We may be in the midst of generating code for an - /// expression, in which case we must generate an `Emit` statement to - /// force evaluation of the IR expressions we've generated so far, add the - /// `Call` statement to the current block, and then resume generating - /// expressions. - /// - /// [`Call`]: crate::Statement::Call - fn call( - &mut self, - span: Span, - function: &ast::Ident<'source>, - arguments: &[Handle>], - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result>, Error<'source>> { - match ctx.globals.get(function.name) { - Some(&LoweredGlobalDecl::Type(ty)) => { - let handle = self.construct( - span, - &ast::ConstructorType::Type(ty), - function.span, - arguments, - ctx.reborrow(), - )?; - Ok(Some(handle)) - } - Some(&LoweredGlobalDecl::Const(_) | &LoweredGlobalDecl::Var(_)) => { - Err(Error::Unexpected(function.span, ExpectedToken::Function)) - } - Some(&LoweredGlobalDecl::EntryPoint) => Err(Error::CalledEntryPoint(function.span)), - Some(&LoweredGlobalDecl::Function(function)) => { - let arguments = arguments - .iter() - .map(|&arg| self.expression(arg, ctx.reborrow())) - .collect::, _>>()?; - - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); - let result = ctx.module.functions[function].result.is_some().then(|| { - ctx.naga_expressions - .append(crate::Expression::CallResult(function), span) - }); - ctx.emitter.start(ctx.naga_expressions); - ctx.block.push( - crate::Statement::Call { - function, - arguments, - result, - }, - span, - ); - - Ok(result) - } - None => { - let span = function.span; - 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.reborrow())?; - args.finish()?; - - crate::Expression::Relational { fun, argument } - } else if let Some(axis) = conv::map_derivative_axis(function.name) { - let mut args = ctx.prepare_args(arguments, 1, span); - let expr = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::Derivative { axis, expr } - } else if let Some(fun) = conv::map_standard_fun(function.name) { - let expected = fun.argument_count() as _; - let mut args = ctx.prepare_args(arguments, expected, span); - - let arg = self.expression(args.next()?, ctx.reborrow())?; - let arg1 = args - .next() - .map(|x| self.expression(x, ctx.reborrow())) - .ok() - .transpose()?; - let arg2 = args - .next() - .map(|x| self.expression(x, ctx.reborrow())) - .ok() - .transpose()?; - let arg3 = args - .next() - .map(|x| self.expression(x, ctx.reborrow())) - .ok() - .transpose()?; - - args.finish()?; - - crate::Expression::Math { - fun, - arg, - arg1, - arg2, - arg3, - } - } else if let Some(fun) = Texture::map(function.name) { - self.texture_sample_helper(fun, arguments, span, ctx.reborrow())? - } else { - match function.name { - "select" => { - let mut args = ctx.prepare_args(arguments, 3, span); - - let reject = self.expression(args.next()?, ctx.reborrow())?; - let accept = self.expression(args.next()?, ctx.reborrow())?; - let condition = self.expression(args.next()?, ctx.reborrow())?; - - args.finish()?; - - crate::Expression::Select { - reject, - accept, - condition, - } - } - "arrayLength" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let expr = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::ArrayLength(expr) - } - "atomicLoad" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::Load { pointer } - } - "atomicStore" => { - let mut args = ctx.prepare_args(arguments, 2, span); - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; - let value = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); - ctx.emitter.start(ctx.naga_expressions); - ctx.block - .push(crate::Statement::Store { pointer, value }, span); - return Ok(None); - } - "atomicAdd" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::Add, - arguments, - ctx.reborrow(), - )?)) - } - "atomicSub" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::Subtract, - arguments, - ctx.reborrow(), - )?)) - } - "atomicAnd" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::And, - arguments, - ctx.reborrow(), - )?)) - } - "atomicOr" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::InclusiveOr, - arguments, - ctx.reborrow(), - )?)) - } - "atomicXor" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::ExclusiveOr, - arguments, - ctx.reborrow(), - )?)) - } - "atomicMin" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::Min, - arguments, - ctx.reborrow(), - )?)) - } - "atomicMax" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::Max, - arguments, - ctx.reborrow(), - )?)) - } - "atomicExchange" => { - return Ok(Some(self.atomic_helper( - span, - crate::AtomicFunction::Exchange { compare: None }, - arguments, - ctx.reborrow(), - )?)) - } - "atomicCompareExchangeWeak" => { - let mut args = ctx.prepare_args(arguments, 3, span); - - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; - - let compare = self.expression(args.next()?, ctx.reborrow())?; - - let value = args.next()?; - let value_span = ctx.ast_expressions.get_span(value); - let value = self.expression(value, ctx.reborrow())?; - ctx.grow_types(value)?; - - args.finish()?; - - let expression = match *ctx.resolved_inner(value) { - crate::TypeInner::Scalar { kind, width } => { - let bool_ty = ctx.module.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { - kind: crate::ScalarKind::Bool, - width: crate::BOOL_WIDTH, - }, - }, - Span::UNDEFINED, - ); - let scalar_ty = ctx.module.types.insert( - crate::Type { - name: None, - inner: crate::TypeInner::Scalar { kind, width }, - }, - Span::UNDEFINED, - ); - let struct_ty = ctx.module.types.insert( - crate::Type { - name: Some( - "__atomic_compare_exchange_result".to_string(), - ), - inner: crate::TypeInner::Struct { - members: vec![ - crate::StructMember { - name: Some("old_value".to_string()), - ty: scalar_ty, - binding: None, - offset: 0, - }, - crate::StructMember { - name: Some("exchanged".to_string()), - ty: bool_ty, - binding: None, - offset: 4, - }, - ], - span: 8, - }, - }, - Span::UNDEFINED, - ); - crate::Expression::AtomicResult { - ty: struct_ty, - comparison: true, - } - } - _ => return Err(Error::InvalidAtomicOperandType(value_span)), - }; - - let result = ctx.interrupt_emitter(expression, span); - ctx.block.push( - crate::Statement::Atomic { - pointer, - fun: crate::AtomicFunction::Exchange { - compare: Some(compare), - }, - value, - result, - }, - span, - ); - return Ok(Some(result)); - } - "storageBarrier" => { - ctx.prepare_args(arguments, 0, span).finish()?; - - ctx.block - .push(crate::Statement::Barrier(crate::Barrier::STORAGE), span); - return Ok(None); - } - "workgroupBarrier" => { - ctx.prepare_args(arguments, 0, span).finish()?; - - ctx.block - .push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP), span); - return Ok(None); - } - "textureStore" => { - let mut args = ctx.prepare_args(arguments, 3, span); - - let image = args.next()?; - let image_span = ctx.ast_expressions.get_span(image); - let image = self.expression(image, ctx.reborrow())?; - - let coordinate = self.expression(args.next()?, ctx.reborrow())?; - - let (_, arrayed) = ctx.image_data(image, image_span)?; - let array_index = arrayed - .then(|| self.expression(args.next()?, ctx.reborrow())) - .transpose()?; - - let value = self.expression(args.next()?, ctx.reborrow())?; - - args.finish()?; - - ctx.block.extend(ctx.emitter.finish(ctx.naga_expressions)); - ctx.emitter.start(ctx.naga_expressions); - let stmt = crate::Statement::ImageStore { - image, - coordinate, - array_index, - value, - }; - ctx.block.push(stmt, span); - return Ok(None); - } - "textureLoad" => { - let mut args = ctx.prepare_args(arguments, 3, span); - - let image = args.next()?; - let image_span = ctx.ast_expressions.get_span(image); - let image = self.expression(image, ctx.reborrow())?; - - let coordinate = self.expression(args.next()?, ctx.reborrow())?; - - let (class, arrayed) = ctx.image_data(image, image_span)?; - let array_index = arrayed - .then(|| self.expression(args.next()?, ctx.reborrow())) - .transpose()?; - - let level = class - .is_mipmapped() - .then(|| self.expression(args.next()?, ctx.reborrow())) - .transpose()?; - - let sample = class - .is_multisampled() - .then(|| self.expression(args.next()?, ctx.reborrow())) - .transpose()?; - - args.finish()?; - - crate::Expression::ImageLoad { - image, - coordinate, - array_index, - level, - sample, - } - } - "textureDimensions" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; - let level = args - .next() - .map(|arg| self.expression(arg, ctx.reborrow())) - .ok() - .transpose()?; - args.finish()?; - - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::Size { level }, - } - } - "textureNumLevels" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::NumLevels, - } - } - "textureNumLayers" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::NumLayers, - } - } - "textureNumSamples" => { - let mut args = ctx.prepare_args(arguments, 1, span); - let image = self.expression(args.next()?, ctx.reborrow())?; - args.finish()?; - - crate::Expression::ImageQuery { - image, - query: crate::ImageQuery::NumSamples, - } - } - _ => return Err(Error::UnknownIdent(function.span, function.name)), - } - }; - - let expr = ctx.naga_expressions.append(expr, span); - Ok(Some(expr)) - } - } - } - - fn atomic_pointer( - &mut self, - expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let span = ctx.ast_expressions.get_span(expr); - let pointer = self.expression(expr, ctx.reborrow())?; - - ctx.grow_types(pointer)?; - match *ctx.resolved_inner(pointer) { - crate::TypeInner::Pointer { base, .. } => match ctx.module.types[base].inner { - crate::TypeInner::Atomic { .. } => Ok(pointer), - ref other => { - log::error!("Pointer type to {:?} passed to atomic op", other); - Err(Error::InvalidAtomicPointer(span)) - } - }, - ref other => { - log::error!("Type {:?} passed to atomic op", other); - Err(Error::InvalidAtomicPointer(span)) - } - } - } - - fn atomic_helper( - &mut self, - span: Span, - fun: crate::AtomicFunction, - args: &[Handle>], - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let mut args = ctx.prepare_args(args, 2, span); - - let pointer = self.atomic_pointer(args.next()?, ctx.reborrow())?; - - let value = args.next()?; - let value = self.expression(value, ctx.reborrow())?; - let ty = ctx.register_type(value)?; - - args.finish()?; - - let result = ctx.interrupt_emitter( - crate::Expression::AtomicResult { - ty, - comparison: false, - }, - span, - ); - ctx.block.push( - crate::Statement::Atomic { - pointer, - fun, - value, - result, - }, - span, - ); - Ok(result) - } - - fn texture_sample_helper( - &mut self, - fun: Texture, - args: &[Handle>], - span: Span, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result> { - let mut args = ctx.prepare_args(args, fun.min_argument_count(), span); - - let (image, gather) = match fun { - Texture::Gather => { - let image_or_component = args.next()?; - match self.gather_component(image_or_component, ctx.reborrow())? { - Some(component) => { - let image = args.next()?; - (image, Some(component)) - } - None => (image_or_component, Some(crate::SwizzleComponent::X)), - } - } - Texture::GatherCompare => { - let image = args.next()?; - (image, Some(crate::SwizzleComponent::X)) - } - - _ => { - let image = args.next()?; - (image, None) - } - }; - - let image_span = ctx.ast_expressions.get_span(image); - let image = self.expression(image, ctx.reborrow())?; - - let sampler = self.expression(args.next()?, ctx.reborrow())?; - - let coordinate = self.expression(args.next()?, ctx.reborrow())?; - - let (_, arrayed) = ctx.image_data(image, image_span)?; - let array_index = arrayed - .then(|| self.expression(args.next()?, ctx.reborrow())) - .transpose()?; - - let (level, depth_ref) = match fun { - Texture::Gather => (crate::SampleLevel::Zero, None), - Texture::GatherCompare => { - let reference = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Zero, Some(reference)) - } - - Texture::Sample => (crate::SampleLevel::Auto, None), - Texture::SampleBias => { - let bias = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Bias(bias), None) - } - Texture::SampleCompare => { - let reference = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Auto, Some(reference)) - } - Texture::SampleCompareLevel => { - let reference = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Zero, Some(reference)) - } - Texture::SampleGrad => { - let x = self.expression(args.next()?, ctx.reborrow())?; - let y = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Gradient { x, y }, None) - } - Texture::SampleLevel => { - let level = self.expression(args.next()?, ctx.reborrow())?; - (crate::SampleLevel::Exact(level), None) - } - }; - - let offset = args - .next() - .map(|arg| self.constant(arg, ctx.as_output())) - .ok() - .transpose()?; - - args.finish()?; - - Ok(crate::Expression::ImageSample { - image, - sampler, - gather, - coordinate, - array_index, - offset, - level, - depth_ref, - }) - } - - fn gather_component( - &mut self, - expr: Handle>, - mut ctx: ExpressionContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let span = ctx.ast_expressions.get_span(expr); - - let constant = match self.constant_inner(expr, ctx.as_output()).ok() { - Some(ConstantOrInner::Constant(c)) => ctx.module.constants[c].inner.clone(), - Some(ConstantOrInner::Inner(inner)) => inner, - None => return Ok(None), - }; - - let int = match constant { - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Sint(i), - .. - } if i >= 0 => i as u64, - crate::ConstantInner::Scalar { - value: crate::ScalarValue::Uint(i), - .. - } => i, - _ => { - return Err(Error::InvalidGatherComponent(span)); - } - }; - - crate::SwizzleComponent::XYZW - .get(int as usize) - .copied() - .map(Some) - .ok_or(Error::InvalidGatherComponent(span)) - } - - fn r#struct( - &mut self, - s: &ast::Struct<'source>, - span: Span, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let mut offset = 0; - let mut struct_alignment = Alignment::ONE; - let mut members = Vec::with_capacity(s.members.len()); - - for member in s.members.iter() { - let ty = self.resolve_ast_type(member.ty, ctx.reborrow())?; - - self.layouter - .update(&ctx.module.types, &ctx.module.constants) - .unwrap(); - - let member_min_size = self.layouter[ty].size; - let member_min_alignment = self.layouter[ty].alignment; - - let member_size = if let Some((size, span)) = member.size { - if size < member_min_size { - return Err(Error::SizeAttributeTooLow(span, member_min_size)); - } else { - size - } - } else { - member_min_size - }; - - let member_alignment = if let Some((align, span)) = member.align { - if let Some(alignment) = Alignment::new(align) { - if alignment < member_min_alignment { - return Err(Error::AlignAttributeTooLow(span, member_min_alignment)); - } else { - alignment - } - } else { - return Err(Error::NonPowerOfTwoAlignAttribute(span)); - } - } else { - member_min_alignment - }; - - let binding = self.interpolate_default(&member.binding, ty, ctx.reborrow()); - - offset = member_alignment.round_up(offset); - struct_alignment = struct_alignment.max(member_alignment); - - members.push(crate::StructMember { - name: Some(member.name.name.to_owned()), - ty, - binding, - offset, - }); - - offset += member_size; - } - - let size = struct_alignment.round_up(offset); - let inner = crate::TypeInner::Struct { - members, - span: size, - }; - - let handle = ctx.module.types.insert( - crate::Type { - name: Some(s.name.name.to_string()), - inner, - }, - span, - ); - Ok(handle) - } - - /// Return a Naga `Handle` representing the front-end type `handle`. - fn resolve_ast_type( - &mut self, - handle: Handle>, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let inner = match ctx.types[handle] { - ast::Type::Scalar { kind, width } => crate::TypeInner::Scalar { kind, width }, - ast::Type::Vector { size, kind, width } => { - crate::TypeInner::Vector { size, kind, width } - } - ast::Type::Matrix { - rows, - columns, - width, - } => crate::TypeInner::Matrix { - columns, - rows, - width, - }, - ast::Type::Atomic { kind, width } => crate::TypeInner::Atomic { kind, width }, - ast::Type::Pointer { base, space } => { - let base = self.resolve_ast_type(base, ctx.reborrow())?; - crate::TypeInner::Pointer { base, space } - } - ast::Type::Array { base, size } => { - let base = self.resolve_ast_type(base, ctx.reborrow())?; - self.layouter - .update(&ctx.module.types, &ctx.module.constants) - .unwrap(); - - crate::TypeInner::Array { - base, - size: match size { - ast::ArraySize::Constant(constant) => { - let constant = self.constant(constant, ctx.reborrow())?; - crate::ArraySize::Constant(constant) - } - ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, - }, - stride: self.layouter[base].to_stride(), - } - } - ast::Type::Image { - dim, - arrayed, - class, - } => crate::TypeInner::Image { - dim, - arrayed, - class, - }, - ast::Type::Sampler { comparison } => crate::TypeInner::Sampler { comparison }, - ast::Type::BindingArray { base, size } => { - let base = self.resolve_ast_type(base, ctx.reborrow())?; - - crate::TypeInner::BindingArray { - base, - size: match size { - ast::ArraySize::Constant(constant) => { - let constant = self.constant(constant, ctx.reborrow())?; - crate::ArraySize::Constant(constant) - } - ast::ArraySize::Dynamic => crate::ArraySize::Dynamic, - }, - } - } - ast::Type::User(ref ident) => { - return match ctx.globals.get(ident.name) { - Some(&LoweredGlobalDecl::Type(handle)) => Ok(handle), - Some(_) => Err(Error::Unexpected(ident.span, ExpectedToken::Type)), - None => Err(Error::UnknownType(ident.span)), - } - } - }; - - Ok(ctx.ensure_type_exists(inner)) - } - - /// Find or construct a Naga [`Constant`] whose value is `expr`. - /// - /// The `ctx` indicates the Naga [`Module`] to which we should add - /// new `Constant`s or [`Type`]s as needed. - /// - /// [`Module`]: crate::Module - /// [`Constant`]: crate::Constant - /// [`Type`]: crate::Type - fn constant( - &mut self, - expr: Handle>, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result, Error<'source>> { - let inner = match self.constant_inner(expr, ctx.reborrow())? { - ConstantOrInner::Constant(c) => return Ok(c), - ConstantOrInner::Inner(inner) => inner, - }; - - let c = ctx.module.constants.fetch_or_append( - crate::Constant { - name: None, - specialization: None, - inner, - }, - Span::UNDEFINED, - ); - Ok(c) - } - - fn constant_inner( - &mut self, - expr: Handle>, - mut ctx: OutputContext<'source, '_, '_>, - ) -> Result> { - let span = ctx.ast_expressions.get_span(expr); - let inner = match ctx.ast_expressions[expr] { - ast::Expression::Literal(literal) => match literal { - ast::Literal::Number(Number::F32(f)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Float(f as _), - }, - ast::Literal::Number(Number::I32(i)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Sint(i as _), - }, - ast::Literal::Number(Number::U32(u)) => crate::ConstantInner::Scalar { - width: 4, - value: crate::ScalarValue::Uint(u as _), - }, - ast::Literal::Number(_) => { - unreachable!("got abstract numeric type when not expected"); - } - ast::Literal::Bool(b) => crate::ConstantInner::Scalar { - width: 1, - value: crate::ScalarValue::Bool(b), - }, - }, - ast::Expression::Ident(ast::IdentExpr::Local(_)) => { - return Err(Error::Unexpected(span, ExpectedToken::Constant)) - } - ast::Expression::Ident(ast::IdentExpr::Unresolved(name)) => { - return if let Some(global) = ctx.globals.get(name) { - match *global { - LoweredGlobalDecl::Const(handle) => Ok(ConstantOrInner::Constant(handle)), - _ => Err(Error::Unexpected(span, ExpectedToken::Constant)), - } - } else { - Err(Error::UnknownIdent(span, name)) - } - } - ast::Expression::Construct { - ref ty, - ref components, - .. - } => self.const_construct(span, ty, components, ctx.reborrow())?, - ast::Expression::Call { - ref function, - ref arguments, - } => match ctx.globals.get(function.name) { - Some(&LoweredGlobalDecl::Type(ty)) => self.const_construct( - span, - &ast::ConstructorType::Type(ty), - arguments, - ctx.reborrow(), - )?, - Some(_) => return Err(Error::ConstExprUnsupported(span)), - None => return Err(Error::UnknownIdent(function.span, function.name)), - }, - _ => return Err(Error::ConstExprUnsupported(span)), - }; - - Ok(ConstantOrInner::Inner(inner)) - } - - fn interpolate_default( - &mut self, - binding: &Option, - ty: Handle, - ctx: OutputContext<'source, '_, '_>, - ) -> Option { - let mut binding = binding.clone(); - if let Some(ref mut binding) = binding { - binding.apply_default_interpolation(&ctx.module.types[ty].inner); - } - - binding - } -} - -pub fn parse_str(source: &str) -> Result { - Parser::new().parse(source) -} diff --git a/src/front/wgsl/ast.rs b/src/front/wgsl/parse/ast.rs similarity index 97% rename from src/front/wgsl/ast.rs rename to src/front/wgsl/parse/ast.rs index eff74530f..734d9769f 100644 --- a/src/front/wgsl/ast.rs +++ b/src/front/wgsl/parse/ast.rs @@ -1,4 +1,4 @@ -use super::Number; +use crate::front::wgsl::parse::number::Number; use crate::{Arena, FastHashSet, Handle, Span}; use std::hash::Hash; @@ -106,6 +106,9 @@ pub struct EntryPoint { pub workgroup_size: [u32; 3], } +#[cfg(doc)] +use crate::front::wgsl::lower::{ExpressionContext, StatementContext}; + #[derive(Debug)] pub struct Function<'a> { pub entry_point: Option, @@ -135,8 +138,8 @@ pub struct Function<'a> { /// [`LocalDecl`]: StatementKind::LocalDecl /// [`arguments`]: Function::arguments /// [`Ident`]: Expression::Ident - /// [`StatementContext::local_table`]: super::StatementContext::local_table - /// [`ExpressionContext::local_table`]: super::ExpressionContext::local_table + /// [`StatementContext::local_table`]: StatementContext::local_table + /// [`ExpressionContext::local_table`]: ExpressionContext::local_table pub locals: Arena, pub body: Block<'a>, @@ -378,6 +381,9 @@ pub enum Literal { Number(Number), } +#[cfg(doc)] +use crate::front::wgsl::lower::Lowerer; + #[derive(Debug)] pub enum Expression<'a> { Literal(Literal), @@ -423,7 +429,7 @@ pub enum Expression<'a> { /// everything's definition in hand, and can decide whether to emit a Naga /// [`Constant`], [`As`], [`Splat`], or [`Compose`] expression. /// - /// [`Lowerer::call`]: super::Lowerer::call + /// [`Lowerer::call`]: Lowerer::call /// [`Constant`]: crate::Expression::Constant /// [`As`]: crate::Expression::As /// [`Splat`]: crate::Expression::Splat diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/parse/conv.rs similarity index 100% rename from src/front/wgsl/conv.rs rename to src/front/wgsl/parse/conv.rs diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/parse/lexer.rs similarity index 90% rename from src/front/wgsl/lexer.rs rename to src/front/wgsl/parse/lexer.rs index d6975bf98..4654d4087 100644 --- a/src/front/wgsl/lexer.rs +++ b/src/front/wgsl/parse/lexer.rs @@ -1,6 +1,29 @@ -use super::{conv, number::consume_number, Error, ExpectedToken, Token, TokenSpan}; +use super::{number::consume_number, Error, ExpectedToken}; +use crate::front::wgsl::error::NumberError; +use crate::front::wgsl::parse::{conv, Number}; use crate::Span; +type TokenSpan<'a> = (Token<'a>, Span); + +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum Token<'a> { + Separator(char), + Paren(char), + Attribute, + Number(Result), + Word(&'a str), + Operation(char), + LogicalOperation(char), + ShiftOperation(char), + AssignmentOperation(char), + IncrementOperation, + DecrementOperation, + Arrow, + Unknown(char), + Trivia, + End, +} + fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) { let pos = input.find(|c| !what(c)).unwrap_or(input.len()); input.split_at(pos) @@ -176,15 +199,15 @@ fn is_word_part(c: char) -> bool { } #[derive(Clone)] -pub(super) struct Lexer<'a> { +pub(in crate::front::wgsl) struct Lexer<'a> { input: &'a str, - pub(super) source: &'a str, + pub(in crate::front::wgsl) source: &'a str, // The byte offset of the end of the last non-trivia token. last_end_offset: usize, } impl<'a> Lexer<'a> { - pub(super) const fn new(input: &'a str) -> Self { + pub(in crate::front::wgsl) const fn new(input: &'a str) -> Self { Lexer { input, source: input, @@ -211,7 +234,7 @@ impl<'a> Lexer<'a> { Ok((res, Span::from(start..end))) } - pub(super) fn start_byte_offset(&mut self) -> usize { + pub(in crate::front::wgsl) fn start_byte_offset(&mut self) -> usize { loop { // Eat all trivia because `next` doesn't eat trailing trivia. let (token, rest) = consume_token(self.input, false); @@ -234,7 +257,7 @@ impl<'a> Lexer<'a> { self.source.len() - self.input.len() } - pub(super) fn span_from(&self, offset: usize) -> Span { + pub(in crate::front::wgsl) fn span_from(&self, offset: usize) -> Span { Span::from(offset..self.last_end_offset) } @@ -243,7 +266,7 @@ impl<'a> Lexer<'a> { /// Assume we are a parse state where bit shift operators may /// occur, but not angle brackets. #[must_use] - pub(super) fn next(&mut self) -> TokenSpan<'a> { + pub(in crate::front::wgsl) fn next(&mut self) -> TokenSpan<'a> { self.next_impl(false) } @@ -252,7 +275,7 @@ impl<'a> Lexer<'a> { /// Assume we are in a parse state where angle brackets may occur, /// but not bit shift operators. #[must_use] - pub(super) fn next_generic(&mut self) -> TokenSpan<'a> { + pub(in crate::front::wgsl) fn next_generic(&mut self) -> TokenSpan<'a> { self.next_impl(true) } @@ -275,12 +298,15 @@ impl<'a> Lexer<'a> { } #[must_use] - pub(super) fn peek(&mut self) -> TokenSpan<'a> { + pub(in crate::front::wgsl) fn peek(&mut self) -> TokenSpan<'a> { let (token, _) = self.peek_token_and_rest(); token } - pub(super) fn expect_span(&mut self, expected: Token<'a>) -> Result> { + pub(in crate::front::wgsl) fn expect_span( + &mut self, + expected: Token<'a>, + ) -> Result> { let next = self.next(); if next.0 == expected { Ok(next.1) @@ -289,12 +315,15 @@ impl<'a> Lexer<'a> { } } - pub(super) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { + pub(in crate::front::wgsl) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> { self.expect_span(expected)?; Ok(()) } - pub(super) fn expect_generic_paren(&mut self, expected: char) -> Result<(), Error<'a>> { + pub(in crate::front::wgsl) fn expect_generic_paren( + &mut self, + expected: char, + ) -> Result<(), Error<'a>> { let next = self.next_generic(); if next.0 == Token::Paren(expected) { Ok(()) @@ -307,7 +336,7 @@ impl<'a> Lexer<'a> { } /// If the next token matches it is skipped and true is returned - pub(super) fn skip(&mut self, what: Token<'_>) -> bool { + pub(in crate::front::wgsl) fn skip(&mut self, what: Token<'_>) -> bool { let (peeked_token, rest) = self.peek_token_and_rest(); if peeked_token.0 == what { self.input = rest; @@ -317,7 +346,9 @@ impl<'a> Lexer<'a> { } } - pub(super) fn next_ident_with_span(&mut self) -> Result<(&'a str, Span), Error<'a>> { + pub(in crate::front::wgsl) fn next_ident_with_span( + &mut self, + ) -> Result<(&'a str, Span), Error<'a>> { match self.next() { (Token::Word(word), span) if word == "_" => { Err(Error::InvalidIdentifierUnderscore(span)) @@ -330,7 +361,9 @@ impl<'a> Lexer<'a> { } } - pub(super) fn next_ident(&mut self) -> Result, Error<'a>> { + pub(in crate::front::wgsl) fn next_ident( + &mut self, + ) -> Result, Error<'a>> { let ident = self .next_ident_with_span() .map(|(name, span)| super::ast::Ident { name, span })?; @@ -343,7 +376,7 @@ impl<'a> Lexer<'a> { } /// Parses a generic scalar type, for example ``. - pub(super) fn next_scalar_generic( + pub(in crate::front::wgsl) fn next_scalar_generic( &mut self, ) -> Result<(crate::ScalarKind, crate::Bytes), Error<'a>> { self.expect_generic_paren('<')?; @@ -360,7 +393,7 @@ impl<'a> Lexer<'a> { /// Parses a generic scalar type, for example ``. /// /// Returns the span covering the inner type, excluding the brackets. - pub(super) fn next_scalar_generic_with_span( + pub(in crate::front::wgsl) fn next_scalar_generic_with_span( &mut self, ) -> Result<(crate::ScalarKind, crate::Bytes, Span), Error<'a>> { self.expect_generic_paren('<')?; @@ -374,7 +407,9 @@ impl<'a> Lexer<'a> { Ok(pair) } - pub(super) fn next_storage_access(&mut self) -> Result> { + pub(in crate::front::wgsl) fn next_storage_access( + &mut self, + ) -> Result> { let (ident, span) = self.next_ident_with_span()?; match ident { "read" => Ok(crate::StorageAccess::LOAD), @@ -384,7 +419,7 @@ impl<'a> Lexer<'a> { } } - pub(super) fn next_format_generic( + pub(in crate::front::wgsl) fn next_format_generic( &mut self, ) -> Result<(crate::StorageFormat, crate::StorageAccess), Error<'a>> { self.expect(Token::Paren('<'))?; @@ -396,16 +431,16 @@ impl<'a> Lexer<'a> { Ok((format, access)) } - pub(super) fn open_arguments(&mut self) -> Result<(), Error<'a>> { + pub(in crate::front::wgsl) fn open_arguments(&mut self) -> Result<(), Error<'a>> { self.expect(Token::Paren('(')) } - pub(super) fn close_arguments(&mut self) -> Result<(), Error<'a>> { + pub(in crate::front::wgsl) fn close_arguments(&mut self) -> Result<(), Error<'a>> { let _ = self.skip(Token::Separator(',')); self.expect(Token::Paren(')')) } - pub(super) fn next_argument(&mut self) -> Result> { + pub(in crate::front::wgsl) fn next_argument(&mut self) -> Result> { let paren = Token::Paren(')'); if self.skip(Token::Separator(',')) { Ok(!self.skip(paren)) @@ -415,9 +450,6 @@ impl<'a> Lexer<'a> { } } -#[cfg(test)] -use super::{number::Number, NumberError}; - #[cfg(test)] fn sub_test(source: &str, expected_tokens: &[Token]) { let mut lex = Lexer::new(source); diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs new file mode 100644 index 000000000..74d7b2030 --- /dev/null +++ b/src/front/wgsl/parse/mod.rs @@ -0,0 +1,2062 @@ +use crate::front::wgsl::error::{Error, ExpectedToken}; +use crate::front::wgsl::parse::lexer::{Lexer, Token}; +use crate::front::wgsl::parse::number::Number; +use crate::front::SymbolTable; +use crate::{Arena, FastHashSet, Handle, Span}; + +pub mod ast; +pub mod conv; +pub mod lexer; +pub mod number; + +/// State for constructing an AST expression. +/// +/// Not to be confused with `lower::ExpressionContext`. +struct ExpressionContext<'input, 'temp, 'out> { + /// The [`TranslationUnit::expressions`] arena to which we should contribute + /// expressions. + /// + /// [`TranslationUnit::expressions`]: ast::TranslationUnit::expressions + expressions: &'out mut Arena>, + + /// The [`TranslationUnit::types`] arena to which we should contribute new + /// types. + /// + /// [`TranslationUnit::types`]: ast::TranslationUnit::types + types: &'out mut Arena>, + + /// A map from identifiers in scope to the locals/arguments they represent. + /// + /// The handles refer to the [`Function::locals`] area; see that field's + /// documentation for details. + /// + /// [`Function::locals`]: ast::Function::locals + local_table: &'temp mut SymbolTable<&'input str, Handle>, + + /// The [`Function::locals`] arena for the function we're building. + /// + /// [`Function::locals`]: ast::Function::locals + locals: &'out mut Arena, + + /// Identifiers used by the current global declaration that have no local definition. + /// + /// This becomes the [`GlobalDecl`]'s [`dependencies`] set. + /// + /// Note that we don't know at parse time what kind of [`GlobalDecl`] the + /// name refers to. We can't look up names until we've seen the entire + /// translation unit. + /// + /// [`GlobalDecl`]: ast::GlobalDecl + /// [`dependencies`]: ast::GlobalDecl::dependencies + unresolved: &'out mut FastHashSet>, +} + +impl<'a> ExpressionContext<'a, '_, '_> { + fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> { + ExpressionContext { + expressions: self.expressions, + types: self.types, + local_table: self.local_table, + locals: self.locals, + unresolved: self.unresolved, + } + } + + fn parse_binary_op( + &mut self, + lexer: &mut Lexer<'a>, + classifier: impl Fn(Token<'a>) -> Option, + mut parser: impl FnMut( + &mut Lexer<'a>, + ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>>, + ) -> Result>, Error<'a>> { + let start = lexer.start_byte_offset(); + let mut accumulator = parser(lexer, self.reborrow())?; + while let Some(op) = classifier(lexer.peek().0) { + let _ = lexer.next(); + let left = accumulator; + let right = parser(lexer, self.reborrow())?; + accumulator = self.expressions.append( + ast::Expression::Binary { op, left, right }, + lexer.span_from(start), + ); + } + Ok(accumulator) + } +} + +/// Which grammar rule we are in the midst of parsing. +/// +/// This is used for error checking. `Parser` maintains a stack of +/// these and (occasionally) checks that it is being pushed and popped +/// as expected. +#[derive(Clone, Debug, PartialEq)] +enum Rule { + Attribute, + VariableDecl, + TypeDecl, + FunctionDecl, + Block, + Statement, + PrimaryExpr, + SingularExpr, + UnaryExpr, + GeneralExpr, +} + +#[derive(Default)] +struct BindingParser { + location: Option, + built_in: Option, + interpolation: Option, + sampling: Option, + invariant: bool, +} + +impl BindingParser { + fn parse<'a>( + &mut self, + lexer: &mut Lexer<'a>, + name: &'a str, + name_span: Span, + ) -> Result<(), Error<'a>> { + match name { + "location" => { + lexer.expect(Token::Paren('('))?; + self.location = Some(Parser::non_negative_i32_literal(lexer)?); + lexer.expect(Token::Paren(')'))?; + } + "builtin" => { + lexer.expect(Token::Paren('('))?; + let (raw, span) = lexer.next_ident_with_span()?; + self.built_in = Some(conv::map_built_in(raw, span)?); + lexer.expect(Token::Paren(')'))?; + } + "interpolate" => { + lexer.expect(Token::Paren('('))?; + let (raw, span) = lexer.next_ident_with_span()?; + self.interpolation = Some(conv::map_interpolation(raw, span)?); + if lexer.skip(Token::Separator(',')) { + let (raw, span) = lexer.next_ident_with_span()?; + self.sampling = Some(conv::map_sampling(raw, span)?); + } + lexer.expect(Token::Paren(')'))?; + } + "invariant" => self.invariant = true, + _ => return Err(Error::UnknownAttribute(name_span)), + } + Ok(()) + } + + const fn finish<'a>(self, span: Span) -> Result, Error<'a>> { + match ( + self.location, + self.built_in, + self.interpolation, + self.sampling, + self.invariant, + ) { + (None, None, None, None, false) => Ok(None), + (Some(location), None, interpolation, sampling, false) => { + // Before handing over the completed `Module`, we call + // `apply_default_interpolation` to ensure that the interpolation and + // sampling have been explicitly specified on all vertex shader output and fragment + // shader input user bindings, so leaving them potentially `None` here is fine. + Ok(Some(crate::Binding::Location { + location, + interpolation, + sampling, + })) + } + (None, Some(crate::BuiltIn::Position { .. }), None, None, invariant) => { + Ok(Some(crate::Binding::BuiltIn(crate::BuiltIn::Position { + invariant, + }))) + } + (None, Some(built_in), None, None, false) => { + Ok(Some(crate::Binding::BuiltIn(built_in))) + } + (_, _, _, _, _) => Err(Error::InconsistentBinding(span)), + } + } +} + +pub struct Parser { + rules: Vec<(Rule, usize)>, +} + +impl Parser { + pub const fn new() -> Self { + Parser { rules: Vec::new() } + } + + fn reset(&mut self) { + self.rules.clear(); + } + + fn push_rule_span(&mut self, rule: Rule, lexer: &mut Lexer<'_>) { + self.rules.push((rule, lexer.start_byte_offset())); + } + + fn pop_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { + let (_, initial) = self.rules.pop().unwrap(); + lexer.span_from(initial) + } + + fn peek_rule_span(&mut self, lexer: &Lexer<'_>) -> Span { + let &(_, initial) = self.rules.last().unwrap(); + lexer.span_from(initial) + } + + fn switch_value<'a>(lexer: &mut Lexer<'a>) -> Result<(ast::SwitchValue, Span), Error<'a>> { + let token_span = lexer.next(); + match token_span.0 { + Token::Word("default") => Ok((ast::SwitchValue::Default, token_span.1)), + Token::Number(Ok(Number::U32(num))) => Ok((ast::SwitchValue::U32(num), token_span.1)), + Token::Number(Ok(Number::I32(num))) => Ok((ast::SwitchValue::I32(num), token_span.1)), + Token::Number(Err(e)) => Err(Error::BadNumber(token_span.1, e)), + _ => Err(Error::Unexpected(token_span.1, ExpectedToken::Integer)), + } + } + + /// Parse a non-negative signed integer literal. + /// This is for attributes like `size`, `location` and others. + fn non_negative_i32_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + match lexer.next() { + (Token::Number(Ok(Number::I32(num))), span) => { + u32::try_from(num).map_err(|_| Error::NegativeInt(span)) + } + (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), + other => Err(Error::Unexpected(other.1, ExpectedToken::Number)), + } + } + + /// Parse a non-negative integer literal that may be either signed or unsigned. + /// This is for the `workgroup_size` attribute and array lengths. + /// Note: these values should be no larger than [`i32::MAX`], but this is not checked here. + fn generic_non_negative_int_literal<'a>(lexer: &mut Lexer<'a>) -> Result> { + match lexer.next() { + (Token::Number(Ok(Number::I32(num))), span) => { + u32::try_from(num).map_err(|_| Error::NegativeInt(span)) + } + (Token::Number(Ok(Number::U32(num))), _) => Ok(num), + (Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)), + other => Err(Error::Unexpected(other.1, ExpectedToken::Number)), + } + } + + /// 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, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + if let Some((kind, width)) = conv::get_scalar_type(word) { + return Ok(Some(ast::ConstructorType::Scalar { kind, width })); + } + + let partial = match word { + "vec2" => ast::ConstructorType::PartialVector { + size: crate::VectorSize::Bi, + }, + "vec3" => ast::ConstructorType::PartialVector { + size: crate::VectorSize::Tri, + }, + "vec4" => ast::ConstructorType::PartialVector { + size: crate::VectorSize::Quad, + }, + "mat2x2" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Bi, + }, + "mat2x3" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Tri, + }, + "mat2x4" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Bi, + rows: crate::VectorSize::Quad, + }, + "mat3x2" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Bi, + }, + "mat3x3" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Tri, + }, + "mat3x4" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Tri, + rows: crate::VectorSize::Quad, + }, + "mat4x2" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Bi, + }, + "mat4x3" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Tri, + }, + "mat4x4" => ast::ConstructorType::PartialMatrix { + columns: crate::VectorSize::Quad, + rows: crate::VectorSize::Quad, + }, + "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_storage_1d" + | "texture_storage_1d_array" + | "texture_storage_2d" + | "texture_storage_2d_array" + | "texture_storage_3d" => return Err(Error::TypeNotConstructible(span)), + _ => return Ok(None), + }; + + // parse component type if present + match (lexer.peek().0, partial) { + (Token::Paren('<'), ast::ConstructorType::PartialVector { size }) => { + let (kind, width) = lexer.next_scalar_generic()?; + Ok(Some(ast::ConstructorType::Vector { size, kind, width })) + } + (Token::Paren('<'), ast::ConstructorType::PartialMatrix { columns, rows }) => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + match kind { + crate::ScalarKind::Float => Ok(Some(ast::ConstructorType::Matrix { + columns, + rows, + width, + })), + _ => Err(Error::BadMatrixScalarKind(span, kind, width)), + } + } + (Token::Paren('<'), ast::ConstructorType::PartialArray) => { + lexer.expect_generic_paren('<')?; + let base = self.type_decl(lexer, ctx.reborrow())?; + let size = if lexer.skip(Token::Separator(',')) { + let expr = self.unary_expression(lexer, ctx.reborrow())?; + ast::ArraySize::Constant(expr) + } else { + ast::ArraySize::Dynamic + }; + lexer.expect_generic_paren('>')?; + + Ok(Some(ast::ConstructorType::Array { base, size })) + } + (_, partial) => Ok(Some(partial)), + } + } + + /// Expects `name` to be consumed (not in lexer). + fn arguments<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>>, Error<'a>> { + lexer.open_arguments()?; + let mut arguments = Vec::new(); + loop { + if !arguments.is_empty() { + if !lexer.next_argument()? { + break; + } + } else if lexer.skip(Token::Paren(')')) { + break; + } + let arg = self.general_expression(lexer, ctx.reborrow())?; + arguments.push(arg); + } + + Ok(arguments) + } + + /// Expects [`Rule::PrimaryExpr`] or [`Rule::SingularExpr`] on top; does not pop it. + /// Expects `name` to be consumed (not in lexer). + fn function_call<'a>( + &mut self, + lexer: &mut Lexer<'a>, + name: &'a str, + name_span: Span, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + assert!(self.rules.last().is_some()); + + let expr = match name { + // bitcast looks like a function call, but it's an operator and must be handled differently. + "bitcast" => { + lexer.expect_generic_paren('<')?; + let start = lexer.start_byte_offset(); + let to = self.type_decl(lexer, ctx.reborrow())?; + let span = lexer.span_from(start); + lexer.expect_generic_paren('>')?; + + lexer.open_arguments()?; + let expr = self.general_expression(lexer, ctx.reborrow())?; + 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 arguments = self.arguments(lexer, ctx.reborrow())?; + ctx.unresolved.insert(ast::Dependency { + ident: name, + usage: name_span, + }); + ast::Expression::Call { + function: ast::Ident { + name, + span: name_span, + }, + arguments, + } + } + }; + + let span = self.peek_rule_span(lexer); + let expr = ctx.expressions.append(expr, span); + Ok(expr) + } + + fn ident_expr<'a>( + &mut self, + name: &'a str, + name_span: Span, + ctx: ExpressionContext<'a, '_, '_>, + ) -> ast::IdentExpr<'a> { + match ctx.local_table.lookup(name) { + Some(&local) => ast::IdentExpr::Local(local), + None => { + ctx.unresolved.insert(ast::Dependency { + ident: name, + usage: name_span, + }); + ast::IdentExpr::Unresolved(name) + } + } + } + + fn primary_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + self.push_rule_span(Rule::PrimaryExpr, lexer); + + let expr = match lexer.peek() { + (Token::Paren('('), _) => { + let _ = lexer.next(); + let expr = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(')'))?; + self.pop_rule_span(lexer); + return Ok(expr); + } + (Token::Word("true"), _) => { + let _ = lexer.next(); + ast::Expression::Literal(ast::Literal::Bool(true)) + } + (Token::Word("false"), _) => { + let _ = lexer.next(); + ast::Expression::Literal(ast::Literal::Bool(false)) + } + (Token::Number(res), span) => { + let _ = lexer.next(); + let num = res.map_err(|err| Error::BadNumber(span, err))?; + ast::Expression::Literal(ast::Literal::Number(num)) + } + (Token::Word(word), span) => { + let start = lexer.start_byte_offset(); + let _ = lexer.next(); + + if let Some(ty) = self.constructor_type(lexer, word, span, ctx.reborrow())? { + let ty_span = lexer.span_from(start); + let components = self.arguments(lexer, ctx.reborrow())?; + ast::Expression::Construct { + ty, + ty_span, + components, + } + } else if let Token::Paren('(') = lexer.peek().0 { + self.pop_rule_span(lexer); + return self.function_call(lexer, word, span, ctx); + } else if word == "bitcast" { + self.pop_rule_span(lexer); + return self.function_call(lexer, word, span, ctx); + } else { + let ident = self.ident_expr(word, span, ctx.reborrow()); + ast::Expression::Ident(ident) + } + } + other => return Err(Error::Unexpected(other.1, ExpectedToken::PrimaryExpression)), + }; + + let span = self.pop_rule_span(lexer); + let expr = ctx.expressions.append(expr, span); + Ok(expr) + } + + fn postfix<'a>( + &mut self, + span_start: usize, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + expr: Handle>, + ) -> Result>, Error<'a>> { + let mut expr = expr; + + loop { + let expression = match lexer.peek().0 { + Token::Separator('.') => { + let _ = lexer.next(); + let field = lexer.next_ident()?; + + ast::Expression::Member { base: expr, field } + } + Token::Paren('[') => { + let _ = lexer.next(); + let index = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren(']'))?; + + ast::Expression::Index { base: expr, index } + } + _ => break, + }; + + let span = lexer.span_from(span_start); + expr = ctx.expressions.append(expression, span); + } + + Ok(expr) + } + + /// Parse a `unary_expression`. + fn unary_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + self.push_rule_span(Rule::UnaryExpr, lexer); + //TODO: refactor this to avoid backing up + let expr = match lexer.peek().0 { + Token::Operation('-') => { + let _ = lexer.next(); + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::Unary { + op: crate::UnaryOperator::Negate, + expr, + }; + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) + } + Token::Operation('!' | '~') => { + let _ = lexer.next(); + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::Unary { + op: crate::UnaryOperator::Not, + expr, + }; + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) + } + Token::Operation('*') => { + let _ = lexer.next(); + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::Deref(expr); + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) + } + Token::Operation('&') => { + let _ = lexer.next(); + let expr = self.unary_expression(lexer, ctx.reborrow())?; + let expr = ast::Expression::AddrOf(expr); + let span = self.peek_rule_span(lexer); + ctx.expressions.append(expr, span) + } + _ => self.singular_expression(lexer, ctx.reborrow())?, + }; + + self.pop_rule_span(lexer); + Ok(expr) + } + + /// Parse a `singular_expression`. + fn singular_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + let start = lexer.start_byte_offset(); + self.push_rule_span(Rule::SingularExpr, lexer); + let primary_expr = self.primary_expression(lexer, ctx.reborrow())?; + let singular_expr = self.postfix(start, lexer, ctx.reborrow(), primary_expr)?; + self.pop_rule_span(lexer); + + Ok(singular_expr) + } + + fn equality_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + // equality_expression + context.parse_binary_op( + lexer, + |token| match token { + Token::LogicalOperation('=') => Some(crate::BinaryOperator::Equal), + Token::LogicalOperation('!') => Some(crate::BinaryOperator::NotEqual), + _ => None, + }, + // relational_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Paren('<') => Some(crate::BinaryOperator::Less), + Token::Paren('>') => Some(crate::BinaryOperator::Greater), + Token::LogicalOperation('<') => Some(crate::BinaryOperator::LessEqual), + Token::LogicalOperation('>') => Some(crate::BinaryOperator::GreaterEqual), + _ => None, + }, + // shift_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::ShiftOperation('<') => { + Some(crate::BinaryOperator::ShiftLeft) + } + Token::ShiftOperation('>') => { + Some(crate::BinaryOperator::ShiftRight) + } + _ => None, + }, + // additive_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('+') => Some(crate::BinaryOperator::Add), + Token::Operation('-') => { + Some(crate::BinaryOperator::Subtract) + } + _ => None, + }, + // multiplicative_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('*') => { + Some(crate::BinaryOperator::Multiply) + } + Token::Operation('/') => { + Some(crate::BinaryOperator::Divide) + } + Token::Operation('%') => { + Some(crate::BinaryOperator::Modulo) + } + _ => None, + }, + |lexer, context| self.unary_expression(lexer, context), + ) + }, + ) + }, + ) + }, + ) + }, + ) + } + + fn general_expression<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + self.general_expression_with_span(lexer, ctx.reborrow()) + .map(|(expr, _)| expr) + } + + fn general_expression_with_span<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, '_>, + ) -> Result<(Handle>, Span), Error<'a>> { + self.push_rule_span(Rule::GeneralExpr, lexer); + // logical_or_expression + let handle = context.parse_binary_op( + lexer, + |token| match token { + Token::LogicalOperation('|') => Some(crate::BinaryOperator::LogicalOr), + _ => None, + }, + // logical_and_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::LogicalOperation('&') => Some(crate::BinaryOperator::LogicalAnd), + _ => None, + }, + // inclusive_or_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('|') => Some(crate::BinaryOperator::InclusiveOr), + _ => None, + }, + // exclusive_or_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('^') => { + Some(crate::BinaryOperator::ExclusiveOr) + } + _ => None, + }, + // and_expression + |lexer, mut context| { + context.parse_binary_op( + lexer, + |token| match token { + Token::Operation('&') => { + Some(crate::BinaryOperator::And) + } + _ => None, + }, + |lexer, context| { + self.equality_expression(lexer, context) + }, + ) + }, + ) + }, + ) + }, + ) + }, + )?; + Ok((handle, self.pop_rule_span(lexer))) + } + + fn variable_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + self.push_rule_span(Rule::VariableDecl, lexer); + let mut space = crate::AddressSpace::Handle; + + if lexer.skip(Token::Paren('<')) { + let (class_str, span) = lexer.next_ident_with_span()?; + space = match class_str { + "storage" => { + let access = if lexer.skip(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.expect(Token::Paren('>'))?; + } + let name = lexer.next_ident()?; + lexer.expect(Token::Separator(':'))?; + let ty = self.type_decl(lexer, ctx.reborrow())?; + + let init = if lexer.skip(Token::Operation('=')) { + let handle = self.general_expression(lexer, ctx.reborrow())?; + Some(handle) + } else { + None + }; + lexer.expect(Token::Separator(';'))?; + self.pop_rule_span(lexer); + + Ok(ast::GlobalVariable { + name, + space, + binding: None, + ty, + init, + }) + } + + fn struct_body<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + let mut members = Vec::new(); + + lexer.expect(Token::Paren('{'))?; + let mut ready = true; + while !lexer.skip(Token::Paren('}')) { + if !ready { + return Err(Error::Unexpected( + lexer.next().1, + ExpectedToken::Token(Token::Separator(',')), + )); + } + let (mut size, mut align) = (None, None); + self.push_rule_span(Rule::Attribute, lexer); + let mut bind_parser = BindingParser::default(); + while lexer.skip(Token::Attribute) { + match lexer.next_ident_with_span()? { + ("size", _) => { + lexer.expect(Token::Paren('('))?; + let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; + lexer.expect(Token::Paren(')'))?; + size = Some((value, span)); + } + ("align", _) => { + lexer.expect(Token::Paren('('))?; + let (value, span) = lexer.capture_span(Self::non_negative_i32_literal)?; + lexer.expect(Token::Paren(')'))?; + align = Some((value, span)); + } + (word, word_span) => bind_parser.parse(lexer, word, word_span)?, + } + } + + let bind_span = self.pop_rule_span(lexer); + let binding = bind_parser.finish(bind_span)?; + + let name = lexer.next_ident()?; + lexer.expect(Token::Separator(':'))?; + let ty = self.type_decl(lexer, ctx.reborrow())?; + ready = lexer.skip(Token::Separator(',')); + + members.push(ast::StructMember { + name, + ty, + binding, + size, + align, + }); + } + + Ok(members) + } + + fn matrix_scalar_type<'a>( + &mut self, + lexer: &mut Lexer<'a>, + columns: crate::VectorSize, + rows: crate::VectorSize, + ) -> Result, Error<'a>> { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + match kind { + crate::ScalarKind::Float => Ok(ast::Type::Matrix { + columns, + rows, + width, + }), + _ => Err(Error::BadMatrixScalarKind(span, kind, width)), + } + } + + fn type_decl_impl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + word: &'a str, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + if let Some((kind, width)) = conv::get_scalar_type(word) { + return Ok(Some(ast::Type::Scalar { kind, width })); + } + + Ok(Some(match word { + "vec2" => { + let (kind, width) = lexer.next_scalar_generic()?; + ast::Type::Vector { + size: crate::VectorSize::Bi, + kind, + width, + } + } + "vec3" => { + let (kind, width) = lexer.next_scalar_generic()?; + ast::Type::Vector { + size: crate::VectorSize::Tri, + kind, + width, + } + } + "vec4" => { + let (kind, width) = lexer.next_scalar_generic()?; + ast::Type::Vector { + size: crate::VectorSize::Quad, + kind, + width, + } + } + "mat2x2" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Bi)? + } + "mat2x3" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Tri)? + } + "mat2x4" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Quad)? + } + "mat3x2" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Bi)? + } + "mat3x3" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Tri)? + } + "mat3x4" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Quad)? + } + "mat4x2" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Bi)? + } + "mat4x3" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Tri)? + } + "mat4x4" => { + self.matrix_scalar_type(lexer, crate::VectorSize::Quad, crate::VectorSize::Quad)? + } + "atomic" => { + let (kind, width) = lexer.next_scalar_generic()?; + ast::Type::Atomic { kind, width } + } + "ptr" => { + lexer.expect_generic_paren('<')?; + let (ident, span) = lexer.next_ident_with_span()?; + let mut space = conv::map_address_space(ident, span)?; + lexer.expect(Token::Separator(','))?; + let base = self.type_decl(lexer, ctx)?; + if let crate::AddressSpace::Storage { ref mut access } = space { + *access = if lexer.skip(Token::Separator(',')) { + lexer.next_storage_access()? + } else { + crate::StorageAccess::LOAD + }; + } + lexer.expect_generic_paren('>')?; + ast::Type::Pointer { base, space } + } + "array" => { + lexer.expect_generic_paren('<')?; + let base = self.type_decl(lexer, ctx.reborrow())?; + let size = if lexer.skip(Token::Separator(',')) { + let size = self.unary_expression(lexer, ctx.reborrow())?; + ast::ArraySize::Constant(size) + } else { + ast::ArraySize::Dynamic + }; + lexer.expect_generic_paren('>')?; + + ast::Type::Array { base, size } + } + "binding_array" => { + lexer.expect_generic_paren('<')?; + let base = self.type_decl(lexer, ctx.reborrow())?; + let size = if lexer.skip(Token::Separator(',')) { + let size = self.unary_expression(lexer, ctx.reborrow())?; + ast::ArraySize::Constant(size) + } else { + ast::ArraySize::Dynamic + }; + lexer.expect_generic_paren('>')?; + + ast::Type::BindingArray { base, size } + } + "sampler" => ast::Type::Sampler { comparison: false }, + "sampler_comparison" => ast::Type::Sampler { comparison: true }, + "texture_1d" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D1, + arrayed: false, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_1d_array" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D1, + arrayed: true, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_2d" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_2d_array" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_3d" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D3, + arrayed: false, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_cube" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::Cube, + arrayed: false, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_cube_array" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::Cube, + arrayed: true, + class: crate::ImageClass::Sampled { kind, multi: false }, + } + } + "texture_multisampled_2d" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Sampled { kind, multi: true }, + } + } + "texture_multisampled_2d_array" => { + let (kind, width, span) = lexer.next_scalar_generic_with_span()?; + Self::check_texture_sample_type(kind, width, span)?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Sampled { kind, multi: true }, + } + } + "texture_depth_2d" => ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Depth { multi: false }, + }, + "texture_depth_2d_array" => ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Depth { multi: false }, + }, + "texture_depth_cube" => ast::Type::Image { + dim: crate::ImageDimension::Cube, + arrayed: false, + class: crate::ImageClass::Depth { multi: false }, + }, + "texture_depth_cube_array" => ast::Type::Image { + dim: crate::ImageDimension::Cube, + arrayed: true, + class: crate::ImageClass::Depth { multi: false }, + }, + "texture_depth_multisampled_2d" => ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Depth { multi: true }, + }, + "texture_storage_1d" => { + let (format, access) = lexer.next_format_generic()?; + ast::Type::Image { + dim: crate::ImageDimension::D1, + arrayed: false, + class: crate::ImageClass::Storage { format, access }, + } + } + "texture_storage_1d_array" => { + let (format, access) = lexer.next_format_generic()?; + ast::Type::Image { + dim: crate::ImageDimension::D1, + arrayed: true, + class: crate::ImageClass::Storage { format, access }, + } + } + "texture_storage_2d" => { + let (format, access) = lexer.next_format_generic()?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: false, + class: crate::ImageClass::Storage { format, access }, + } + } + "texture_storage_2d_array" => { + let (format, access) = lexer.next_format_generic()?; + ast::Type::Image { + dim: crate::ImageDimension::D2, + arrayed: true, + class: crate::ImageClass::Storage { format, access }, + } + } + "texture_storage_3d" => { + let (format, access) = lexer.next_format_generic()?; + ast::Type::Image { + dim: crate::ImageDimension::D3, + arrayed: false, + class: crate::ImageClass::Storage { format, access }, + } + } + _ => return Ok(None), + })) + } + + const fn check_texture_sample_type( + kind: crate::ScalarKind, + width: u8, + span: Span, + ) -> Result<(), Error<'static>> { + use crate::ScalarKind::*; + // Validate according to https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type + match (kind, width) { + (Float | Sint | Uint, 4) => Ok(()), + _ => Err(Error::BadTextureSampleType { span, kind, width }), + } + } + + /// Parse type declaration of a given name. + fn type_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result>, Error<'a>> { + self.push_rule_span(Rule::TypeDecl, lexer); + + let (name, span) = lexer.next_ident_with_span()?; + + let ty = match self.type_decl_impl(lexer, name, ctx.reborrow())? { + Some(ty) => ty, + None => { + ctx.unresolved.insert(ast::Dependency { + ident: name, + usage: span, + }); + ast::Type::User(ast::Ident { name, span }) + } + }; + + self.pop_rule_span(lexer); + + let handle = ctx.types.append(ty, Span::UNDEFINED); + Ok(handle) + } + + fn assignment_op_and_rhs<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + target: Handle>, + span_start: usize, + ) -> Result<(), Error<'a>> { + use crate::BinaryOperator as Bo; + + let op = lexer.next(); + let (op, value) = match op { + (Token::Operation('='), _) => { + let value = self.general_expression(lexer, ctx.reborrow())?; + (None, value) + } + (Token::AssignmentOperation(c), _) => { + let op = match c { + '<' => Bo::ShiftLeft, + '>' => Bo::ShiftRight, + '+' => Bo::Add, + '-' => Bo::Subtract, + '*' => Bo::Multiply, + '/' => Bo::Divide, + '%' => Bo::Modulo, + '&' => Bo::And, + '|' => Bo::InclusiveOr, + '^' => Bo::ExclusiveOr, + // Note: `consume_token` shouldn't produce any other assignment ops + _ => unreachable!(), + }; + + let value = self.general_expression(lexer, ctx.reborrow())?; + (Some(op), value) + } + token @ (Token::IncrementOperation | Token::DecrementOperation, _) => { + let op = match token.0 { + Token::IncrementOperation => ast::StatementKind::Increment, + Token::DecrementOperation => ast::StatementKind::Decrement, + _ => unreachable!(), + }; + + let span = lexer.span_from(span_start); + block.stmts.push(ast::Statement { + kind: op(target), + span, + }); + return Ok(()); + } + _ => return Err(Error::Unexpected(op.1, ExpectedToken::Assignment)), + }; + + let span = lexer.span_from(span_start); + block.stmts.push(ast::Statement { + kind: ast::StatementKind::Assign { target, op, value }, + span, + }); + Ok(()) + } + + /// Parse an assignment statement (will also parse increment and decrement statements) + fn assignment_statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + ) -> Result<(), Error<'a>> { + let span_start = lexer.start_byte_offset(); + let target = self.general_expression(lexer, ctx.reborrow())?; + self.assignment_op_and_rhs(lexer, ctx, block, target, span_start) + } + + /// Parse a function call statement. + /// Expects `ident` to be consumed (not in the lexer). + fn function_statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + ident: &'a str, + ident_span: Span, + span_start: usize, + mut context: ExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + ) -> Result<(), Error<'a>> { + self.push_rule_span(Rule::SingularExpr, lexer); + + context.unresolved.insert(ast::Dependency { + ident, + usage: ident_span, + }); + let arguments = self.arguments(lexer, context.reborrow())?; + let span = lexer.span_from(span_start); + + block.stmts.push(ast::Statement { + kind: ast::StatementKind::Call { + function: ast::Ident { + name: ident, + span: ident_span, + }, + arguments, + }, + span, + }); + + self.pop_rule_span(lexer); + + Ok(()) + } + + fn function_call_or_assignment_statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut context: ExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + ) -> Result<(), Error<'a>> { + let span_start = lexer.start_byte_offset(); + match lexer.peek() { + (Token::Word(name), span) => { + // A little hack for 2 token lookahead. + let cloned = lexer.clone(); + let _ = lexer.next(); + match lexer.peek() { + (Token::Paren('('), _) => self.function_statement( + lexer, + name, + span, + span_start, + context.reborrow(), + block, + ), + _ => { + *lexer = cloned; + self.assignment_statement(lexer, context.reborrow(), block) + } + } + } + _ => self.assignment_statement(lexer, context.reborrow(), block), + } + } + + fn statement<'a, 'out>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, 'out>, + block: &'out mut ast::Block<'a>, + ) -> Result<(), Error<'a>> { + self.push_rule_span(Rule::Statement, lexer); + match lexer.peek() { + (Token::Separator(';'), _) => { + let _ = lexer.next(); + self.pop_rule_span(lexer); + return Ok(()); + } + (Token::Paren('{'), _) => { + let (inner, span) = self.block(lexer, ctx.reborrow())?; + block.stmts.push(ast::Statement { + kind: ast::StatementKind::Block(inner), + span, + }); + self.pop_rule_span(lexer); + return Ok(()); + } + (Token::Word(word), _) => { + let kind = match word { + "_" => { + let _ = lexer.next(); + lexer.expect(Token::Operation('='))?; + let expr = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(';'))?; + + ast::StatementKind::Ignore(expr) + } + "let" => { + let _ = lexer.next(); + let name = lexer.next_ident()?; + + let given_ty = if lexer.skip(Token::Separator(':')) { + let ty = self.type_decl(lexer, ctx.reborrow())?; + Some(ty) + } else { + None + }; + lexer.expect(Token::Operation('='))?; + let expr_id = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(';'))?; + + let handle = ctx.locals.append(ast::Local, name.span); + if let Some(old) = ctx.local_table.add(name.name, handle) { + return Err(Error::Redefinition { + previous: ctx.locals.get_span(old), + current: name.span, + }); + } + + ast::StatementKind::LocalDecl(ast::LocalDecl::Let(ast::Let { + name, + ty: given_ty, + init: expr_id, + handle, + })) + } + "var" => { + let _ = lexer.next(); + + let name = lexer.next_ident()?; + let ty = if lexer.skip(Token::Separator(':')) { + let ty = self.type_decl(lexer, ctx.reborrow())?; + Some(ty) + } else { + None + }; + + let init = if lexer.skip(Token::Operation('=')) { + let init = self.general_expression(lexer, ctx.reborrow())?; + Some(init) + } else { + None + }; + + lexer.expect(Token::Separator(';'))?; + + let handle = ctx.locals.append(ast::Local, name.span); + if let Some(old) = ctx.local_table.add(name.name, handle) { + return Err(Error::Redefinition { + previous: ctx.locals.get_span(old), + current: name.span, + }); + } + + ast::StatementKind::LocalDecl(ast::LocalDecl::Var(ast::LocalVariable { + name, + ty, + init, + handle, + })) + } + "return" => { + let _ = lexer.next(); + let value = if lexer.peek().0 != Token::Separator(';') { + let handle = self.general_expression(lexer, ctx.reborrow())?; + Some(handle) + } else { + None + }; + lexer.expect(Token::Separator(';'))?; + ast::StatementKind::Return { value } + } + "if" => { + let _ = lexer.next(); + let condition = self.general_expression(lexer, ctx.reborrow())?; + + let accept = self.block(lexer, ctx.reborrow())?.0; + + let mut elsif_stack = Vec::new(); + let mut elseif_span_start = lexer.start_byte_offset(); + let mut reject = loop { + if !lexer.skip(Token::Word("else")) { + break ast::Block::default(); + } + + if !lexer.skip(Token::Word("if")) { + // ... else { ... } + break self.block(lexer, ctx.reborrow())?.0; + } + + // ... else if (...) { ... } + let other_condition = self.general_expression(lexer, ctx.reborrow())?; + let other_block = self.block(lexer, ctx.reborrow())?; + elsif_stack.push((elseif_span_start, other_condition, other_block)); + elseif_span_start = lexer.start_byte_offset(); + }; + + // reverse-fold the else-if blocks + //Note: we may consider uplifting this to the IR + for (other_span_start, other_cond, other_block) in + elsif_stack.into_iter().rev() + { + let sub_stmt = ast::StatementKind::If { + condition: other_cond, + accept: other_block.0, + reject, + }; + reject = ast::Block::default(); + let span = lexer.span_from(other_span_start); + reject.stmts.push(ast::Statement { + kind: sub_stmt, + span, + }) + } + + ast::StatementKind::If { + condition, + accept, + reject, + } + } + "switch" => { + let _ = lexer.next(); + let selector = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Paren('{'))?; + let mut cases = Vec::new(); + + loop { + // cases + default + match lexer.next() { + (Token::Word("case"), _) => { + // parse a list of values + let (value, value_span) = loop { + let (value, value_span) = Self::switch_value(lexer)?; + if lexer.skip(Token::Separator(',')) { + if lexer.skip(Token::Separator(':')) { + break (value, value_span); + } + } else { + lexer.skip(Token::Separator(':')); + break (value, value_span); + } + cases.push(ast::SwitchCase { + value, + value_span, + body: ast::Block::default(), + fall_through: true, + }); + }; + + let body = self.block(lexer, ctx.reborrow())?.0; + + cases.push(ast::SwitchCase { + value, + value_span, + body, + fall_through: false, + }); + } + (Token::Word("default"), value_span) => { + lexer.skip(Token::Separator(':')); + let body = self.block(lexer, ctx.reborrow())?.0; + cases.push(ast::SwitchCase { + value: ast::SwitchValue::Default, + value_span, + body, + fall_through: false, + }); + } + (Token::Paren('}'), _) => break, + (_, span) => { + return Err(Error::Unexpected(span, ExpectedToken::SwitchItem)) + } + } + } + + ast::StatementKind::Switch { selector, cases } + } + "loop" => self.r#loop(lexer, ctx.reborrow())?, + "while" => { + let _ = lexer.next(); + let mut body = ast::Block::default(); + + let (condition, span) = lexer.capture_span(|lexer| { + let condition = self.general_expression(lexer, ctx.reborrow())?; + Ok(condition) + })?; + let mut reject = ast::Block::default(); + reject.stmts.push(ast::Statement { + kind: ast::StatementKind::Break, + span, + }); + + body.stmts.push(ast::Statement { + kind: ast::StatementKind::If { + condition, + accept: ast::Block::default(), + reject, + }, + span, + }); + + let (block, span) = self.block(lexer, ctx.reborrow())?; + body.stmts.push(ast::Statement { + kind: ast::StatementKind::Block(block), + span, + }); + + ast::StatementKind::Loop { + body, + continuing: ast::Block::default(), + break_if: None, + } + } + "for" => { + let _ = lexer.next(); + lexer.expect(Token::Paren('('))?; + + ctx.local_table.push_scope(); + + if !lexer.skip(Token::Separator(';')) { + let num_statements = block.stmts.len(); + let (_, span) = lexer.capture_span(|lexer| { + self.statement(lexer, ctx.reborrow(), block) + })?; + + if block.stmts.len() != num_statements { + match block.stmts.last().unwrap().kind { + ast::StatementKind::Call { .. } + | ast::StatementKind::Assign { .. } + | ast::StatementKind::LocalDecl(_) => {} + _ => return Err(Error::InvalidForInitializer(span)), + } + } + }; + + let mut body = ast::Block::default(); + if !lexer.skip(Token::Separator(';')) { + let (condition, span) = lexer.capture_span(|lexer| { + let condition = self.general_expression(lexer, ctx.reborrow())?; + lexer.expect(Token::Separator(';'))?; + Ok(condition) + })?; + let mut reject = ast::Block::default(); + reject.stmts.push(ast::Statement { + kind: ast::StatementKind::Break, + span, + }); + body.stmts.push(ast::Statement { + kind: ast::StatementKind::If { + condition, + accept: ast::Block::default(), + reject, + }, + span, + }); + }; + + let mut continuing = ast::Block::default(); + if !lexer.skip(Token::Paren(')')) { + self.function_call_or_assignment_statement( + lexer, + ctx.reborrow(), + &mut continuing, + )?; + lexer.expect(Token::Paren(')'))?; + } + + let (block, span) = self.block(lexer, ctx.reborrow())?; + body.stmts.push(ast::Statement { + kind: ast::StatementKind::Block(block), + span, + }); + + ctx.local_table.pop_scope(); + + ast::StatementKind::Loop { + body, + continuing, + break_if: None, + } + } + "break" => { + let (_, span) = lexer.next(); + // Check if the next token is an `if`, this indicates + // that the user tried to type out a `break if` which + // is illegal in this position. + let (peeked_token, peeked_span) = lexer.peek(); + if let Token::Word("if") = peeked_token { + let span = span.until(&peeked_span); + return Err(Error::InvalidBreakIf(span)); + } + ast::StatementKind::Break + } + "continue" => { + let _ = lexer.next(); + ast::StatementKind::Continue + } + "discard" => { + let _ = lexer.next(); + ast::StatementKind::Kill + } + // assignment or a function call + _ => { + self.function_call_or_assignment_statement(lexer, ctx.reborrow(), block)?; + lexer.expect(Token::Separator(';'))?; + self.pop_rule_span(lexer); + return Ok(()); + } + }; + + let span = self.pop_rule_span(lexer); + block.stmts.push(ast::Statement { kind, span }); + } + _ => { + self.assignment_statement(lexer, ctx.reborrow(), block)?; + self.pop_rule_span(lexer); + } + } + Ok(()) + } + + fn r#loop<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result, Error<'a>> { + let _ = lexer.next(); + let mut body = ast::Block::default(); + let mut continuing = ast::Block::default(); + let mut break_if = None; + + lexer.expect(Token::Paren('{'))?; + + ctx.local_table.push_scope(); + + loop { + if lexer.skip(Token::Word("continuing")) { + // Branch for the `continuing` block, this must be + // the last thing in the loop body + + // Expect a opening brace to start the continuing block + lexer.expect(Token::Paren('{'))?; + loop { + if lexer.skip(Token::Word("break")) { + // Branch for the `break if` statement, this statement + // has the form `break if ;` and must be the last + // statement in a continuing block + + // The break must be followed by an `if` to form + // the break if + lexer.expect(Token::Word("if"))?; + + let condition = self.general_expression(lexer, ctx.reborrow())?; + // Set the condition of the break if to the newly parsed + // expression + break_if = Some(condition); + + // Expect a semicolon to close the statement + lexer.expect(Token::Separator(';'))?; + // Expect a closing brace to close the continuing block, + // since the break if must be the last statement + lexer.expect(Token::Paren('}'))?; + // Stop parsing the continuing block + break; + } else if lexer.skip(Token::Paren('}')) { + // If we encounter a closing brace it means we have reached + // the end of the continuing block and should stop processing + break; + } else { + // Otherwise try to parse a statement + self.statement(lexer, ctx.reborrow(), &mut continuing)?; + } + } + // Since the continuing block must be the last part of the loop body, + // we expect to see a closing brace to end the loop body + lexer.expect(Token::Paren('}'))?; + break; + } + if lexer.skip(Token::Paren('}')) { + // If we encounter a closing brace it means we have reached + // the end of the loop body and should stop processing + break; + } + // Otherwise try to parse a statement + self.statement(lexer, ctx.reborrow(), &mut body)?; + } + + ctx.local_table.pop_scope(); + + Ok(ast::StatementKind::Loop { + body, + continuing, + break_if, + }) + } + + /// compound_statement + fn block<'a>( + &mut self, + lexer: &mut Lexer<'a>, + mut ctx: ExpressionContext<'a, '_, '_>, + ) -> Result<(ast::Block<'a>, Span), Error<'a>> { + self.push_rule_span(Rule::Block, lexer); + + ctx.local_table.push_scope(); + + let _ = lexer.next(); + let mut statements = ast::Block::default(); + while !lexer.skip(Token::Paren('}')) { + self.statement(lexer, ctx.reborrow(), &mut statements)?; + } + + ctx.local_table.pop_scope(); + + let span = self.pop_rule_span(lexer); + Ok((statements, span)) + } + + fn varying_binding<'a>( + &mut self, + lexer: &mut Lexer<'a>, + ) -> Result, Error<'a>> { + let mut bind_parser = BindingParser::default(); + self.push_rule_span(Rule::Attribute, lexer); + + while lexer.skip(Token::Attribute) { + let (word, span) = lexer.next_ident_with_span()?; + bind_parser.parse(lexer, word, span)?; + } + + let span = self.pop_rule_span(lexer); + bind_parser.finish(span) + } + + fn function_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + out: &mut ast::TranslationUnit<'a>, + dependencies: &mut FastHashSet>, + ) -> Result, Error<'a>> { + self.push_rule_span(Rule::FunctionDecl, lexer); + // read function name + let fun_name = lexer.next_ident()?; + + let mut locals = Arena::new(); + + let mut ctx = ExpressionContext { + expressions: &mut out.expressions, + local_table: &mut SymbolTable::default(), + locals: &mut locals, + types: &mut out.types, + unresolved: dependencies, + }; + + // read parameter list + let mut arguments = Vec::new(); + lexer.expect(Token::Paren('('))?; + let mut ready = true; + while !lexer.skip(Token::Paren(')')) { + if !ready { + return Err(Error::Unexpected( + lexer.next().1, + ExpectedToken::Token(Token::Separator(',')), + )); + } + let binding = self.varying_binding(lexer)?; + + let param_name = lexer.next_ident()?; + + lexer.expect(Token::Separator(':'))?; + let param_type = self.type_decl(lexer, ctx.reborrow())?; + + let handle = ctx.locals.append(ast::Local, param_name.span); + ctx.local_table.add(param_name.name, handle); + arguments.push(ast::FunctionArgument { + name: param_name, + ty: param_type, + binding, + handle, + }); + ready = lexer.skip(Token::Separator(',')); + } + // read return type + let result = if lexer.skip(Token::Arrow) && !lexer.skip(Token::Word("void")) { + let binding = self.varying_binding(lexer)?; + let ty = self.type_decl(lexer, ctx.reborrow())?; + Some(ast::FunctionResult { ty, binding }) + } else { + None + }; + + // read body + let body = self.block(lexer, ctx)?.0; + + let fun = ast::Function { + entry_point: None, + name: fun_name, + arguments, + result, + body, + locals, + }; + + // done + self.pop_rule_span(lexer); + + Ok(fun) + } + + fn global_decl<'a>( + &mut self, + lexer: &mut Lexer<'a>, + out: &mut ast::TranslationUnit<'a>, + ) -> Result<(), Error<'a>> { + // read attributes + let mut binding = None; + let mut stage = None; + let mut workgroup_size = [0u32; 3]; + let mut early_depth_test = None; + let (mut bind_index, mut bind_group) = (None, None); + + self.push_rule_span(Rule::Attribute, lexer); + while lexer.skip(Token::Attribute) { + match lexer.next_ident_with_span()? { + ("binding", _) => { + lexer.expect(Token::Paren('('))?; + bind_index = Some(Self::non_negative_i32_literal(lexer)?); + lexer.expect(Token::Paren(')'))?; + } + ("group", _) => { + lexer.expect(Token::Paren('('))?; + bind_group = Some(Self::non_negative_i32_literal(lexer)?); + lexer.expect(Token::Paren(')'))?; + } + ("vertex", _) => { + stage = Some(crate::ShaderStage::Vertex); + } + ("fragment", _) => { + stage = Some(crate::ShaderStage::Fragment); + } + ("compute", _) => { + stage = Some(crate::ShaderStage::Compute); + } + ("workgroup_size", _) => { + lexer.expect(Token::Paren('('))?; + workgroup_size = [1u32; 3]; + for (i, size) in workgroup_size.iter_mut().enumerate() { + *size = Self::generic_non_negative_int_literal(lexer)?; + match lexer.next() { + (Token::Paren(')'), _) => break, + (Token::Separator(','), _) if i != 2 => (), + other => { + return Err(Error::Unexpected( + other.1, + ExpectedToken::WorkgroupSizeSeparator, + )) + } + } + } + } + ("early_depth_test", _) => { + let conservative = if lexer.skip(Token::Paren('(')) { + let (ident, ident_span) = lexer.next_ident_with_span()?; + let value = conv::map_conservative_depth(ident, ident_span)?; + lexer.expect(Token::Paren(')'))?; + Some(value) + } else { + None + }; + early_depth_test = Some(crate::EarlyDepthTest { conservative }); + } + (_, word_span) => return Err(Error::UnknownAttribute(word_span)), + } + } + + let attrib_span = self.pop_rule_span(lexer); + match (bind_group, bind_index) { + (Some(group), Some(index)) => { + binding = Some(crate::ResourceBinding { + group, + binding: index, + }); + } + (Some(_), None) => return Err(Error::MissingAttribute("binding", attrib_span)), + (None, Some(_)) => return Err(Error::MissingAttribute("group", attrib_span)), + (None, None) => {} + } + + let mut dependencies = FastHashSet::default(); + let mut ctx = ExpressionContext { + expressions: &mut out.expressions, + local_table: &mut SymbolTable::default(), + locals: &mut Arena::new(), + types: &mut out.types, + unresolved: &mut dependencies, + }; + + // read item + let start = lexer.start_byte_offset(); + let kind = match lexer.next() { + (Token::Separator(';'), _) => None, + (Token::Word("struct"), _) => { + let name = lexer.next_ident()?; + + let members = self.struct_body(lexer, ctx)?; + Some(ast::GlobalDeclKind::Struct(ast::Struct { name, members })) + } + (Token::Word("type"), _) => { + let name = lexer.next_ident()?; + + lexer.expect(Token::Operation('='))?; + let ty = self.type_decl(lexer, ctx)?; + lexer.expect(Token::Separator(';'))?; + Some(ast::GlobalDeclKind::Type(ast::TypeAlias { name, ty })) + } + (Token::Word("const"), _) => { + let name = lexer.next_ident()?; + + let ty = if lexer.skip(Token::Separator(':')) { + let ty = self.type_decl(lexer, ctx.reborrow())?; + Some(ty) + } else { + None + }; + + lexer.expect(Token::Operation('='))?; + let init = self.general_expression(lexer, ctx)?; + lexer.expect(Token::Separator(';'))?; + + Some(ast::GlobalDeclKind::Const(ast::Const { name, ty, init })) + } + (Token::Word("var"), _) => { + let mut var = self.variable_decl(lexer, ctx)?; + var.binding = binding.take(); + Some(ast::GlobalDeclKind::Var(var)) + } + (Token::Word("fn"), _) => { + let function = self.function_decl(lexer, out, &mut dependencies)?; + Some(ast::GlobalDeclKind::Fn(ast::Function { + entry_point: stage.map(|stage| ast::EntryPoint { + stage, + early_depth_test, + workgroup_size, + }), + ..function + })) + } + (Token::End, _) => return Ok(()), + other => return Err(Error::Unexpected(other.1, ExpectedToken::GlobalItem)), + }; + + if let Some(kind) = kind { + out.decls.append( + ast::GlobalDecl { kind, dependencies }, + lexer.span_from(start), + ); + } + + if !self.rules.is_empty() { + log::error!("Reached the end of global decl, but rule stack is not empty"); + log::error!("Rules: {:?}", self.rules); + return Err(Error::Other); + }; + + match binding { + None => Ok(()), + // we had the attribute but no var? + Some(_) => Err(Error::Other), + } + } + + pub fn parse<'a>(&mut self, source: &'a str) -> Result, Error<'a>> { + self.reset(); + + let mut lexer = Lexer::new(source); + let mut tu = ast::TranslationUnit::default(); + loop { + match self.global_decl(&mut lexer, &mut tu) { + Err(error) => return Err(error), + Ok(()) => { + if lexer.peek().0 == Token::End { + break; + } + } + } + } + + Ok(tu) + } +} diff --git a/src/front/wgsl/number.rs b/src/front/wgsl/parse/number.rs similarity index 98% rename from src/front/wgsl/number.rs rename to src/front/wgsl/parse/number.rs index cd7b88c7e..57a2be614 100644 --- a/src/front/wgsl/number.rs +++ b/src/front/wgsl/parse/number.rs @@ -1,6 +1,7 @@ use std::borrow::Cow; -use super::{NumberError, Token}; +use crate::front::wgsl::error::NumberError; +use crate::front::wgsl::parse::lexer::Token; /// When using this type assume no Abstract Int/Float for now #[derive(Copy, Clone, Debug, PartialEq)] @@ -42,7 +43,7 @@ impl Number { // TODO: when implementing Creation-Time Expressions, remove the ability to match the minus sign -pub(super) fn consume_number(input: &str) -> (Token<'_>, &str) { +pub(in crate::front::wgsl) fn consume_number(input: &str) -> (Token<'_>, &str) { let (result, rest) = parse(input); ( Token::Number(result.and_then(Number::abstract_to_concrete)), @@ -146,7 +147,7 @@ fn parse(input: &str) -> (Result, &str) { impl<'a> ExtractSubStr<'a> { /// given an `input` and a `start` (tail of the `input`) - /// creates a new [ExtractSubStr] + /// creates a new [`ExtractSubStr`](`Self`) fn start(input: &'a str, start: &'a [u8]) -> Self { let start = input.len() - start.len(); Self(&input[start..]) diff --git a/tests/snapshots.rs b/tests/snapshots.rs index ad15d614f..466f1739f 100644 --- a/tests/snapshots.rs +++ b/tests/snapshots.rs @@ -623,7 +623,7 @@ fn convert_glsl_variations_check() { let root = env!("CARGO_MANIFEST_DIR"); let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/variations.glsl")) .expect("Couldn't find glsl file"); - let mut parser = naga::front::glsl::Parser::default(); + let mut parser = naga::front::glsl::Frontend::default(); let module = parser .parse( &naga::front::glsl::Options { @@ -654,7 +654,7 @@ fn convert_glsl_folder() { } println!("Processing {file_name}"); - let mut parser = naga::front::glsl::Parser::default(); + let mut parser = naga::front::glsl::Frontend::default(); let module = parser .parse( &naga::front::glsl::Options {