onion-vm 0.2.1

Virtual machine runtime for the Onion programming language with async execution and garbage collection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use arc_gc::gc::GC;

use crate::{
    lambda::runnable::{Runnable, RuntimeError, StepResult},
    onion_tuple,
    types::{
        lambda::definition::{LambdaBody, OnionLambdaDefinition},
        object::{OnionObject, OnionObjectCell, OnionStaticObject},
        tuple::OnionTuple,
    },
    unwrap_step_result,
};

pub struct NativeMethodGenerator<F>
where
    F: Fn(
            Option<&OnionStaticObject>,
            &OnionStaticObject,
            &mut GC<OnionObjectCell>,
        ) -> Result<OnionStaticObject, RuntimeError>
        + 'static,
{
    argument: OnionStaticObject,
    self_object: Option<OnionStaticObject>,
    function: &'static F,
}

impl<F> Runnable for NativeMethodGenerator<F>
where
    F: Fn(
            Option<&OnionStaticObject>,
            &OnionStaticObject,
            &mut GC<OnionObjectCell>,
        ) -> Result<OnionStaticObject, RuntimeError>
        + Send
        + Sync
        + 'static,
{
    fn step(&mut self, gc: &mut GC<OnionObjectCell>) -> StepResult {
        unwrap_step_result!(
            (self.function)(self.self_object.as_ref(), &self.argument, gc)
                .map(|result| StepResult::Return(result.into()))
        )
    }

    fn receive(
        &mut self,
        step_result: &StepResult,
        _gc: &mut GC<OnionObjectCell>,
    ) -> Result<(), RuntimeError> {
        match step_result {
            StepResult::Return(result) => {
                self.argument = result.as_ref().clone();
                Ok(())
            }
            StepResult::SetSelfObject(self_object) => {
                self.self_object = Some(self_object.as_ref().clone());
                Ok(())
            }
            _ => Err(RuntimeError::DetailedError(
                "NativeFunctionGenerator received unexpected step result"
                    .to_string()
                    .into(),
            )),
        }
    }

    fn copy(&self) -> Box<dyn Runnable> {
        Box::new(NativeMethodGenerator {
            argument: self.argument.clone(),
            self_object: self.self_object.clone(),
            function: self.function,
        })
    }

    fn format_context(&self) -> Result<serde_json::Value, RuntimeError> {
        Ok(serde_json::json!({
            "type": "NativeMethodGenerator",
            "argument": self.argument.to_string(),
        }))
    }
}

pub(crate) fn native_int_converter(
    self_object: Option<&OnionStaticObject>,
    _argument: &OnionStaticObject,
    _gc: &mut GC<OnionObjectCell>,
) -> Result<OnionStaticObject, RuntimeError> {
    let Some(self_obj) = self_object else {
        return Err(RuntimeError::DetailedError(
            "Native int converter requires a self object"
                .to_string()
                .into(),
        ));
    };

    self_obj.weak().with_data(|obj: &OnionObject| {
        match obj {
            OnionObject::Integer(v) => {
                // 如果已经是整数,直接返回
                Ok(OnionObject::Integer(*v).stabilize())
            }
            OnionObject::Float(v) => {
                // 浮点数转整数(截断)
                Ok(OnionObject::Integer(*v as i64).stabilize())
            }
            OnionObject::String(s) => {
                // 字符串解析为整数
                match s.parse::<i64>() {
                    Ok(parsed) => Ok(OnionObject::Integer(parsed).stabilize()),
                    Err(_) => Err(RuntimeError::DetailedError(
                        format!("Cannot convert string '{}' to integer", s).into(),
                    )),
                }
            }
            OnionObject::Boolean(b) => {
                // 布尔值转整数:true->1, false->0
                Ok(OnionObject::Integer(if *b { 1 } else { 0 }).stabilize())
            }
            OnionObject::Bytes(bytes) => {
                // 如果字节数组可以解析为UTF-8字符串,再转整数
                match std::str::from_utf8(bytes) {
                    Ok(s) => match s.parse::<i64>() {
                        Ok(parsed) => Ok(OnionObject::Integer(parsed).stabilize()),
                        Err(_) => Err(RuntimeError::DetailedError(
                            format!("Cannot convert bytes to integer: invalid format").into(),
                        )),
                    },
                    Err(_) => Err(RuntimeError::DetailedError(
                        "Cannot convert non-UTF8 bytes to integer"
                            .to_string()
                            .into(),
                    )),
                }
            }
            _ => Err(RuntimeError::DetailedError(
                format!(
                    "Cannot convert {} to integer",
                    obj.type_of().unwrap_or("unknown".to_string())
                )
                .into(),
            )),
        }
    })
}

pub(crate) fn native_float_converter(
    self_object: Option<&OnionStaticObject>,
    _argument: &OnionStaticObject,
    _gc: &mut GC<OnionObjectCell>,
) -> Result<OnionStaticObject, RuntimeError> {
    let Some(self_obj) = self_object else {
        return Err(RuntimeError::DetailedError(
            "Native float converter requires a self object"
                .to_string()
                .into(),
        ));
    };

    self_obj.weak().with_data(|obj: &OnionObject| {
        match obj {
            OnionObject::Float(v) => {
                // 如果已经是浮点数,直接返回
                Ok(OnionObject::Float(*v).stabilize())
            }
            OnionObject::Integer(v) => {
                // 整数转浮点数
                Ok(OnionObject::Float(*v as f64).stabilize())
            }
            OnionObject::String(s) => {
                // 字符串解析为浮点数
                match s.parse::<f64>() {
                    Ok(parsed) => Ok(OnionObject::Float(parsed).stabilize()),
                    Err(_) => Err(RuntimeError::DetailedError(
                        format!("Cannot convert string '{}' to float", s).into(),
                    )),
                }
            }
            OnionObject::Boolean(b) => {
                // 布尔值转浮点数:true->1.0, false->0.0
                Ok(OnionObject::Float(if *b { 1.0 } else { 0.0 }).stabilize())
            }
            OnionObject::Bytes(bytes) => {
                // 如果字节数组可以解析为UTF-8字符串,再转浮点数
                match std::str::from_utf8(bytes) {
                    Ok(s) => match s.parse::<f64>() {
                        Ok(parsed) => Ok(OnionObject::Float(parsed).stabilize()),
                        Err(_) => Err(RuntimeError::DetailedError(
                            format!("Cannot convert bytes to float: invalid format").into(),
                        )),
                    },
                    Err(_) => Err(RuntimeError::DetailedError(
                        "Cannot convert non-UTF8 bytes to float".to_string().into(),
                    )),
                }
            }
            _ => Err(RuntimeError::DetailedError(
                format!(
                    "Cannot convert {} to float",
                    obj.type_of().unwrap_or("unknown".to_string())
                )
                .into(),
            )),
        }
    })
}

pub(crate) fn native_string_converter(
    self_object: Option<&OnionStaticObject>,
    _argument: &OnionStaticObject,
    _gc: &mut GC<OnionObjectCell>,
) -> Result<OnionStaticObject, RuntimeError> {
    let Some(self_obj) = self_object else {
        return Err(RuntimeError::DetailedError(
            "Native string converter requires a self object"
                .to_string()
                .into(),
        ));
    };

    self_obj.weak().with_data(|obj: &OnionObject| {
        match obj {
            OnionObject::String(s) => {
                // 如果已经是字符串,直接返回
                Ok(OnionObject::String(s.clone()).stabilize())
            }
            OnionObject::Integer(v) => {
                // 整数转字符串
                Ok(OnionObject::String(std::sync::Arc::new(v.to_string())).stabilize())
            }
            OnionObject::Float(v) => {
                // 浮点数转字符串
                Ok(OnionObject::String(std::sync::Arc::new(v.to_string())).stabilize())
            }
            OnionObject::Boolean(b) => {
                // 布尔值转字符串
                Ok(OnionObject::String(std::sync::Arc::new(b.to_string())).stabilize())
            }
            OnionObject::Bytes(bytes) => {
                // 字节数组转字符串(UTF-8)
                match std::str::from_utf8(bytes) {
                    Ok(s) => {
                        Ok(OnionObject::String(std::sync::Arc::new(s.to_string())).stabilize())
                    }
                    Err(_) => {
                        // 如果不是有效UTF-8,使用lossy转换
                        let s = String::from_utf8_lossy(bytes);
                        Ok(OnionObject::String(std::sync::Arc::new(s.to_string())).stabilize())
                    }
                }
            }
            OnionObject::Null => {
                Ok(OnionObject::String(std::sync::Arc::new("null".to_string())).stabilize())
            }
            OnionObject::Undefined(_) => {
                Ok(OnionObject::String(std::sync::Arc::new("undefined".to_string())).stabilize())
            }
            OnionObject::Range(start, end) => Ok(OnionObject::String(std::sync::Arc::new(
                format!("{}..{}", start, end),
            ))
            .stabilize()),
            _ => {
                // 对于复杂对象,使用 repr 方法
                match obj.repr(&vec![]) {
                    Ok(repr_str) => {
                        Ok(OnionObject::String(std::sync::Arc::new(repr_str)).stabilize())
                    }
                    Err(_) => Ok(OnionObject::String(std::sync::Arc::new(format!(
                        "<{}>",
                        obj.type_of().unwrap_or("object".to_string())
                    )))
                    .stabilize()),
                }
            }
        }
    })
}

pub(crate) fn native_bool_converter(
    self_object: Option<&OnionStaticObject>,
    _argument: &OnionStaticObject,
    _gc: &mut GC<OnionObjectCell>,
) -> Result<OnionStaticObject, RuntimeError> {
    let Some(self_obj) = self_object else {
        return Err(RuntimeError::DetailedError(
            "Native bool converter requires a self object"
                .to_string()
                .into(),
        ));
    };

    self_obj.weak().with_data(|obj: &OnionObject| {
        match obj {
            OnionObject::Boolean(b) => {
                // 如果已经是布尔值,直接返回
                Ok(OnionObject::Boolean(*b).stabilize())
            }
            OnionObject::Integer(v) => {
                // 整数转布尔值:0为false,非0为true
                Ok(OnionObject::Boolean(*v != 0).stabilize())
            }
            OnionObject::Float(v) => {
                // 浮点数转布尔值:0.0为false,非0为true
                Ok(OnionObject::Boolean(*v != 0.0).stabilize())
            }
            OnionObject::String(s) => {
                // 字符串转布尔值:空字符串为false,非空为true
                Ok(OnionObject::Boolean(!s.is_empty()).stabilize())
            }
            OnionObject::Bytes(bytes) => {
                // 字节数组转布尔值:空数组为false,非空为true
                Ok(OnionObject::Boolean(!bytes.is_empty()).stabilize())
            }
            OnionObject::Null => {
                // null 为 false
                Ok(OnionObject::Boolean(false).stabilize())
            }
            OnionObject::Undefined(_) => {
                // undefined 为 false
                Ok(OnionObject::Boolean(false).stabilize())
            }
            OnionObject::Tuple(tuple) => {
                // 元组转布尔值:空元组为false,非空为true
                Ok(OnionObject::Boolean(!tuple.get_elements().is_empty()).stabilize())
            }
            _ => {
                // 其他对象都为 true(存在即为真)
                Ok(OnionObject::Boolean(true).stabilize())
            }
        }
    })
}

pub(crate) fn native_bytes_converter(
    self_object: Option<&OnionStaticObject>,
    _argument: &OnionStaticObject,
    _gc: &mut GC<OnionObjectCell>,
) -> Result<OnionStaticObject, RuntimeError> {
    let Some(self_obj) = self_object else {
        return Err(RuntimeError::DetailedError(
            "Native bytes converter requires a self object"
                .to_string()
                .into(),
        ));
    };

    self_obj.weak().with_data(|obj: &OnionObject| {
        match obj {
            OnionObject::Bytes(bytes) => {
                // 如果已经是字节数组,直接返回
                Ok(OnionObject::Bytes(bytes.clone()).stabilize())
            }
            OnionObject::String(s) => {
                // 字符串转字节数组(UTF-8编码)
                Ok(OnionObject::Bytes(std::sync::Arc::new(s.as_bytes().to_vec())).stabilize())
            }
            OnionObject::Integer(v) => {
                // 整数转字节数组(大端序)
                Ok(OnionObject::Bytes(std::sync::Arc::new(v.to_be_bytes().to_vec())).stabilize())
            }
            OnionObject::Float(v) => {
                // 浮点数转字节数组(大端序)
                Ok(OnionObject::Bytes(std::sync::Arc::new(v.to_be_bytes().to_vec())).stabilize())
            }
            OnionObject::Boolean(b) => {
                // 布尔值转字节数组:true->1, false->0
                Ok(OnionObject::Bytes(std::sync::Arc::new(vec![if *b { 1 } else { 0 }])).stabilize())
            }
            OnionObject::Tuple(tuple) => {
                // 元组转字节数组:尝试将每个元素转换为字节
                let mut result = Vec::new();
                for element in tuple.get_elements().iter() {
                    match element {
                        OnionObject::Integer(v) => {
                            if *v >= 0 && *v <= 255 {
                                result.push(*v as u8);
                            } else {
                                return Err(RuntimeError::DetailedError(
                                    format!("Integer {} is out of byte range (0-255)", v).into(),
                                ));
                            }
                        }
                        _ => {
                            return Err(RuntimeError::DetailedError(
                                "Tuple elements must be integers in range 0-255 to convert to bytes".to_string().into(),
                            ));
                        }
                    }
                }
                Ok(OnionObject::Bytes(std::sync::Arc::new(result)).stabilize())
            }
            _ => Err(RuntimeError::DetailedError(
                format!("Cannot convert {} to bytes", obj.type_of().unwrap_or("unknown".to_string())).into(),
            )),
        }
    })
}

pub(crate) fn native_length_method(
    self_object: Option<&OnionStaticObject>,
    _argument: &OnionStaticObject,
    _gc: &mut GC<OnionObjectCell>,
) -> Result<OnionStaticObject, RuntimeError> {
    let Some(self_obj) = self_object else {
        return Err(RuntimeError::DetailedError(
            "Native length method requires a self object"
                .to_string()
                .into(),
        ));
    };

    self_obj.weak().with_data(|obj: &OnionObject| match obj {
        OnionObject::String(s) => Ok(OnionObject::Integer(s.len() as i64).stabilize()),
        OnionObject::Bytes(b) => Ok(OnionObject::Integer(b.len() as i64).stabilize()),
        OnionObject::Range(start, end) => {
            Ok(OnionObject::Integer((end - start) as i64).stabilize())
        }
        OnionObject::Tuple(tuple) => {
            Ok(OnionObject::Integer(tuple.get_elements().len() as i64).stabilize())
        }
        _ => Err(RuntimeError::DetailedError(
            format!(
                "Object of type {} does not have a length",
                obj.type_of().unwrap_or("unknown".to_string())
            )
            .into(),
        )),
    })
}

pub(crate) fn native_elements_method(
    self_object: Option<&OnionStaticObject>,
    _argument: &OnionStaticObject,
    _gc: &mut GC<OnionObjectCell>,
) -> Result<OnionStaticObject, RuntimeError> {
    let Some(self_obj) = self_object else {
        return Err(RuntimeError::DetailedError(
            "Native elements method requires a self object"
                .to_string()
                .into(),
        ));
    };

    self_obj.weak().with_data(|obj: &OnionObject| {
        match obj {
            OnionObject::String(s) => {
                let elements = OnionTuple::new_static_no_ref(
                    &s.chars()
                        .map(|c| {
                            OnionStaticObject::new(OnionObject::String(std::sync::Arc::new(
                                c.to_string(),
                            )))
                        })
                        .collect::<Vec<_>>(),
                );
                Ok(elements)
            }
            OnionObject::Bytes(b) => {
                let elements = OnionTuple::new_static_no_ref(
                    &b.iter()
                        .map(|byte| OnionStaticObject::new(OnionObject::Integer(*byte as i64)))
                        .collect::<Vec<_>>(),
                );
                Ok(elements)
            }
            OnionObject::Range(start, end) => {
                let elements = OnionTuple::new_static_no_ref(
                    &(*start..*end)
                        .map(|i| OnionStaticObject::new(OnionObject::Integer(i as i64)))
                        .collect::<Vec<_>>(),
                );
                Ok(elements)
            }
            OnionObject::Tuple(_) => {
                // 对于元组,直接返回自己
                Ok(self_obj.clone())
            }
            _ => Err(RuntimeError::DetailedError(
                format!(
                    "Object of type {} does not have elements",
                    obj.type_of().unwrap_or("unknown".to_string())
                )
                .into(),
            )),
        }
    })
}

pub(crate) fn wrap_native_function<F>(
    params: &OnionStaticObject,
    capture: Option<&OnionStaticObject>,
    self_object: Option<&OnionStaticObject>,
    signature: String,
    function: &'static F,
) -> OnionStaticObject
where
    F: Fn(
            Option<&OnionStaticObject>,
            &OnionStaticObject,
            &mut GC<OnionObjectCell>,
        ) -> Result<OnionStaticObject, RuntimeError>
        + Send
        + Sync
        + 'static,
{
    OnionLambdaDefinition::new_static(
        params,
        LambdaBody::NativeFunction(Box::new(NativeMethodGenerator {
            argument: onion_tuple!(),
            self_object: self_object.cloned(),
            function: function,
        })),
        capture,
        self_object,
        signature,
    )
}