aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBruce Hill <bruce@bruce-hill.com>2024-09-11 23:13:41 -0400
committerBruce Hill <bruce@bruce-hill.com>2024-09-11 23:13:41 -0400
commitcfef667a899339a0fd5b79214d581db6ede10748 (patch)
tree6bcb59e695888c8b691cf39a6789202df7691112
parent0f7cf28af1b204d0f979dd7b97133329f16ffe55 (diff)
Fix optional integer promotion
-rw-r--r--compile.c13
-rw-r--r--test/optionals.tm21
2 files changed, 28 insertions, 6 deletions
diff --git a/compile.c b/compile.c
index f5ed809d..8da5eba4 100644
--- a/compile.c
+++ b/compile.c
@@ -44,6 +44,7 @@ CORD promote_to_optional(type_t *t, CORD code)
return code;
}
}
+
static bool promote(env_t *env, CORD *code, type_t *actual, type_t *needed)
{
if (type_eq(actual, needed))
@@ -52,6 +53,12 @@ static bool promote(env_t *env, CORD *code, type_t *actual, type_t *needed)
if (!can_promote(actual, needed))
return false;
+ // Optional promotion:
+ if (needed->tag == OptionalType && type_eq(actual, Match(needed, OptionalType)->type)) {
+ *code = promote_to_optional(actual, *code);
+ return true;
+ }
+
if (actual->tag == IntType && needed->tag == BigIntType) {
*code = CORD_all("I(", *code, ")");
return true;
@@ -81,12 +88,6 @@ static bool promote(env_t *env, CORD *code, type_t *actual, type_t *needed)
return promote(env, code, Match(actual, PointerType)->pointed, needed);
}
- // Optional promotion:
- if (needed->tag == OptionalType && type_eq(actual, Match(needed, OptionalType)->type)) {
- *code = promote_to_optional(actual, *code);
- return true;
- }
-
// Stack ref promotion:
if (actual->tag == PointerType && needed->tag == PointerType)
return true;
diff --git a/test/optionals.tm b/test/optionals.tm
index e5ee9bcc..e2cdf9a6 100644
--- a/test/optionals.tm
+++ b/test/optionals.tm
@@ -19,6 +19,12 @@ func maybe_int(should_i:Bool)->Int?:
else:
return !Int
+func maybe_int64(should_i:Bool)->Int64?:
+ if should_i:
+ return 123_i64
+ else:
+ return !Int64
+
func maybe_array(should_i:Bool)->[Int]?:
if should_i:
return [10, 20, 30]
@@ -93,6 +99,21 @@ func main():
do:
!! ...
+ !! Int64s:
+ >> yep := maybe_int64(yes)
+ = 123_i64?
+ >> nope := maybe_int64(no)
+ = !Int64
+ >> if yep:
+ >> yep
+ = 123_i64
+ else: fail("Falsey: $yep")
+ >> if nope:
+ fail("Truthy: $nope")
+ else: !! Falsey: $nope
+
+ do:
+ !! ...
!! Arrays:
>> yep := maybe_array(yes)
= [10, 20, 30]?