use std::sync::Arc;
use crate::codegen::backend::{CodegenError, CodegenResult};
use crate::codegen::builder::values;
use crate::codegen::ir::*;
use super::MirLowerer;
pub(super) enum UnwrapFail {
Fixed(&'static str),
FixedWithErr(&'static str, MirType),
Expect(MirValue),
ExpectWithErr(MirValue, MirType),
}
fn err_kind(ty: &MirType) -> i128 {
match ty {
MirType::Struct(n) if n.as_ref() == "BuildString" => 1,
MirType::Int(IntSize::I128, _) => 0,
MirType::Int(_, true) => 2,
MirType::Int(_, false) => 3,
MirType::Float(_) => 4,
_ => 0,
}
}
impl MirLowerer<'_> {
pub(super) fn trap_unless(
&mut self,
scrut: LocalId,
flag: &str,
want: bool,
fail: UnwrapFail,
) -> CodegenResult<()> {
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
let present = builder.create_local(MirType::Bool);
builder.assign(
present,
MirRValue::FieldAccess {
base: values::local(scrut),
field_name: Arc::from(flag),
field_ty: MirType::Bool,
},
);
let ok_bb = builder.create_block();
let fail_bb = builder.create_block();
if want {
builder.branch(values::local(present), ok_bb, fail_bb);
} else {
builder.branch(values::local(present), fail_bb, ok_bb);
}
builder.switch_to_block(fail_bb);
let (func, args) = match fail {
UnwrapFail::Fixed(msg) => {
let idx = self.module.intern_string(Arc::from(msg));
("bl_unwrap_none", vec![MirValue::Const(MirConst::Str(idx))])
}
UnwrapFail::FixedWithErr(msg, ty) => {
let idx = self.module.intern_string(Arc::from(msg));
(
"bl_unwrap_fail",
vec![
MirValue::Const(MirConst::Str(idx)),
values::local(scrut),
MirValue::Const(MirConst::Int(err_kind(&ty), MirType::i32())),
],
)
}
UnwrapFail::Expect(msg) => ("bl_expect_none", vec![msg]),
UnwrapFail::ExpectWithErr(msg, ty) => (
"bl_expect_fail",
vec![
msg,
values::local(scrut),
MirValue::Const(MirConst::Int(err_kind(&ty), MirType::i32())),
],
),
};
let builder = self.current_fn.as_mut().unwrap();
let dead = builder.create_block();
builder.call(MirValue::Function(Arc::from(func)), args, None, dead);
builder.switch_to_block(dead);
builder.abort();
builder.switch_to_block(ok_bb);
Ok(())
}
}