Use assert for type checking

This commit is contained in:
2025-06-19 21:38:34 +10:00
parent 1c821d8804
commit 1ebeaa9e95
4 changed files with 23 additions and 31 deletions

View File

@@ -146,14 +146,14 @@ impl Visitor {
//
if let Expr::Cast(cast) = expr {
let arg = (*cast.expr).clone();
let mut init: Option<Stmt> = None;
let mut prelude: Option<Stmt> = None;
let ty: LuaType = (&*cast.ty).try_into()?;
let ty_str = format!("{ty}");
let (ident, msg) = match unwrap_expr_ident(&arg).ok() {
Some(ident) => (ident.clone(), format!("{ty} expected in '{ident}', got ")),
None => {
let ident = Ident::new("_", arg.span());
init = Some(parse_quote! { let #ident = #arg; });
prelude = Some(parse_quote! { let #ident = #arg; });
(ident, format!("{ty} expected, got "))
}
};
@@ -163,40 +163,32 @@ impl Visitor {
*expr = match ty {
LuaType::Any => parse_quote_spanned!(span => {}),
LuaType::Nil => parse_quote_spanned!(span => {
#init
if #ident != () {
return error(concat!(#msg, r#type(#ident)));
}
#prelude
assert(#ident == (), concat!(#msg, r#type(#ident)));
}),
LuaType::Number => parse_quote_spanned!(span => {
#init
#prelude
let #tmp = #ident;
#ident = tonumber(#ident);
if #ident == () {
return error(concat!(#msg, r#type(#tmp)));
}
assert(#ident != (), concat!(#msg, r#type(#tmp)));
}),
LuaType::Integer => parse_quote_spanned!(span => {
#init
#prelude
let #tmp = #ident;
#ident = tonumber(#ident);
if #ident == () || math::floor(#ident) != #ident {
return error(concat!(#msg, r#type(#tmp)));
}
assert(#ident != () && math::floor(#ident) == #ident, concat!(#msg, r#type(#tmp)));
}),
LuaType::String => parse_quote_spanned!(span => {
#init
#prelude
if r#type(#ident) == "number" {
#ident = tostring(#ident);
} else if r#type(#ident) != "string" {
return error(concat!(#msg, r#type(#ident)));
} else {
assert(r#type(#ident) == "string", concat!(#msg, r#type(#ident)));
}
}),
_ => parse_quote_spanned!(span => {
#init
if r#type(#ident) != #ty_str {
return error(concat!(#msg, r#type(#ident)));
}
#prelude
assert(r#type(#ident) == #ty_str, concat!(#msg, r#type(#ident)));
}),
}
}