boa_engine/vm/opcode/unary_ops/
decrement.rs

1use crate::{
2    Context, JsBigInt, JsResult,
3    value::{JsValue, JsVariant, Numeric},
4    vm::opcode::{Operation, VaryingOperand},
5};
6
7/// `Dec` implements the Opcode Operation for `Opcode::Dec`
8///
9/// Operation:
10///  - Unary `--` operator.
11#[derive(Debug, Clone, Copy)]
12pub(crate) struct Dec;
13
14impl Dec {
15    #[inline(always)]
16    pub(crate) fn operation(
17        (dst, src): (VaryingOperand, VaryingOperand),
18        context: &mut Context,
19    ) -> JsResult<()> {
20        let value = context.vm.get_register(src.into()).clone();
21
22        let (numeric, value) = match value.variant() {
23            JsVariant::Integer32(number) if number > i32::MIN => {
24                (JsValue::from(number), JsValue::from(number - 1))
25            }
26            _ => match value.to_numeric(context)? {
27                Numeric::Number(number) => (JsValue::from(number), JsValue::from(number - 1f64)),
28                Numeric::BigInt(bigint) => (
29                    JsValue::from(bigint.clone()),
30                    JsValue::from(JsBigInt::sub(&bigint, &JsBigInt::one())),
31                ),
32            },
33        };
34        context.vm.set_register(src.into(), numeric);
35        context.vm.set_register(dst.into(), value);
36        Ok(())
37    }
38}
39
40impl Operation for Dec {
41    const NAME: &'static str = "Dec";
42    const INSTRUCTION: &'static str = "INST - Dec";
43    const COST: u8 = 3;
44}