Skip to main content

code_transpiler/
runtime.rs

1#[derive(Debug, Clone, PartialEq)]
2pub enum RValue {
3    Null,
4    Num(f64),
5    Bool(bool),
6    Str(String),
7    Vec(Vec<RValue>),
8    Int { raw: u128, bits: u32, signed: bool },
9}
10
11impl RValue {
12    pub fn number(&self) -> f64 {
13        match self {
14            Self::Num(x) => *x,
15            Self::Bool(x) => {
16                if *x {
17                    1.0
18                } else {
19                    0.0
20                }
21            }
22            _ => f64::NAN,
23        }
24    }
25    pub fn truth(&self) -> bool {
26        match self {
27            Self::Null => false,
28            Self::Bool(x) => *x,
29            Self::Num(x) => *x != 0.0 && !x.is_nan(),
30            Self::Str(x) => !x.is_empty(),
31            Self::Vec(x) => !x.is_empty(),
32            Self::Int { raw, .. } => *raw != 0,
33        }
34    }
35    pub fn into_iter_values(self) -> Vec<RValue> {
36        match self {
37            Self::Vec(x) => x,
38            x => vec![x],
39        }
40    }
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct RuntimeError(pub String);
45impl std::fmt::Display for RuntimeError {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.write_str(&self.0)
48    }
49}
50impl std::error::Error for RuntimeError {}
51
52pub fn r_bind(args: &[RValue], index: usize, default: RValue) -> RValue {
53    args.get(index).cloned().unwrap_or(default)
54}
55
56fn binary(op: &str, a: &RValue, b: &RValue) -> Result<RValue, RuntimeError> {
57    if matches!(op, "==" | "!=") {
58        if let (RValue::Str(x), RValue::Str(y)) = (a, b) {
59            return Ok(RValue::Bool(if op == "==" { x == y } else { x != y }));
60        }
61    }
62    let x = a.number();
63    let y = b.number();
64    Ok(match op {
65        "+" => RValue::Num(x + y),
66        "-" => RValue::Num(x - y),
67        "*" => RValue::Num(x * y),
68        "/" => RValue::Num(x / y),
69        "%%" | "%" => RValue::Num(x % y),
70        "%/%" => RValue::Num((x / y).floor()),
71        "^" | "**" => RValue::Num(x.powf(y)),
72        "==" => RValue::Bool(x == y),
73        "!=" => RValue::Bool(x != y),
74        "<" => RValue::Bool(x < y),
75        "<=" => RValue::Bool(x <= y),
76        ">" => RValue::Bool(x > y),
77        ">=" => RValue::Bool(x >= y),
78        "&" | "&&" => RValue::Bool(a.truth() && b.truth()),
79        "|" | "||" => RValue::Bool(a.truth() || b.truth()),
80        ":" => {
81            let mut out = Vec::new();
82            let step = if x <= y { 1.0 } else { -1.0 };
83            let mut q = x;
84            while if step > 0.0 { q <= y } else { q >= y } {
85                out.push(RValue::Num(q));
86                q += step;
87            }
88            RValue::Vec(out)
89        }
90        _ => return Err(RuntimeError(format!("unsupported binary operator: {op}"))),
91    })
92}
93
94pub fn r_call(kernel: &str, name: &str, args: Vec<RValue>) -> Result<RValue, RuntimeError> {
95    if let Some(op) = name.strip_prefix("__binary_") {
96        let a = args
97            .first()
98            .ok_or_else(|| RuntimeError("binary call missing lhs".into()))?;
99        let b = args
100            .get(1)
101            .ok_or_else(|| RuntimeError("binary call missing rhs".into()))?;
102        return binary(op, a, b);
103    }
104    if let Some(op) = name.strip_prefix("__unary_") {
105        let a = args
106            .first()
107            .ok_or_else(|| RuntimeError("unary call missing operand".into()))?;
108        return match op {
109            "!" => Ok(RValue::Bool(!a.truth())),
110            "-" => Ok(RValue::Num(-a.number())),
111            "+" => Ok(RValue::Num(a.number())),
112            _ => Err(RuntimeError(format!("unsupported unary operator: {op}"))),
113        };
114    }
115    match name {
116        "c" | "list" => Ok(RValue::Vec(args)),
117        "length" => Ok(RValue::Num(
118            args.first()
119                .cloned()
120                .unwrap_or(RValue::Null)
121                .into_iter_values()
122                .len() as f64,
123        )),
124        "[" | "[[" => {
125            let seq = args
126                .first()
127                .cloned()
128                .unwrap_or(RValue::Null)
129                .into_iter_values();
130            let one_based = args.get(1).map(RValue::number).unwrap_or(f64::NAN) as isize;
131            if one_based >= 1 && (one_based as usize) <= seq.len() {
132                Ok(seq[one_based as usize - 1].clone())
133            } else {
134                Ok(RValue::Null)
135            }
136        }
137        "print" => Ok(args.first().cloned().unwrap_or(RValue::Null)),
138        _ if kernel == "predicate" || kernel == "numeric-predicate" || kernel == "missingness" => {
139            Ok(RValue::Bool(false))
140        }
141        _ => Err(RuntimeError(format!(
142            "runtime primitive not yet implemented: {kernel}/{name}"
143        ))),
144    }
145}