From 3b74ee086e4b59e4265fa632c6db93fd0a9d07ea Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Sun, 2 Aug 2026 11:59:27 +0100 Subject: Introduce SumTypeInfo --- .../compiler/typechecker/TypesInfoInMemory.java | 45 +++++++++++----------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/zwobble/hobgoblin/compiler/typechecker/TypesInfoInMemory.java b/src/main/java/org/zwobble/hobgoblin/compiler/typechecker/TypesInfoInMemory.java index 7da4d2c..64c285b 100644 --- a/src/main/java/org/zwobble/hobgoblin/compiler/typechecker/TypesInfoInMemory.java +++ b/src/main/java/org/zwobble/hobgoblin/compiler/typechecker/TypesInfoInMemory.java @@ -5,12 +5,16 @@ import org.zwobble.hobgoblin.compiler.types.*; import java.util.*; public class TypesInfoInMemory implements TypesInfo { + private record SumTypeInfo( + List variants, + List fields + ) {} + public static TypesInfoInMemory empty() { return new TypesInfoInMemory( new HashMap<>(), new HashMap<>(), new HashMap<>(), - new HashMap<>(), new HashMap<>() ); } @@ -19,21 +23,18 @@ public class TypesInfoInMemory implements TypesInfo { private final Map>> structFields; - private final Map> sumFields; - private final Map> sumToVariants; + private final Map sumTypeInfos; private final Map> variantToSums; - public TypesInfoInMemory( + private TypesInfoInMemory( Map> enumVariants, Map>> structFields, - Map> sumFields, - Map> sumToVariants, + Map sumTypeInfos, Map> variantToSums ) { this.enumVariants = enumVariants; this.structFields = structFields; - this.sumFields = sumFields; - this.sumToVariants = sumToVariants; + this.sumTypeInfos = sumTypeInfos; this.variantToSums = variantToSums; } @@ -70,12 +71,13 @@ public class TypesInfoInMemory implements TypesInfo { List variants, List fields ) { - this.sumToVariants.put(sumType, variants); + var sumTypeInfo = new SumTypeInfo(variants, fields); + this.sumTypeInfos.put(sumType, sumTypeInfo); + for (var variant : variants) { this.variantToSums.putIfAbsent(variant.valueType(), new ArrayList<>()); this.variantToSums.get(variant.valueType()).add(sumType); } - this.sumFields.put(sumType, fields); } public List variantOf(StructType variantType) { @@ -83,21 +85,20 @@ public class TypesInfoInMemory implements TypesInfo { } public List sumVariants(SumType type) { - var variants = this.sumToVariants.get(type); - if (variants == null) { - // TODO: better error - throw new RuntimeException("sum not defined"); - } else { - return variants; - } + return sumTypeInfo(type).variants; } - public List fieldsOf(SumType sumType) { - var fields = this.sumFields.get(sumType); - if (fields == null) { - return List.of(); + public List fieldsOf(SumType type) { + return sumTypeInfo(type).fields; + } + + private SumTypeInfo sumTypeInfo(SumType type) { + var typeInfo = this.sumTypeInfos.get(type); + if (typeInfo == null) { + // TODO: better error + throw new RuntimeException("sum not defined"); } else { - return fields; + return typeInfo; } } } -- cgit v1.2.3