nac3core/artiq: raise ValueError for unwrap none

This commit is contained in:
ychenfo 2022-03-26 01:44:50 +08:00
parent 91d697c327
commit aebfd0a37d
3 changed files with 23 additions and 6 deletions

View File

@ -46,6 +46,8 @@ class Option(Generic[T]):
return not self.is_none() return not self.is_none()
def unwrap(self): def unwrap(self):
if self.is_none():
raise ValueError("unwrap on none")
return self._nac3_option return self._nac3_option
def __repr__(self) -> str: def __repr__(self) -> str:

View File

@ -1309,6 +1309,26 @@ pub fn gen_expr<'ctx, 'a, G: CodeGenerator>(
unreachable!() unreachable!()
} }
}; };
// directly generate code for option.unwrap
// since it needs location information from ast
if attr == &"unwrap".into()
&& id == ctx.primitives.option.get_obj_id(&ctx.unifier)
{
if let BasicValueEnum::PointerValue(ptr) = val.to_basic_value_enum(ctx, generator)? {
let not_null = ctx.builder.build_is_not_null(ptr, "unwrap_not_null");
ctx.make_assert(
generator,
not_null,
"0:ValueError",
"unwrap on none",
[None, None, None],
expr.location,
);
return Ok(Some(ctx.builder.build_load(ptr, "unwrap_some").into()))
} else {
unreachable!("option must be ptr")
}
}
return Ok(generator return Ok(generator
.gen_call( .gen_call(
ctx, ctx,

View File

@ -263,12 +263,7 @@ pub fn get_builtins(primitives: &mut (PrimitiveStore, Unifier)) -> BuiltinInfo {
resolver: None, resolver: None,
codegen_callback: Some(Arc::new(GenCall::new(Box::new( codegen_callback: Some(Arc::new(GenCall::new(Box::new(
|ctx, obj, _, _, generator| { |ctx, obj, _, _, generator| {
let obj_val = obj.unwrap().1.clone().to_basic_value_enum(ctx, generator)?; unreachable!("handled in gen_expr")
if let BasicValueEnum::PointerValue(ptr) = obj_val {
Ok(Some(ctx.builder.build_load(ptr, "unwrap_some")))
} else {
unreachable!("option must be ptr")
}
}, },
)))), )))),
loc: None, loc: None,