From 9fdfa1e32374f8d862c98ad241757853386f66e6 Mon Sep 17 00:00:00 2001 From: Antonio Maiorano Date: Mon, 10 May 2021 13:46:06 +0000 Subject: [PATCH] Resolver: validate else condition is boolean Bug: tint:786 Change-Id: I5e4987e4eeb0608c640fc5c8ea035c8dca0ef187 Reviewed-on: https://dawn-review.googlesource.com/c/tint/+/50461 Kokoro: Kokoro Reviewed-by: Ben Clayton Commit-Queue: Antonio Maiorano --- src/resolver/resolver.cc | 9 +++++++++ src/resolver/resolver_test.cc | 2 +- src/resolver/validation_test.cc | 14 ++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/resolver/resolver.cc b/src/resolver/resolver.cc index 78f91fa701..658fca881a 100644 --- a/src/resolver/resolver.cc +++ b/src/resolver/resolver.cc @@ -1196,6 +1196,15 @@ bool Resolver::IfStatement(ast::IfStatement* stmt) { if (!Expression(cond)) { return false; } + + auto* else_cond_type = TypeOf(cond)->UnwrapAll(); + if (else_cond_type != builder_->ty.bool_()) { + diagnostics_.add_error( + "else statement condition must be bool, got " + + else_cond_type->FriendlyName(builder_->Symbols()), + cond->source()); + return false; + } } Mark(else_stmt->body()); if (!BlockStatement(else_stmt->body())) { diff --git a/src/resolver/resolver_test.cc b/src/resolver/resolver_test.cc index 88cfbb6d8a..1d6f22f87e 100644 --- a/src/resolver/resolver_test.cc +++ b/src/resolver/resolver_test.cc @@ -125,7 +125,7 @@ TEST_F(ResolverTest, Stmt_If) { auto* else_body = Block(Assign(else_lhs, else_rhs)); - auto* else_cond = Expr(3); + auto* else_cond = Expr(true); auto* else_stmt = create(else_cond, else_body); auto* lhs = Expr("v"); diff --git a/src/resolver/validation_test.cc b/src/resolver/validation_test.cc index 4ffb66055f..6ad9df8ca0 100644 --- a/src/resolver/validation_test.cc +++ b/src/resolver/validation_test.cc @@ -147,6 +147,20 @@ TEST_F(ResolverValidationTest, Stmt_If_NonBool) { "12:34 error: if statement condition must be bool, got f32"); } +TEST_F(ResolverValidationTest, Stmt_Else_NonBool) { + // else (1.23f) {} + + WrapInFunction(If(Expr(true), Block(), + Else(create( + Source{{12, 34}}, Literal(1.23f)), + Block()))); + + EXPECT_FALSE(r()->Resolve()); + + EXPECT_EQ(r()->error(), + "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