From 7bc7dbd5f5d73c1c070ed69af2ab143d7a1c199e Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Sun, 29 Oct 2023 18:22:31 +0000 Subject: Support inferring return type from multiple return statements --- .../typechecker/TypeCheckerFunctionBodyTests.java | 40 ++++++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) (limited to 'src/test/java') diff --git a/src/test/java/org/shedlang/compiler/typechecker/TypeCheckerFunctionBodyTests.java b/src/test/java/org/shedlang/compiler/typechecker/TypeCheckerFunctionBodyTests.java index 5e80c9a0..8b7bc4f6 100644 --- a/src/test/java/org/shedlang/compiler/typechecker/TypeCheckerFunctionBodyTests.java +++ b/src/test/java/org/shedlang/compiler/typechecker/TypeCheckerFunctionBodyTests.java @@ -217,7 +217,7 @@ public class TypeCheckerFunctionBodyTests { } @Test - public void givenNoExplicitReturnTypeWhenNoExplicitReturnsThenReturnTypeIsUnit() { + public void givenNoExplicitReturnTypeWhenNoReturnStatementsThenReturnTypeIsUnit() { var untyped = Untyped.block(List.of( Untyped.expressionStatement(Untyped.stringLiteral("")) )); @@ -236,7 +236,7 @@ public class TypeCheckerFunctionBodyTests { } @Test - public void givenNoExplicitReturnTypeWhenThereAreExplicitReturnsThenAllBranchesMustReturn() { + public void givenNoExplicitReturnTypeWhenThereAreNonUnitReturnStatementsThenAllBranchesMustReturn() { var untyped = Untyped.block(List.of( Untyped.expressionStatement(Untyped.if_( List.of( @@ -268,7 +268,7 @@ public class TypeCheckerFunctionBodyTests { } @Test - public void givenNoExplicitReturnTypeWhenThereIsOneExplicitReturnThenReturnTypeIsTypeOfReturnExpression() { + public void givenNoExplicitReturnTypeWhenThereIsOneReturnStatementThenReturnTypeIsTypeOfReturnExpression() { var untyped = Untyped.block(List.of( Untyped.functionReturn(Untyped.stringLiteral("")) )); @@ -286,6 +286,40 @@ public class TypeCheckerFunctionBodyTests { ); } + @Test + public void givenNoExplicitReturnTypeWhenThereAreMultipleReturnStatementsThenReturnTypeIsCommonSupertypeOfReturnExpressions() { + var untyped = Untyped.block(List.of( + Untyped.expressionStatement(Untyped.if_( + List.of( + Untyped.conditionalBranch( + Untyped.reference("c"), + Untyped.block(List.of( + Untyped.functionReturn(Untyped.stringLiteral("")) + )) + ) + ), + Untyped.block(List.of( + Untyped.functionReturn(Untyped.intLiteral(0)) + )) + )) + )); + var signature = TypedFunctionSignatureNode.builder() + .withoutReturnType() + .build(); + var context = TypeCheckerContext.EMPTY + .enterGlobal(P.map( + Map.entry("c", Types.BOOL) + )); + + var typed = typeCheckFunctionBody(untyped, signature, context); + + assertThat( + typed.value(), + isTypedFunctionBodyNode() + .withType(Types.TOP) + ); + } + @Test public void freeVariablesIncludeVariablesReferencedInFunctionButDefinedOutsideOfFunction() { var untyped = Untyped.block(List.of( -- cgit v1.2.3