From 8ebbd6ae54bf96b6e8fea8577ede66e5c5d88551 Mon Sep 17 00:00:00 2001 From: nitrix Date: Fri, 14 Feb 2020 14:10:48 +0100 Subject: [PATCH] implement null type --- .../hsrm/compiler/Klang/types/NullType.java | 36 +++++++++++++++++++ .../hsrm/compiler/Klang/types/StructType.java | 6 ++++ .../de/hsrm/compiler/Klang/types/Type.java | 5 +++ 3 files changed, 47 insertions(+) create mode 100644 src/main/java/de/hsrm/compiler/Klang/types/NullType.java diff --git a/src/main/java/de/hsrm/compiler/Klang/types/NullType.java b/src/main/java/de/hsrm/compiler/Klang/types/NullType.java new file mode 100644 index 0000000..ffb5a33 --- /dev/null +++ b/src/main/java/de/hsrm/compiler/Klang/types/NullType.java @@ -0,0 +1,36 @@ +package de.hsrm.compiler.Klang.types; + +public class NullType extends Type { + + private static NullType instance = null; + + public static NullType getType() { + if (instance != null) { + return instance; + } + instance = new NullType(); + return instance; + } + + @Override + public String getName() { + return "naught"; + } + + @Override + public Type combine(Type that) { + // You can not combine null with a primitive type + if (that.isPrimitiveType()) { + throw new RuntimeException("Type missmatch: cannot combine " + this.getName() + " and " + that.getName()); + } + + // Everything else combines with null to the type it was before + return that; + } + + @Override + public boolean isPrimitiveType() { + return false; + } + +} \ No newline at end of file diff --git a/src/main/java/de/hsrm/compiler/Klang/types/StructType.java b/src/main/java/de/hsrm/compiler/Klang/types/StructType.java index 9fac760..adf3f8b 100644 --- a/src/main/java/de/hsrm/compiler/Klang/types/StructType.java +++ b/src/main/java/de/hsrm/compiler/Klang/types/StructType.java @@ -19,6 +19,12 @@ public class StructType extends Type { return this; } + // If you combine a null type with a struct type, you + // always get the struct type back. + if (that == NullType.getType()) { + return this; + } + throw new RuntimeException("Type missmatch: cannot combine " + this.getName() + " and " + that.getName()); } diff --git a/src/main/java/de/hsrm/compiler/Klang/types/Type.java b/src/main/java/de/hsrm/compiler/Klang/types/Type.java index cfd4791..15b2810 100644 --- a/src/main/java/de/hsrm/compiler/Klang/types/Type.java +++ b/src/main/java/de/hsrm/compiler/Klang/types/Type.java @@ -16,11 +16,16 @@ public abstract class Type { return FloatType.getType(); } + public static NullType getNullType() { + return NullType.getType(); + } + public static Type getByName(String name) { switch (name) { case "bool": return getBooleanType(); case "int": return getIntegerType(); case "float": return getFloatType(); + case "null": return getNullType(); default: return new StructType(name); } }