Explorer: assert Optional not empty on Get() (#2587)

Prevent from unwrapping an empty Optional
This commit is contained in:
Adrien Leravat
2023-02-09 22:39:43 -08:00
committed by GitHub
parent b2c60b4f53
commit 266fa401e6
2 changed files with 41 additions and 21 deletions
+26 -21
View File
@@ -663,8 +663,27 @@ impl i32 as Dec {
}
}
// ------------------------
// Miscellaneous utilities.
// ------------------------
// Note that Print is experimental, and not part of an accepted proposal, but
// is included here for printing state in tests.
// TODO: Remove Print special casing once we have variadics or overloads.
// fn Print(format_str: String) {
// __intrinsic_print(format_str);
// }
fn Assert(condition: bool, message: String){
__intrinsic_assert(condition, message);
}
fn Rand(low: i32, high: i32) -> i32{
return __intrinsic_rand(low,high);
}
//-------------------------
// Optional
// Optional.
//-------------------------
choice OptionalElement(T:! type) {
None(),
@@ -687,37 +706,23 @@ class Optional(T:! type) {
}
fn Get[self: Self]() -> T {
var y: T;
match(self.element) {
case OptionalElement(T).Element(x: T) => {
return x;
}
}
// TODO: Use assert as soon as available
Assert(false, "Attempted to unwrap empty Optional");
// TODO: Drop uninitialized variable & return when we can flag unreachable paths.
var y: T;
return y;
}
var element: OptionalElement(T);
}
// ------------------------
// Miscellaneous utilities.
// ------------------------
// Note that Print is experimental, and not part of an accepted proposal, but
// is included here for printing state in tests.
// TODO: Remove Print special casing once we have variadics or overloads.
// fn Print(format_str: String) {
// __intrinsic_print(format_str);
// }
fn Assert(condition: bool, message: String){
__intrinsic_assert(condition, message);
}
fn Rand(low: i32, high: i32) -> i32{
return __intrinsic_rand(low,high);
}
//-------------------------
// Heap.
//-------------------------
class Heap {
fn New[T:! type, self: Self](x : T) -> T* {