harn-vm 0.7.44

Async bytecode virtual machine for the Harn programming language
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use std::rc::Rc;

use crate::chunk::{InlineCacheEntry, MethodCacheTarget};
use crate::value::{VmClosure, VmError, VmValue};
use crate::BuiltinId;

use super::super::CallFrame;

impl super::super::Vm {
    fn try_cached_method(
        cache: &InlineCacheEntry,
        name_idx: u16,
        argc: usize,
        obj: &VmValue,
    ) -> Option<VmValue> {
        let InlineCacheEntry::Method {
            name_idx: cached_name_idx,
            argc: cached_argc,
            target,
        } = cache
        else {
            return None;
        };
        if *cached_name_idx != name_idx || *cached_argc != argc {
            return None;
        }

        match (target, obj) {
            (MethodCacheTarget::ListCount, VmValue::List(items)) => {
                Some(VmValue::Int(items.len() as i64))
            }
            (MethodCacheTarget::ListEmpty, VmValue::List(items)) => {
                Some(VmValue::Bool(items.is_empty()))
            }
            (MethodCacheTarget::StringCount, VmValue::String(s)) => {
                Some(VmValue::Int(s.chars().count() as i64))
            }
            (MethodCacheTarget::StringEmpty, VmValue::String(s)) => {
                Some(VmValue::Bool(s.is_empty()))
            }
            (MethodCacheTarget::DictCount, VmValue::Dict(map)) => {
                Some(VmValue::Int(map.len() as i64))
            }
            (MethodCacheTarget::RangeCount | MethodCacheTarget::RangeLen, VmValue::Range(r)) => {
                Some(VmValue::Int(r.len()))
            }
            (MethodCacheTarget::RangeEmpty, VmValue::Range(r)) => Some(VmValue::Bool(r.is_empty())),
            (MethodCacheTarget::RangeFirst, VmValue::Range(r)) => {
                Some(r.first().map(VmValue::Int).unwrap_or(VmValue::Nil))
            }
            (MethodCacheTarget::RangeLast, VmValue::Range(r)) => {
                Some(r.last().map(VmValue::Int).unwrap_or(VmValue::Nil))
            }
            (MethodCacheTarget::SetCount | MethodCacheTarget::SetLen, VmValue::Set(items)) => {
                Some(VmValue::Int(items.len() as i64))
            }
            (MethodCacheTarget::SetEmpty, VmValue::Set(items)) => {
                Some(VmValue::Bool(items.is_empty()))
            }
            _ => None,
        }
    }

    fn method_cache_target(obj: &VmValue, method: &str, argc: usize) -> Option<MethodCacheTarget> {
        if argc != 0 {
            return None;
        }
        match obj {
            VmValue::List(_) => match method {
                "count" => Some(MethodCacheTarget::ListCount),
                "empty" => Some(MethodCacheTarget::ListEmpty),
                _ => None,
            },
            VmValue::String(_) => match method {
                "count" | "len" => Some(MethodCacheTarget::StringCount),
                "empty" => Some(MethodCacheTarget::StringEmpty),
                _ => None,
            },
            VmValue::Dict(_) => match method {
                "count" => Some(MethodCacheTarget::DictCount),
                _ => None,
            },
            VmValue::Range(_) => match method {
                "count" => Some(MethodCacheTarget::RangeCount),
                "len" => Some(MethodCacheTarget::RangeLen),
                "empty" => Some(MethodCacheTarget::RangeEmpty),
                "first" => Some(MethodCacheTarget::RangeFirst),
                "last" => Some(MethodCacheTarget::RangeLast),
                _ => None,
            },
            VmValue::Set(_) => match method {
                "count" => Some(MethodCacheTarget::SetCount),
                "len" => Some(MethodCacheTarget::SetLen),
                "empty" => Some(MethodCacheTarget::SetEmpty),
                _ => None,
            },
            _ => None,
        }
    }

    async fn try_call_special_name(
        &mut self,
        name: &str,
        args: &[VmValue],
    ) -> Result<bool, VmError> {
        if name == "await" {
            let task_id = args.first().and_then(|a| match a {
                VmValue::TaskHandle(id) => Some(id.clone()),
                _ => None,
            });
            if let Some(id) = task_id {
                if let Some(handle) = self.spawned_tasks.remove(&id) {
                    let (result, task_output) = handle
                        .handle
                        .await
                        .map_err(|e| VmError::Runtime(format!("Task join error: {e}")))??;
                    self.output.push_str(&task_output);
                    self.stack.push(result);
                } else {
                    self.stack.push(VmValue::Nil);
                }
            } else {
                self.stack
                    .push(args.first().cloned().unwrap_or(VmValue::Nil));
            }
            return Ok(true);
        }

        if name == "cancel" {
            if let Some(VmValue::TaskHandle(id)) = args.first() {
                if let Some(handle) = self.spawned_tasks.remove(id) {
                    handle.handle.abort();
                }
            }
            self.stack.push(VmValue::Nil);
            return Ok(true);
        }

        if name == "cancel_graceful" {
            let task_id = args.first().and_then(|a| match a {
                VmValue::TaskHandle(id) => Some(id.clone()),
                _ => None,
            });
            let timeout_ms = args
                .get(1)
                .and_then(|a| match a {
                    VmValue::Int(n) => Some(*n as u64),
                    VmValue::Duration(ms) => Some((*ms).max(0) as u64),
                    _ => None,
                })
                .unwrap_or(5000);
            if let Some(id) = task_id {
                if let Some(task) = self.spawned_tasks.remove(&id) {
                    task.cancel_token
                        .store(true, std::sync::atomic::Ordering::SeqCst);
                    let mut handle = task.handle;
                    let timeout =
                        tokio::time::sleep(tokio::time::Duration::from_millis(timeout_ms));
                    tokio::pin!(timeout);
                    tokio::select! {
                        joined = &mut handle => {
                            match joined {
                                Ok(Ok((result, output))) => {
                                    self.output.push_str(&output);
                                    self.stack.push(VmValue::enum_variant("Result", "Ok", vec![result]));
                                }
                                Ok(Err(e)) => {
                                    self.stack.push(VmValue::enum_variant(
                                        "Result",
                                        "Err",
                                        vec![VmValue::String(Rc::from(e.to_string()))],
                                    ));
                                }
                                Err(e) => {
                                    self.stack.push(VmValue::enum_variant(
                                        "Result",
                                        "Err",
                                        vec![VmValue::String(Rc::from(format!("Task join error: {e}")))],
                                    ));
                                }
                            }
                        }
                        _ = &mut timeout => {
                            handle.abort();
                            self.stack.push(VmValue::enum_variant(
                                "Result",
                                "Err",
                                vec![VmValue::String(Rc::from(
                                    "cancel_graceful: timeout, task forcefully aborted",
                                ))],
                            ));
                        }
                    }
                } else {
                    self.stack
                        .push(VmValue::enum_variant("Result", "Ok", vec![VmValue::Nil]));
                }
            } else {
                self.stack.push(VmValue::Nil);
            }
            return Ok(true);
        }

        if name == "is_cancelled" {
            let cancelled = self
                .cancel_token
                .as_ref()
                .map(|t| t.load(std::sync::atomic::Ordering::SeqCst))
                .unwrap_or(false);
            self.stack.push(VmValue::Bool(cancelled));
            return Ok(true);
        }

        Ok(false)
    }

    async fn call_named_value(
        &mut self,
        name: &str,
        args: Vec<VmValue>,
        direct_id: Option<BuiltinId>,
    ) -> Result<(), VmError> {
        if self.try_call_special_name(name, &args).await? {
            return Ok(());
        }
        if let Some(closure) = self.resolve_named_closure(name) {
            if closure.func.is_generator {
                let gen = self.create_generator(&closure, &args);
                self.stack.push(gen);
            } else {
                self.push_closure_frame(&closure, &args)?;
            }
        } else {
            let result = if let Some(id) = direct_id {
                self.call_builtin_id_or_name(id, name, args).await?
            } else {
                self.call_named_builtin(name, args).await?
            };
            self.stack.push(result);
        }
        Ok(())
    }

    pub(super) async fn execute_call(&mut self) -> Result<(), VmError> {
        let frame = self.frames.last_mut().unwrap();
        let argc = frame.chunk.code[frame.ip] as usize;
        frame.ip += 1;

        let args: Vec<VmValue> = self.stack.split_off(self.stack.len().saturating_sub(argc));
        let callee = self.pop()?;

        match callee {
            VmValue::String(name) => {
                self.call_named_value(&name, args, None).await?;
            }
            VmValue::Closure(closure) => {
                if closure.func.is_generator {
                    let gen = self.create_generator(&closure, &args);
                    self.stack.push(gen);
                } else {
                    self.push_closure_frame(&closure, &args)?;
                }
            }
            VmValue::BuiltinRef(name) => {
                self.call_named_value(&name, args, None).await?;
            }
            VmValue::BuiltinRefId { id, name } => {
                self.call_named_value(&name, args, Some(id)).await?;
            }
            _ => {
                return Err(VmError::TypeError(format!(
                    "Cannot call {}",
                    callee.display()
                )))
            }
        }
        Ok(())
    }

    pub(super) async fn execute_call_spread(&mut self) -> Result<(), VmError> {
        let args_val = self.pop()?;
        let callee = self.pop()?;
        let args = match args_val {
            VmValue::List(items) => (*items).clone(),
            _ => {
                return Err(VmError::TypeError(
                    "spread call requires list arguments".into(),
                ))
            }
        };
        match callee {
            VmValue::String(name) => {
                self.call_named_value(&name, args, None).await?;
            }
            VmValue::Closure(closure) => {
                if closure.func.is_generator {
                    let gen = self.create_generator(&closure, &args);
                    self.stack.push(gen);
                } else {
                    self.push_closure_frame(&closure, &args)?;
                }
            }
            VmValue::BuiltinRef(name) => {
                self.call_named_value(&name, args, None).await?;
            }
            VmValue::BuiltinRefId { id, name } => {
                self.call_named_value(&name, args, Some(id)).await?;
            }
            _ => {
                return Err(VmError::TypeError(format!(
                    "Cannot call {}",
                    callee.display()
                )))
            }
        }
        Ok(())
    }

    pub(super) async fn execute_call_builtin(&mut self) -> Result<(), VmError> {
        let frame = self.frames.last_mut().unwrap();
        let id = BuiltinId::from_raw(frame.chunk.read_u64(frame.ip));
        frame.ip += 8;
        let name_idx = frame.chunk.read_u16(frame.ip) as usize;
        frame.ip += 2;
        let argc = frame.chunk.code[frame.ip] as usize;
        frame.ip += 1;
        let name = Self::const_string(&frame.chunk.constants[name_idx])?;
        let args: Vec<VmValue> = self.stack.split_off(self.stack.len().saturating_sub(argc));
        self.call_named_value(&name, args, Some(id)).await
    }

    pub(super) async fn execute_call_builtin_spread(&mut self) -> Result<(), VmError> {
        let frame = self.frames.last_mut().unwrap();
        let id = BuiltinId::from_raw(frame.chunk.read_u64(frame.ip));
        frame.ip += 8;
        let name_idx = frame.chunk.read_u16(frame.ip) as usize;
        frame.ip += 2;
        let name = Self::const_string(&frame.chunk.constants[name_idx])?;
        let args_val = self.pop()?;
        let args = match args_val {
            VmValue::List(items) => (*items).clone(),
            _ => {
                return Err(VmError::TypeError(
                    "spread call requires list arguments".into(),
                ))
            }
        };
        self.call_named_value(&name, args, Some(id)).await
    }

    pub(super) async fn execute_tail_call(&mut self) -> Result<(), VmError> {
        let frame = self.frames.last_mut().unwrap();
        let argc = frame.chunk.code[frame.ip] as usize;
        frame.ip += 1;

        let args: Vec<VmValue> = self.stack.split_off(self.stack.len().saturating_sub(argc));
        let callee = self.pop()?;

        let resolved_closure = match &callee {
            VmValue::Closure(cl) => Some(Rc::clone(cl)),
            VmValue::String(name) => self.resolve_named_closure(name),
            _ => None,
        };

        if let Some(closure) = resolved_closure {
            if closure.func.is_generator {
                // Generators cannot be tail-call optimized.
                let gen = self.create_generator(&closure, &args);
                return Err(VmError::Return(gen));
            }
            let mut call_env = self.closure_call_env_for_current_frame(&closure);
            // TCO: reuse the current frame's stack_base / saved_env.
            let popped = self.frames.pop().unwrap();
            let stack_base = popped.stack_base;
            let parent_env = popped.saved_env;

            if let Some(ref dir) = popped.saved_source_dir {
                crate::stdlib::set_thread_source_dir(dir);
            }

            self.stack.truncate(stack_base);

            let saved_source_dir = if let Some(ref dir) = closure.source_dir {
                let prev = crate::stdlib::process::VM_SOURCE_DIR.with(|sd| sd.borrow().clone());
                crate::stdlib::set_thread_source_dir(dir);
                prev
            } else {
                None
            };

            call_env.push_scope();
            let initial_env = call_env.clone();
            self.env = call_env;
            let mut local_slots = Self::fresh_local_slots(&closure.func.chunk);
            Self::bind_param_slots(&mut local_slots, &closure.func, &args, false);
            let initial_local_slots = local_slots.clone();

            let argc = args.len();
            self.frames.push(CallFrame {
                chunk: Rc::clone(&closure.func.chunk),
                ip: 0,
                stack_base,
                saved_env: parent_env,
                initial_env: Some(initial_env),
                initial_local_slots: Some(initial_local_slots),
                saved_iterator_depth: self.iterators.len(),
                fn_name: closure.func.name.clone(),
                argc,
                saved_source_dir,
                module_functions: closure.module_functions.clone(),
                module_state: closure.module_state.clone(),
                local_slots,
                local_scope_base: self.env.scope_depth().saturating_sub(1),
                local_scope_depth: 0,
            });
        } else {
            match callee {
                VmValue::String(name) => {
                    let result = self.call_named_builtin(&name, args).await?;
                    self.stack.push(result);
                }
                _ => {
                    return Err(VmError::TypeError(format!(
                        "Cannot call {}",
                        callee.display()
                    )))
                }
            }
        }
        Ok(())
    }

    pub(super) fn execute_return(&mut self) -> VmError {
        let val = self.pop().unwrap_or(VmValue::Nil);
        VmError::Return(val)
    }

    pub(super) fn execute_closure(&mut self) {
        self.sync_current_frame_locals_to_env();
        let frame = self.frames.last_mut().unwrap();
        let fn_idx = frame.chunk.read_u16(frame.ip) as usize;
        frame.ip += 2;
        let func = frame.chunk.functions[fn_idx].clone();
        let closure = VmClosure {
            func,
            env: self.env.clone(),
            source_dir: None,
            module_functions: self
                .frames
                .last()
                .and_then(|frame| frame.module_functions.clone()),
            // Inherit module state so closures created inside a module function
            // see and mutate the same module-level vars.
            module_state: self
                .frames
                .last()
                .and_then(|frame| frame.module_state.clone()),
        };
        self.stack.push(VmValue::Closure(Rc::new(closure)));
    }

    pub(super) async fn execute_method_call(&mut self, optional: bool) -> Result<(), VmError> {
        let (name_idx, argc, cache_slot, cache_entry) = {
            let frame = self.frames.last_mut().unwrap();
            let op_offset = frame.ip.saturating_sub(1);
            let name_idx = frame.chunk.read_u16(frame.ip);
            frame.ip += 2;
            let argc = frame.chunk.code[frame.ip] as usize;
            frame.ip += 1;
            let cache_slot = frame.chunk.inline_cache_slot(op_offset);
            let cache_entry = cache_slot
                .map(|slot| frame.chunk.inline_cache_entry(slot))
                .unwrap_or(InlineCacheEntry::Empty);
            (name_idx, argc, cache_slot, cache_entry)
        };
        let args: Vec<VmValue> = self.stack.split_off(self.stack.len().saturating_sub(argc));
        let obj = self.pop()?;
        if optional && matches!(obj, VmValue::Nil) {
            self.stack.push(VmValue::Nil);
        } else if let Some(result) = Self::try_cached_method(&cache_entry, name_idx, argc, &obj) {
            self.stack.push(result);
        } else {
            let method = {
                let frame = self.frames.last().unwrap();
                Self::const_string(&frame.chunk.constants[name_idx as usize])?
            };
            let cache_target = Self::method_cache_target(&obj, &method, args.len());
            let result = self.call_method(obj, &method, &args).await?;
            if let (Some(slot), Some(target)) = (cache_slot, cache_target) {
                let frame = self.frames.last().unwrap();
                frame.chunk.set_inline_cache_entry(
                    slot,
                    InlineCacheEntry::Method {
                        name_idx,
                        argc,
                        target,
                    },
                );
            }
            self.stack.push(result);
        }
        Ok(())
    }

    pub(super) async fn execute_method_call_spread(&mut self) -> Result<(), VmError> {
        let (name_idx, cache_slot, cache_entry) = {
            let frame = self.frames.last_mut().unwrap();
            let op_offset = frame.ip.saturating_sub(1);
            let name_idx = frame.chunk.read_u16(frame.ip);
            frame.ip += 2;
            let cache_slot = frame.chunk.inline_cache_slot(op_offset);
            let cache_entry = cache_slot
                .map(|slot| frame.chunk.inline_cache_entry(slot))
                .unwrap_or(InlineCacheEntry::Empty);
            (name_idx, cache_slot, cache_entry)
        };
        let args_val = self.pop()?;
        let obj = self.pop()?;
        let args = match args_val {
            VmValue::List(items) => (*items).clone(),
            _ => {
                return Err(VmError::TypeError(
                    "spread method call requires list arguments".into(),
                ))
            }
        };
        if let Some(result) = Self::try_cached_method(&cache_entry, name_idx, args.len(), &obj) {
            self.stack.push(result);
        } else {
            let method = {
                let frame = self.frames.last().unwrap();
                Self::const_string(&frame.chunk.constants[name_idx as usize])?
            };
            let cache_target = Self::method_cache_target(&obj, &method, args.len());
            let result = self.call_method(obj, &method, &args).await?;
            if let (Some(slot), Some(target)) = (cache_slot, cache_target) {
                let frame = self.frames.last().unwrap();
                frame.chunk.set_inline_cache_entry(
                    slot,
                    InlineCacheEntry::Method {
                        name_idx,
                        argc: args.len(),
                        target,
                    },
                );
            }
            self.stack.push(result);
        }
        Ok(())
    }

    pub(super) async fn execute_pipe(&mut self) -> Result<(), VmError> {
        let callable = self.pop()?;
        let value = self.pop()?;
        match callable {
            VmValue::Closure(closure) => {
                self.push_closure_frame(&closure, &[value])?;
            }
            VmValue::String(name) => {
                self.call_named_value(&name, vec![value], None).await?;
            }
            VmValue::BuiltinRef(name) => {
                self.call_named_value(&name, vec![value], None).await?;
            }
            VmValue::BuiltinRefId { id, name } => {
                self.call_named_value(&name, vec![value], Some(id)).await?;
            }
            _ => {
                return Err(VmError::TypeError(format!(
                    "cannot pipe into {}",
                    callable.type_name()
                )));
            }
        }
        Ok(())
    }
}