1
//! `SYMBOLP`, `KEYWORDP` and `SYMBOL-NAME`. `nil` and `t` are symbols. A
2
//! static operand folds; a runtime `SymbolRef` or `Bool` has its answer from
3
//! its type, and an `AnyRef` is tested for its shape (`nil` is `ref.null`, `t`
4
//! the `$t` singleton, a symbol a `$symbol`).
5

            
6
use super::NativeSpec;
7
use super::comparison::bool_result;
8
use crate::ast::{Expr, WasmType};
9
use crate::compiler::context::CompileContext;
10
use crate::compiler::emit::FunctionEmitter;
11
use crate::compiler::expr::{
12
    NilRepr, compile_for_stack, describe_operand, eval_value, fold_call, nil_repr,
13
};
14
use crate::error::{Error, Result};
15
use crate::runtime::SymbolTable;
16
use wasm_encoder::BlockType;
17

            
18
pub(super) const NATIVES: &[NativeSpec] = &[
19
    NativeSpec {
20
        name: "SYMBOLP",
21
        eval: symbolp,
22
        stack: Some(compile_symbolp_to_stack),
23
        effect: None,
24
    },
25
    NativeSpec {
26
        name: "KEYWORDP",
27
        eval: keywordp,
28
        stack: Some(compile_keywordp_to_stack),
29
        effect: None,
30
    },
31
    NativeSpec {
32
        name: "SYMBOL-NAME",
33
        eval: symbol_name,
34
        stack: Some(compile_symbol_name_to_stack),
35
        effect: None,
36
    },
37
];
38

            
39
/// What an evaluated operand is, as far as the symbol natives can tell.
40
enum Operand {
41
    Symbol { name: String, keyword: bool },
42
    Other,
43
    Runtime(WasmType),
44
}
45

            
46
114
fn symbol_operand(name: &str, keyword: bool) -> Operand {
47
114
    Operand::Symbol {
48
114
        name: name.to_string(),
49
114
        keyword,
50
114
    }
51
114
}
52

            
53
255
fn classify(value: &Expr) -> Operand {
54
255
    if let Some(ty) = value.wasm_type() {
55
66
        return Operand::Runtime(ty);
56
189
    }
57
189
    match value {
58
30
        Expr::Nil => symbol_operand("NIL", false),
59
33
        Expr::T => symbol_operand("T", false),
60
        Expr::Symbol(name) => symbol_operand(name, false),
61
34
        Expr::Keyword(name) => symbol_operand(name, true),
62
31
        Expr::Datum(inner) | Expr::Quote(inner) => match inner.as_ref() {
63
17
            Expr::Symbol(name) => symbol_operand(name, false),
64
            Expr::Keyword(name) => symbol_operand(name, true),
65
14
            _ => Operand::Other,
66
        },
67
61
        _ => Operand::Other,
68
    }
69
255
}
70

            
71
343
fn check_arity(name: &str, args: &[Expr]) -> Result<()> {
72
343
    if args.len() == 1 {
73
340
        return Ok(());
74
3
    }
75
3
    Err(Error::Arity {
76
3
        name: name.to_string(),
77
3
        expected: 1,
78
3
        actual: args.len(),
79
3
    })
80
343
}
81

            
82
258
fn operand(symbols: &mut SymbolTable, name: &str, args: &[Expr]) -> Result<Operand> {
83
258
    check_arity(name, args)?;
84
255
    eval_value(symbols, &args[0]).map(|value| classify(&value))
85
258
}
86

            
87
113
fn symbolp(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
88
113
    Ok(match operand(symbols, "SYMBOLP", args)? {
89
38
        Operand::Symbol { .. } => bool_result(true),
90
52
        Operand::Other => bool_result(false),
91
22
        Operand::Runtime(_) => Expr::WasmRuntime(WasmType::Bool),
92
    })
93
113
}
94

            
95
56
fn keywordp(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
96
56
    Ok(match operand(symbols, "KEYWORDP", args)? {
97
29
        Operand::Symbol { keyword, .. } => bool_result(keyword),
98
17
        Operand::Other => bool_result(false),
99
9
        Operand::Runtime(_) => Expr::WasmRuntime(WasmType::Bool),
100
    })
101
56
}
102

            
103
89
fn symbol_name(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
104
89
    match operand(symbols, "SYMBOL-NAME", args)? {
105
47
        Operand::Symbol { name, .. } => Ok(Expr::String(name)),
106
35
        Operand::Runtime(ty) if names_a_symbol(ty) => Ok(Expr::WasmRuntime(WasmType::StringRef)),
107
1
        Operand::Runtime(ty) => Err(not_a_symbol(&ty.to_string())),
108
6
        Operand::Other => Err(not_a_symbol("a non-symbol value")),
109
    }
110
89
}
111

            
112
62
fn names_a_symbol(ty: WasmType) -> bool {
113
62
    matches!(ty, WasmType::Bool | WasmType::SymbolRef | WasmType::AnyRef)
114
62
}
115

            
116
11
fn not_a_symbol(got: &str) -> Error {
117
11
    Error::Compile(format!("SYMBOL-NAME expects a symbol, got {got}"))
118
11
}
119

            
120
39
fn compile_symbolp_to_stack(
121
39
    ctx: &mut CompileContext,
122
39
    emit: &mut FunctionEmitter,
123
39
    symbols: &mut SymbolTable,
124
39
    args: &[Expr],
125
39
) -> Result<WasmType> {
126
39
    check_arity("SYMBOLP", args)?;
127
39
    if let Some(folded) = fold_call(symbols, "SYMBOLP", args)? {
128
16
        emit.i32_const(i32::from(!folded.is_nil()));
129
16
        return Ok(WasmType::Bool);
130
23
    }
131
23
    let ty = compile_for_stack(ctx, emit, symbols, &args[0])?;
132
23
    emit_symbolp(ctx, emit, ty)?;
133
23
    Ok(WasmType::Bool)
134
39
}
135

            
136
23
fn emit_symbolp(ctx: &mut CompileContext, emit: &mut FunctionEmitter, ty: WasmType) -> Result<()> {
137
23
    match ty {
138
16
        WasmType::Bool | WasmType::SymbolRef => emit_constant(emit, true),
139
        WasmType::AnyRef => {
140
3
            let local = ctx.alloc_local(ty)?;
141
3
            emit.local_tee(local);
142
3
            emit.ref_test(ctx.ids.ty_symbol);
143
3
            emit.local_get(local);
144
3
            emit.ref_cast_eq();
145
3
            emit.global_get(ctx.ids.global_t);
146
3
            emit.ref_eq();
147
3
            emit.i32_or();
148
        }
149
4
        _ => match nil_repr(&ty) {
150
            NilRepr::Null => emit.ref_is_null(),
151
4
            NilRepr::Never | NilRepr::I32Zero => emit_constant(emit, false),
152
        },
153
    }
154
23
    Ok(())
155
23
}
156

            
157
/// Replaces the operand on top of the stack with a constant truth value.
158
24
fn emit_constant(emit: &mut FunctionEmitter, value: bool) {
159
24
    emit.drop_value();
160
24
    emit.i32_const(i32::from(value));
161
24
}
162

            
163
14
fn compile_keywordp_to_stack(
164
14
    ctx: &mut CompileContext,
165
14
    emit: &mut FunctionEmitter,
166
14
    symbols: &mut SymbolTable,
167
14
    args: &[Expr],
168
14
) -> Result<WasmType> {
169
14
    check_arity("KEYWORDP", args)?;
170
14
    if let Some(folded) = fold_call(symbols, "KEYWORDP", args)? {
171
6
        emit.i32_const(i32::from(!folded.is_nil()));
172
6
        return Ok(WasmType::Bool);
173
8
    }
174
8
    let ty = compile_for_stack(ctx, emit, symbols, &args[0])?;
175
8
    emit_keywordp(ctx, emit, ty)?;
176
8
    Ok(WasmType::Bool)
177
14
}
178

            
179
8
fn emit_keywordp(ctx: &mut CompileContext, emit: &mut FunctionEmitter, ty: WasmType) -> Result<()> {
180
8
    match ty {
181
4
        WasmType::SymbolRef => emit.call(ctx.ids.symbol_keyword_p),
182
        WasmType::AnyRef => {
183
            let local = ctx.alloc_local(ty)?;
184
            emit.local_tee(local);
185
            emit.ref_test(ctx.ids.ty_symbol);
186
            emit.if_block(BlockType::Result(wasm_encoder::ValType::I32));
187
            emit.local_get(local);
188
            emit.ref_cast_nullable(ctx.ids.ty_symbol);
189
            emit.call(ctx.ids.symbol_keyword_p);
190
            emit.else_block();
191
            emit.i32_const(0);
192
            emit.block_end()?;
193
        }
194
4
        _ => emit_constant(emit, false),
195
    }
196
8
    Ok(())
197
8
}
198

            
199
32
fn compile_symbol_name_to_stack(
200
32
    ctx: &mut CompileContext,
201
32
    emit: &mut FunctionEmitter,
202
32
    symbols: &mut SymbolTable,
203
32
    args: &[Expr],
204
32
) -> Result<WasmType> {
205
32
    check_arity("SYMBOL-NAME", args)?;
206
32
    if let Some(Expr::String(name)) = fold_call(symbols, "SYMBOL-NAME", args)? {
207
5
        return compile_for_stack(ctx, emit, symbols, &Expr::String(name));
208
27
    }
209
27
    let ty = compile_for_stack(ctx, emit, symbols, &args[0])?;
210
27
    if !names_a_symbol(ty) {
211
4
        let got = describe_operand(symbols, &args[0], ty);
212
4
        emit.reject_if_live(not_a_symbol(&got))?;
213
        return Ok(WasmType::StringRef);
214
23
    }
215
23
    emit_symbol_name(ctx, emit, symbols, ty)?;
216
23
    Ok(WasmType::StringRef)
217
32
}
218

            
219
23
fn emit_symbol_name(
220
23
    ctx: &mut CompileContext,
221
23
    emit: &mut FunctionEmitter,
222
23
    symbols: &mut SymbolTable,
223
23
    ty: WasmType,
224
23
) -> Result<()> {
225
23
    let string = BlockType::Result(ctx.string_ref());
226
23
    match ty {
227
        WasmType::Bool => {
228
7
            emit.if_block(string);
229
7
            push_name(ctx, emit, symbols, "T")?;
230
7
            emit.else_block();
231
7
            push_name(ctx, emit, symbols, "NIL")?;
232
7
            emit.block_end()
233
        }
234
        WasmType::SymbolRef => {
235
10
            let local = ctx.alloc_local(ty)?;
236
10
            emit.local_tee(local);
237
10
            emit.ref_is_null();
238
10
            emit.if_block(string);
239
10
            push_name(ctx, emit, symbols, "NIL")?;
240
10
            emit.else_block();
241
10
            emit.local_get(local);
242
10
            emit.call(ctx.ids.symbol_designator);
243
10
            emit.block_end()
244
        }
245
6
        _ => emit_any_symbol_name(ctx, emit, symbols, ty, string),
246
    }
247
23
}
248

            
249
/// An `AnyRef` operand: `nil`, `t` or a `$symbol` names itself, anything else
250
/// throws a catchable `TYPE-ERROR`.
251
6
fn emit_any_symbol_name(
252
6
    ctx: &mut CompileContext,
253
6
    emit: &mut FunctionEmitter,
254
6
    symbols: &mut SymbolTable,
255
6
    ty: WasmType,
256
6
    string: BlockType,
257
6
) -> Result<()> {
258
6
    let local = ctx.alloc_local(ty)?;
259
6
    emit.local_tee(local);
260
6
    emit.ref_is_null();
261
6
    emit.if_block(string);
262
6
    push_name(ctx, emit, symbols, "NIL")?;
263
6
    emit.else_block();
264
6
    emit.local_get(local);
265
6
    emit.ref_test(ctx.ids.ty_symbol);
266
6
    emit.if_block(string);
267
6
    emit.local_get(local);
268
6
    emit.ref_cast_nullable(ctx.ids.ty_symbol);
269
6
    emit.call(ctx.ids.symbol_designator);
270
6
    emit.else_block();
271
6
    emit.local_get(local);
272
6
    emit.ref_cast_eq();
273
6
    emit.global_get(ctx.ids.global_t);
274
6
    emit.ref_eq();
275
6
    emit.if_block(string);
276
6
    push_name(ctx, emit, symbols, "T")?;
277
6
    emit.else_block();
278
6
    emit.call(ctx.ids.not_a_symbol);
279
6
    emit.unreachable();
280
6
    emit.block_end()?;
281
6
    emit.block_end()?;
282
6
    emit.block_end()
283
6
}
284

            
285
36
fn push_name(
286
36
    ctx: &mut CompileContext,
287
36
    emit: &mut FunctionEmitter,
288
36
    symbols: &mut SymbolTable,
289
36
    name: &str,
290
36
) -> Result<()> {
291
36
    compile_for_stack(ctx, emit, symbols, &Expr::String(name.to_string())).map(drop)
292
36
}
293

            
294
#[cfg(test)]
295
#[path = "symbol_tests.rs"]
296
mod tests;