From af0f173fcc0bf84316e188a0e6d4da4dfe11b021 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Fri, 28 Aug 2026 13:52:34 +0100 Subject: Throw appropriate error if enum variant is not recognised --- .../javatransient0/JavaTransient0Generator.java | 46 +++++++++++++++++----- 1 file changed, 36 insertions(+), 10 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/org/zwobble/hobgoblin/compiler/output/generators/javatransient0/JavaTransient0Generator.java b/src/main/java/org/zwobble/hobgoblin/compiler/output/generators/javatransient0/JavaTransient0Generator.java index 3a7f0ff..4197a24 100644 --- a/src/main/java/org/zwobble/hobgoblin/compiler/output/generators/javatransient0/JavaTransient0Generator.java +++ b/src/main/java/org/zwobble/hobgoblin/compiler/output/generators/javatransient0/JavaTransient0Generator.java @@ -653,11 +653,30 @@ public class JavaTransient0Generator implements Generator { enumDefinition.type(), new JavaBlock(Stream.concat( generateDecode(ordinal, NativeTypes.INT_32, context).stream(), - // TODO: handle ordinal not in array - Stream.of(new JavaReturn(new JavaArrayAccess( - new JavaRef(enumValues), - new JavaRef(ordinal) - ))) + Stream.of(new JavaIfStatement( + new JavaBinaryOperation( + JavaBinaryOperator.LOGICAL_AND, + new JavaBinaryOperation( + JavaBinaryOperator.GREATER_THAN_OR_EQUAL, + new JavaRef(ordinal), + new JavaIntegerLiteral(0) + ), + new JavaBinaryOperation( + JavaBinaryOperator.LESS_THAN, + new JavaRef(ordinal), + new JavaIntegerLiteral(enumDefinition.variants().size()) + ) + ), + new JavaBlock(List.of( + new JavaReturn(new JavaArrayAccess( + new JavaRef(enumValues), + new JavaRef(ordinal) + )) + )), + new JavaBlock(List.of( + throwUnrecognisedVariantException(enumDefinition.type(), new JavaRef(ordinal)) + )) + )) ).toList()) ) ); @@ -804,11 +823,7 @@ public class JavaTransient0Generator implements Generator { cases.add(new JavaSwitchRule( new JavaCaseDefault(), new JavaBlock(List.of( - throwIoException(new JavaBinaryOperation( - JavaBinaryOperator.ADD, - new JavaStringLiteral("unrecognised variant tag for " + sumDefinition.type().describe() + ": "), - new JavaRef(variantTag) - )) + throwUnrecognisedVariantException(sumDefinition.type(), new JavaRef(variantTag)) )) )); @@ -1631,6 +1646,17 @@ public class JavaTransient0Generator implements Generator { ); } + private static JavaThrowStatement throwUnrecognisedVariantException( + Type type, + JavaExpression tag + ) { + return throwIoException(new JavaBinaryOperation( + JavaBinaryOperator.ADD, + new JavaStringLiteral("unrecognised variant tag for " + type.describe() + ": "), + tag + )); + } + private static JavaThrowStatement throwIoException(String errorMessage) { return throwIoException(new JavaStringLiteral(errorMessage)); } -- cgit v1.2.3