Lines
98.5 %
Functions
87.5 %
Branches
100 %
//! `(the TYPE form)`: the checked narrowing of an `any` value (CL `THE`).
//! TYPE is `index`, `scalar`, `money` or `string`. A statically typed form
//! must already be of that type — `THE` narrows, it never converts; a runtime
//! `AnyRef` is tested and throws a catchable `TYPE-ERROR` on a mismatch.
use super::NativeSpec;
use super::list::emit_pair_car_downcast;
use crate::ast::{Expr, Number, PairElement, WasmType};
use crate::compiler::context::CompileContext;
use crate::compiler::emit::FunctionEmitter;
use crate::compiler::expr::{
compile_for_stack, compile_index_operand, compile_ratio_operand, eval_value, format_expr,
probe_value,
};
use crate::error::{Error, Result, with_article};
use crate::runtime::{DOTIMES_COUNT, SymbolTable};
use wasm_encoder::{BlockType, HeapType};
pub(super) const NATIVES: &[NativeSpec] = &[NativeSpec {
name: "THE",
eval: the_eval,
stack: Some(compile_the_to_stack),
effect: None,
}];
/// Who asked for the narrowing, so a refusal names what the user wrote.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Subject {
The,
DotimesCount,
}
pub(in crate::compiler) enum Target {
Index,
Scalar,
Money,
String,
impl Target {
fn parse(name: &str) -> Result<(Self, Subject)> {
match name.to_ascii_lowercase().as_str() {
"index" => Ok((Self::Index, Subject::The)),
"scalar" => Ok((Self::Scalar, Subject::The)),
"money" => Ok((Self::Money, Subject::The)),
"string" => Ok((Self::String, Subject::The)),
_ if name.eq_ignore_ascii_case(DOTIMES_COUNT) => {
Ok((Self::Index, Subject::DotimesCount))
_ => Err(Error::Compile(format!(
"THE type must be one of index, scalar, money, string, got {name}"
))),
/// The target whose narrowed value has type `ty`.
pub(in crate::compiler) fn from_wasm(ty: WasmType) -> Option<Self> {
match ty {
WasmType::I32 => Some(Self::Index),
WasmType::Ratio => Some(Self::Scalar),
WasmType::Commodity => Some(Self::Money),
WasmType::StringRef => Some(Self::String),
_ => None,
fn wasm(self) -> WasmType {
match self {
Self::Index => WasmType::I32,
Self::Scalar => WasmType::Ratio,
Self::Money => WasmType::Commodity,
Self::String => WasmType::StringRef,
fn element(self) -> PairElement {
Self::Index => PairElement::I32,
Self::Scalar => PairElement::Ratio,
Self::Money => PairElement::Commodity,
Self::String => PairElement::StringRef,
fn word(self) -> &'static str {
Self::Index => "index",
Self::Scalar => "scalar",
Self::Money => "money",
Self::String => "string",
fn mismatch(self, subject: Subject, got: &str) -> Error {
let article = with_article(self.word());
let message = match subject {
Subject::The => format!(
"THE {} expects {article} value, got {got}; THE narrows, it never converts",
self.word()
),
Subject::DotimesCount => format!("DOTIMES count expects {article} value, got {got}"),
Self::String => Error::Compile(message),
_ => Error::Dimension(message),
/// The type a `(the TYPE form)` call lowers to, for the stack-type classifier.
pub(in crate::compiler) fn the_result_type(elems: &[Expr]) -> Option<WasmType> {
match elems {
[Expr::Symbol(head), Expr::Symbol(name), _] if head.eq_ignore_ascii_case("THE") => {
Target::parse(name).ok().map(|(target, _)| target.wasm())
fn parse_args(args: &[Expr]) -> Result<(Target, Subject, &Expr)> {
match args {
[Expr::Symbol(name), form] => {
let (target, subject) = Target::parse(name)?;
Ok((target, subject, form))
[_, _] => Err(Error::Compile(
"THE type must be one of index, scalar, money, string".to_string(),
)),
_ => Err(Error::Arity {
name: "THE".to_string(),
expected: 2,
actual: args.len(),
}),
fn the_eval(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
let (target, subject, form) = parse_args(args)?;
let value = eval_value(symbols, form)?;
let want = target.wasm();
match (&value, target) {
(Expr::Number(Number::Index(_)), Target::Index)
| (Expr::Number(Number::Scalar(_)), Target::Scalar) => Ok(value),
(Expr::Number(Number::Index(_)), Target::Scalar) => Ok(Expr::WasmRuntime(want)),
(Expr::Number(Number::Scalar(_)), Target::Index) => {
Err(target.mismatch(subject, &WasmType::Ratio.to_string()))
(Expr::String(_), Target::String) => Ok(value),
_ => match value.wasm_type() {
Some(ty) if ty == want => Ok(value),
Some(WasmType::AnyRef) => Ok(Expr::WasmRuntime(want)),
Some(ty) => Err(target.mismatch(subject, &ty.to_string())),
None => Err(target.mismatch(subject, &format_expr(&value))),
},
fn compile_the_to_stack(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
symbols: &mut SymbolTable,
args: &[Expr],
) -> Result<WasmType> {
if let Expr::Number(n) = probe_value(&mut symbols.clone(), form)? {
match target {
Target::Index if matches!(n, Number::Scalar(_)) => {
emit.reject_if_live(target.mismatch(subject, &WasmType::Ratio.to_string()))?;
Target::Index => compile_index_operand(ctx, emit, symbols, form)?,
Target::Scalar => compile_ratio_operand(ctx, emit, symbols, form)?,
Target::Money | Target::String => {
emit.reject_if_live(target.mismatch(subject, "a number literal"))?;
return Ok(want);
match compile_for_stack(ctx, emit, symbols, form)? {
ty if ty == want => {}
WasmType::AnyRef => emit_narrow(ctx, emit, target)?,
ty => emit.reject_if_live(target.mismatch(subject, &ty.to_string()))?,
Ok(want)
/// Tests the `AnyRef` on the stack for `target` (a non-null instance) and
/// casts it, throwing the target's `TYPE-ERROR` otherwise.
pub(in crate::compiler) fn emit_narrow(
target: Target,
) -> Result<()> {
let local = ctx.alloc_local(WasmType::AnyRef)?;
emit.local_tee(local);
let (heap, throw) = match target {
Target::Index => (HeapType::I31, ctx.ids.not_an_index),
Target::Scalar => (HeapType::Concrete(ctx.ids.ty_ratio), ctx.ids.not_a_scalar),
Target::Money => (HeapType::Concrete(ctx.ids.ty_commodity), ctx.ids.not_money),
Target::String => (
HeapType::Concrete(ctx.ids.ty_i8_array),
ctx.ids.not_a_string,
emit.ref_test_non_null(heap);
emit.if_block(BlockType::Result(ctx.wasm_val_type(target.wasm())?));
emit.local_get(local);
emit_pair_car_downcast(ctx, emit, target.element())?;
emit.else_block();
emit.call(throw);
emit.unreachable();
emit.block_end()
#[cfg(test)]
#[path = "the_tests.rs"]
mod tests;