1
//! `(error 'code "message")` special form. Lowers to a native wasm
2
//! `struct.new $nomi_condition` + `throw $nomi_error` (Tier 3,
3
//! ADR-0026; an optional third argument is the structured detail), so an
4
//! enclosing `(handler-case)` / `(unwind-protect)` `try_table` can catch it
5
//! in-module. An uncaught raise is caught by the compiler-emitted boundary
6
//! wrapper around each host-invoked body, which bridges it to `__nomi_raise`
7
//! for the classifier. The form never returns normally — execution does not
8
//! continue past the throw.
9

            
10
use crate::ast::{Expr, WasmType};
11
use crate::compiler::context::CompileContext;
12
use crate::compiler::emit::FunctionEmitter;
13
use crate::compiler::expr::{compile_for_stack, compile_for_stack_as, probe_value};
14
use crate::compiler::expr::{fold_value, format_form};
15
use crate::compiler::join::NEVER_RETURNS;
16
use crate::compiler::native::push_anyref_car;
17
use crate::compiler::special::binding::shared::fully_macro_expanded;
18
use crate::error::{Error, Result};
19
use crate::runtime::SymbolTable;
20

            
21
const NAME: &str = "error";
22

            
23
94450
pub(super) fn eval_error(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
24
94450
    expect_arity(args)?;
25
94450
    expect_code_symbol(symbols, &args[0])?;
26
94450
    if let Some(Expr::String(message)) = args.get(1)
27
94450
        && symbols.is_macro_expansion()
28
446
        && !symbols.is_under_any_runtime_guard()
29
    {
30
446
        return Err(Error::Compile(message.clone()));
31
94004
    }
32
94004
    symbols.measurements().note_exit();
33
94004
    Ok(Expr::WasmRuntime(NEVER_RETURNS))
34
94450
}
35

            
36
29211
pub(in crate::compiler) fn compile_error(
37
29211
    ctx: &mut CompileContext,
38
29211
    emit: &mut FunctionEmitter,
39
29211
    symbols: &mut SymbolTable,
40
29211
    args: &[Expr],
41
29211
) -> Result<()> {
42
29211
    emit_raise_call(ctx, emit, symbols, args)
43
29211
}
44

            
45
43275
pub(in crate::compiler) fn compile_error_for_stack(
46
43275
    ctx: &mut CompileContext,
47
43275
    emit: &mut FunctionEmitter,
48
43275
    symbols: &mut SymbolTable,
49
43275
    args: &[Expr],
50
43275
) -> Result<WasmType> {
51
43275
    emit_raise_call(ctx, emit, symbols, args)?;
52
    // The host fn never returns normally, but the wasm validator still
53
    // demands a stack-shaped value of the caller's expected type.
54
    // `unreachable` engages wasm's stack-polymorphism so any branch
55
    // type the IF / COND BlockType picked matches without forcing the
56
    // caller to plumb an expected type down here.
57
41189
    emit.unreachable();
58
41189
    Ok(NEVER_RETURNS)
59
43275
}
60

            
61
72486
fn emit_raise_call(
62
72486
    ctx: &mut CompileContext,
63
72486
    emit: &mut FunctionEmitter,
64
72486
    symbols: &mut SymbolTable,
65
72486
    args: &[Expr],
66
72486
) -> Result<()> {
67
72486
    expect_arity(args)?;
68
71651
    let code = expect_code_symbol(symbols, &args[0])?;
69
71430
    push_string_literal(ctx, emit, &code)?;
70
71430
    push_message(ctx, emit, symbols, &args[1])?;
71
    // The detail is evaluated before the message check (CL argument order);
72
    // it waits in a local while the check runs on the message.
73
70390
    push_detail(ctx, emit, symbols, args.get(2))?;
74
70390
    let detail = ctx.alloc_local(WasmType::AnyRef)?;
75
70390
    emit.local_set(detail);
76
    // A Bool-typed message is a compile-time type error; this guards a
77
    // nil-able message (e.g. an `if` whose branch is nil) at runtime —
78
    // `TYPE-ERROR` instead of a condition with no readable message.
79
    // A real "" message stays valid.
80
70390
    crate::compiler::native::nullable::require_non_null(
81
70390
        ctx,
82
70390
        emit,
83
70390
        WasmType::StringRef,
84
70390
        ctx.ids.nil_string,
85
70390
    )?;
86
    // code + message + detail are on the stack in field order; pack them
87
    // into a `$nomi_condition` and throw `$nomi_error`. Catchable by an
88
    // in-module `try_table`; the boundary wrapper bridges an uncaught
89
    // throw to `__nomi_raise`.
90
70390
    emit.local_get(detail);
91
70390
    emit.struct_new(ctx.condition_type_idx());
92
70390
    emit.throw(ctx.nomi_error_tag()?);
93
70390
    Ok(())
94
72486
}
95

            
96
/// Pushes the optional detail as an `anyref`; an absent one is nil.
97
70390
fn push_detail(
98
70390
    ctx: &mut CompileContext,
99
70390
    emit: &mut FunctionEmitter,
100
70390
    symbols: &mut SymbolTable,
101
70390
    detail: Option<&Expr>,
102
70390
) -> Result<()> {
103
70390
    match detail {
104
3985
        Some(form) => push_anyref_car(ctx, emit, symbols, form),
105
        None => {
106
66405
            emit.ref_null_any();
107
66405
            Ok(())
108
        }
109
    }
110
70390
}
111

            
112
/// Pushes the message as a `StringRef`; a literal `nil` lowers to a nullable
113
/// one (ADR-0033 Phase 5), and a message of any other type is a compile error.
114
71430
fn push_message(
115
71430
    ctx: &mut CompileContext,
116
71430
    emit: &mut FunctionEmitter,
117
71430
    symbols: &mut SymbolTable,
118
71430
    message: &Expr,
119
71430
) -> Result<()> {
120
71430
    if matches!(probe_value(&mut symbols.clone(), message)?, Expr::Nil) {
121
208
        return compile_for_stack_as(ctx, emit, symbols, message, WasmType::StringRef);
122
71222
    }
123
71222
    match compile_for_stack(ctx, emit, symbols, message)? {
124
70182
        WasmType::StringRef => Ok(()),
125
832
        ty => emit.reject_if_live(message_type_error(ty)),
126
    }
127
71430
}
128

            
129
832
fn message_type_error(ty: WasmType) -> Error {
130
832
    Error::Type {
131
832
        expected: format!("a string message for '{NAME}'"),
132
832
        actual: ty.to_string(),
133
832
    }
134
832
}
135

            
136
185780
pub(in crate::compiler) fn push_string_literal(
137
185780
    ctx: &mut CompileContext,
138
185780
    emit: &mut FunctionEmitter,
139
185780
    value: &str,
140
185780
) -> Result<()> {
141
185780
    let data_idx = ctx.add_data(value.as_bytes())?;
142
185780
    emit.i32_const(0);
143
185780
    emit.i32_const(value.len() as i32);
144
185780
    emit.array_new_data(ctx.ids.ty_i8_array, data_idx);
145
185780
    Ok(())
146
185780
}
147

            
148
166936
fn expect_arity(args: &[Expr]) -> Result<()> {
149
166936
    let expected = args.len().clamp(2, 3);
150
166936
    if args.len() != expected {
151
835
        return Err(Error::Arity {
152
835
            name: NAME.to_string(),
153
835
            expected,
154
835
            actual: args.len(),
155
835
        });
156
166101
    }
157
166101
    Ok(())
158
166936
}
159

            
160
166101
fn expect_code_symbol(symbols: &mut SymbolTable, arg: &Expr) -> Result<String> {
161
166101
    let arg = &fully_macro_expanded(symbols, arg)?;
162
166101
    let datum = match arg {
163
165636
        Expr::Quote(inner) | Expr::Datum(inner) => inner.as_ref().clone(),
164
247
        Expr::List(_) => match fold_value(symbols, arg)? {
165
247
            Some(Expr::Datum(inner)) => *inner,
166
            _ => arg.clone(),
167
        },
168
218
        other => other.clone(),
169
    };
170
166101
    match datum {
171
165880
        Expr::Symbol(name) if !matches!(arg, Expr::Symbol(_)) => Ok(name),
172
221
        other => Err(Error::Type {
173
221
            expected: format!("quoted symbol for argument 0 of '{NAME}'"),
174
221
            actual: format_form(&other),
175
221
        }),
176
    }
177
166101
}