Lines
100 %
Functions
Branches
//! `NOT` and `NULL?` predicates. Both natives short-circuit at compile time
//! on constant operands and emit a wasm `i32_eqz` / `ref.is_null` check on
//! runtime values.
use crate::ast::{Expr, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
NilRepr, compile_for_stack, eval_value, fold_call, nil_repr, serialize_stack_to_output,
};
use crate::error::{Error, Result};
use crate::runtime::SymbolTable;
use super::shared::{bool_result, emit_bool};
pub(super) fn not_fn(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
if args.len() != 1 {
return Err(Error::Arity {
name: "NOT".to_string(),
expected: 1,
actual: args.len(),
});
}
let val = eval_value(symbols, &args[0])?;
if val.wasm_type().is_some() {
return Ok(Expr::WasmRuntime(WasmType::Bool));
Ok(bool_result(val.is_nil()))
pub(super) fn null_p(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
name: "NULL?".to_string(),
Ok(bool_result(matches!(val, Expr::Nil)))
pub(super) fn compile_not(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<()> {
check_arity("NOT", args)?;
if let Some(folded) = fold_call(symbols, "NOT", args)? {
return emit_bool(ctx, emit, !folded.is_nil());
let ty = compile_nil_test(ctx, emit, symbols, &args[0])?;
serialize_stack_to_output(ctx, emit, ty)
fn check_arity(name: &str, args: &[Expr]) -> Result<()> {
if args.len() == 1 {
return Ok(());
Err(Error::Arity {
name: name.to_string(),
})
/// Compiles `arg` and tests the result for nil.
fn compile_nil_test(
arg: &Expr,
) -> Result<WasmType> {
let ty = compile_for_stack(ctx, emit, symbols, arg)?;
emit_nil_test(emit, &ty);
Ok(WasmType::Bool)
pub(super) fn compile_null_p(
check_arity("NULL?", args)?;
if let Some(folded) = fold_call(symbols, "NULL?", args)? {
pub(super) fn compile_not_to_stack(
emit.i32_const(i32::from(!folded.is_nil()));
return Ok(WasmType::Bool);
compile_nil_test(ctx, emit, symbols, &args[0])
/// A bool is nil at zero, every reference (a pair, a string, an anyref cell's
/// null nil, …) at null, and an index is never nil (a count of zero is still a
/// count) — its operand runs for effect and the test is false.
fn emit_nil_test(emit: &mut FunctionEmitter, ty: &WasmType) {
match nil_repr(ty) {
NilRepr::Never => {
emit.drop_value();
emit.i32_const(0);
NilRepr::I32Zero => emit.i32_eqz(),
NilRepr::Null => emit.ref_is_null(),
pub(super) fn compile_null_p_to_stack(