From 502067ade0e38e4b84134d729dee3e34c8d2890e Mon Sep 17 00:00:00 2001 From: Mustafa Quraish Date: Sun, 6 Feb 2022 23:13:05 -0500 Subject: [cup] Port over all the type-checking/pointer arithmetic stuff There's still some work to be done when checking function call args, etc, but the general mechanism of actually propagating the type back up the AST is now here from the C compiler. ... Not to say that was very good, but it's passable enough for now. More improvements to come in the future! --- compiler/types.cup | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) (limited to 'compiler/types.cup') diff --git a/compiler/types.cup b/compiler/types.cup index e6cb233..2addd95 100644 --- a/compiler/types.cup +++ b/compiler/types.cup @@ -89,4 +89,46 @@ fn create_type_string(typ: Type *): char* { else die("type_to_string: unknown type"); return buf; -} \ No newline at end of file +} + +fn is_int_type(typ: Type*): int { + if (typ.typ == TYPE_INT) return true; + if (typ.typ == TYPE_CHAR) return true; + return false; +} + + +fn types_equal(a: Type*, b: Type*): int { + if (a == null && b == null) + return true; + if (a == null || b == null) + return false; + if (a.typ == TYPE_ANY || b.typ == TYPE_ANY) + return true; + return a.typ == b.typ && types_equal(a.ptr, b.ptr); +} + +fn is_convertible(from: Type*, to: Type*): int { + if (from.typ == TYPE_ANY || to.typ == TYPE_ANY) + return true; + + // Allow converstions to and from void* to any other pointer type + if (from.typ == TYPE_PTR && to.typ == TYPE_PTR) + if (from.ptr.typ == TYPE_VOID || to.ptr.typ == TYPE_VOID) + return true; + + // TODO: Should we rause a warning if the target type is narrower + // than the source type? + if (is_int_type(from) && is_int_type(to)) + return true; + return types_equal(from, to); +} + +fn is_struct_or_structptr(typ: Type*): int { + if (typ.typ == TYPE_STRUCT || typ.typ == TYPE_UNION) + return true; + if (typ.typ == TYPE_PTR) + if (typ.ptr.typ == TYPE_STRUCT || typ.ptr.typ == TYPE_UNION) + return true; + return false; +} -- cgit v1.2.3