diff options
| author | Michael Williamson <mike@zwobble.org> | 2023-07-14 21:09:42 +0100 |
|---|---|---|
| committer | Michael Williamson <mike@zwobble.org> | 2023-07-14 21:09:42 +0100 |
| commit | d024723fb80ed28e6eea333f83481397a0cba7ea (patch) | |
| tree | f230743734529e170fb63b8178d384979ff968f7 /src/main/java | |
| parent | 5b999386f081b1f7e5259e26ffd33ea85e3e7a2b (diff) | |
Type if expression properly
Diffstat (limited to 'src/main/java')
| -rw-r--r-- | src/main/java/org/shedlang/compiler/typechecker/TypeChecker.java | 9 | ||||
| -rw-r--r-- | src/main/java/org/shedlang/compiler/types/Types.java | 12 |
2 files changed, 19 insertions, 2 deletions
diff --git a/src/main/java/org/shedlang/compiler/typechecker/TypeChecker.java b/src/main/java/org/shedlang/compiler/typechecker/TypeChecker.java index b6233c04..359c49d1 100644 --- a/src/main/java/org/shedlang/compiler/typechecker/TypeChecker.java +++ b/src/main/java/org/shedlang/compiler/typechecker/TypeChecker.java @@ -497,11 +497,16 @@ public class TypeChecker { var typedElseBody = typedElseBodyResult.value(); context = typedElseBodyResult.context(); + var branchTypes = Stream.concat( + typedConditionalBranches.stream() + .map(conditionalBranch -> conditionalBranch.body().type()), + Stream.of(typedElseBody.type()) + ).toList(); + var typed = new TypedIfNode( typedConditionalBranches, typedElseBody, - // TODO: consider type of conditional branches - typedElseBody.type(), + Types.commonSupertype(branchTypes), untyped.source() ); diff --git a/src/main/java/org/shedlang/compiler/types/Types.java b/src/main/java/org/shedlang/compiler/types/Types.java index f192c98e..92ae294d 100644 --- a/src/main/java/org/shedlang/compiler/types/Types.java +++ b/src/main/java/org/shedlang/compiler/types/Types.java @@ -1,5 +1,8 @@ package org.shedlang.compiler.types; +import java.util.HashSet; +import java.util.List; + public class Types { private Types() { } @@ -18,4 +21,13 @@ public class Types { public static Type effectType(Effect effect) { return new TypeLevelValueType(effect); } + + public static Type commonSupertype(List<Type> subtypes) { + var uniqueSubtypes = new HashSet<>(subtypes); + if (uniqueSubtypes.size() == 1) { + return subtypes.get(0); + } else { + return TOP; + } + } } |
