1
//! `ZEROP`, `PLUSP`, `MINUSP` (CL): the sign of an index, scalar or money.
2
//! An index is tested on its i32; a scalar or money on its numerator, since a
3
//! canonical denominator is positive — so money needs no currency and a
4
//! compound unit term is answered too. An `any` operand must be narrowed with
5
//! `THE` first.
6

            
7
use super::NativeSpec;
8
use super::comparison::bool_result;
9
use super::convert::one_arg;
10
use crate::ast::{Expr, Number, WasmType};
11
use crate::compiler::context::CompileContext;
12
use crate::compiler::emit::FunctionEmitter;
13
use crate::compiler::expr::{compile_for_stack, eval_value, fold_call, format_expr, index_literal};
14
use crate::error::{Error, Result};
15
use crate::runtime::SymbolTable;
16

            
17
pub(super) const NATIVES: &[NativeSpec] = &[
18
    NativeSpec {
19
        name: "ZEROP",
20
        eval: zerop_eval,
21
        stack: Some(compile_zerop),
22
        effect: None,
23
    },
24
    NativeSpec {
25
        name: "PLUSP",
26
        eval: plusp_eval,
27
        stack: Some(compile_plusp),
28
        effect: None,
29
    },
30
    NativeSpec {
31
        name: "MINUSP",
32
        eval: minusp_eval,
33
        stack: Some(compile_minusp),
34
        effect: None,
35
    },
36
];
37

            
38
/// The `$ratio` and `$commodity` structs both keep the numerator in field 0.
39
const NUMERATOR: u32 = 0;
40

            
41
#[derive(Clone, Copy, Debug)]
42
enum Sign {
43
    Zero,
44
    Plus,
45
    Minus,
46
}
47

            
48
impl Sign {
49
795
    fn name(self) -> &'static str {
50
795
        match self {
51
275
            Self::Zero => "ZEROP",
52
248
            Self::Plus => "PLUSP",
53
272
            Self::Minus => "MINUSP",
54
        }
55
795
    }
56

            
57
139
    fn holds(self, numerator: i64) -> bool {
58
139
        match self {
59
48
            Self::Zero => numerator == 0,
60
43
            Self::Plus => numerator > 0,
61
48
            Self::Minus => numerator < 0,
62
        }
63
139
    }
64

            
65
    /// Replaces the i64 numerator on the stack by the i32 truth value.
66
129
    fn emit_test(self, emit: &mut FunctionEmitter) {
67
129
        match self {
68
42
            Self::Zero => emit.i64_eqz(),
69
            Self::Plus => {
70
45
                emit.i64_const(0);
71
45
                emit.i64_gt_s();
72
            }
73
            Self::Minus => {
74
42
                emit.i64_const(0);
75
42
                emit.i64_lt_s();
76
            }
77
        }
78
129
    }
79

            
80
21
    fn mismatch(self, got: &str) -> Error {
81
21
        Error::Compile(format!(
82
21
            "{} expects an index, scalar or money, got {got}",
83
21
            self.name().to_ascii_lowercase()
84
21
        ))
85
21
    }
86

            
87
15
    fn type_error(self, ty: WasmType) -> Error {
88
15
        match ty {
89
10
            WasmType::AnyRef => self.mismatch("any; narrow it with THE, e.g. (the scalar x)"),
90
5
            other => self.mismatch(&other.to_string()),
91
        }
92
15
    }
93
}
94

            
95
141
fn zerop_eval(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
96
141
    sign_eval(symbols, args, Sign::Zero)
97
141
}
98

            
99
131
fn plusp_eval(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
100
131
    sign_eval(symbols, args, Sign::Plus)
101
131
}
102

            
103
142
fn minusp_eval(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
104
142
    sign_eval(symbols, args, Sign::Minus)
105
142
}
106

            
107
446
fn sign_eval(symbols: &mut SymbolTable, args: &[Expr], sign: Sign) -> Result<Expr> {
108
446
    let value = eval_value(symbols, one_arg(args, sign.name())?)?;
109
443
    match (&value, value.wasm_type()) {
110
        (Expr::Number(n), _) => {
111
142
            if let Number::Index(i) = n {
112
60
                index_literal(*i)?;
113
82
            }
114
139
            Ok(bool_result(sign.holds(*n.value().numer())))
115
        }
116
        (_, Some(WasmType::I32 | WasmType::Ratio | WasmType::Commodity)) => {
117
291
            Ok(Expr::WasmRuntime(WasmType::Bool))
118
        }
119
4
        (_, Some(ty)) => Err(sign.type_error(ty)),
120
6
        (_, None) => Err(sign.mismatch(&format_expr(&value))),
121
    }
122
446
}
123

            
124
54
fn compile_zerop(
125
54
    ctx: &mut CompileContext,
126
54
    emit: &mut FunctionEmitter,
127
54
    symbols: &mut SymbolTable,
128
54
    args: &[Expr],
129
54
) -> Result<WasmType> {
130
54
    compile_sign(ctx, emit, symbols, args, Sign::Zero)
131
54
}
132

            
133
51
fn compile_plusp(
134
51
    ctx: &mut CompileContext,
135
51
    emit: &mut FunctionEmitter,
136
51
    symbols: &mut SymbolTable,
137
51
    args: &[Expr],
138
51
) -> Result<WasmType> {
139
51
    compile_sign(ctx, emit, symbols, args, Sign::Plus)
140
51
}
141

            
142
51
fn compile_minusp(
143
51
    ctx: &mut CompileContext,
144
51
    emit: &mut FunctionEmitter,
145
51
    symbols: &mut SymbolTable,
146
51
    args: &[Expr],
147
51
) -> Result<WasmType> {
148
51
    compile_sign(ctx, emit, symbols, args, Sign::Minus)
149
51
}
150

            
151
167
fn compile_sign(
152
167
    ctx: &mut CompileContext,
153
167
    emit: &mut FunctionEmitter,
154
167
    symbols: &mut SymbolTable,
155
167
    args: &[Expr],
156
167
    sign: Sign,
157
167
) -> Result<WasmType> {
158
167
    let arg = one_arg(args, sign.name())?;
159
161
    if let Some(folded) = fold_call(symbols, sign.name(), args)? {
160
18
        emit.i32_const(i32::from(!folded.is_nil()));
161
18
        return Ok(WasmType::Bool);
162
143
    }
163
143
    match compile_for_stack(ctx, emit, symbols, arg)? {
164
42
        WasmType::I32 => emit.i64_extend_i32_s(),
165
36
        WasmType::Ratio => emit.struct_get(ctx.ids.ty_ratio, NUMERATOR),
166
51
        WasmType::Commodity => emit.struct_get(ctx.ids.ty_commodity, NUMERATOR),
167
        ty => {
168
11
            emit.reject_if_live(sign.type_error(ty))?;
169
            return Ok(WasmType::Bool);
170
        }
171
    }
172
129
    sign.emit_test(emit);
173
129
    Ok(WasmType::Bool)
174
167
}
175

            
176
#[cfg(test)]
177
#[path = "sign_tests.rs"]
178
mod tests;