Implement Pointers and References This change implements pointers and references as described by the WGSL specification change in https://github.com/gpuweb/gpuweb/pull/1569. reader/spirv: * Now emits address-of `&expr` and indirection `*expr` operators as needed. * As an identifier may now resolve to a pointer or reference type depending on whether the declaration is a `var`, `let` or parameter, `Function::identifier_values_` has been changed from an ID set to an ID -> Type* map. resolver: * Now correctly resolves all expressions to either a value type, reference type or pointer type. * Validates pointer / reference rules on assignment, `var` and `let` construction, and usage. * Handles the address-of and indirection operators. * No longer does any implicit loads of pointer types. * Storage class validation is still TODO (crbug.com/tint/809) writer/spirv: * Correctly handles variables and expressions of pointer and reference types, emitting OpLoads where necessary. test: * Lots of new test cases Fixed: tint:727 Change-Id: I77d3281590e35e5a3122f5b74cdeb71a6fe51f74 Reviewed-on: https://dawn-review.googlesource.com/c/tint/+/50740 Commit-Queue: Ben Clayton <bclayton@chromium.org> Kokoro: Kokoro <noreply+kokoro@google.com> Reviewed-by: David Neto <dneto@google.com>
diff --git a/src/resolver/assignment_validation_test.cc b/src/resolver/assignment_validation_test.cc index 1c5e696..86a92c2 100644 --- a/src/resolver/assignment_validation_test.cc +++ b/src/resolver/assignment_validation_test.cc
@@ -31,39 +31,13 @@ // } auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); - auto* lhs = Expr("a"); - auto* rhs = Expr(2.3f); - auto* assign = Assign(Source{{12, 34}}, lhs, rhs); + auto* assign = Assign(Source{{12, 34}}, "a", 2.3f); WrapInFunction(var, assign); ASSERT_FALSE(r()->Resolve()); - EXPECT_EQ( - r()->error(), - R"(12:34 error: invalid assignment: cannot assign value of type 'f32' to a variable of type 'i32')"); -} - -TEST_F(ResolverAssignmentValidationTest, - AssignThroughPointerWrongeStoreType_Fail) { - // var a : f32; - // let b : ptr<function,f32> = a; - // b = 2; - const auto priv = ast::StorageClass::kFunction; - auto* var_a = Var("a", ty.f32(), priv); - auto* var_b = Const("b", ty.pointer<float>(priv), Expr("a"), {}); - - auto* lhs = Expr("a"); - auto* rhs = Expr(2); - - auto* assign = Assign(Source{{12, 34}}, lhs, rhs); - WrapInFunction(var_a, var_b, assign); - - ASSERT_FALSE(r()->Resolve()); - - EXPECT_EQ( - r()->error(), - R"(12:34 error: invalid assignment: cannot assign value of type 'i32' to a variable of type 'f32')"); + EXPECT_EQ(r()->error(), "12:34 error: cannot assign 'f32' to 'i32'"); } TEST_F(ResolverAssignmentValidationTest, @@ -73,11 +47,7 @@ // a = 2 // } auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); - auto* lhs = Expr("a"); - auto* rhs = Expr(2); - - auto* body = Block(Decl(var), Assign(Source{{12, 34}}, lhs, rhs)); - WrapInFunction(body); + WrapInFunction(var, Assign("a", 2)); ASSERT_TRUE(r()->Resolve()) << r()->error(); } @@ -90,17 +60,11 @@ // } auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); - auto* lhs = Expr("a"); - auto* rhs = Expr(2.3f); - - auto* block = Block(Decl(var), Assign(Source{{12, 34}}, lhs, rhs)); - WrapInFunction(block); + WrapInFunction(var, Assign(Source{{12, 34}}, "a", 2.3f)); ASSERT_FALSE(r()->Resolve()); - EXPECT_EQ( - r()->error(), - R"(12:34 error: invalid assignment: cannot assign value of type 'f32' to a variable of type 'i32')"); + EXPECT_EQ(r()->error(), "12:34 error: cannot assign 'f32' to 'i32'"); } TEST_F(ResolverAssignmentValidationTest, @@ -113,20 +77,13 @@ // } auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); - auto* lhs = Expr("a"); - auto* rhs = Expr(2.3f); - - auto* inner_block = Block(Decl(var), Assign(Source{{12, 34}}, lhs, rhs)); - + auto* inner_block = Block(Decl(var), Assign(Source{{12, 34}}, "a", 2.3f)); auto* outer_block = Block(inner_block); - WrapInFunction(outer_block); ASSERT_FALSE(r()->Resolve()); - EXPECT_EQ( - r()->error(), - R"(12:34 error: invalid assignment: cannot assign value of type 'f32' to a variable of type 'i32')"); + EXPECT_EQ(r()->error(), "12:34 error: cannot assign 'f32' to 'i32'"); } TEST_F(ResolverAssignmentValidationTest, AssignToScalar_Fail) { @@ -134,28 +91,17 @@ // 1 = my_var; auto* var = Var("my_var", ty.i32(), ast::StorageClass::kNone, Expr(2)); - auto* lhs = Expr(1); - auto* rhs = Expr("my_var"); - - auto* assign = Assign(Source{{12, 34}}, lhs, rhs); - WrapInFunction(Decl(var), assign); + WrapInFunction(var, Assign(Expr(Source{{12, 34}}, 1), "my_var")); EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ(r()->error(), - "12:34 error v-000x: invalid assignment: left-hand-side does not " - "reference storage: i32"); + EXPECT_EQ(r()->error(), "12:34 error: cannot assign to value of type 'i32'"); } TEST_F(ResolverAssignmentValidationTest, AssignCompatibleTypes_Pass) { - // var a :i32 = 2; + // var a : i32 = 2; // a = 2 auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); - - auto* lhs = Expr("a"); - auto* rhs = Expr(2); - - auto* assign = Assign(Source{Source::Location{12, 34}}, lhs, rhs); - WrapInFunction(Decl(var), assign); + WrapInFunction(var, Assign(Source{{12, 34}}, "a", 2)); EXPECT_TRUE(r()->Resolve()) << r()->error(); } @@ -163,17 +109,12 @@ TEST_F(ResolverAssignmentValidationTest, AssignCompatibleTypesThroughAlias_Pass) { // alias myint = i32; - // var a :myint = 2; + // var a : myint = 2; // a = 2 auto* myint = ty.alias("myint", ty.i32()); AST().AddConstructedType(myint); auto* var = Var("a", myint, ast::StorageClass::kNone, Expr(2)); - - auto* lhs = Expr("a"); - auto* rhs = Expr(2); - - auto* assign = Assign(Source{Source::Location{12, 34}}, lhs, rhs); - WrapInFunction(Decl(var), assign); + WrapInFunction(var, Assign(Source{{12, 34}}, "a", 2)); EXPECT_TRUE(r()->Resolve()) << r()->error(); } @@ -185,29 +126,19 @@ // a = b; auto* var_a = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); auto* var_b = Var("b", ty.i32(), ast::StorageClass::kNone, Expr(3)); - - auto* lhs = Expr("a"); - auto* rhs = Expr("b"); - - auto* assign = Assign(Source{Source::Location{12, 34}}, lhs, rhs); - WrapInFunction(Decl(var_a), Decl(var_b), assign); + WrapInFunction(var_a, var_b, Assign(Source{{12, 34}}, "a", "b")); EXPECT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverAssignmentValidationTest, AssignThroughPointer_Pass) { - // var a :i32; - // let b : ptr<function,i32> = a; - // b = 2; + // var a : i32; + // let b : ptr<function,i32> = &a; + // *b = 2; const auto func = ast::StorageClass::kFunction; auto* var_a = Var("a", ty.i32(), func, Expr(2), {}); - auto* var_b = Const("b", ty.pointer<int>(func), Expr("a"), {}); - - auto* lhs = Expr("b"); - auto* rhs = Expr(2); - - auto* assign = Assign(Source{Source::Location{12, 34}}, lhs, rhs); - WrapInFunction(Decl(var_a), Decl(var_b), assign); + auto* var_b = Const("b", ty.pointer<int>(func), AddressOf(Expr("a")), {}); + WrapInFunction(var_a, var_b, Assign(Source{{12, 34}}, Deref("b"), 2)); EXPECT_TRUE(r()->Resolve()) << r()->error(); } @@ -218,21 +149,13 @@ // a = 2 // } auto* var = Const("a", ty.i32(), Expr(2)); - - auto* lhs = Expr("a"); - auto* rhs = Expr(2); - - auto* body = - Block(Decl(var), Assign(Source{Source::Location{12, 34}}, lhs, rhs)); - - WrapInFunction(body); + WrapInFunction(var, Assign(Expr(Source{{12, 34}}, "a"), 2)); EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ(r()->error(), - "12:34 error v-0021: cannot re-assign a constant: 'a'"); + EXPECT_EQ(r()->error(), "12:34 error: cannot assign to value of type 'i32'"); } -TEST_F(ResolverAssignmentValidationTest, AssignFromPointer_Fail) { +TEST_F(ResolverAssignmentValidationTest, AssignNonStorable_Fail) { // var a : [[access(read)]] texture_storage_1d<rgba8unorm>; // var b : [[access(read)]] texture_storage_1d<rgba8unorm>; // a = b; @@ -243,24 +166,23 @@ return ty.access(ast::AccessControl::kReadOnly, tex_type); }; - auto* var_a = Global("a", make_type(), ast::StorageClass::kNone, nullptr, - { - create<ast::BindingDecoration>(0), - create<ast::GroupDecoration>(0), - }); - auto* var_b = Global("b", make_type(), ast::StorageClass::kNone, nullptr, - { - create<ast::BindingDecoration>(1), - create<ast::GroupDecoration>(0), - }); + Global("a", make_type(), ast::StorageClass::kNone, nullptr, + { + create<ast::BindingDecoration>(0), + create<ast::GroupDecoration>(0), + }); + Global("b", make_type(), ast::StorageClass::kNone, nullptr, + { + create<ast::BindingDecoration>(1), + create<ast::GroupDecoration>(0), + }); - WrapInFunction(Assign(Source{{12, 34}}, var_a, var_b)); + WrapInFunction(Assign("a", Expr(Source{{12, 34}}, "b"))); EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ(r()->error(), - "12:34 error v-000x: invalid assignment: right-hand-side is not " - "storable: ptr<uniform_constant, texture_storage_1d<rgba8unorm, " - "read_only>>"); + EXPECT_EQ( + r()->error(), + R"(12:34 error: '[[access(read)]] texture_storage_1d<rgba8unorm>' is not storable)"); } } // namespace
diff --git a/src/resolver/builtins_validation_test.cc b/src/resolver/builtins_validation_test.cc index 363b35a..fe2b59d 100644 --- a/src/resolver/builtins_validation_test.cc +++ b/src/resolver/builtins_validation_test.cc
@@ -108,7 +108,7 @@ TEST_F(ResolverBuiltinsValidationTest, Frexp_Scalar) { auto* a = Var("a", ty.i32()); - auto* builtin = Call("frexp", 1.0f, Expr("a")); + auto* builtin = Call("frexp", 1.0f, AddressOf(Expr("a"))); WrapInFunction(Decl(a), builtin); EXPECT_TRUE(r()->Resolve()) << r()->error(); @@ -118,10 +118,8 @@ TEST_F(ResolverBuiltinsValidationTest, Frexp_Vec2) { auto* a = Var("a", ty.vec2<int>()); - auto* b = Const("b", ty.pointer(ty.vec2<i32>(), ast::StorageClass::kFunction), - Expr("a"), {}); - auto* builtin = Call("frexp", vec2<f32>(1.0f, 1.0f), Expr("b")); - WrapInFunction(Decl(a), Decl(b), builtin); + auto* builtin = Call("frexp", vec2<f32>(1.0f, 1.0f), AddressOf(Expr("a"))); + WrapInFunction(Decl(a), builtin); EXPECT_TRUE(r()->Resolve()) << r()->error(); EXPECT_TRUE(TypeOf(builtin)->is_float_vector()); @@ -130,10 +128,9 @@ TEST_F(ResolverBuiltinsValidationTest, Frexp_Vec3) { auto* a = Var("a", ty.vec3<int>()); - auto* b = Const("b", ty.pointer(ty.vec3<i32>(), ast::StorageClass::kFunction), - Expr("a"), {}); - auto* builtin = Call("frexp", vec3<f32>(1.0f, 1.0f, 1.0f), Expr("b")); - WrapInFunction(Decl(a), Decl(b), builtin); + auto* builtin = + Call("frexp", vec3<f32>(1.0f, 1.0f, 1.0f), AddressOf(Expr("a"))); + WrapInFunction(Decl(a), builtin); EXPECT_TRUE(r()->Resolve()) << r()->error(); EXPECT_TRUE(TypeOf(builtin)->is_float_vector()); @@ -142,10 +139,9 @@ TEST_F(ResolverBuiltinsValidationTest, Frexp_Vec4) { auto* a = Var("a", ty.vec4<int>()); - auto* b = Const("b", ty.pointer(ty.vec4<i32>(), ast::StorageClass::kFunction), - Expr("a"), {}); - auto* builtin = Call("frexp", vec4<f32>(1.0f, 1.0f, 1.0f, 1.0f), Expr("b")); - WrapInFunction(Decl(a), Decl(b), builtin); + auto* builtin = + Call("frexp", vec4<f32>(1.0f, 1.0f, 1.0f, 1.0f), AddressOf(Expr("a"))); + WrapInFunction(Decl(a), builtin); EXPECT_TRUE(r()->Resolve()) << r()->error(); EXPECT_TRUE(TypeOf(builtin)->is_float_vector()); @@ -154,10 +150,8 @@ TEST_F(ResolverBuiltinsValidationTest, Modf_Scalar) { auto* a = Var("a", ty.f32()); - auto* b = - Const("b", ty.pointer<f32>(ast::StorageClass::kFunction), Expr("a"), {}); - auto* builtin = Call("modf", 1.0f, Expr("b")); - WrapInFunction(Decl(a), Decl(b), builtin); + auto* builtin = Call("modf", 1.0f, AddressOf(Expr("a"))); + WrapInFunction(Decl(a), builtin); EXPECT_TRUE(r()->Resolve()) << r()->error(); EXPECT_TRUE(TypeOf(builtin)->Is<sem::F32>()); @@ -166,10 +160,8 @@ TEST_F(ResolverBuiltinsValidationTest, Modf_Vec2) { auto* a = Var("a", ty.vec2<f32>()); - auto* b = Const("b", ty.pointer(ty.vec2<f32>(), ast::StorageClass::kFunction), - Expr("a"), {}); - auto* builtin = Call("modf", vec2<f32>(1.0f, 1.0f), Expr("b")); - WrapInFunction(Decl(a), Decl(b), builtin); + auto* builtin = Call("modf", vec2<f32>(1.0f, 1.0f), AddressOf(Expr("a"))); + WrapInFunction(Decl(a), builtin); EXPECT_TRUE(r()->Resolve()) << r()->error(); EXPECT_TRUE(TypeOf(builtin)->is_float_vector()); @@ -178,10 +170,9 @@ TEST_F(ResolverBuiltinsValidationTest, Modf_Vec3) { auto* a = Var("a", ty.vec3<f32>()); - auto* b = Const("b", ty.pointer(ty.vec3<f32>(), ast::StorageClass::kFunction), - Expr("a"), {}); - auto* builtin = Call("modf", vec3<f32>(1.0f, 1.0f, 1.0f), Expr("b")); - WrapInFunction(Decl(a), Decl(b), builtin); + auto* builtin = + Call("modf", vec3<f32>(1.0f, 1.0f, 1.0f), AddressOf(Expr("a"))); + WrapInFunction(Decl(a), builtin); EXPECT_TRUE(r()->Resolve()) << r()->error(); EXPECT_TRUE(TypeOf(builtin)->is_float_vector()); @@ -190,10 +181,9 @@ TEST_F(ResolverBuiltinsValidationTest, Modf_Vec4) { auto* a = Var("a", ty.vec4<f32>()); - auto* b = Const("b", ty.pointer(ty.vec4<f32>(), ast::StorageClass::kFunction), - Expr("a"), {}); - auto* builtin = Call("modf", vec4<f32>(1.0f, 1.0f, 1.0f, 1.0f), Expr("b")); - WrapInFunction(Decl(a), Decl(b), builtin); + auto* builtin = + Call("modf", vec4<f32>(1.0f, 1.0f, 1.0f, 1.0f), AddressOf(Expr("a"))); + WrapInFunction(Decl(a), builtin); EXPECT_TRUE(r()->Resolve()) << r()->error(); EXPECT_TRUE(TypeOf(builtin)->is_float_vector());
diff --git a/src/resolver/intrinsic_test.cc b/src/resolver/intrinsic_test.cc index af7323d..eb704bf 100644 --- a/src/resolver/intrinsic_test.cc +++ b/src/resolver/intrinsic_test.cc
@@ -182,7 +182,7 @@ EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "error: no matching call to " + name + - "(ptr<in, f32>, f32)\n\n" + "(f32, f32)\n\n" "2 candidate functions:\n " + name + "(f32) -> bool\n " + name + "(vecN<f32>) -> vecN<bool>\n"); @@ -435,9 +435,8 @@ EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ( - r()->error(), - R"(error: no matching call to dot(ptr<in, vec4<i32>>, ptr<in, vec4<i32>>) + EXPECT_EQ(r()->error(), + R"(error: no matching call to dot(vec4<i32>, vec4<i32>) 1 candidate function: dot(vecN<f32>, vecN<f32>) -> f32 @@ -793,7 +792,7 @@ EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), - "error: no matching call to arrayLength(ptr<in, array<i32, 4>>)\n\n" + "error: no matching call to arrayLength(array<i32, 4>)\n\n" "1 candidate function:\n" " arrayLength(array<T>) -> u32\n"); } @@ -823,7 +822,7 @@ TEST_F(ResolverIntrinsicDataTest, FrexpScalar) { Global("exp", ty.i32(), ast::StorageClass::kWorkgroup); - auto* call = Call("frexp", 1.0f, "exp"); + auto* call = Call("frexp", 1.0f, AddressOf("exp")); WrapInFunction(call); EXPECT_TRUE(r()->Resolve()) << r()->error(); @@ -834,7 +833,7 @@ TEST_F(ResolverIntrinsicDataTest, FrexpVector) { Global("exp", ty.vec3<i32>(), ast::StorageClass::kWorkgroup); - auto* call = Call("frexp", vec3<f32>(1.0f, 2.0f, 3.0f), "exp"); + auto* call = Call("frexp", vec3<f32>(1.0f, 2.0f, 3.0f), AddressOf("exp")); WrapInFunction(call); EXPECT_TRUE(r()->Resolve()) << r()->error(); @@ -846,7 +845,7 @@ TEST_F(ResolverIntrinsicDataTest, Frexp_Error_FirstParamInt) { Global("exp", ty.i32(), ast::StorageClass::kWorkgroup); - auto* call = Call("frexp", 1, "exp"); + auto* call = Call("frexp", 1, AddressOf("exp")); WrapInFunction(call); EXPECT_FALSE(r()->Resolve()); @@ -861,7 +860,7 @@ TEST_F(ResolverIntrinsicDataTest, Frexp_Error_SecondParamFloatPtr) { Global("exp", ty.f32(), ast::StorageClass::kWorkgroup); - auto* call = Call("frexp", 1.0f, "exp"); + auto* call = Call("frexp", 1.0f, AddressOf("exp")); WrapInFunction(call); EXPECT_FALSE(r()->Resolve()); @@ -890,23 +889,24 @@ TEST_F(ResolverIntrinsicDataTest, Frexp_Error_VectorSizesDontMatch) { Global("exp", ty.vec4<i32>(), ast::StorageClass::kWorkgroup); - auto* call = Call("frexp", vec2<f32>(1.0f, 2.0f), "exp"); + auto* call = Call("frexp", vec2<f32>(1.0f, 2.0f), AddressOf("exp")); WrapInFunction(call); EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ(r()->error(), - "error: no matching call to frexp(vec2<f32>, ptr<workgroup, " - "vec4<i32>>)\n\n" - "2 candidate functions:\n" - " frexp(f32, ptr<T>) -> f32 where: T is i32 or u32\n" - " frexp(vecN<f32>, ptr<vecN<T>>) -> vecN<f32> " - "where: T is i32 or u32\n"); + EXPECT_EQ( + r()->error(), + R"(error: no matching call to frexp(vec2<f32>, ptr<workgroup, vec4<i32>>) + +2 candidate functions: + frexp(f32, ptr<T>) -> f32 where: T is i32 or u32 + frexp(vecN<f32>, ptr<vecN<T>>) -> vecN<f32> where: T is i32 or u32 +)"); } TEST_F(ResolverIntrinsicDataTest, ModfScalar) { Global("whole", ty.f32(), ast::StorageClass::kWorkgroup); - auto* call = Call("modf", 1.0f, "whole"); + auto* call = Call("modf", 1.0f, AddressOf("whole")); WrapInFunction(call); EXPECT_TRUE(r()->Resolve()) << r()->error(); @@ -917,7 +917,7 @@ TEST_F(ResolverIntrinsicDataTest, ModfVector) { Global("whole", ty.vec3<f32>(), ast::StorageClass::kWorkgroup); - auto* call = Call("modf", vec3<f32>(1.0f, 2.0f, 3.0f), "whole"); + auto* call = Call("modf", vec3<f32>(1.0f, 2.0f, 3.0f), AddressOf("whole")); WrapInFunction(call); EXPECT_TRUE(r()->Resolve()) << r()->error(); @@ -929,7 +929,7 @@ TEST_F(ResolverIntrinsicDataTest, Modf_Error_FirstParamInt) { Global("whole", ty.f32(), ast::StorageClass::kWorkgroup); - auto* call = Call("modf", 1, "whole"); + auto* call = Call("modf", 1, AddressOf("whole")); WrapInFunction(call); EXPECT_FALSE(r()->Resolve()); @@ -943,7 +943,7 @@ TEST_F(ResolverIntrinsicDataTest, Modf_Error_SecondParamIntPtr) { Global("whole", ty.i32(), ast::StorageClass::kWorkgroup); - auto* call = Call("modf", 1.0f, "whole"); + auto* call = Call("modf", 1.0f, AddressOf("whole")); WrapInFunction(call); EXPECT_FALSE(r()->Resolve()); @@ -970,17 +970,19 @@ TEST_F(ResolverIntrinsicDataTest, Modf_Error_VectorSizesDontMatch) { Global("whole", ty.vec4<f32>(), ast::StorageClass::kWorkgroup); - auto* call = Call("modf", vec2<f32>(1.0f, 2.0f), "whole"); + auto* call = Call("modf", vec2<f32>(1.0f, 2.0f), AddressOf("whole")); WrapInFunction(call); EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ(r()->error(), - "error: no matching call to modf(vec2<f32>, ptr<workgroup, " - "vec4<f32>>)\n\n" - "2 candidate functions:\n" - " modf(vecN<f32>, ptr<vecN<f32>>) -> vecN<f32>\n" - " modf(f32, ptr<f32>) -> f32\n"); + EXPECT_EQ( + r()->error(), + R"(error: no matching call to modf(vec2<f32>, ptr<workgroup, vec4<f32>>) + +2 candidate functions: + modf(vecN<f32>, ptr<vecN<f32>>) -> vecN<f32> + modf(f32, ptr<f32>) -> f32 +)"); } using ResolverIntrinsicTest_SingleParam_FloatOrInt = @@ -1652,11 +1654,10 @@ EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ( - r()->error(), - "error: no matching call to determinant(ptr<private, mat2x3<f32>>)\n\n" - "1 candidate function:\n" - " determinant(matNxN<f32>) -> f32\n"); + EXPECT_EQ(r()->error(), + "error: no matching call to determinant(mat2x3<f32>)\n\n" + "1 candidate function:\n" + " determinant(matNxN<f32>) -> f32\n"); } TEST_F(ResolverIntrinsicTest, Determinant_NotMatrix) { @@ -1668,7 +1669,7 @@ EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), - "error: no matching call to determinant(ptr<private, f32>)\n\n" + "error: no matching call to determinant(f32)\n\n" "1 candidate function:\n" " determinant(matNxN<f32>) -> f32\n"); }
diff --git a/src/resolver/ptr_ref_test.cc b/src/resolver/ptr_ref_test.cc new file mode 100644 index 0000000..e66a0ce --- /dev/null +++ b/src/resolver/ptr_ref_test.cc
@@ -0,0 +1,62 @@ +// Copyright 2021 The Tint Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "src/resolver/resolver.h" +#include "src/resolver/resolver_test_helper.h" +#include "src/sem/reference_type.h" + +#include "gmock/gmock.h" + +namespace tint { +namespace resolver { +namespace { + +struct ResolverPtrRefTest : public resolver::TestHelper, + public testing::Test {}; + +TEST_F(ResolverPtrRefTest, AddressOf) { + // var v : i32; + // &v + + auto* v = Var("v", ty.i32(), ast::StorageClass::kNone); + auto* expr = AddressOf(v); + + WrapInFunction(v, expr); + + EXPECT_TRUE(r()->Resolve()) << r()->error(); + + ASSERT_TRUE(TypeOf(expr)->Is<sem::Pointer>()); + EXPECT_TRUE(TypeOf(expr)->As<sem::Pointer>()->StoreType()->Is<sem::I32>()); + EXPECT_EQ(TypeOf(expr)->As<sem::Pointer>()->StorageClass(), + ast::StorageClass::kFunction); +} + +TEST_F(ResolverPtrRefTest, AddressOfThenDeref) { + // var v : i32; + // *(&v) + + auto* v = Var("v", ty.i32(), ast::StorageClass::kNone); + auto* expr = Deref(AddressOf(v)); + + WrapInFunction(v, expr); + + EXPECT_TRUE(r()->Resolve()) << r()->error(); + + ASSERT_TRUE(TypeOf(expr)->Is<sem::Reference>()); + EXPECT_TRUE(TypeOf(expr)->As<sem::Reference>()->StoreType()->Is<sem::I32>()); +} + +} // namespace +} // namespace resolver +} // namespace tint
diff --git a/src/resolver/ptr_ref_validation_test.cc b/src/resolver/ptr_ref_validation_test.cc new file mode 100644 index 0000000..0b2d07d --- /dev/null +++ b/src/resolver/ptr_ref_validation_test.cc
@@ -0,0 +1,82 @@ +// Copyright 2021 The Tint Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "src/resolver/resolver.h" +#include "src/resolver/resolver_test_helper.h" +#include "src/sem/reference_type.h" + +#include "gmock/gmock.h" + +namespace tint { +namespace resolver { +namespace { + +struct ResolverPtrRefValidationTest : public resolver::TestHelper, + public testing::Test {}; + +TEST_F(ResolverPtrRefValidationTest, AddressOfLiteral) { + // &1 + + auto* expr = AddressOf(Expr(Source{{12, 34}}, 1)); + + WrapInFunction(expr); + + EXPECT_FALSE(r()->Resolve()); + + EXPECT_EQ(r()->error(), "12:34 error: cannot take the address of expression"); +} + +TEST_F(ResolverPtrRefValidationTest, AddressOfLet) { + // let l : i32 = 1; + // &l + auto* l = Const("l", ty.i32(), Expr(1)); + auto* expr = AddressOf(Expr(Source{{12, 34}}, "l")); + + WrapInFunction(l, expr); + + EXPECT_FALSE(r()->Resolve()); + + EXPECT_EQ(r()->error(), "12:34 error: cannot take the address of expression"); +} + +TEST_F(ResolverPtrRefValidationTest, DerefOfLiteral) { + // *1 + + auto* expr = Deref(Expr(Source{{12, 34}}, 1)); + + WrapInFunction(expr); + + EXPECT_FALSE(r()->Resolve()); + + EXPECT_EQ(r()->error(), + "12:34 error: cannot dereference expression of type 'i32'"); +} + +TEST_F(ResolverPtrRefValidationTest, DerefOfVar) { + // var v : i32 = 1; + // *1 + auto* v = Var("v", ty.i32()); + auto* expr = Deref(Expr(Source{{12, 34}}, "v")); + + WrapInFunction(v, expr); + + EXPECT_FALSE(r()->Resolve()); + + EXPECT_EQ(r()->error(), + "12:34 error: cannot dereference expression of type 'i32'"); +} + +} // namespace +} // namespace resolver +} // namespace tint
diff --git a/src/resolver/resolver.cc b/src/resolver/resolver.cc index 67b0734..a5e3379 100644 --- a/src/resolver/resolver.cc +++ b/src/resolver/resolver.cc
@@ -53,6 +53,7 @@ #include "src/sem/member_accessor_expression.h" #include "src/sem/multisampled_texture_type.h" #include "src/sem/pointer_type.h" +#include "src/sem/reference_type.h" #include "src/sem/sampled_texture_type.h" #include "src/sem/sampler_type.h" #include "src/sem/statement.h" @@ -226,22 +227,6 @@ return false; } -bool Resolver::IsValidAssignment(const sem::Type* lhs, const sem::Type* rhs) { - // TODO(crbug.com/tint/659): This is a rough approximation, and is missing - // checks for writability of pointer storage class, access control, etc. - // This will need to be fixed after WGSL agrees the behavior of pointers / - // references. - // Check: - if (lhs->UnwrapAccess() != rhs->UnwrapAccess()) { - // Try RHS dereference - if (lhs->UnwrapAccess() != rhs->UnwrapAll()) { - return false; - } - } - - return true; -} - bool Resolver::ResolveInternal() { Mark(&builder_->AST()); @@ -438,7 +423,7 @@ } Resolver::VariableInfo* Resolver::Variable(ast::Variable* var, - bool is_parameter) { + VariableKind kind) { if (variable_to_info_.count(var)) { TINT_ICE(diagnostics_) << "Variable " << builder_->Symbols().NameFor(var->symbol()) @@ -446,17 +431,21 @@ return nullptr; } - // If the variable has a declared type, resolve it. std::string type_name; - const sem::Type* type = nullptr; + const sem::Type* storage_type = nullptr; + + // If the variable has a declared type, resolve it. if (auto* ty = var->type()) { type_name = ty->FriendlyName(builder_->Symbols()); - type = Type(ty); - if (!type) { + storage_type = Type(ty); + if (!storage_type) { return nullptr; } } + std::string rhs_type_name; + const sem::Type* rhs_type = nullptr; + // Does the variable have a constructor? if (auto* ctor = var->constructor()) { Mark(var->constructor()); @@ -465,32 +454,57 @@ } // Fetch the constructor's type - auto* rhs_type = TypeOf(ctor); + rhs_type_name = TypeNameOf(ctor); + rhs_type = TypeOf(ctor); if (!rhs_type) { return nullptr; } // If the variable has no declared type, infer it from the RHS - if (type == nullptr) { - type_name = TypeNameOf(ctor); - type = rhs_type->UnwrapPtr(); + if (!storage_type) { + type_name = rhs_type_name; + storage_type = rhs_type->UnwrapRef(); // Implicit load of RHS } - - if (!IsValidAssignment(type, rhs_type)) { - diagnostics_.add_error( - "variable of type '" + type_name + - "' cannot be initialized with a value of type '" + - TypeNameOf(ctor) + "'", - var->source()); - return nullptr; - } - } else if (var->is_const() && !is_parameter && + } else if (var->is_const() && kind != VariableKind::kParameter && !ast::HasDecoration<ast::OverrideDecoration>(var->decorations())) { diagnostics_.add_error("let declarations must have initializers", var->source()); return nullptr; } + if (!storage_type) { + TINT_ICE(diagnostics_) + << "failed to determine storage type for variable '" + + builder_->Symbols().NameFor(var->symbol()) + "'\n" + << "Source: " << var->source(); + return nullptr; + } + + auto storage_class = var->declared_storage_class(); + if (storage_class == ast::StorageClass::kNone) { + if (storage_type->UnwrapRef()->is_handle()) { + // https://gpuweb.github.io/gpuweb/wgsl/#module-scope-variables + // If the store type is a texture type or a sampler type, then the + // variable declaration must not have a storage class decoration. The + // storage class will always be handle. + storage_class = ast::StorageClass::kUniformConstant; + } else if (kind == VariableKind::kLocal && !var->is_const()) { + storage_class = ast::StorageClass::kFunction; + } + } + + auto* type = storage_type; + if (!var->is_const()) { + // Variable declaration. Unlike `let`, `var` has storage. + // Variables are always of a reference type to the declared storage type. + type = builder_->create<sem::Reference>(storage_type, storage_class); + } + + if (rhs_type && !ValidateVariableConstructor(var, storage_type, type_name, + rhs_type, rhs_type_name)) { + return nullptr; + } + // TODO(crbug.com/tint/802): Temporary while ast::AccessControl exits. auto find_first_access_control = [this](ast::Type* ty) -> ast::AccessControl* { @@ -519,12 +533,39 @@ } auto* info = variable_infos_.Create(var, const_cast<sem::Type*>(type), - type_name, access_control); + type_name, storage_class, access_control); variable_to_info_.emplace(var, info); return info; } +bool Resolver::ValidateVariableConstructor(const ast::Variable* var, + const sem::Type* storage_type, + const std::string& type_name, + const sem::Type* rhs_type, + const std::string& rhs_type_name) { + auto* value_type = rhs_type->UnwrapRef(); // Implicit load of RHS + + // RHS needs to be of a storable type + if (!var->is_const() && !IsStorable(value_type)) { + diagnostics_.add_error( + "'" + rhs_type_name + "' is not storable for assignment", + var->constructor()->source()); + return false; + } + + // Value type has to match storage type + if (storage_type->UnwrapAccess() != value_type->UnwrapAccess()) { + std::string decl = var->is_const() ? "let" : "var"; + diagnostics_.add_error("cannot initialize " + decl + " of type '" + + type_name + "' with value of type '" + + rhs_type_name + "'", + var->source()); + return false; + } + return true; +} + bool Resolver::GlobalVariable(ast::Variable* var) { if (variable_stack_.has(var->symbol())) { diagnostics_.add_error("v-0011", @@ -534,7 +575,7 @@ return false; } - auto* info = Variable(var, /* is_parameter */ false); + auto* info = Variable(var, VariableKind::kGlobal); if (!info) { return false; } @@ -571,8 +612,9 @@ return false; } - if (!ApplyStorageClassUsageToType(info->storage_class, info->type, - var->source())) { + if (!ApplyStorageClassUsageToType( + info->storage_class, const_cast<sem::Type*>(info->type->UnwrapRef()), + var->source())) { diagnostics_.add_note("while instantiating variable " + builder_->Symbols().NameFor(var->symbol()), var->source()); @@ -636,7 +678,8 @@ // attributes. if (!binding_point) { diagnostics_.add_error( - "resource variables require [[group]] and [[binding]] decorations", + "resource variables require [[group]] and [[binding]] " + "decorations", info->declaration->source()); return false; } @@ -666,7 +709,7 @@ // attribute, satisfying the storage class constraints. auto* str = info->access_control != ast::AccessControl::kInvalid - ? info->type->As<sem::Struct>() + ? info->type->UnwrapRef()->As<sem::Struct>() : nullptr; if (!str) { @@ -695,7 +738,7 @@ // A variable in the uniform storage class is a uniform buffer variable. // Its store type must be a host-shareable structure type with block // attribute, satisfying the storage class constraints. - auto* str = info->type->As<sem::Struct>(); + auto* str = info->type->UnwrapRef()->As<sem::Struct>(); if (!str) { diagnostics_.add_error( "variables declared in the <uniform> storage class must be of a " @@ -726,8 +769,8 @@ bool Resolver::ValidateVariable(const VariableInfo* info) { auto* var = info->declaration; - auto* type = info->type; - if (auto* r = type->As<sem::Array>()) { + auto* storage_type = info->type->UnwrapRef(); + if (auto* r = storage_type->As<sem::Array>()) { if (r->IsRuntimeSized()) { diagnostics_.add_error( "v-0015", @@ -737,15 +780,14 @@ } } - if (auto* r = type->As<sem::MultisampledTexture>()) { + if (auto* r = storage_type->As<sem::MultisampledTexture>()) { if (r->dim() != ast::TextureDimension::k2d) { diagnostics_.add_error("Only 2d multisampled textures are supported", var->source()); return false; } - auto* data_type = r->type()->UnwrapAll(); - if (!data_type->is_numeric_scalar()) { + if (!r->type()->UnwrapRef()->is_numeric_scalar()) { diagnostics_.add_error( "texture_multisampled_2d<type>: type must be f32, i32 or u32", var->source()); @@ -753,7 +795,7 @@ } } - if (auto* storage_tex = type->As<sem::StorageTexture>()) { + if (auto* storage_tex = info->type->UnwrapRef()->As<sem::StorageTexture>()) { if (storage_tex->access_control() == ast::AccessControl::kInvalid) { diagnostics_.add_error("Storage Textures must have access control.", var->source()); @@ -786,12 +828,12 @@ } } - if (type->UnwrapAll()->is_handle() && + if (storage_type->is_handle() && var->declared_storage_class() != ast::StorageClass::kNone) { // https://gpuweb.github.io/gpuweb/wgsl/#module-scope-variables - // If the store type is a texture type or a sampler type, then the variable - // declaration must not have a storage class decoration. The storage class - // will always be handle. + // If the store type is a texture type or a sampler type, then the + // variable declaration must not have a storage class decoration. The + // storage class will always be handle. diagnostics_.add_error("variables of type '" + info->type_name + "' must not have a storage class", var->source()); @@ -893,10 +935,10 @@ bool Resolver::ValidateEntryPoint(const ast::Function* func, const FunctionInfo* info) { // Use a lambda to validate the entry point decorations for a type. - // Persistent state is used to track which builtins and locations have already - // been seen, in order to catch conflicts. - // TODO(jrprice): This state could be stored in FunctionInfo instead, and then - // passed to sem::Function since it would be useful there too. + // Persistent state is used to track which builtins and locations have + // already been seen, in order to catch conflicts. + // TODO(jrprice): This state could be stored in FunctionInfo instead, and + // then passed to sem::Function since it would be useful there too. std::unordered_set<ast::Builtin> builtins; std::unordered_set<uint32_t> locations; enum class ParamOrRetType { @@ -1147,7 +1189,7 @@ variable_stack_.push_scope(); for (auto* param : func->params()) { Mark(param); - auto* param_info = Variable(param, /* is_parameter */ true); + auto* param_info = Variable(param, VariableKind::kParameter); if (!param_info) { return false; } @@ -1377,7 +1419,7 @@ return false; } - auto* cond_type = TypeOf(stmt->condition())->UnwrapAll(); + auto* cond_type = TypeOf(stmt->condition())->UnwrapRef(); if (cond_type != builder_->ty.bool_()) { diagnostics_.add_error("if statement condition must be bool, got " + cond_type->FriendlyName(builder_->Symbols()), @@ -1409,7 +1451,7 @@ return false; } - auto* else_cond_type = TypeOf(cond)->UnwrapAll(); + auto* else_cond_type = TypeOf(cond)->UnwrapRef(); if (else_cond_type != builder_->ty.bool_()) { diagnostics_.add_error( "else statement condition must be bool, got " + @@ -1525,7 +1567,7 @@ } auto* res = TypeOf(expr->array()); - auto* parent_type = res->UnwrapAll(); + auto* parent_type = res->UnwrapRef(); const sem::Type* ret = nullptr; if (auto* arr = parent_type->As<sem::Array>()) { ret = arr->ElemType(); @@ -1540,15 +1582,9 @@ return false; } - // If we're extracting from a pointer, we return a pointer. - if (auto* ptr = res->As<sem::Pointer>()) { - ret = builder_->create<sem::Pointer>(ret, ptr->StorageClass()); - } else if (auto* arr = parent_type->As<sem::Array>()) { - if (!arr->ElemType()->is_scalar()) { - // If we extract a non-scalar from an array then we also get a pointer. We - // will generate a Function storage class variable to store this into. - ret = builder_->create<sem::Pointer>(ret, ast::StorageClass::kFunction); - } + // If we're extracting from a reference, we return a reference. + if (auto* ref = res->As<sem::Reference>()) { + ret = builder_->create<sem::Reference>(ret, ref->StorageClass()); } SetType(expr, ret); @@ -1569,9 +1605,9 @@ return false; } - // The expression has to be an identifier as you can't store function pointers - // but, if it isn't we'll just use the normal result determination to be on - // the safe side. + // The expression has to be an identifier as you can't store function + // pointers but, if it isn't we'll just use the normal result determination + // to be on the safe side. Mark(call->func()); auto* ident = call->func()->As<ast::IdentifierExpression>(); if (!ident) { @@ -1605,7 +1641,8 @@ auto* callee_func = callee_func_it->second; // Note: Requires called functions to be resolved first. - // This is currently guaranteed as functions must be declared before use. + // This is currently guaranteed as functions must be declared before + // use. current_function_->transitive_calls.add(callee_func); for (auto* transitive_call : callee_func->transitive_calls) { current_function_->transitive_calls.add(transitive_call); @@ -1692,10 +1729,10 @@ const ast::TypeConstructorExpression* ctor, const sem::Vector* vec_type) { auto& values = ctor->values(); - auto* elem_type = vec_type->type()->UnwrapAll(); + auto* elem_type = vec_type->type(); size_t value_cardinality_sum = 0; for (auto* value : values) { - auto* value_type = TypeOf(value)->UnwrapAll(); + auto* value_type = TypeOf(value)->UnwrapRef(); if (value_type->is_scalar()) { if (elem_type != value_type) { diagnostics_.add_error( @@ -1709,7 +1746,7 @@ value_cardinality_sum++; } else if (auto* value_vec = value_type->As<sem::Vector>()) { - auto* value_elem_type = value_vec->type()->UnwrapAll(); + auto* value_elem_type = value_vec->type(); // A mismatch of vector type parameter T is only an error if multiple // arguments are present. A single argument constructor constitutes a // type conversion expression. @@ -1766,7 +1803,7 @@ return true; } - auto* elem_type = matrix_type->type()->UnwrapAll(); + auto* elem_type = matrix_type->type(); if (matrix_type->columns() != values.size()) { const Source& values_start = values[0]->source(); const Source& values_end = values[values.size() - 1]->source(); @@ -1780,11 +1817,11 @@ } for (auto* value : values) { - auto* value_type = TypeOf(value)->UnwrapAll(); + auto* value_type = TypeOf(value)->UnwrapRef(); auto* value_vec = value_type->As<sem::Vector>(); if (!value_vec || value_vec->size() != matrix_type->rows() || - elem_type != value_vec->type()->UnwrapAll()) { + elem_type != value_vec->type()) { diagnostics_.add_error("expected argument type '" + VectorPretty(matrix_type->rows(), elem_type) + "' in '" + TypeNameOf(ctor) + @@ -1802,26 +1839,15 @@ auto symbol = expr->symbol(); VariableInfo* var; if (variable_stack_.get(symbol, &var)) { - // A constant is the type, but a variable is always a pointer so synthesize - // the pointer around the variable type. - if (var->declaration->is_const()) { - SetType(expr, var->type, var->type_name); - } else if (var->type->Is<sem::Pointer>()) { - SetType(expr, var->type, var->type_name); - } else { - SetType(expr, - builder_->create<sem::Pointer>(const_cast<sem::Type*>(var->type), - var->storage_class), - var->type_name); - } + SetType(expr, var->type, var->type_name); var->users.push_back(expr); set_referenced_from_function_if_needed(var, true); if (current_block_) { - // If identifier is part of a loop continuing block, make sure it doesn't - // refer to a variable that is bypassed by a continue statement in the - // loop's body block. + // If identifier is part of a loop continuing block, make sure it + // doesn't refer to a variable that is bypassed by a continue statement + // in the loop's body block. if (auto* continuing_block = current_block_->FindFirstParent( sem::BlockStatement::Type::kLoopContinuing)) { auto* loop_block = @@ -1878,13 +1904,13 @@ return false; } - auto* res = TypeOf(expr->structure()); - auto* data_type = res->UnwrapAll(); + auto* structure = TypeOf(expr->structure()); + auto* storage_type = structure->UnwrapRef(); sem::Type* ret = nullptr; std::vector<uint32_t> swizzle; - if (auto* str = data_type->As<sem::Struct>()) { + if (auto* str = storage_type->As<sem::Struct>()) { Mark(expr->member()); auto symbol = expr->member()->symbol(); @@ -1904,14 +1930,14 @@ return false; } - // If we're extracting from a pointer, we return a pointer. - if (auto* ptr = res->As<sem::Pointer>()) { - ret = builder_->create<sem::Pointer>(ret, ptr->StorageClass()); + // If we're extracting from a reference, we return a reference. + if (auto* ref = structure->As<sem::Reference>()) { + ret = builder_->create<sem::Reference>(ret, ref->StorageClass()); } builder_->Sem().Add(expr, builder_->create<sem::StructMemberAccess>( expr, ret, current_statement_, member)); - } else if (auto* vec = data_type->As<sem::Vector>()) { + } else if (auto* vec = storage_type->As<sem::Vector>()) { Mark(expr->member()); std::string s = builder_->Symbols().NameFor(expr->member()->symbol()); auto size = s.size(); @@ -1967,9 +1993,9 @@ if (size == 1) { // A single element swizzle is just the type of the vector. ret = vec->type(); - // If we're extracting from a pointer, we return a pointer. - if (auto* ptr = res->As<sem::Pointer>()) { - ret = builder_->create<sem::Pointer>(ret, ptr->StorageClass()); + // If we're extracting from a reference, we return a reference. + if (auto* ref = structure->As<sem::Reference>()) { + ret = builder_->create<sem::Reference>(ret, ref->StorageClass()); } } else { // The vector will have a number of components equal to the length of @@ -1983,7 +2009,7 @@ } else { diagnostics_.add_error( "invalid use of member accessor on a non-vector/non-struct " + - data_type->type_name(), + TypeNameOf(expr->structure()), expr->source()); return false; } @@ -2001,8 +2027,8 @@ using Matrix = sem::Matrix; using Vector = sem::Vector; - auto* lhs_type = const_cast<sem::Type*>(TypeOf(expr->lhs())->UnwrapAll()); - auto* rhs_type = const_cast<sem::Type*>(TypeOf(expr->rhs())->UnwrapAll()); + auto* lhs_type = const_cast<sem::Type*>(TypeOf(expr->lhs())->UnwrapRef()); + auto* rhs_type = const_cast<sem::Type*>(TypeOf(expr->rhs())->UnwrapRef()); auto* lhs_vec = lhs_type->As<Vector>(); auto* lhs_vec_elem_type = lhs_vec ? lhs_vec->type() : nullptr; @@ -2169,7 +2195,7 @@ if (expr->IsAnd() || expr->IsOr() || expr->IsXor() || expr->IsShiftLeft() || expr->IsShiftRight() || expr->IsAdd() || expr->IsSubtract() || expr->IsDivide() || expr->IsModulo()) { - SetType(expr, TypeOf(expr->lhs())->UnwrapPtr()); + SetType(expr, TypeOf(expr->lhs())->UnwrapRef()); return true; } // Result type is a scalar or vector of boolean type @@ -2177,7 +2203,7 @@ expr->IsNotEqual() || expr->IsLessThan() || expr->IsGreaterThan() || expr->IsLessThanEqual() || expr->IsGreaterThanEqual()) { auto* bool_type = builder_->create<sem::Bool>(); - auto* param_type = TypeOf(expr->lhs())->UnwrapAll(); + auto* param_type = TypeOf(expr->lhs())->UnwrapRef(); sem::Type* result_type = bool_type; if (auto* vec = param_type->As<sem::Vector>()) { result_type = builder_->create<sem::Vector>(bool_type, vec->size()); @@ -2186,8 +2212,8 @@ return true; } if (expr->IsMultiply()) { - auto* lhs_type = TypeOf(expr->lhs())->UnwrapAll(); - auto* rhs_type = TypeOf(expr->rhs())->UnwrapAll(); + auto* lhs_type = TypeOf(expr->lhs())->UnwrapRef(); + auto* rhs_type = TypeOf(expr->rhs())->UnwrapRef(); // Note, the ordering here matters. The later checks depend on the prior // checks having been done. @@ -2234,16 +2260,55 @@ return false; } -bool Resolver::UnaryOp(ast::UnaryOpExpression* expr) { - Mark(expr->expr()); +bool Resolver::UnaryOp(ast::UnaryOpExpression* unary) { + Mark(unary->expr()); - // Result type matches the parameter type. - if (!Expression(expr->expr())) { + // Resolve the inner expression + if (!Expression(unary->expr())) { return false; } - auto* result_type = TypeOf(expr->expr())->UnwrapPtr(); - SetType(expr, result_type); + auto* expr_type = TypeOf(unary->expr()); + if (!expr_type) { + return false; + } + + std::string type_name; + const sem::Type* type = nullptr; + + switch (unary->op()) { + case ast::UnaryOp::kNegation: + case ast::UnaryOp::kNot: + // Result type matches the deref'd inner type. + type_name = TypeNameOf(unary->expr()); + type = expr_type->UnwrapRef(); + break; + + case ast::UnaryOp::kAddressOf: + if (auto* ref = expr_type->As<sem::Reference>()) { + type = builder_->create<sem::Pointer>(ref->StoreType(), + ref->StorageClass()); + } else { + diagnostics_.add_error("cannot take the address of expression", + unary->expr()->source()); + return false; + } + break; + + case ast::UnaryOp::kIndirection: + if (auto* ptr = expr_type->As<sem::Pointer>()) { + type = builder_->create<sem::Reference>(ptr->StoreType(), + ptr->StorageClass()); + } else { + diagnostics_.add_error("cannot dereference expression of type '" + + TypeNameOf(unary->expr()) + "'", + unary->expr()->source()); + return false; + } + break; + } + + SetType(unary, type); return true; } @@ -2257,11 +2322,11 @@ diagnostics_.add_error(error_code, "redeclared identifier '" + builder_->Symbols().NameFor(var->symbol()) + "'", - stmt->source()); + var->source()); return false; } - auto* info = Variable(var, /* is_parameter */ false); + auto* info = Variable(var, VariableKind::kLocal); if (!info) { return false; } @@ -2357,8 +2422,8 @@ void Resolver::CreateSemanticNodes() const { auto& sem = builder_->Sem(); - // Collate all the 'ancestor_entry_points' - this is a map of function symbol - // to all the entry points that transitively call the function. + // Collate all the 'ancestor_entry_points' - this is a map of function + // symbol to all the entry points that transitively call the function. std::unordered_map<Symbol, std::vector<Symbol>> ancestor_entry_points; for (auto* func : builder_->AST().Functions()) { auto it = function_to_info_.find(func); @@ -2641,7 +2706,7 @@ bool Resolver::ValidateStructure(const sem::Struct* str) { for (auto* member : str->Members()) { - if (auto* r = member->Type()->UnwrapAll()->As<sem::Array>()) { + if (auto* r = member->Type()->As<sem::Array>()) { if (r->IsRuntimeSized()) { if (member != str->Members().back()) { diagnostics_.add_error( @@ -2738,8 +2803,8 @@ for (auto* deco : member->decorations()) { Mark(deco); if (auto* o = deco->As<ast::StructMemberOffsetDecoration>()) { - // Offset decorations are not part of the WGSL spec, but are emitted by - // the SPIR-V reader. + // Offset decorations are not part of the WGSL spec, but are emitted + // by the SPIR-V reader. if (o->offset() < struct_size) { diagnostics_.add_error("offsets must be in ascending order", o->source()); @@ -2805,10 +2870,10 @@ bool Resolver::ValidateReturn(const ast::ReturnStatement* ret) { auto* func_type = current_function_->return_type; - auto* ret_type = ret->has_value() ? TypeOf(ret->value())->UnwrapAll() + auto* ret_type = ret->has_value() ? TypeOf(ret->value())->UnwrapRef() : builder_->ty.void_(); - if (func_type->UnwrapAll() != ret_type) { + if (func_type->UnwrapRef() != ret_type) { diagnostics_.add_error("v-000y", "return statement type must match its function " "return type, returned '" + @@ -2828,8 +2893,8 @@ if (auto* value = ret->value()) { Mark(value); - // Validate after processing the return value expression so that its type is - // available for validation + // Validate after processing the return value expression so that its type + // is available for validation return Expression(value) && ValidateReturn(ret); } @@ -2837,7 +2902,7 @@ } bool Resolver::ValidateSwitch(const ast::SwitchStatement* s) { - auto* cond_type = TypeOf(s->condition())->UnwrapAll(); + auto* cond_type = TypeOf(s->condition())->UnwrapRef(); if (!cond_type->is_integer_scalar()) { diagnostics_.add_error("v-0025", "switch statement selector expression must be of a " @@ -2928,67 +2993,6 @@ return true; } -bool Resolver::ValidateAssignment(const ast::AssignmentStatement* a) { - auto* lhs = a->lhs(); - auto* rhs = a->rhs(); - - // TODO(crbug.com/tint/659): This logic needs updating once pointers are - // pinned down in the WGSL spec. - auto* lhs_type = TypeOf(lhs)->UnwrapAll(); - auto* rhs_type = TypeOf(rhs); - if (!IsValidAssignment(lhs_type, rhs_type)) { - diagnostics_.add_error("invalid assignment: cannot assign value of type '" + - rhs_type->FriendlyName(builder_->Symbols()) + - "' to a variable of type '" + - lhs_type->FriendlyName(builder_->Symbols()) + - "'", - a->source()); - return false; - } - - // Pointers are not storable in WGSL, but the right-hand side must be - // storable. The raw right-hand side might be a pointer value which must be - // loaded (dereferenced) to provide the value to be stored. - auto* rhs_result_type = TypeOf(rhs)->UnwrapAll(); - if (!IsStorable(rhs_result_type)) { - diagnostics_.add_error( - "v-000x", - "invalid assignment: right-hand-side is not storable: " + - TypeOf(rhs)->FriendlyName(builder_->Symbols()), - a->source()); - return false; - } - - // lhs must be a pointer or a constant - auto* lhs_result_type = TypeOf(lhs)->UnwrapAccess(); - if (!lhs_result_type->Is<sem::Pointer>()) { - // In case lhs is a constant identifier, output a nicer message as it's - // likely to be a common programmer error. - if (auto* ident = lhs->As<ast::IdentifierExpression>()) { - VariableInfo* var; - if (variable_stack_.get(ident->symbol(), &var) && - var->declaration->is_const()) { - diagnostics_.add_error( - "v-0021", - "cannot re-assign a constant: '" + - builder_->Symbols().NameFor(ident->symbol()) + "'", - a->source()); - return false; - } - } - - // Issue a generic error. - diagnostics_.add_error( - "v-000x", - "invalid assignment: left-hand-side does not reference storage: " + - TypeOf(lhs)->FriendlyName(builder_->Symbols()), - a->source()); - return false; - } - - return true; -} - bool Resolver::Assignment(ast::AssignmentStatement* a) { Mark(a->lhs()); Mark(a->rhs()); @@ -2999,10 +3003,52 @@ return ValidateAssignment(a); } +bool Resolver::ValidateAssignment(const ast::AssignmentStatement* a) { + // https://gpuweb.github.io/gpuweb/wgsl/#assignment-statement + auto const* lhs_type = TypeOf(a->lhs()); + auto const* rhs_type = TypeOf(a->rhs()); + + auto* lhs_ref = lhs_type->As<sem::Reference>(); + if (!lhs_ref) { + // LHS is not a reference, so it has no storage. + diagnostics_.add_error( + "cannot assign to value of type '" + TypeNameOf(a->lhs()) + "'", + a->lhs()->source()); + + return false; + } + + auto* storage_type_with_access = lhs_ref->StoreType(); + + // TODO(crbug.com/tint/809): The originating variable of the left-hand side + // must not have an access(read) access attribute. + // https://gpuweb.github.io/gpuweb/wgsl/#assignment + + auto* storage_type = storage_type_with_access->UnwrapAccess(); + auto* value_type = rhs_type->UnwrapRef(); // Implicit load of RHS + + // RHS needs to be of a storable type + if (!IsStorable(value_type)) { + diagnostics_.add_error("'" + TypeNameOf(a->rhs()) + "' is not storable", + a->rhs()->source()); + return false; + } + + // Value type has to match storage type + if (storage_type != value_type) { + diagnostics_.add_error("cannot assign '" + TypeNameOf(a->rhs()) + "' to '" + + TypeNameOf(a->lhs()) + "'", + a->source()); + return false; + } + + return true; +} + bool Resolver::ApplyStorageClassUsageToType(ast::StorageClass sc, sem::Type* ty, const Source& usage) { - ty = const_cast<sem::Type*>(ty->UnwrapAccess()); + ty = const_cast<sem::Type*>(ty->UnwrapRef()); if (auto* str = ty->As<sem::Struct>()) { if (str->StorageClassUsage().count(sc)) { @@ -3079,23 +3125,15 @@ } Resolver::VariableInfo::VariableInfo(const ast::Variable* decl, - sem::Type* ctype, + sem::Type* ty, const std::string& tn, + ast::StorageClass sc, ast::AccessControl::Access ac) : declaration(decl), - type(ctype), + type(ty), type_name(tn), - storage_class(decl->declared_storage_class()), - access_control(ac) { - if (storage_class == ast::StorageClass::kNone && - type->UnwrapAll()->is_handle()) { - // https://gpuweb.github.io/gpuweb/wgsl/#module-scope-variables - // If the store type is a texture type or a sampler type, then the variable - // declaration must not have a storage class decoration. The storage class - // will always be handle. - storage_class = ast::StorageClass::kUniformConstant; - } -} + storage_class(sc), + access_control(ac) {} Resolver::VariableInfo::~VariableInfo() = default;
diff --git a/src/resolver/resolver.h b/src/resolver/resolver.h index 3b8b05e..76a722f 100644 --- a/src/resolver/resolver.h +++ b/src/resolver/resolver.h
@@ -79,13 +79,6 @@ /// @returns true if the given type is host-shareable bool IsHostShareable(const sem::Type* type); - /// @param lhs the assignment store type (non-pointer) - /// @param rhs the assignment source type (non-pointer or pointer with - /// auto-deref) - /// @returns true an expression of type `rhs` can be assigned to a variable, - /// structure member or array element of type `lhs` - static bool IsValidAssignment(const sem::Type* lhs, const sem::Type* rhs); - private: /// Structure holding semantic information about a variable. /// Used to build the sem::Variable nodes at the end of resolving. @@ -93,6 +86,7 @@ VariableInfo(const ast::Variable* decl, sem::Type* type, const std::string& type_name, + ast::StorageClass storage_class, ast::AccessControl::Access ac); ~VariableInfo(); @@ -139,6 +133,43 @@ sem::Statement* statement; }; + /// Structure holding semantic information about a block (i.e. scope), such as + /// parent block and variables declared in the block. + /// Used to validate variable scoping rules. + struct BlockInfo { + enum class Type { kGeneric, kLoop, kLoopContinuing, kSwitchCase }; + + BlockInfo(const ast::BlockStatement* block, Type type, BlockInfo* parent); + ~BlockInfo(); + + template <typename Pred> + BlockInfo* FindFirstParent(Pred&& pred) { + BlockInfo* curr = this; + while (curr && !pred(curr)) { + curr = curr->parent; + } + return curr; + } + + BlockInfo* FindFirstParent(BlockInfo::Type ty) { + return FindFirstParent( + [ty](auto* block_info) { return block_info->type == ty; }); + } + + ast::BlockStatement const* const block; + Type const type; + BlockInfo* const parent; + std::vector<const ast::Variable*> decls; + + // first_continue is set to the index of the first variable in decls + // declared after the first continue statement in a loop block, if any. + constexpr static size_t kNoContinue = size_t(~0); + size_t first_continue = kNoContinue; + }; + + /// Describes the context in which a variable is declared + enum class VariableKind { kParameter, kLocal, kGlobal }; + /// Resolves the program, without creating final the semantic nodes. /// @returns true on success, false on error bool ResolveInternal(); @@ -207,6 +238,11 @@ bool ValidateStructure(const sem::Struct* str); bool ValidateSwitch(const ast::SwitchStatement* s); bool ValidateVariable(const VariableInfo* info); + bool ValidateVariableConstructor(const ast::Variable* var, + const sem::Type* storage_type, + const std::string& type_name, + const sem::Type* rhs_type, + const std::string& rhs_type_name); bool ValidateVectorConstructor(const ast::TypeConstructorExpression* ctor, const sem::Vector* vec_type); @@ -235,8 +271,8 @@ /// @note this method does not resolve the decorations as these are /// context-dependent (global, local, parameter) /// @param var the variable to create or return the `VariableInfo` for - /// @param is_parameter true if the variable represents a parameter - VariableInfo* Variable(ast::Variable* var, bool is_parameter); + /// @param kind what kind of variable we are declaring + VariableInfo* Variable(ast::Variable* var, VariableKind kind); /// Records the storage class usage for the given type, and any transient /// dependencies of the type. Validates that the type can be used for the
diff --git a/src/resolver/resolver_test.cc b/src/resolver/resolver_test.cc index 330492e..e81be39 100644 --- a/src/resolver/resolver_test.cc +++ b/src/resolver/resolver_test.cc
@@ -36,6 +36,7 @@ #include "src/sem/call.h" #include "src/sem/function.h" #include "src/sem/member_accessor_expression.h" +#include "src/sem/reference_type.h" #include "src/sem/sampled_texture_type.h" #include "src/sem/statement.h" #include "src/sem/variable.h" @@ -66,7 +67,7 @@ ASSERT_NE(TypeOf(lhs), nullptr); ASSERT_NE(TypeOf(rhs), nullptr); - EXPECT_TRUE(TypeOf(lhs)->UnwrapAll()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(lhs)->UnwrapRef()->Is<sem::F32>()); EXPECT_TRUE(TypeOf(rhs)->Is<sem::F32>()); EXPECT_EQ(StmtOf(lhs), assign); EXPECT_EQ(StmtOf(rhs), assign); @@ -90,7 +91,7 @@ ASSERT_NE(TypeOf(lhs), nullptr); ASSERT_NE(TypeOf(rhs), nullptr); - EXPECT_TRUE(TypeOf(lhs)->UnwrapAll()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(lhs)->UnwrapRef()->Is<sem::F32>()); EXPECT_TRUE(TypeOf(rhs)->Is<sem::F32>()); EXPECT_EQ(StmtOf(lhs), assign); EXPECT_EQ(StmtOf(rhs), assign); @@ -110,7 +111,7 @@ ASSERT_NE(TypeOf(lhs), nullptr); ASSERT_NE(TypeOf(rhs), nullptr); - EXPECT_TRUE(TypeOf(lhs)->UnwrapAll()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(lhs)->UnwrapRef()->Is<sem::F32>()); EXPECT_TRUE(TypeOf(rhs)->Is<sem::F32>()); EXPECT_EQ(StmtOf(lhs), assign); EXPECT_EQ(StmtOf(rhs), assign); @@ -147,9 +148,9 @@ ASSERT_NE(TypeOf(lhs), nullptr); ASSERT_NE(TypeOf(rhs), nullptr); EXPECT_TRUE(TypeOf(stmt->condition())->Is<sem::Bool>()); - EXPECT_TRUE(TypeOf(else_lhs)->UnwrapAll()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(else_lhs)->UnwrapRef()->Is<sem::F32>()); EXPECT_TRUE(TypeOf(else_rhs)->Is<sem::F32>()); - EXPECT_TRUE(TypeOf(lhs)->UnwrapAll()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(lhs)->UnwrapRef()->Is<sem::F32>()); EXPECT_TRUE(TypeOf(rhs)->Is<sem::F32>()); EXPECT_EQ(StmtOf(lhs), assign); EXPECT_EQ(StmtOf(rhs), assign); @@ -180,9 +181,9 @@ ASSERT_NE(TypeOf(body_rhs), nullptr); ASSERT_NE(TypeOf(continuing_lhs), nullptr); ASSERT_NE(TypeOf(continuing_rhs), nullptr); - EXPECT_TRUE(TypeOf(body_lhs)->UnwrapAll()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(body_lhs)->UnwrapRef()->Is<sem::F32>()); EXPECT_TRUE(TypeOf(body_rhs)->Is<sem::F32>()); - EXPECT_TRUE(TypeOf(continuing_lhs)->UnwrapAll()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(continuing_lhs)->UnwrapRef()->Is<sem::F32>()); EXPECT_TRUE(TypeOf(continuing_rhs)->Is<sem::F32>()); EXPECT_EQ(BlockOf(body_lhs), body); EXPECT_EQ(BlockOf(body_rhs), body); @@ -224,7 +225,7 @@ ASSERT_NE(TypeOf(rhs), nullptr); EXPECT_TRUE(TypeOf(stmt->condition())->Is<sem::I32>()); - EXPECT_TRUE(TypeOf(lhs)->UnwrapAll()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(lhs)->UnwrapRef()->Is<sem::F32>()); EXPECT_TRUE(TypeOf(rhs)->Is<sem::F32>()); EXPECT_EQ(BlockOf(lhs), case_block); EXPECT_EQ(BlockOf(rhs), case_block); @@ -328,9 +329,9 @@ ASSERT_NE(TypeOf(foo_f32_init), nullptr); EXPECT_TRUE(TypeOf(foo_f32_init)->Is<sem::F32>()); ASSERT_NE(TypeOf(bar_i32_init), nullptr); - EXPECT_TRUE(TypeOf(bar_i32_init)->UnwrapAll()->Is<sem::I32>()); + EXPECT_TRUE(TypeOf(bar_i32_init)->UnwrapRef()->Is<sem::I32>()); ASSERT_NE(TypeOf(bar_f32_init), nullptr); - EXPECT_TRUE(TypeOf(bar_f32_init)->UnwrapAll()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(bar_f32_init)->UnwrapRef()->Is<sem::F32>()); EXPECT_EQ(StmtOf(foo_i32_init), foo_i32_decl); EXPECT_EQ(StmtOf(bar_i32_init), bar_i32_decl); EXPECT_EQ(StmtOf(foo_f32_init), foo_f32_decl); @@ -377,7 +378,7 @@ ASSERT_NE(TypeOf(fn_i32_init), nullptr); EXPECT_TRUE(TypeOf(fn_i32_init)->Is<sem::I32>()); ASSERT_NE(TypeOf(fn_f32_init), nullptr); - EXPECT_TRUE(TypeOf(fn_f32_init)->UnwrapAll()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(fn_f32_init)->UnwrapRef()->Is<sem::F32>()); EXPECT_EQ(StmtOf(fn_i32_init), fn_i32_decl); EXPECT_EQ(StmtOf(mod_init), nullptr); EXPECT_EQ(StmtOf(fn_f32_init), fn_f32_decl); @@ -397,10 +398,10 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); ASSERT_NE(TypeOf(acc), nullptr); - ASSERT_TRUE(TypeOf(acc)->Is<sem::Pointer>()); + ASSERT_TRUE(TypeOf(acc)->Is<sem::Reference>()); - auto* ptr = TypeOf(acc)->As<sem::Pointer>(); - EXPECT_TRUE(ptr->StoreType()->Is<sem::F32>()); + auto* ref = TypeOf(acc)->As<sem::Reference>(); + EXPECT_TRUE(ref->StoreType()->Is<sem::F32>()); } TEST_F(ResolverTest, Expr_ArrayAccessor_Alias_Array) { @@ -415,10 +416,10 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); ASSERT_NE(TypeOf(acc), nullptr); - ASSERT_TRUE(TypeOf(acc)->Is<sem::Pointer>()); + ASSERT_TRUE(TypeOf(acc)->Is<sem::Reference>()); - auto* ptr = TypeOf(acc)->As<sem::Pointer>(); - EXPECT_TRUE(ptr->StoreType()->Is<sem::F32>()); + auto* ref = TypeOf(acc)->As<sem::Reference>(); + EXPECT_TRUE(ref->StoreType()->Is<sem::F32>()); } TEST_F(ResolverTest, Expr_ArrayAccessor_Array_Constant) { @@ -442,11 +443,11 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); ASSERT_NE(TypeOf(acc), nullptr); - ASSERT_TRUE(TypeOf(acc)->Is<sem::Pointer>()); + ASSERT_TRUE(TypeOf(acc)->Is<sem::Reference>()); - auto* ptr = TypeOf(acc)->As<sem::Pointer>(); - ASSERT_TRUE(ptr->StoreType()->Is<sem::Vector>()); - EXPECT_EQ(ptr->StoreType()->As<sem::Vector>()->size(), 3u); + auto* ref = TypeOf(acc)->As<sem::Reference>(); + ASSERT_TRUE(ref->StoreType()->Is<sem::Vector>()); + EXPECT_EQ(ref->StoreType()->As<sem::Vector>()->size(), 3u); } TEST_F(ResolverTest, Expr_ArrayAccessor_Matrix_BothDimensions) { @@ -458,10 +459,10 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); ASSERT_NE(TypeOf(acc), nullptr); - ASSERT_TRUE(TypeOf(acc)->Is<sem::Pointer>()); + ASSERT_TRUE(TypeOf(acc)->Is<sem::Reference>()); - auto* ptr = TypeOf(acc)->As<sem::Pointer>(); - EXPECT_TRUE(ptr->StoreType()->Is<sem::F32>()); + auto* ref = TypeOf(acc)->As<sem::Reference>(); + EXPECT_TRUE(ref->StoreType()->Is<sem::F32>()); } TEST_F(ResolverTest, Expr_ArrayAccessor_Vector) { @@ -473,10 +474,10 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); ASSERT_NE(TypeOf(acc), nullptr); - ASSERT_TRUE(TypeOf(acc)->Is<sem::Pointer>()); + ASSERT_TRUE(TypeOf(acc)->Is<sem::Reference>()); - auto* ptr = TypeOf(acc)->As<sem::Pointer>(); - EXPECT_TRUE(ptr->StoreType()->Is<sem::F32>()); + auto* ref = TypeOf(acc)->As<sem::Reference>(); + EXPECT_TRUE(ref->StoreType()->Is<sem::F32>()); } TEST_F(ResolverTest, Expr_Bitcast) { @@ -519,7 +520,10 @@ TEST_F(ResolverTest, Expr_Call_WithParams) { ast::VariableList params; - Func("my_func", params, ty.void_(), {}, ast::DecorationList{}); + Func("my_func", params, ty.f32(), + { + Return(1.2f), + }); auto* param = Expr(2.4f); @@ -609,8 +613,8 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); ASSERT_NE(TypeOf(ident), nullptr); - EXPECT_TRUE(TypeOf(ident)->Is<sem::Pointer>()); - EXPECT_TRUE(TypeOf(ident)->As<sem::Pointer>()->StoreType()->Is<sem::F32>()); + ASSERT_TRUE(TypeOf(ident)->Is<sem::Reference>()); + EXPECT_TRUE(TypeOf(ident)->UnwrapRef()->Is<sem::F32>()); EXPECT_TRUE(CheckVarUsers(my_var, {ident})); ASSERT_NE(VarOf(ident), nullptr); EXPECT_EQ(VarOf(ident)->Declaration(), my_var); @@ -674,14 +678,12 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); ASSERT_NE(TypeOf(my_var_a), nullptr); - EXPECT_TRUE(TypeOf(my_var_a)->Is<sem::Pointer>()); - EXPECT_TRUE( - TypeOf(my_var_a)->As<sem::Pointer>()->StoreType()->Is<sem::F32>()); + ASSERT_TRUE(TypeOf(my_var_a)->Is<sem::Reference>()); + EXPECT_TRUE(TypeOf(my_var_a)->UnwrapRef()->Is<sem::F32>()); EXPECT_EQ(StmtOf(my_var_a), assign); ASSERT_NE(TypeOf(my_var_b), nullptr); - EXPECT_TRUE(TypeOf(my_var_b)->Is<sem::Pointer>()); - EXPECT_TRUE( - TypeOf(my_var_b)->As<sem::Pointer>()->StoreType()->Is<sem::F32>()); + ASSERT_TRUE(TypeOf(my_var_b)->Is<sem::Reference>()); + EXPECT_TRUE(TypeOf(my_var_b)->UnwrapRef()->Is<sem::F32>()); EXPECT_EQ(StmtOf(my_var_b), assign); EXPECT_TRUE(CheckVarUsers(var, {my_var_a, my_var_b})); ASSERT_NE(VarOf(my_var_a), nullptr); @@ -691,29 +693,30 @@ } TEST_F(ResolverTest, Expr_Identifier_Function_Ptr) { - auto* my_var_a = Expr("my_var"); - auto* my_var_b = Expr("my_var"); - auto* assign = Assign(my_var_a, my_var_b); - + auto* v = Expr("v"); + auto* p = Expr("p"); + auto* v_decl = Decl(Var("v", ty.f32())); + auto* p_decl = Decl( + Const("p", ty.pointer<f32>(ast::StorageClass::kFunction), AddressOf(v))); + auto* assign = Assign(Deref(p), 1.23f); Func("my_func", ast::VariableList{}, ty.void_(), { - Decl(Var("my_var", ty.pointer<f32>(ast::StorageClass::kFunction))), + v_decl, + p_decl, assign, }, ast::DecorationList{}); EXPECT_TRUE(r()->Resolve()) << r()->error(); - ASSERT_NE(TypeOf(my_var_a), nullptr); - EXPECT_TRUE(TypeOf(my_var_a)->Is<sem::Pointer>()); - EXPECT_TRUE( - TypeOf(my_var_a)->As<sem::Pointer>()->StoreType()->Is<sem::F32>()); - EXPECT_EQ(StmtOf(my_var_a), assign); - ASSERT_NE(TypeOf(my_var_b), nullptr); - EXPECT_TRUE(TypeOf(my_var_b)->Is<sem::Pointer>()); - EXPECT_TRUE( - TypeOf(my_var_b)->As<sem::Pointer>()->StoreType()->Is<sem::F32>()); - EXPECT_EQ(StmtOf(my_var_b), assign); + ASSERT_NE(TypeOf(v), nullptr); + ASSERT_TRUE(TypeOf(v)->Is<sem::Reference>()); + EXPECT_TRUE(TypeOf(v)->UnwrapRef()->Is<sem::F32>()); + EXPECT_EQ(StmtOf(v), p_decl); + ASSERT_NE(TypeOf(p), nullptr); + ASSERT_TRUE(TypeOf(p)->Is<sem::Pointer>()); + EXPECT_TRUE(TypeOf(p)->UnwrapPtr()->Is<sem::F32>()); + EXPECT_EQ(StmtOf(p), assign); } TEST_F(ResolverTest, Expr_Call_Function) { @@ -895,10 +898,10 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); ASSERT_NE(TypeOf(mem), nullptr); - ASSERT_TRUE(TypeOf(mem)->Is<sem::Pointer>()); + ASSERT_TRUE(TypeOf(mem)->Is<sem::Reference>()); - auto* ptr = TypeOf(mem)->As<sem::Pointer>(); - EXPECT_TRUE(ptr->StoreType()->Is<sem::F32>()); + auto* ref = TypeOf(mem)->As<sem::Reference>(); + EXPECT_TRUE(ref->StoreType()->Is<sem::F32>()); auto* sma = Sem().Get(mem)->As<sem::StructMemberAccess>(); ASSERT_NE(sma, nullptr); EXPECT_EQ(sma->Member()->Type(), ty.f32()); @@ -920,10 +923,10 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); ASSERT_NE(TypeOf(mem), nullptr); - ASSERT_TRUE(TypeOf(mem)->Is<sem::Pointer>()); + ASSERT_TRUE(TypeOf(mem)->Is<sem::Reference>()); - auto* ptr = TypeOf(mem)->As<sem::Pointer>(); - EXPECT_TRUE(ptr->StoreType()->Is<sem::F32>()); + auto* ref = TypeOf(mem)->As<sem::Reference>(); + EXPECT_TRUE(ref->StoreType()->Is<sem::F32>()); auto* sma = Sem().Get(mem)->As<sem::StructMemberAccess>(); ASSERT_NE(sma, nullptr); EXPECT_EQ(sma->Member()->Type(), ty.f32()); @@ -956,10 +959,10 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); ASSERT_NE(TypeOf(mem), nullptr); - ASSERT_TRUE(TypeOf(mem)->Is<sem::Pointer>()); + ASSERT_TRUE(TypeOf(mem)->Is<sem::Reference>()); - auto* ptr = TypeOf(mem)->As<sem::Pointer>(); - ASSERT_TRUE(ptr->StoreType()->Is<sem::F32>()); + auto* ref = TypeOf(mem)->As<sem::Reference>(); + ASSERT_TRUE(ref->StoreType()->Is<sem::F32>()); ASSERT_TRUE(Sem().Get(mem)->Is<sem::Swizzle>()); EXPECT_THAT(Sem().Get(mem)->As<sem::Swizzle>()->Indices(), ElementsAre(2)); }
diff --git a/src/resolver/type_constructor_validation_test.cc b/src/resolver/type_constructor_validation_test.cc index e5d06d0..94fc5ee 100644 --- a/src/resolver/type_constructor_validation_test.cc +++ b/src/resolver/type_constructor_validation_test.cc
@@ -13,6 +13,7 @@ // limitations under the License. #include "src/resolver/resolver_test_helper.h" +#include "src/sem/reference_type.h" namespace tint { namespace resolver { @@ -51,13 +52,19 @@ auto* a_ident = Expr("a"); auto* b_ident = Expr("b"); - WrapInFunction(Decl(a), Decl(b), Assign(a_ident, "a"), Assign(b_ident, "b")); + WrapInFunction(a, b, Assign(a_ident, "a"), Assign(b_ident, "b")); ASSERT_TRUE(r()->Resolve()) << r()->error(); - ASSERT_EQ(TypeOf(a_ident), - ty.pointer(ty.i32(), ast::StorageClass::kFunction)); - ASSERT_EQ(TypeOf(b_ident), - ty.pointer(ty.i32(), ast::StorageClass::kFunction)); + ASSERT_TRUE(TypeOf(a_ident)->Is<sem::Reference>()); + EXPECT_TRUE( + TypeOf(a_ident)->As<sem::Reference>()->StoreType()->Is<sem::I32>()); + EXPECT_EQ(TypeOf(a_ident)->As<sem::Reference>()->StorageClass(), + ast::StorageClass::kFunction); + ASSERT_TRUE(TypeOf(b_ident)->Is<sem::Reference>()); + EXPECT_TRUE( + TypeOf(b_ident)->As<sem::Reference>()->StoreType()->Is<sem::I32>()); + EXPECT_EQ(TypeOf(b_ident)->As<sem::Reference>()->StorageClass(), + ast::StorageClass::kFunction); } using InferTypeTest_FromConstructorExpression = ResolverTestWithParam<Params>; @@ -79,9 +86,8 @@ ASSERT_TRUE(r()->Resolve()) << r()->error(); auto* got = TypeOf(a_ident); - auto* expected = - ty.pointer(params.create_rhs_sem_type(ty), ast::StorageClass::kFunction) - .sem; + auto* expected = create<sem::Reference>(params.create_rhs_sem_type(ty), + ast::StorageClass::kFunction); ASSERT_EQ(got, expected) << "got: " << FriendlyName(got) << "\n" << "expected: " << FriendlyName(expected) << "\n"; } @@ -134,9 +140,8 @@ ASSERT_TRUE(r()->Resolve()) << r()->error(); auto* got = TypeOf(a_ident); - auto* expected = - ty.pointer(params.create_rhs_sem_type(ty), ast::StorageClass::kFunction) - .sem; + auto* expected = create<sem::Reference>(params.create_rhs_sem_type(ty), + ast::StorageClass::kFunction); ASSERT_EQ(got, expected) << "got: " << FriendlyName(got) << "\n" << "expected: " << FriendlyName(expected) << "\n"; } @@ -184,9 +189,8 @@ ASSERT_TRUE(r()->Resolve()) << r()->error(); auto* got = TypeOf(a_ident); - auto* expected = - ty.pointer(params.create_rhs_sem_type(ty), ast::StorageClass::kFunction) - .sem; + auto* expected = create<sem::Reference>(params.create_rhs_sem_type(ty), + ast::StorageClass::kFunction); ASSERT_EQ(got, expected) << "got: " << FriendlyName(got) << "\n" << "expected: " << FriendlyName(expected) << "\n"; }
diff --git a/src/resolver/type_validation_test.cc b/src/resolver/type_validation_test.cc index beec7d5..de11bb9 100644 --- a/src/resolver/type_validation_test.cc +++ b/src/resolver/type_validation_test.cc
@@ -49,27 +49,6 @@ ASSERT_NE(TypeOf(rhs), nullptr); } -TEST_F(ResolverTypeValidationTest, FunctionConstantNoConstructor_Fail) { - // { - // let a :i32; - // } - auto* var = Const(Source{{12, 34}}, "a", ty.i32(), nullptr); - WrapInFunction(var); - - EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ(r()->error(), - "12:34 error: let declarations must have initializers"); -} - -TEST_F(ResolverTypeValidationTest, GlobalConstantNoConstructor_Fail) { - // let a :i32; - GlobalConst(Source{{12, 34}}, "a", ty.i32(), nullptr); - - EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ(r()->error(), - "12:34 error: let declarations must have initializers"); -} - TEST_F(ResolverTypeValidationTest, GlobalConstantNoConstructor_Pass) { // [[override(0)]] let a :i32; GlobalConst(Source{{12, 34}}, "a", ty.i32(), nullptr, @@ -117,19 +96,6 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); } -TEST_F(ResolverTypeValidationTest, GlobalVariableNotUnique_Fail) { - // var global_var : f32 = 0.1; - // var global_var : i32 = 0; - Global("global_var", ty.f32(), ast::StorageClass::kPrivate, Expr(0.1f)); - - Global(Source{{12, 34}}, "global_var", ty.i32(), ast::StorageClass::kPrivate, - Expr(0)); - - EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ(r()->error(), - "12:34 error v-0011: redeclared global identifier 'global_var'"); -} - TEST_F(ResolverTypeValidationTest, GlobalVariableFunctionVariableNotUnique_Pass) { // fn my_func() { @@ -146,48 +112,6 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); } -TEST_F(ResolverTypeValidationTest, - GlobalVariableFunctionVariableNotUnique_Fail) { - // var a: f32 = 2.1; - // fn my_func() { - // var a: f32 = 2.0; - // return 0; - // } - - Global("a", ty.f32(), ast::StorageClass::kPrivate, Expr(2.1f)); - - auto* var = Var("a", ty.f32(), ast::StorageClass::kNone, Expr(2.0f)); - - Func("my_func", ast::VariableList{}, ty.void_(), - ast::StatementList{ - Decl(Source{{12, 34}}, var), - }, - ast::DecorationList{}); - - EXPECT_FALSE(r()->Resolve()) << r()->error(); - EXPECT_EQ(r()->error(), "12:34 error v-0013: redeclared identifier 'a'"); -} - -TEST_F(ResolverTypeValidationTest, RedeclaredIdentifier_Fail) { - // fn my_func()() { - // var a :i32 = 2; - // var a :f21 = 2.0; - // } - auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); - - auto* var_a_float = Var("a", ty.f32(), ast::StorageClass::kNone, Expr(0.1f)); - - Func("my_func", ast::VariableList{}, ty.void_(), - ast::StatementList{ - Decl(var), - Decl(Source{{12, 34}}, var_a_float), - }, - ast::DecorationList{}); - - EXPECT_FALSE(r()->Resolve()) << r()->error(); - EXPECT_EQ(r()->error(), "12:34 error v-0014: redeclared identifier 'a'"); -} - TEST_F(ResolverTypeValidationTest, RedeclaredIdentifierInnerScope_Pass) { // { // if (true) { var a : f32 = 2.0; } @@ -209,31 +133,6 @@ EXPECT_TRUE(r()->Resolve()); } -TEST_F(ResolverTypeValidationTest, - DISABLED_RedeclaredIdentifierInnerScope_False) { - // TODO(sarahM0): remove DISABLED after implementing ValidateIfStatement - // and it should just work - // { - // var a : f32 = 3.14; - // if (true) { var a : f32 = 2.0; } - // } - auto* var_a_float = Var("a", ty.f32(), ast::StorageClass::kNone, Expr(3.1f)); - - auto* var = Var("a", ty.f32(), ast::StorageClass::kNone, Expr(2.0f)); - - auto* cond = Expr(true); - auto* body = Block(Decl(Source{{12, 34}}, var)); - - auto* outer_body = - Block(Decl(var_a_float), - create<ast::IfStatement>(cond, body, ast::ElseStatementList{})); - - WrapInFunction(outer_body); - - EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ(r()->error(), "12:34 error v-0014: redeclared identifier 'a'"); -} - TEST_F(ResolverTypeValidationTest, RedeclaredIdentifierInnerScopeBlock_Pass) { // { // { var a : f32; } @@ -250,23 +149,6 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); } -TEST_F(ResolverTypeValidationTest, RedeclaredIdentifierInnerScopeBlock_Fail) { - // { - // var a : f32; - // { var a : f32; } - // } - auto* var_inner = Var("a", ty.f32(), ast::StorageClass::kNone); - auto* inner = Block(Decl(Source{{12, 34}}, var_inner)); - - auto* var_outer = Var("a", ty.f32(), ast::StorageClass::kNone); - auto* outer_body = Block(Decl(var_outer), inner); - - WrapInFunction(outer_body); - - EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ(r()->error(), "12:34 error v-0014: redeclared identifier 'a'"); -} - TEST_F(ResolverTypeValidationTest, RedeclaredIdentifierDifferentFunctions_Pass) { // func0 { var a : f32 = 2.0; return; } @@ -519,7 +401,7 @@ EXPECT_TRUE(r()->Resolve()) << r()->error(); - auto* got = TypeOf(expr)->UnwrapPtr(); + auto* got = TypeOf(expr)->UnwrapRef(); auto* expected = params.create_sem_type(ty); EXPECT_EQ(got, expected) << "got: " << FriendlyName(got) << "\n"
diff --git a/src/resolver/validation_test.cc b/src/resolver/validation_test.cc index 9440f1f..ed4d089 100644 --- a/src/resolver/validation_test.cc +++ b/src/resolver/validation_test.cc
@@ -160,34 +160,6 @@ "12:34 error: else statement condition must be bool, got f32"); } -TEST_F(ResolverValidationTest, - Stmt_VariableDecl_MismatchedTypeScalarConstructor) { - u32 unsigned_value = 2u; // Type does not match variable type - auto* decl = Decl(Var(Source{{3, 3}}, "my_var", ty.i32(), - ast::StorageClass::kNone, Expr(unsigned_value))); - WrapInFunction(decl); - - EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ( - r()->error(), - R"(3:3 error: variable of type 'i32' cannot be initialized with a value of type 'u32')"); -} - -TEST_F(ResolverValidationTest, - Stmt_VariableDecl_MismatchedTypeScalarConstructor_Alias) { - auto* my_int = ty.alias("MyInt", ty.i32()); - AST().AddConstructedType(my_int); - u32 unsigned_value = 2u; // Type does not match variable type - auto* decl = Decl(Var(Source{{3, 3}}, "my_var", my_int, - ast::StorageClass::kNone, Expr(unsigned_value))); - WrapInFunction(decl); - - EXPECT_FALSE(r()->Resolve()); - EXPECT_EQ( - r()->error(), - R"(3:3 error: variable of type 'MyInt' cannot be initialized with a value of type 'u32')"); -} - TEST_F(ResolverValidationTest, Expr_Error_Unknown) { auto* e = create<FakeExpr>(Source{Source::Location{2, 30}}); WrapInFunction(e);
diff --git a/src/resolver/var_let_test.cc b/src/resolver/var_let_test.cc new file mode 100644 index 0000000..bf37ace --- /dev/null +++ b/src/resolver/var_let_test.cc
@@ -0,0 +1,133 @@ +// Copyright 2021 The Tint Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "src/resolver/resolver.h" +#include "src/resolver/resolver_test_helper.h" +#include "src/sem/reference_type.h" + +#include "gmock/gmock.h" + +namespace tint { +namespace resolver { +namespace { + +struct ResolverVarLetTest : public resolver::TestHelper, + public testing::Test {}; + +TEST_F(ResolverVarLetTest, TypeOfVar) { + // struct S { i : i32; } + // alias A = S; + // fn F(){ + // var i : i32; + // var u : u32; + // var f : f32; + // var b : bool; + // var s : S; + // var a : A; + // } + + auto* S = Structure("S", {Member("i", ty.i32())}); + auto* A = ty.alias("A", S); + AST().AddConstructedType(A); + + auto* i = Var("i", ty.i32(), ast::StorageClass::kNone); + auto* u = Var("u", ty.u32(), ast::StorageClass::kNone); + auto* f = Var("f", ty.f32(), ast::StorageClass::kNone); + auto* b = Var("b", ty.bool_(), ast::StorageClass::kNone); + auto* s = Var("s", S, ast::StorageClass::kNone); + auto* a = Var("a", A, ast::StorageClass::kNone); + + Func("F", {}, ty.void_(), + { + Decl(i), + Decl(u), + Decl(f), + Decl(b), + Decl(s), + Decl(a), + }); + + EXPECT_TRUE(r()->Resolve()) << r()->error(); + + // `var` declarations are always of reference type + ASSERT_TRUE(TypeOf(i)->Is<sem::Reference>()); + ASSERT_TRUE(TypeOf(u)->Is<sem::Reference>()); + ASSERT_TRUE(TypeOf(f)->Is<sem::Reference>()); + ASSERT_TRUE(TypeOf(b)->Is<sem::Reference>()); + ASSERT_TRUE(TypeOf(s)->Is<sem::Reference>()); + ASSERT_TRUE(TypeOf(a)->Is<sem::Reference>()); + + EXPECT_TRUE(TypeOf(i)->As<sem::Reference>()->StoreType()->Is<sem::I32>()); + EXPECT_TRUE(TypeOf(u)->As<sem::Reference>()->StoreType()->Is<sem::U32>()); + EXPECT_TRUE(TypeOf(f)->As<sem::Reference>()->StoreType()->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(b)->As<sem::Reference>()->StoreType()->Is<sem::Bool>()); + EXPECT_TRUE(TypeOf(s)->As<sem::Reference>()->StoreType()->Is<sem::Struct>()); + EXPECT_TRUE(TypeOf(a)->As<sem::Reference>()->StoreType()->Is<sem::Struct>()); +} + +TEST_F(ResolverVarLetTest, TypeOfLet) { + // struct S { i : i32; } + // fn F(){ + // var v : i32; + // let i : i32 = 1; + // let u : u32 = 1u; + // let f : f32 = 1.; + // let b : bool = true; + // let s : S = S(1); + // let a : A = A(1); + // let p : pointer<function, i32> = &V; + // } + + auto* S = Structure("S", {Member("i", ty.i32())}); + auto* A = ty.alias("A", S); + AST().AddConstructedType(A); + + auto* v = Var("v", ty.i32(), ast::StorageClass::kNone); + auto* i = Const("i", ty.i32(), Expr(1)); + auto* u = Const("u", ty.u32(), Expr(1u)); + auto* f = Const("f", ty.f32(), Expr(1.f)); + auto* b = Const("b", ty.bool_(), Expr(true)); + auto* s = Const("s", S, Construct(S, Expr(1))); + auto* a = Const("a", A, Construct(A, Expr(1))); + auto* p = + Const("p", ty.pointer<i32>(ast::StorageClass::kFunction), AddressOf(v)); + + Func("F", {}, ty.void_(), + { + Decl(v), + Decl(i), + Decl(u), + Decl(f), + Decl(b), + Decl(s), + Decl(a), + Decl(p), + }); + + EXPECT_TRUE(r()->Resolve()) << r()->error(); + + // `let` declarations are always of the storage type + EXPECT_TRUE(TypeOf(i)->Is<sem::I32>()); + EXPECT_TRUE(TypeOf(u)->Is<sem::U32>()); + EXPECT_TRUE(TypeOf(f)->Is<sem::F32>()); + EXPECT_TRUE(TypeOf(b)->Is<sem::Bool>()); + EXPECT_TRUE(TypeOf(s)->Is<sem::Struct>()); + EXPECT_TRUE(TypeOf(a)->Is<sem::Struct>()); + ASSERT_TRUE(TypeOf(p)->Is<sem::Pointer>()); + EXPECT_TRUE(TypeOf(p)->As<sem::Pointer>()->StoreType()->Is<sem::I32>()); +} + +} // namespace +} // namespace resolver +} // namespace tint
diff --git a/src/resolver/var_let_validation_test.cc b/src/resolver/var_let_validation_test.cc new file mode 100644 index 0000000..23c42e9 --- /dev/null +++ b/src/resolver/var_let_validation_test.cc
@@ -0,0 +1,220 @@ +// Copyright 2021 The Tint Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "src/resolver/resolver.h" +#include "src/resolver/resolver_test_helper.h" + +#include "gmock/gmock.h" + +namespace tint { +namespace resolver { +namespace { + +struct ResolverVarLetValidationTest : public resolver::TestHelper, + public testing::Test {}; + +TEST_F(ResolverVarLetValidationTest, LetNoInitializer) { + // let a : i32; + WrapInFunction(Const(Source{{12, 34}}, "a", ty.i32(), nullptr)); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ(r()->error(), + "12:34 error: let declarations must have initializers"); +} + +TEST_F(ResolverVarLetValidationTest, GlobalLetNoInitializer) { + // let a : i32; + GlobalConst(Source{{12, 34}}, "a", ty.i32(), nullptr); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ(r()->error(), + "12:34 error: let declarations must have initializers"); +} + +TEST_F(ResolverVarLetValidationTest, VarConstructorNotStorable) { + // var i : i32; + // var p : pointer<function, i32> = &v; + auto* i = Var("i", ty.i32(), ast::StorageClass::kNone); + auto* p = Var("a", ty.i32(), ast::StorageClass::kNone, + AddressOf(Source{{12, 34}}, "i")); + WrapInFunction(i, p); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ(r()->error(), + "12:34 error: 'ptr<function, i32>' is not storable for assignment"); +} + +TEST_F(ResolverVarLetValidationTest, LetConstructorWrongType) { + // var v : i32 = 2u + WrapInFunction(Const(Source{{3, 3}}, "v", ty.i32(), Expr(2u))); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ( + r()->error(), + R"(3:3 error: cannot initialize let of type 'i32' with value of type 'u32')"); +} + +TEST_F(ResolverVarLetValidationTest, VarConstructorWrongType) { + // var v : i32 = 2u + WrapInFunction( + Var(Source{{3, 3}}, "v", ty.i32(), ast::StorageClass::kNone, Expr(2u))); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ( + r()->error(), + R"(3:3 error: cannot initialize var of type 'i32' with value of type 'u32')"); +} + +TEST_F(ResolverVarLetValidationTest, LetConstructorWrongTypeViaAlias) { + auto* a = ty.alias("I32", ty.i32()); + AST().AddConstructedType(a); + WrapInFunction(Const(Source{{3, 3}}, "v", a, Expr(2u))); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ( + r()->error(), + R"(3:3 error: cannot initialize let of type 'I32' with value of type 'u32')"); +} + +TEST_F(ResolverVarLetValidationTest, VarConstructorWrongTypeViaAlias) { + auto* a = ty.alias("I32", ty.i32()); + AST().AddConstructedType(a); + WrapInFunction( + Var(Source{{3, 3}}, "v", a, ast::StorageClass::kNone, Expr(2u))); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ( + r()->error(), + R"(3:3 error: cannot initialize var of type 'I32' with value of type 'u32')"); +} + +TEST_F(ResolverVarLetValidationTest, LetOfPtrConstructedWithRef) { + // var a : f32; + // let b : ptr<function,f32> = a; + const auto priv = ast::StorageClass::kFunction; + auto* var_a = Var("a", ty.f32(), priv); + auto* var_b = + Const(Source{{12, 34}}, "b", ty.pointer<float>(priv), Expr("a"), {}); + WrapInFunction(var_a, var_b); + + ASSERT_FALSE(r()->Resolve()); + + EXPECT_EQ( + r()->error(), + R"(12:34 error: cannot initialize let of type 'ptr<function, f32>' with value of type 'f32')"); +} + +TEST_F(ResolverVarLetValidationTest, LocalVarRedeclared) { + // var v : f32; + // var v : i32; + auto* v1 = Var("v", ty.f32(), ast::StorageClass::kNone); + auto* v2 = Var(Source{{12, 34}}, "v", ty.i32(), ast::StorageClass::kNone); + WrapInFunction(v1, v2); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ(r()->error(), "12:34 error v-0014: redeclared identifier 'v'"); +} + +TEST_F(ResolverVarLetValidationTest, LocalLetRedeclared) { + // let l : f32 = 1.; + // let l : i32 = 0; + auto* l1 = Const("l", ty.f32(), Expr(1.f)); + auto* l2 = Const(Source{{12, 34}}, "l", ty.i32(), Expr(0)); + WrapInFunction(l1, l2); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ(r()->error(), "12:34 error v-0014: redeclared identifier 'l'"); +} + +TEST_F(ResolverVarLetValidationTest, GlobalVarRedeclared) { + // var v : f32; + // var v : i32; + Global("v", ty.f32(), ast::StorageClass::kPrivate); + Global(Source{{12, 34}}, "v", ty.i32(), ast::StorageClass::kPrivate); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ(r()->error(), + "12:34 error v-0011: redeclared global identifier 'v'"); +} + +TEST_F(ResolverVarLetValidationTest, GlobalLetRedeclared) { + // let l : f32 = 0.1; + // let l : i32 = 0; + GlobalConst("l", ty.f32(), Expr(0.1f)); + GlobalConst(Source{{12, 34}}, "l", ty.i32(), Expr(0)); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ(r()->error(), + "12:34 error v-0011: redeclared global identifier 'l'"); +} + +TEST_F(ResolverVarLetValidationTest, GlobalVarRedeclaredAsLocal) { + // var v : f32 = 2.1; + // fn my_func() { + // var v : f32 = 2.0; + // return 0; + // } + + Global("v", ty.f32(), ast::StorageClass::kPrivate, Expr(2.1f)); + + WrapInFunction(Var(Source{{12, 34}}, "v", ty.f32(), ast::StorageClass::kNone, + Expr(2.0f))); + + EXPECT_FALSE(r()->Resolve()) << r()->error(); + EXPECT_EQ(r()->error(), "12:34 error v-0013: redeclared identifier 'v'"); +} + +TEST_F(ResolverVarLetValidationTest, VarRedeclaredInInnerBlock) { + // { + // var v : f32; + // { var v : f32; } + // } + auto* var_outer = Var("v", ty.f32(), ast::StorageClass::kNone); + auto* var_inner = + Var(Source{{12, 34}}, "v", ty.f32(), ast::StorageClass::kNone); + auto* inner = Block(Decl(var_inner)); + auto* outer_body = Block(Decl(var_outer), inner); + + WrapInFunction(outer_body); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ(r()->error(), "12:34 error v-0014: redeclared identifier 'v'"); +} + +TEST_F(ResolverVarLetValidationTest, VarRedeclaredInIfBlock) { + // { + // var v : f32 = 3.14; + // if (true) { var v : f32 = 2.0; } + // } + auto* var_a_float = Var("v", ty.f32(), ast::StorageClass::kNone, Expr(3.1f)); + + auto* var = Var(Source{{12, 34}}, "v", ty.f32(), ast::StorageClass::kNone, + Expr(2.0f)); + + auto* cond = Expr(true); + auto* body = Block(Decl(var)); + + auto* outer_body = + Block(Decl(var_a_float), + create<ast::IfStatement>(cond, body, ast::ElseStatementList{})); + + WrapInFunction(outer_body); + + EXPECT_FALSE(r()->Resolve()); + EXPECT_EQ(r()->error(), "12:34 error v-0014: redeclared identifier 'v'"); +} + +} // namespace +} // namespace resolver +} // namespace tint