mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-10-06 09:14:42 +01:00
Explorer: assert Optional not empty on Get() (#2587)
Prevent from unwrapping an empty Optional
This commit is contained in:
@@ -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* {
|
||||
|
||||
Reference in New Issue
Block a user