run-rs 0.3.2

Run a subset of Rust as an interpreted script
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Methods on live host resources:
//! files, readers, writers, sockets, children, clocks, and temp files, all
//! behind `Value::Native(Arc<Mutex<Native>>)`.

use std::io::{Seek, SeekFrom, Write};
use std::sync::Arc;

use anyhow::{Result, bail};
use parking_lot::Mutex;

use super::native::Native;
use super::value::Value;

type Handle = Arc<Mutex<Native>>;

/// Pull the next line from a lazy `Lines` iterator, `None` at end of input.
/// Each item is a `Result<String>` so a script can use `line?` in the loop.
pub(super) fn lines_next(handle: &Handle) -> Option<Value> {
    let mut h = handle.lock();
    if let Native::Lines(it) = &mut *h {
        match it.next() {
            Some(Ok(line)) => Some(Value::ok(Value::str(line))),
            Some(Err(e)) => Some(Value::err(Value::str(e.to_string()))),
            None => None,
        }
    } else {
        None
    }
}

/// Drain a lazy `Lines` iterator fully, for `.collect()` or a materializing
/// `for` loop.
pub(super) fn drain_lines(handle: &Handle) -> Vec<Value> {
    let mut out = Vec::new();
    while let Some(v) = lines_next(handle) {
        out.push(v);
    }
    out
}

/// A byte count as the integer scripts see.
fn int_len(n: usize) -> i64 {
    i64::try_from(n).expect("length exceeds i64")
}

fn io_err<T>(r: std::io::Result<T>, on_ok: impl FnOnce(T) -> Value) -> Value {
    match r {
        Ok(v) => Value::ok(on_ok(v)),
        Err(e) => Value::err(Value::str(e.to_string())),
    }
}

/// The buffer arrives as a copy of the script variable, so the vm moves the
/// updated value back into the variable register after the call, see the
/// mut-reference handling in `compile_method`.
fn append_string(target: &mut Value, text: &str) {
    if let Value::Str(s) = target {
        let mut out = s.to_string();
        out.push_str(text);
        *target = Value::str(out);
    }
}

/// A `u8` argument, which a script writes as `b'\n'` or as a plain integer.
fn byte_arg(arg: Option<&Value>, method: &str) -> Result<u8> {
    let Some(Value::Int(n)) = arg else {
        bail!("{method} needs a byte as its first argument");
    };
    match u8::try_from(*n) {
        Ok(b) => Ok(b),
        Err(_) => bail!("{method} got {n}, which is not a byte"),
    }
}

fn append_bytes(target: &Value, bytes: &[u8]) {
    if let Value::Vec(v) = target {
        v.lock()
            .extend(bytes.iter().map(|b| Value::Int(i64::from(*b))));
    }
}

/// Dispatch a method call on a native handle. Returns `Ok(None)` when the
/// method is unknown for this handle so the caller can raise a good error.
pub(super) fn native_method(
    handle: &Handle,
    method: &str,
    args: &mut [Value],
) -> Result<Option<Value>> {
    // A lopdf Document dispatches by receiver first, its method names mirror
    // the real crate and must not collide with the name-keyed arms below.
    if matches!(&*handle.lock(), Native::Pdf(_)) {
        let mut h = handle.lock();
        let Native::Pdf(doc) = &mut *h else {
            unreachable!()
        };
        if let Some(v) = super::pdf_bridge::document_method(doc, method, args)? {
            return Ok(Some(v));
        }
    }
    if let Some(v) = super::crates_bridge::sha256_method(handle, method, args)? {
        return Ok(Some(v));
    }
    // The families use disjoint method names, so the first helper that
    // recognizes the name answers. Handles that consume self or hand out
    // sub-handles move out of the Mutex inside their family helper.
    if let Some(v) = reader_native_method(handle, method, args)? {
        return Ok(Some(v));
    }
    if let Some(v) = writer_native_method(handle, method, args) {
        return Ok(Some(v));
    }
    if let Some(v) = file_native_method(handle, method, args)? {
        return Ok(Some(v));
    }
    if let Some(v) = child_native_method(handle, method)? {
        return Ok(Some(v));
    }
    if let Some(v) = net_native_method(handle, method)? {
        return Ok(Some(v));
    }
    if let Some(v) = udp_native_method(handle, method, args)? {
        return Ok(Some(v));
    }
    if let Some(v) = time_native_method(handle, method, args)? {
        return Ok(Some(v));
    }
    temp_native_method(handle, method)
}

/// Readers: files, socket readers, and lazy line iterators.
fn reader_native_method(
    handle: &Handle,
    method: &str,
    args: &mut [Value],
) -> Result<Option<Value>> {
    match method {
        "read_line" => {
            let mut h = handle.lock();
            let Some(r) = h.as_buf_read() else {
                bail!("read_line on non-reader {}", h.type_name());
            };
            let mut buf = String::new();
            let read = r.read_line(&mut buf);
            drop(h);
            return Ok(Some(io_err(read, |n| {
                if let Some(t) = args.first_mut() {
                    append_string(t, &buf);
                }
                Value::Int(int_len(n))
            })));
        }
        "read_to_string" => {
            let mut h = handle.lock();
            let Some(r) = h.as_read() else {
                bail!("read_to_string on non-reader {}", h.type_name());
            };
            let mut buf = String::new();
            let read = r.read_to_string(&mut buf);
            drop(h);
            return Ok(Some(io_err(read, |n| {
                if let Some(t) = args.first_mut() {
                    append_string(t, &buf);
                }
                Value::Int(int_len(n))
            })));
        }
        "read" => {
            let mut h = handle.lock();
            let Some(r) = h.as_read() else {
                bail!("read on non-reader {}", h.type_name());
            };
            // Fill up to the script buffer's length, then copy back into it,
            // since the buffer arg arrives as a shared Vec value.
            let len = match args.first() {
                Some(Value::Vec(v)) => v.lock().len(),
                _ => 0,
            };
            let mut buf = vec![0u8; len];
            let read = r.read(&mut buf);
            drop(h);
            return Ok(Some(io_err(read, |n| {
                if let Some(Value::Vec(v)) = args.first() {
                    let mut items = v.lock();
                    for (i, byte) in buf.iter().take(n).enumerate() {
                        items[i] = Value::Int(i64::from(*byte));
                    }
                }
                Value::Int(int_len(n))
            })));
        }
        "read_to_end" => {
            let mut h = handle.lock();
            let Some(r) = h.as_read() else {
                bail!("read_to_end on non-reader {}", h.type_name());
            };
            let mut buf = Vec::new();
            let read = r.read_to_end(&mut buf);
            drop(h);
            return Ok(Some(io_err(read, |n| {
                if let Some(t) = args.first() {
                    append_bytes(t, &buf);
                }
                Value::Int(int_len(n))
            })));
        }
        // The byte oriented counterpart of read_line, for output that is not
        // guaranteed to be UTF-8. The delimiter is kept in the buffer, as the
        // real method does, so a caller can tell a final unterminated line
        // from a terminated one.
        "read_until" => {
            let delim = byte_arg(args.first(), "read_until")?;
            let mut h = handle.lock();
            let Some(r) = h.as_buf_read() else {
                bail!("read_until on non-reader {}", h.type_name());
            };
            let mut buf = Vec::new();
            let read = r.read_until(delim, &mut buf);
            drop(h);
            return Ok(Some(io_err(read, |n| {
                if let Some(t) = args.get(1) {
                    append_bytes(t, &buf);
                }
                Value::Int(int_len(n))
            })));
        }
        "lines" | "next" | "collect" => return Ok(lines_native_method(handle, method)),
        _ => {}
    }
    Ok(None)
}

/// The lazy line iterator family: `lines()` moves the reader out, `next` and
/// `collect` walk the iterator it left behind.
fn lines_native_method(handle: &Handle, method: &str) -> Option<Value> {
    match method {
        "lines" => {
            // Move the reader out into a lazy line iterator so a for-loop can
            // stream it. The original handle is left empty.
            let taken = std::mem::replace(&mut *handle.lock(), Native::Taken);
            let iter: super::native::LineIter = match taken {
                Native::File(r) => {
                    use std::io::BufRead;
                    Box::new(r.lines())
                }
                Native::Reader(r) => {
                    use std::io::BufRead;
                    Box::new(r.lines())
                }
                other => {
                    *handle.lock() = other;
                    return None;
                }
            };
            Some(Native::Lines(iter).wrap())
        }
        "next" => {
            if matches!(&*handle.lock(), Native::Lines(_)) {
                return Some(match lines_next(handle) {
                    Some(v) => Value::some(v),
                    None => Value::none(),
                });
            }
            None
        }
        "collect" => {
            if matches!(&*handle.lock(), Native::Lines(_)) {
                return Some(Value::vec(drain_lines(handle)));
            }
            None
        }
        _ => None,
    }
}

/// Writers shared by files, sockets, and process stdin.
fn writer_native_method(handle: &Handle, method: &str, args: &mut [Value]) -> Option<Value> {
    match method {
        "write_all" | "write" => {
            let bytes = value_to_bytes(args.first());
            let mut h = handle.lock();
            if !matches!(
                &*h,
                Native::File(_) | Native::Writer(_) | Native::ChildStdin(_) | Native::Stream(_)
            ) {
                return None;
            }
            let n = bytes.len();
            let r = write_bytes(&mut h, &bytes);
            let is_write = method == "write";
            return Some(io_err(r, |()| {
                if is_write {
                    Value::Int(int_len(n))
                } else {
                    Value::Unit
                }
            }));
        }
        "flush" => {
            let mut h = handle.lock();
            let r = flush_writer(&mut h);
            return Some(io_err(r, |()| Value::Unit));
        }
        _ => {}
    }
    None
}

/// File-only extras beyond plain reads and writes.
fn file_native_method(handle: &Handle, method: &str, args: &mut [Value]) -> Result<Option<Value>> {
    match method {
        "seek" => {
            let pos = seek_from(args.first());
            let mut h = handle.lock();
            if let Native::File(r) = &mut *h {
                return Ok(Some(io_err(r.seek(pos), |n| {
                    Value::Int(i64::try_from(n).unwrap_or(i64::MAX))
                })));
            }
            bail!("seek on non-file {}", h.type_name());
        }
        "sync_all" | "sync_data" => {
            let mut h = handle.lock();
            if let Native::File(r) = &mut *h {
                return Ok(Some(io_err(r.get_ref().sync_all(), |()| Value::Unit)));
            }
            bail!("sync on non-file {}", h.type_name());
        }
        "set_len" => {
            let n = as_int(args.first())
                .and_then(|n| u64::try_from(n).ok())
                .unwrap_or(0);
            let mut h = handle.lock();
            if let Native::File(r) = &mut *h {
                return Ok(Some(io_err(r.get_ref().set_len(n), |()| Value::Unit)));
            }
            bail!("set_len on non-file {}", h.type_name());
        }
        "set_modified" => {
            let time = match args.first() {
                Some(Value::Native(other)) => match &*other.lock() {
                    Native::SystemTime(t) => *t,
                    o => bail!("set_modified needs a SystemTime, got {}", o.type_name()),
                },
                _ => bail!("set_modified needs a SystemTime argument"),
            };
            let h = handle.lock();
            if let Native::File(r) = &*h {
                return Ok(Some(io_err(r.get_ref().set_modified(time), |()| {
                    Value::Unit
                })));
            }
            bail!("set_modified on non-file {}", h.type_name());
        }
        "metadata" => {
            let h = handle.lock();
            if let Native::File(r) = &*h {
                return Ok(Some(io_err(r.get_ref().metadata(), |m| {
                    super::std_bridge::make_metadata(&m)
                })));
            }
            bail!("metadata on non-file {}", h.type_name());
        }
        _ => {}
    }
    Ok(None)
}

/// A spawned child process.
fn child_native_method(handle: &Handle, method: &str) -> Result<Option<Value>> {
    match method {
        "wait" => {
            let mut h = handle.lock();
            if let Native::Child(c) = &mut *h {
                return Ok(Some(io_err(c.wait(), |s| {
                    super::process::make_exit_status(s)
                })));
            }
            bail!("wait on non-child {}", h.type_name());
        }
        "try_wait" => {
            let mut h = handle.lock();
            if let Native::Child(c) = &mut *h {
                return Ok(Some(match c.try_wait() {
                    Ok(Some(s)) => Value::ok(Value::some(super::process::make_exit_status(s))),
                    Ok(None) => Value::ok(Value::none()),
                    Err(e) => Value::err(Value::str(e.to_string())),
                }));
            }
            bail!("try_wait on non-child {}", h.type_name());
        }
        "kill" => {
            let mut h = handle.lock();
            if let Native::Child(c) = &mut *h {
                return Ok(Some(io_err(c.kill(), |()| Value::Unit)));
            }
            bail!("kill on non-child {}", h.type_name());
        }
        "id" => {
            let h = handle.lock();
            if let Native::Child(c) = &*h {
                return Ok(Some(Value::Int(i64::from(c.id()))));
            }
        }
        "wait_with_output" => {
            if !matches!(&*handle.lock(), Native::Child(_)) {
                return Ok(None);
            }
            let taken = std::mem::replace(&mut *handle.lock(), Native::Taken);
            if let Native::Child(c) = taken {
                return Ok(Some(match c.wait_with_output() {
                    Ok(o) => Value::ok(super::process::make_output(o)),
                    Err(e) => Value::err(Value::str(e.to_string())),
                }));
            }
            bail!("wait_with_output on non-child");
        }
        _ => {}
    }
    Ok(None)
}

/// TCP listeners and streams.
fn net_native_method(handle: &Handle, method: &str) -> Result<Option<Value>> {
    match method {
        "accept" => {
            let h = handle.lock();
            if let Native::Listener(l) = &*h {
                return Ok(Some(match l.accept() {
                    Ok((stream, addr)) => Value::ok(Value::tuple(vec![
                        Native::Stream(stream).wrap(),
                        Value::str(addr.to_string()),
                    ])),
                    Err(e) => Value::err(Value::str(e.to_string())),
                }));
            }
            bail!("accept on non-listener {}", h.type_name());
        }
        "incoming" => {
            bail!("incoming() is not supported; loop with listener.accept() instead");
        }
        "local_addr" => {
            let h = handle.lock();
            let addr = match &*h {
                Native::Listener(l) => l.local_addr(),
                Native::Stream(s) => s.local_addr(),
                Native::Udp(s) => s.local_addr(),
                _ => bail!("local_addr on {}", h.type_name()),
            };
            return Ok(Some(io_err(addr, |a| Value::str(a.to_string()))));
        }
        "peer_addr" => {
            let h = handle.lock();
            if let Native::Stream(s) = &*h {
                return Ok(Some(io_err(s.peer_addr(), |a| Value::str(a.to_string()))));
            }
            bail!("peer_addr on {}", h.type_name());
        }
        "shutdown" => {
            let h = handle.lock();
            if let Native::Stream(s) = &*h {
                return Ok(Some(io_err(s.shutdown(std::net::Shutdown::Both), |()| {
                    Value::Unit
                })));
            }
            bail!("shutdown on {}", h.type_name());
        }
        "try_clone" => {
            let h = handle.lock();
            match &*h {
                Native::Stream(s) => {
                    return Ok(Some(io_err(s.try_clone(), |s| Native::Stream(s).wrap())));
                }
                Native::Udp(s) => {
                    return Ok(Some(io_err(s.try_clone(), |s| Native::Udp(s).wrap())));
                }
                _ => bail!("try_clone on {}", h.type_name()),
            }
        }
        _ => {}
    }
    Ok(None)
}

/// UDP sockets.
fn udp_native_method(handle: &Handle, method: &str, args: &mut [Value]) -> Result<Option<Value>> {
    match method {
        "set_broadcast" => {
            let on = matches!(args.first(), Some(Value::Bool(true)));
            let h = handle.lock();
            if let Native::Udp(s) = &*h {
                return Ok(Some(io_err(s.set_broadcast(on), |()| Value::Unit)));
            }
            bail!("set_broadcast on {}", h.type_name());
        }
        "send_to" => {
            let bytes = value_to_bytes(args.first());
            let addr = args.get(1).map(Value::display).unwrap_or_default();
            let h = handle.lock();
            if let Native::Udp(s) = &*h {
                return Ok(Some(io_err(s.send_to(&bytes, addr), |n| {
                    Value::Int(int_len(n))
                })));
            }
            bail!("send_to on {}", h.type_name());
        }
        "send" => {
            let bytes = value_to_bytes(args.first());
            let h = handle.lock();
            if let Native::Udp(s) = &*h {
                return Ok(Some(io_err(s.send(&bytes), |n| Value::Int(int_len(n)))));
            }
            bail!("send on {}", h.type_name());
        }
        "connect" => {
            let addr = args.first().map(Value::display).unwrap_or_default();
            let h = handle.lock();
            if let Native::Udp(s) = &*h {
                return Ok(Some(io_err(s.connect(addr), |()| Value::Unit)));
            }
            bail!("connect on {}", h.type_name());
        }
        _ => {}
    }
    Ok(None)
}

/// `Instant` and `SystemTime`.
fn time_native_method(handle: &Handle, method: &str, args: &mut [Value]) -> Result<Option<Value>> {
    match method {
        "elapsed" => {
            let h = handle.lock();
            match &*h {
                Native::Instant(t) => {
                    return Ok(Some(super::std_bridge::make_duration(t.elapsed())));
                }
                Native::SystemTime(t) => {
                    return Ok(Some(match t.elapsed() {
                        Ok(d) => Value::ok(super::std_bridge::make_duration(d)),
                        Err(e) => Value::err(Value::str(e.to_string())),
                    }));
                }
                _ => bail!("elapsed on {}", h.type_name()),
            }
        }
        "duration_since" => {
            let h = handle.lock();
            match (&*h, args.first()) {
                (Native::Instant(t), Some(Value::Native(other))) => {
                    if let Native::Instant(o) = &*other.lock() {
                        return Ok(Some(super::std_bridge::make_duration(t.duration_since(*o))));
                    }
                }
                (Native::SystemTime(t), Some(Value::Native(other))) => {
                    if let Native::SystemTime(o) = &*other.lock() {
                        return Ok(Some(match t.duration_since(*o) {
                            Ok(d) => Value::ok(super::std_bridge::make_duration(d)),
                            Err(e) => Value::err(Value::str(e.to_string())),
                        }));
                    }
                }
                _ => {}
            }
            bail!("duration_since arguments mismatch");
        }
        _ => {}
    }
    Ok(None)
}

/// Temp dirs and named temp files.
fn temp_native_method(handle: &Handle, method: &str) -> Result<Option<Value>> {
    match method {
        "path" => {
            let h = handle.lock();
            match &*h {
                Native::TempDir(d) => {
                    return Ok(Some(super::std_bridge::make_path(
                        d.path().display().to_string(),
                    )));
                }
                Native::NamedTempFile(f) => {
                    return Ok(Some(super::std_bridge::make_path(
                        f.path().display().to_string(),
                    )));
                }
                _ => {}
            }
        }
        "close" => {
            if !matches!(&*handle.lock(), Native::TempDir(_)) {
                return Ok(None);
            }
            let taken = std::mem::replace(&mut *handle.lock(), Native::Taken);
            if let Native::TempDir(d) = taken {
                return Ok(Some(io_err(d.close(), |()| Value::Unit)));
            }
            bail!("close on non-tempdir");
        }
        _ => {}
    }
    Ok(None)
}

fn write_bytes(h: &mut Native, bytes: &[u8]) -> std::io::Result<()> {
    match h {
        Native::File(r) => r.get_mut().write_all(bytes),
        Native::Writer(w) => w.write_all(bytes),
        Native::ChildStdin(w) => w.write_all(bytes),
        Native::Stream(s) => s.write_all(bytes),
        other => Err(std::io::Error::other(format!(
            "cannot write to {}",
            other.type_name()
        ))),
    }
}

fn flush_writer(h: &mut Native) -> std::io::Result<()> {
    match h {
        Native::File(r) => r.get_mut().flush(),
        Native::Writer(w) => w.flush(),
        Native::ChildStdin(w) => w.flush(),
        Native::Stream(s) => s.flush(),
        _ => Ok(()),
    }
}

pub(super) fn value_to_bytes(v: Option<&Value>) -> Vec<u8> {
    match v {
        Some(Value::Str(s)) => s.as_bytes().to_vec(),
        Some(Value::Vec(items)) => items
            .lock()
            .iter()
            .filter_map(|x| match x {
                Value::Int(i) => u8::try_from(*i).ok(),
                _ => None,
            })
            .collect(),
        Some(other) => other.display().into_bytes(),
        None => Vec::new(),
    }
}

fn as_int(v: Option<&Value>) -> Option<i64> {
    match v {
        Some(Value::Int(i)) => Some(*i),
        _ => None,
    }
}

fn seek_from(v: Option<&Value>) -> SeekFrom {
    // A script passes SeekFrom::Start(n) etc., which the interpreter models as
    // an enum value carrying the offset.
    if let Some(Value::Enum { variant, data, .. }) = v {
        let n = data.first().and_then(|x| match x {
            Value::Int(i) => Some(*i),
            _ => None,
        });
        match (&**variant, n) {
            ("Start", Some(n)) => return SeekFrom::Start(u64::try_from(n).unwrap_or_default()),
            ("End", Some(n)) => return SeekFrom::End(n),
            ("Current", Some(n)) => return SeekFrom::Current(n),
            _ => {}
        }
    }
    SeekFrom::Current(0)
}