From f04a07c86c0ee6ac4184acb74f0a6e82efecf13f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Mon, 14 Sep 2020 01:14:51 -0400 Subject: [PATCH] proc: make typifier work with gaps in the type graph --- src/back/glsl.rs | 28 +-- src/back/msl.rs | 36 ++-- src/front/spv/rosetta.rs | 3 +- src/front/wgsl/mod.rs | 155 ++++++++++------- src/proc/mod.rs | 2 +- src/proc/typifier.rs | 363 +++++++++++++++++++++------------------ 6 files changed, 322 insertions(+), 265 deletions(-) diff --git a/src/back/glsl.rs b/src/back/glsl.rs index dd472e32e..ed8f3feb0 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,4 +1,4 @@ -use super::{BorrowType, MaybeOwned}; +use super::BorrowType; use crate::{ proc::{Interface, Visitor}, Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, @@ -661,14 +661,14 @@ fn write_expression<'a, 'b>( let inner = match *ty.borrow() { TypeInner::Vector { kind, width, .. } => { - MaybeOwned::Owned(TypeInner::Scalar { kind, width }) + BorrowType::Owned(TypeInner::Scalar { kind, width }) } TypeInner::Matrix { kind, width, columns, .. - } => MaybeOwned::Owned(TypeInner::Vector { + } => BorrowType::Owned(TypeInner::Vector { kind, width, size: columns, @@ -692,7 +692,7 @@ fn write_expression<'a, 'b>( match *ty.borrow() { TypeInner::Vector { kind, width, .. } => ( Cow::Owned(format!("{}[{}]", base_expr, index)), - MaybeOwned::Owned(TypeInner::Scalar { kind, width }), + BorrowType::Owned(TypeInner::Scalar { kind, width }), ), TypeInner::Matrix { kind, @@ -701,7 +701,7 @@ fn write_expression<'a, 'b>( .. } => ( Cow::Owned(format!("{}[{}]", base_expr, index)), - MaybeOwned::Owned(TypeInner::Vector { + BorrowType::Owned(TypeInner::Vector { kind, width, size: columns, @@ -869,9 +869,9 @@ fn write_expression<'a, 'b>( let width = 4; let ty = if shadow { - MaybeOwned::Owned(TypeInner::Scalar { kind, width }) + BorrowType::Owned(TypeInner::Scalar { kind, width }) } else { - MaybeOwned::Owned(TypeInner::Vector { kind, width, size }) + BorrowType::Owned(TypeInner::Vector { kind, width, size }) }; (Cow::Owned(expr), ty) @@ -942,7 +942,7 @@ fn write_expression<'a, 'b>( let width = 4; ( Cow::Owned(expr), - MaybeOwned::Owned(TypeInner::Vector { kind, width, size }), + BorrowType::Owned(TypeInner::Vector { kind, width, size }), ) } Expression::Unary { op, expr } => { @@ -1043,7 +1043,7 @@ fn write_expression<'a, 'b>( | BinaryOperator::Less | BinaryOperator::LessEqual | BinaryOperator::Greater - | BinaryOperator::GreaterEqual => MaybeOwned::Owned(TypeInner::Scalar { + | BinaryOperator::GreaterEqual => BorrowType::Owned(TypeInner::Scalar { kind: ScalarKind::Bool, width: 1, }), @@ -1083,7 +1083,7 @@ fn write_expression<'a, 'b>( rows, kind, width, - } => MaybeOwned::Owned(TypeInner::Matrix { + } => BorrowType::Owned(TypeInner::Matrix { columns: rows, rows: columns, kind, @@ -1106,7 +1106,7 @@ fn write_expression<'a, 'b>( let ty = match *left_ty.borrow() { TypeInner::Vector { kind, width, .. } => { - MaybeOwned::Owned(TypeInner::Scalar { kind, width }) + BorrowType::Owned(TypeInner::Scalar { kind, width }) } _ => { return Err(Error::Custom(format!( @@ -1140,7 +1140,7 @@ fn write_expression<'a, 'b>( TypeInner::Scalar { width, kind } => ( kind, Cow::Borrowed(map_scalar(kind, width, builder.features)?.full), - MaybeOwned::Owned(TypeInner::Scalar { kind, width }), + BorrowType::Owned(TypeInner::Scalar { kind, width }), ), TypeInner::Vector { width, kind, size } => ( kind, @@ -1148,7 +1148,7 @@ fn write_expression<'a, 'b>( "{}vec", map_scalar(kind, width, builder.features)?.prefix )), - MaybeOwned::Owned(TypeInner::Vector { kind, width, size }), + BorrowType::Owned(TypeInner::Vector { kind, width, size }), ), _ => return Err(Error::Custom(format!("Cannot convert {}", value_expr))), }; @@ -1196,7 +1196,7 @@ fn write_expression<'a, 'b>( FunctionOrigin::Local(function) => module.functions[function] .return_type .map(|ty| module.borrow_type(ty)) - .unwrap_or(MaybeOwned::Owned( + .unwrap_or(BorrowType::Owned( TypeInner::Sampler { comparison: false }, /*Dummy type*/ )), FunctionOrigin::External(_) => { diff --git a/src/back/msl.rs b/src/back/msl.rs index 251dfd503..e35a6bfc8 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -14,7 +14,7 @@ the output struct. If there is a structure in the outputs, and it contains any b we move them up to the root output structure that we define ourselves. !*/ -use super::{BorrowType, MaybeOwned}; +use super::BorrowType; use crate::{arena::Handle, FastHashMap}; use std::fmt::{Display, Error as FmtError, Formatter, Write}; @@ -410,7 +410,7 @@ impl Writer { rows, kind, width, .. } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; - Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + Ok(BorrowType::Owned(crate::TypeInner::Vector { size: rows, kind, width, @@ -418,7 +418,7 @@ impl Writer { } crate::TypeInner::Vector { kind, width, .. } => { write!(self.out, ".{}", COMPONENTS[index as usize])?; - Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width })) + Ok(BorrowType::Owned(crate::TypeInner::Scalar { kind, width })) } crate::TypeInner::Array { base, @@ -460,7 +460,7 @@ impl Writer { } _ => return Err(Error::UnsupportedCompose(ty)), } - Ok(MaybeOwned::Borrowed(inner)) + Ok(BorrowType::Borrowed(inner)) } crate::Expression::GlobalVariable(handle) => { let var = &module.global_variables[handle]; @@ -468,7 +468,7 @@ impl Writer { match var.class { crate::StorageClass::Output => { if let crate::TypeInner::Struct { .. } = *inner { - return Ok(MaybeOwned::Borrowed(inner)); + return Ok(BorrowType::Borrowed(inner)); } write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?; } @@ -481,14 +481,14 @@ impl Writer { } let name = var.name.or_index(handle); write!(self.out, "{}", name)?; - Ok(MaybeOwned::Borrowed(inner)) + Ok(BorrowType::Borrowed(inner)) } crate::Expression::LocalVariable(handle) => { let var = &function.local_variables[handle]; let inner = &module.types[var.ty].inner; let name = var.name.or_index(handle); write!(self.out, "{}", name)?; - Ok(MaybeOwned::Borrowed(inner)) + Ok(BorrowType::Borrowed(inner)) } crate::Expression::Load { pointer } => { //write!(self.out, "*")?; @@ -533,7 +533,7 @@ impl Writer { ( &crate::TypeInner::Scalar { kind, width }, &crate::TypeInner::Scalar { .. }, - ) => MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width }), + ) => BorrowType::Owned(crate::TypeInner::Scalar { kind, width }), ( &crate::TypeInner::Scalar { .. }, &crate::TypeInner::Vector { size, kind, width }, @@ -545,7 +545,7 @@ impl Writer { | ( &crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Vector { .. }, - ) => MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }), + ) => BorrowType::Owned(crate::TypeInner::Vector { size, kind, width }), ( &crate::TypeInner::Matrix { rows, @@ -554,7 +554,7 @@ impl Writer { width, }, &crate::TypeInner::Vector { .. }, - ) => MaybeOwned::Owned(crate::TypeInner::Vector { + ) => BorrowType::Owned(crate::TypeInner::Vector { size: rows, kind, width, @@ -564,7 +564,7 @@ impl Writer { } } } else { - MaybeOwned::Owned(crate::TypeInner::Scalar { + BorrowType::Owned(crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: 1, }) @@ -599,7 +599,7 @@ impl Writer { write!(self.out, ")")?; match *ty_image.borrow() { crate::TypeInner::Image { kind, .. } => { - Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + Ok(BorrowType::Owned(crate::TypeInner::Vector { size: crate::VectorSize::Quad, kind, width: 4, @@ -633,7 +633,7 @@ impl Writer { crate::SampleLevel::Bias(_) => return Err(Error::UnexpectedSampleLevel(level)), } write!(self.out, ")")?; - Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { + Ok(BorrowType::Owned(crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width: 4, })) @@ -652,7 +652,7 @@ impl Writer { write!(self.out, ")")?; match *ty_image.borrow() { crate::TypeInner::Image { kind, .. } => { - Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + Ok(BorrowType::Owned(crate::TypeInner::Vector { size: crate::VectorSize::Quad, kind, width: 4, @@ -701,7 +701,7 @@ impl Writer { write!(self.out, ", ")?; self.put_expression(arguments[1], function, module)?; write!(self.out, ")")?; - Ok(MaybeOwned::Owned(result)) + Ok(BorrowType::Owned(result)) } "length" => { write!(self.out, "length(")?; @@ -713,7 +713,7 @@ impl Writer { _ => return Err(Error::UnexpectedDistanceArgument(ty_arg)), }; write!(self.out, ")")?; - Ok(MaybeOwned::Owned(result)) + Ok(BorrowType::Owned(result)) } "mix" => { write!(self.out, "mix(")?; @@ -735,7 +735,7 @@ impl Writer { &'w mut self, handle: Handle, module: &'a crate::Module, - ) -> Result, Error<'a>> { + ) -> Result, Error<'a>> { let constant = &module.constants[handle]; let ty = &module.types[constant.ty]; @@ -768,7 +768,7 @@ impl Writer { } } - Ok(MaybeOwned::Borrowed(&ty.inner)) + Ok(BorrowType::Borrowed(&ty.inner)) } fn put_statement<'w, 'a: 'w>( diff --git a/src/front/spv/rosetta.rs b/src/front/spv/rosetta.rs index 0dffc79de..c787e7646 100644 --- a/src/front/spv/rosetta.rs +++ b/src/front/spv/rosetta.rs @@ -12,8 +12,7 @@ fn rosetta_test(file_name: &str) { let module = super::parse_u8_slice(&input).unwrap(); let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap(); - let expected = - fs::read_to_string(file_path.with_extension("expected.ron")).unwrap(); + let expected = fs::read_to_string(file_path.with_extension("expected.ron")).unwrap(); difference::assert_diff!(output.as_str(), expected.as_str(), "", 0); } diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs index f291057b1..f3f980e9b 100644 --- a/src/front/wgsl/mod.rs +++ b/src/front/wgsl/mod.rs @@ -8,7 +8,7 @@ mod rosetta_tests; use crate::{ arena::{Arena, Handle}, - proc::{ResolveError, Typifier}, + proc::{ResolveContext, ResolveError, Typifier}, FastHashMap, }; @@ -156,19 +156,22 @@ impl<'a> ExpressionContext<'a, '_, '_> { fn resolve_type( &mut self, handle: Handle, - ) -> Result, Error<'a>> { - self.typifier - .resolve( - handle, - self.expressions, - self.types, - self.constants, - self.global_vars, - self.local_vars, - &Arena::new(), //TODO - self.parameter_types, - ) - .map_err(Error::InvalidResolve) + ) -> Result<&crate::TypeInner, Error<'a>> { + let functions = Arena::new(); //TODO + let resolve_ctx = ResolveContext { + constants: self.constants, + global_vars: self.global_vars, + local_vars: self.local_vars, + functions: &functions, + parameter_types: self.parameter_types, + }; + match self + .typifier + .grow(handle, self.expressions, self.types, &resolve_ctx) + { + Err(e) => Err(Error::InvalidResolve(e)), + Ok(()) => Ok(self.typifier.get(handle, self.types)), + } } fn parse_binary_op( @@ -194,6 +197,51 @@ impl<'a> ExpressionContext<'a, '_, '_> { } } +enum Composition { + Single(crate::Expression), + Multi(crate::VectorSize, Vec>), +} + +impl Composition { + fn make<'a>( + base: Handle, + base_size: crate::VectorSize, + name: &'a str, + expressions: &mut Arena, + ) -> Result> { + const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; + + Ok(if name.len() > 1 { + let mut components = Vec::with_capacity(name.len()); + for ch in name.chars() { + let expr = crate::Expression::AccessIndex { + base, + index: MEMBERS[..base_size as usize] + .iter() + .position(|&m| m == ch) + .ok_or(Error::BadAccessor(name))? as u32, + }; + components.push(expressions.append(expr)); + } + + let size = match name.len() { + 2 => crate::VectorSize::Bi, + 3 => crate::VectorSize::Tri, + 4 => crate::VectorSize::Quad, + _ => return Err(Error::BadAccessor(name)), + }; + Composition::Multi(size, components) + } else { + let ch = name.chars().next().ok_or(Error::BadAccessor(name))?; + let index = MEMBERS[..base_size as usize] + .iter() + .position(|&m| m == ch) + .ok_or(Error::BadAccessor(name))? as u32; + Composition::Single(crate::Expression::AccessIndex { base, index }) + }) + } +} + #[derive(Clone, Debug, PartialEq)] pub enum Scope { Decoration, @@ -515,9 +563,8 @@ impl Parser { Token::Separator('.') => { let _ = lexer.next(); let name = lexer.next_ident()?; - let type_handle = ctx.resolve_type(handle)?; - let base_type = &ctx.types[type_handle]; - let expression = match base_type.inner { + println!("Resolving '{}' for {:?}", name, ctx.resolve_type(handle)); //TEMP + let expression = match *ctx.resolve_type(handle)? { crate::TypeInner::Struct { ref members } => { let index = members .iter() @@ -529,44 +576,32 @@ impl Parser { index, } } - crate::TypeInner::Vector { size, kind, width } - | crate::TypeInner::Matrix { - columns: size, + crate::TypeInner::Vector { size, kind, width } => { + match Composition::make(handle, size, name, ctx.expressions)? { + Composition::Multi(size, components) => { + let inner = crate::TypeInner::Vector { size, kind, width }; + crate::Expression::Compose { + ty: ctx + .types + .fetch_or_append(crate::Type { name: None, inner }), + components, + } + } + Composition::Single(expr) => expr, + } + } + crate::TypeInner::Matrix { + rows, + columns, kind, width, - .. - } => { - const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w']; - if name.len() > 1 { - let mut components = Vec::with_capacity(name.len()); - for ch in name.chars() { - let expr = crate::Expression::AccessIndex { - base: handle, - index: MEMBERS[..size as usize] - .iter() - .position(|&m| m == ch) - .ok_or(Error::BadAccessor(name))? - as u32, - }; - components.push(ctx.expressions.append(expr)); - } - let size = match name.len() { - 2 => crate::VectorSize::Bi, - 3 => crate::VectorSize::Tri, - 4 => crate::VectorSize::Quad, - _ => return Err(Error::BadAccessor(name)), - }; - let inner = if let crate::TypeInner::Matrix { rows, .. } = - base_type.inner - { - crate::TypeInner::Matrix { - columns: size, - rows, - kind, - width, - } - } else { - crate::TypeInner::Vector { size, kind, width } + } => match Composition::make(handle, columns, name, ctx.expressions)? { + Composition::Multi(columns, components) => { + let inner = crate::TypeInner::Matrix { + columns, + rows, + kind, + width, }; crate::Expression::Compose { ty: ctx @@ -574,19 +609,9 @@ impl Parser { .fetch_or_append(crate::Type { name: None, inner }), components, } - } else { - let ch = name.chars().next().unwrap(); - let index = MEMBERS[..size as usize] - .iter() - .position(|&m| m == ch) - .ok_or(Error::BadAccessor(name))? - as u32; - crate::Expression::AccessIndex { - base: handle, - index, - } } - } + Composition::Single(expr) => expr, + }, _ => return Err(Error::BadAccessor(name)), }; handle = ctx.expressions.append(expression); diff --git a/src/proc/mod.rs b/src/proc/mod.rs index a37d5bf22..827d40358 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -5,5 +5,5 @@ mod typifier; mod validator; pub use interface::{Interface, Visitor}; -pub use typifier::{check_constant_type, ResolveError, Typifier}; +pub use typifier::{check_constant_type, ResolveContext, ResolveError, Typifier}; pub use validator::{ValidationError, Validator}; diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index 58e0edc3e..793d50043 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -2,8 +2,43 @@ use crate::arena::{Arena, Handle}; use thiserror::Error; +#[derive(Debug, PartialEq)] +enum Resolution { + Handle(Handle), + Value(crate::TypeInner), +} + +// Clone is only implemented for numeric variants of `TypeInner`. +impl Clone for Resolution { + fn clone(&self) -> Self { + match *self { + Resolution::Handle(handle) => Resolution::Handle(handle), + Resolution::Value(ref v) => Resolution::Value(match *v { + crate::TypeInner::Scalar { kind, width } => { + crate::TypeInner::Scalar { kind, width } + } + crate::TypeInner::Vector { size, kind, width } => { + crate::TypeInner::Vector { size, kind, width } + } + crate::TypeInner::Matrix { + rows, + columns, + kind, + width, + } => crate::TypeInner::Matrix { + rows, + columns, + kind, + width, + }, + _ => panic!("Unepxected clone type: {:?}", v), + }), + } + } +} + pub struct Typifier { - types: Vec>, + resolutions: Vec, } #[derive(Clone, Debug, Error)] @@ -18,125 +53,132 @@ pub enum ResolveError { TypeNotFound, } -#[derive(Debug)] -enum Resolution { - Handle(crate::Handle), - Value(crate::TypeInner), +pub struct ResolveContext<'a> { + pub constants: &'a Arena, + pub global_vars: &'a Arena, + pub local_vars: &'a Arena, + pub functions: &'a Arena, + pub parameter_types: &'a [Handle], } impl Typifier { pub fn new() -> Self { - Typifier { types: Vec::new() } + Typifier { + resolutions: Vec::new(), + } + } + + pub fn clear(&mut self) { + self.resolutions.clear() + } + + pub fn get<'a>( + &'a self, + expr_handle: Handle, + types: &'a Arena, + ) -> &'a crate::TypeInner { + match self.resolutions[expr_handle.index()] { + Resolution::Handle(ty_handle) => &types[ty_handle].inner, + Resolution::Value(ref inner) => inner, + } } - #[allow(clippy::too_many_arguments)] fn resolve_impl( &self, expr: &crate::Expression, - arena: &Arena, - constants: &Arena, - global_vars: &Arena, - local_vars: &Arena, - functions: &Arena, - parameter_types: &[Handle], + types: &Arena, + ctx: &ResolveContext, ) -> Result { Ok(match *expr { - crate::Expression::Access { base, .. } => match arena[self.types[base.index()]].inner { + crate::Expression::Access { base, .. } => match *self.get(base, types) { crate::TypeInner::Array { base, .. } => Resolution::Handle(base), ref other => panic!("Can't access into {:?}", other), }, - crate::Expression::AccessIndex { base, index } => { - match arena[self.types[base.index()]].inner { - crate::TypeInner::Vector { size, kind, width } => { - if index >= size as u32 { - return Err(ResolveError::InvalidAccessIndex); - } - Resolution::Value(crate::TypeInner::Scalar { kind, width }) + crate::Expression::AccessIndex { base, index } => match *self.get(base, types) { + crate::TypeInner::Vector { size, kind, width } => { + if index >= size as u32 { + return Err(ResolveError::InvalidAccessIndex); } - crate::TypeInner::Matrix { - columns, - rows, + Resolution::Value(crate::TypeInner::Scalar { kind, width }) + } + crate::TypeInner::Matrix { + columns, + rows, + kind, + width, + } => { + if index >= columns as u32 { + return Err(ResolveError::InvalidAccessIndex); + } + Resolution::Value(crate::TypeInner::Vector { + size: rows, kind, width, - } => { - if index >= columns as u32 { - return Err(ResolveError::InvalidAccessIndex); - } - Resolution::Value(crate::TypeInner::Vector { - size: rows, - kind, - width, - }) - } - crate::TypeInner::Array { base, .. } => Resolution::Handle(base), - crate::TypeInner::Struct { ref members } => { - let member = members - .get(index as usize) - .ok_or(ResolveError::InvalidAccessIndex)?; - Resolution::Handle(member.ty) - } - ref other => panic!("Can't access into {:?}", other), + }) } - } - crate::Expression::Constant(h) => Resolution::Handle(constants[h].ty), + crate::TypeInner::Array { base, .. } => Resolution::Handle(base), + crate::TypeInner::Struct { ref members } => { + let member = members + .get(index as usize) + .ok_or(ResolveError::InvalidAccessIndex)?; + Resolution::Handle(member.ty) + } + ref other => panic!("Can't access into {:?}", other), + }, + crate::Expression::Constant(h) => Resolution::Handle(ctx.constants[h].ty), crate::Expression::Compose { ty, .. } => Resolution::Handle(ty), crate::Expression::FunctionParameter(index) => { - Resolution::Handle(parameter_types[index as usize]) + Resolution::Handle(ctx.parameter_types[index as usize]) } - crate::Expression::GlobalVariable(h) => Resolution::Handle(global_vars[h].ty), - crate::Expression::LocalVariable(h) => Resolution::Handle(local_vars[h].ty), + crate::Expression::GlobalVariable(h) => Resolution::Handle(ctx.global_vars[h].ty), + crate::Expression::LocalVariable(h) => Resolution::Handle(ctx.local_vars[h].ty), crate::Expression::Load { .. } => unimplemented!(), crate::Expression::ImageSample { image, .. } - | crate::Expression::ImageLoad { image, .. } => { - let image_ty = self.types[image.index()]; - match arena[image_ty].inner { - crate::TypeInner::Image { + | crate::Expression::ImageLoad { image, .. } => match *self.get(image, types) { + crate::TypeInner::Image { + kind, + class: crate::ImageClass::Depth, + .. + } => Resolution::Value(crate::TypeInner::Scalar { kind, width: 4 }), + crate::TypeInner::Image { kind, .. } => { + Resolution::Value(crate::TypeInner::Vector { kind, - class: crate::ImageClass::Depth, - .. - } => Resolution::Value(crate::TypeInner::Scalar { kind, width: 4 }), - crate::TypeInner::Image { kind, .. } => { - Resolution::Value(crate::TypeInner::Vector { - kind, - width: 4, - size: crate::VectorSize::Quad, - }) - } - _ => unreachable!(), + width: 4, + size: crate::VectorSize::Quad, + }) } - } - crate::Expression::Unary { expr, .. } => Resolution::Handle(self.types[expr.index()]), + _ => unreachable!(), + }, + crate::Expression::Unary { expr, .. } => self.resolutions[expr.index()].clone(), crate::Expression::Binary { op, left, right } => match op { crate::BinaryOperator::Add | crate::BinaryOperator::Subtract | crate::BinaryOperator::Divide - | crate::BinaryOperator::Modulo => Resolution::Handle(self.types[left.index()]), + | crate::BinaryOperator::Modulo => self.resolutions[left.index()].clone(), crate::BinaryOperator::Multiply => { - let ty_left = self.types[left.index()]; - let ty_right = self.types[right.index()]; + let ty_left = self.get(left, types); + let ty_right = self.get(right, types); if ty_left == ty_right { - Resolution::Handle(ty_left) - } else if let crate::TypeInner::Scalar { .. } = arena[ty_right].inner { - Resolution::Handle(ty_left) - } else if let crate::TypeInner::Scalar { .. } = arena[ty_left].inner { - Resolution::Handle(ty_right) - } else if let crate::TypeInner::Matrix { - columns, - kind, - width, - .. - } = arena[ty_left].inner - { - Resolution::Value(crate::TypeInner::Vector { - size: columns, - kind, - width, - }) + self.resolutions[left.index()].clone() + } else if let crate::TypeInner::Scalar { .. } = *ty_right { + self.resolutions[left.index()].clone() } else { - panic!( - "Incompatible arguments {:?} x {:?}", - arena[ty_left], arena[ty_right] - ); + match *ty_left { + crate::TypeInner::Scalar { .. } => { + self.resolutions[right.index()].clone() + } + crate::TypeInner::Matrix { + columns, + rows: _, + kind, + width, + } => Resolution::Value(crate::TypeInner::Vector { + size: columns, + kind, + width, + }), + _ => panic!("Incompatible arguments {:?} x {:?}", ty_left, ty_right), + } } } crate::BinaryOperator::Equal @@ -146,80 +188,68 @@ impl Typifier { | crate::BinaryOperator::Greater | crate::BinaryOperator::GreaterEqual | crate::BinaryOperator::LogicalAnd - | crate::BinaryOperator::LogicalOr => Resolution::Handle(self.types[left.index()]), + | crate::BinaryOperator::LogicalOr => self.resolutions[left.index()].clone(), crate::BinaryOperator::And | crate::BinaryOperator::ExclusiveOr | crate::BinaryOperator::InclusiveOr | crate::BinaryOperator::ShiftLeftLogical | crate::BinaryOperator::ShiftRightLogical | crate::BinaryOperator::ShiftRightArithmetic => { - Resolution::Handle(self.types[left.index()]) + self.resolutions[left.index()].clone() } }, crate::Expression::Intrinsic { .. } => unimplemented!(), - crate::Expression::Transpose(expr) => { - let ty_handle = self.types[expr.index()]; - match arena[ty_handle].inner { - crate::TypeInner::Matrix { - columns, - rows, - kind, - width, - } => Resolution::Value(crate::TypeInner::Matrix { - columns: rows, - rows: columns, - kind, - width, - }), - ref other => panic!("incompatible transpose of {:?}", other), - } - } - crate::Expression::DotProduct(left_expr, _) => { - let left_ty = self.types[left_expr.index()]; - match arena[left_ty].inner { - crate::TypeInner::Vector { - kind, - size: _, - width, - } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), - ref other => panic!("incompatible dot of {:?}", other), - } - } + crate::Expression::Transpose(expr) => match *self.get(expr, types) { + crate::TypeInner::Matrix { + columns, + rows, + kind, + width, + } => Resolution::Value(crate::TypeInner::Matrix { + columns: rows, + rows: columns, + kind, + width, + }), + ref other => panic!("incompatible transpose of {:?}", other), + }, + crate::Expression::DotProduct(left_expr, _) => match *self.get(left_expr, types) { + crate::TypeInner::Vector { + kind, + size: _, + width, + } => Resolution::Value(crate::TypeInner::Scalar { kind, width }), + ref other => panic!("incompatible dot of {:?}", other), + }, crate::Expression::CrossProduct(_, _) => unimplemented!(), crate::Expression::As { expr, kind, convert: _, - } => { - let ty_handle = self.types[expr.index()]; - match arena[ty_handle].inner { - crate::TypeInner::Scalar { kind: _, width } => { - Resolution::Value(crate::TypeInner::Scalar { kind, width }) - } - crate::TypeInner::Vector { - kind: _, - size, - width, - } => Resolution::Value(crate::TypeInner::Vector { kind, size, width }), - ref other => panic!("incompatible as of {:?}", other), + } => match *self.get(expr, types) { + crate::TypeInner::Scalar { kind: _, width } => { + Resolution::Value(crate::TypeInner::Scalar { kind, width }) } - } + crate::TypeInner::Vector { + kind: _, + size, + width, + } => Resolution::Value(crate::TypeInner::Vector { kind, size, width }), + ref other => panic!("incompatible as of {:?}", other), + }, crate::Expression::Derivative { .. } => unimplemented!(), crate::Expression::Call { origin: crate::FunctionOrigin::External(ref name), ref arguments, } => match name.as_str() { - "distance" | "length" | "dot" => { - let ty_handle = self.types[arguments[0].index()]; - match arena[ty_handle].inner { - crate::TypeInner::Vector { kind, width, .. } => { - Resolution::Value(crate::TypeInner::Scalar { kind, width }) - } - ref other => panic!("Unexpected argument {:?}", other), + "distance" | "length" | "dot" => match *self.get(arguments[0], types) { + crate::TypeInner::Vector { kind, width, .. } => { + Resolution::Value(crate::TypeInner::Scalar { kind, width }) } - } + ref other => panic!("Unexpected argument {:?}", other), + }, "normalize" | "fclamp" | "max" | "reflect" | "pow" | "clamp" | "mix" => { - Resolution::Handle(self.types[arguments[0].index()]) + self.resolutions[arguments[0].index()].clone() } _ => return Err(ResolveError::FunctionNotDefined { name: name.clone() }), }, @@ -227,7 +257,7 @@ impl Typifier { origin: crate::FunctionOrigin::Local(handle), arguments: _, } => { - let ty = functions[handle] + let ty = ctx.functions[handle] .return_type .ok_or(ResolveError::FunctionReturnsVoid)?; Resolution::Handle(ty) @@ -235,40 +265,43 @@ impl Typifier { }) } - #[allow(clippy::too_many_arguments)] - pub fn resolve( + pub fn grow( &mut self, expr_handle: Handle, expressions: &Arena, - arena: &mut Arena, - constants: &Arena, - global_vars: &Arena, - local_vars: &Arena, - functions: &Arena, - parameter_types: &[Handle], - ) -> Result, ResolveError> { - if self.types.len() <= expr_handle.index() { - for (eh, expr) in expressions.iter().skip(self.types.len()) { - let resolution = self.resolve_impl( - expr, - arena, - constants, - global_vars, - local_vars, - functions, - parameter_types, - )?; + types: &mut Arena, + ctx: &ResolveContext, + ) -> Result<(), ResolveError> { + if self.resolutions.len() <= expr_handle.index() { + for (eh, expr) in expressions.iter().skip(self.resolutions.len()) { + let resolution = self.resolve_impl(expr, types, ctx)?; log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution); - self.types.push(match resolution { + + let ty_handle = match resolution { Resolution::Handle(h) => h, - Resolution::Value(inner) => arena + Resolution::Value(inner) => types .fetch_if_or_append(crate::Type { name: None, inner }, |a, b| { a.inner == b.inner }), - }); + }; + self.resolutions.push(Resolution::Handle(ty_handle)); } } - Ok(self.types[expr_handle.index()]) + Ok(()) + } + + pub fn resolve_all( + &mut self, + expressions: &Arena, + types: &Arena, + ctx: &ResolveContext, + ) -> Result<(), ResolveError> { + self.clear(); + for (_, expr) in expressions.iter() { + let resolution = self.resolve_impl(expr, types, ctx)?; + self.resolutions.push(resolution); + } + Ok(()) } }