run-rs 0.2.30

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
//! Bridges for the `std` paths a `#[tokio::main]` script calls: fs, io
//! streams, env, dirs, and numeric conversions. Mirrors `std_bridge.rs` on the
//! `Send + Sync` value model, so a parallel script can walk directories and
//! probe streams the same way a fast-engine script does.

use std::sync::Arc;

use anyhow::{Result, bail};

use super::int_methods::{from_bytes, from_bytes_order};
use super::numeric::IntWidth;
use super::pvalue::{PStructData, PValue};

/// Native implementations of the supported std subset, dispatched by the last
/// two path segments as `module::func`. Returns None when the path is not
/// covered here, so the caller can try user functions next.
pub(super) fn native_call(module: &str, func: &str, args: &[PValue]) -> Result<Option<PValue>> {
    let s = |i: usize| -> Result<String> {
        match args.get(i) {
            Some(v) => Ok(path_like(v)),
            None => bail!("missing argument {i} for {module}::{func}"),
        }
    };
    Ok(Some(match (module, func) {
        ("fs", "read_to_string") => wrap_io(std::fs::read_to_string(s(0)?)),
        ("fs", "read") => wrap_bytes(std::fs::read(s(0)?)),
        ("fs", "write") => wrap_unit(std::fs::write(s(0)?, s(1)?)),
        ("fs", "create_dir_all") => wrap_unit(std::fs::create_dir_all(s(0)?)),
        ("fs", "read_dir") => match std::fs::read_dir(s(0)?) {
            Ok(rd) => {
                let mut items = Vec::new();
                for e in rd {
                    match e {
                        Ok(entry) => items.push(PValue::ok(make_dir_entry(&entry))),
                        Err(err) => items.push(PValue::err(PValue::str(err.to_string()))),
                    }
                }
                PValue::ok(PValue::vec(items))
            }
            Err(e) => PValue::err(PValue::str(e.to_string())),
        },
        ("fs", "metadata") => match std::fs::metadata(s(0)?) {
            Ok(m) => PValue::ok(make_metadata(&m)),
            Err(e) => PValue::err(PValue::str(e.to_string())),
        },
        ("env", "var") => match std::env::var(s(0)?) {
            Ok(v) => PValue::ok(PValue::str(v)),
            Err(e) => PValue::err(PValue::str(e.to_string())),
        },
        ("io", "stdin" | "stdout" | "stderr") => make_std_stream(func),
        ("dirs", "home_dir") => match dirs::home_dir() {
            Some(p) => PValue::some(make_path(p.display().to_string())),
            None => PValue::none(),
        },
        ("which", "which") => match which::which(s(0)?) {
            Ok(p) => PValue::ok(make_path(p.display().to_string())),
            Err(e) => PValue::err(PValue::str(e.to_string())),
        },
        ("String", "from_utf8_lossy") => PValue::str(bytes_to_string(args.first())),
        // `char::from` only converts a u8 in real Rust, so the byte range is
        // enforced even though every integer is an i64 here.
        ("char", "from") => match args.first() {
            Some(PValue::Char(c)) => PValue::Char(*c),
            Some(PValue::Int(n)) if (0..=255).contains(n) => PValue::Char(char::from(*n as u8)),
            _ => bail!("`char::from` needs a u8"),
        },
        // Every integer type parses the same way here, values are untyped ints.
        (
            "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64" | "u128"
            | "usize",
            "from_str_radix",
        ) => {
            let text = args.first().map(PValue::display).unwrap_or_default();
            let radix = match args.get(1) {
                Some(PValue::Int(i)) => *i as u32,
                _ => 10,
            };
            match i64::from_str_radix(text.trim(), radix) {
                Ok(n) => PValue::ok(PValue::Int(n)),
                Err(e) => PValue::err(PValue::str(e.to_string())),
            }
        }
        // Numeric `T::from(x)`. Every integer is an i64 here, so a widening
        // conversion just carries the value.
        (
            "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64" | "u128"
            | "usize",
            "from",
        ) => PValue::Int(int_from_arg(module, args.first())?),
        ("f32" | "f64", "from") => match args.first() {
            Some(PValue::Float(f)) => PValue::Float(*f),
            Some(PValue::Int(n)) => PValue::Float(*n as f64),
            Some(PValue::Bool(b)) => PValue::Float(if *b { 1.0 } else { 0.0 }),
            _ => bail!("`{module}::from` needs a number"),
        },
        // Fallible `T::try_from(x)`. The value fits when it lands inside the
        // target range, so a narrowing conversion reports overflow with the
        // same message as the real `TryFromIntError`.
        (
            "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64" | "u128"
            | "usize",
            "try_from",
        ) => {
            let n = int_from_arg(module, args.first())?;
            if int_fits(module, n) {
                PValue::ok(PValue::Int(n))
            } else {
                PValue::err(PValue::str(
                    "out of range integral type conversion attempted",
                ))
            }
        }
        // `T::from_le_bytes` and its be and ne siblings, over the same shared
        // core the fast engine and the `to_*_bytes` methods use.
        (
            "i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64" | "usize",
            "from_le_bytes" | "from_be_bytes" | "from_ne_bytes",
        ) => int_from_bytes(module, func, args)?,
        ("terminal", "size") => terminal_size(),
        ("terminal_light", "luma") => terminal_luma(),
        _ => return Ok(None),
    }))
}

/// `crossterm::terminal::size`. The pair is columns then rows, the order the
/// real call returns, which is the opposite of how a `Rect` is written.
fn terminal_size() -> PValue {
    match crossterm::terminal::size() {
        Ok((cols, rows)) => PValue::ok(PValue::tuple(vec![
            PValue::Int(i64::from(cols)),
            PValue::Int(i64::from(rows)),
        ])),
        Err(e) => PValue::err(PValue::str(e.to_string())),
    }
}

/// `terminal_light::luma`, the background brightness from 0 for black to 1 for
/// white. The crate asks the terminal over an escape sequence and falls back to
/// `$COLORFGBG`, so an error means neither source answered.
fn terminal_luma() -> PValue {
    match terminal_light::luma() {
        Ok(luma) => PValue::ok(PValue::F32(luma)),
        Err(e) => PValue::err(PValue::str(e.to_string())),
    }
}

// -- path, directory entry, file type, metadata, streams --------------------

pub(super) fn make_path(s: impl Into<String>) -> PValue {
    PValue::struct_of("Path", [("s".into(), PValue::str(s.into()))])
}

fn make_dir_entry(entry: &std::fs::DirEntry) -> PValue {
    PValue::struct_of(
        "DirEntry",
        [
            (
                "path".into(),
                PValue::str(entry.path().display().to_string()),
            ),
            (
                "name".into(),
                PValue::str(entry.file_name().to_string_lossy().into_owned()),
            ),
        ],
    )
}

fn make_file_type(path: &std::path::Path) -> PValue {
    // DirEntry::file_type does not follow symlinks, so a symlink to a dir
    // reports is_symlink, not is_dir, same as the real std.
    let ft = path.symlink_metadata().map(|m| m.file_type());
    let is =
        |f: &dyn Fn(&std::fs::FileType) -> bool| PValue::Bool(ft.as_ref().map(f).unwrap_or(false));
    PValue::struct_of(
        "FileType",
        [
            ("is_dir".into(), is(&|t| t.is_dir())),
            ("is_file".into(), is(&|t| t.is_file())),
            ("is_symlink".into(), is(&|t| t.is_symlink())),
        ],
    )
}

fn make_metadata(m: &std::fs::Metadata) -> PValue {
    PValue::struct_of(
        "Metadata",
        [
            ("len".into(), PValue::Int(m.len() as i64)),
            ("is_dir".into(), PValue::Bool(m.is_dir())),
            ("is_file".into(), PValue::Bool(m.is_file())),
            ("is_symlink".into(), PValue::Bool(m.is_symlink())),
            ("readonly".into(), PValue::Bool(m.permissions().readonly())),
        ],
    )
}

fn make_std_stream(kind: &str) -> PValue {
    PValue::struct_of("StdStream", [("kind".into(), PValue::str(kind))])
}

pub(super) fn path_method(st: &Arc<PStructData>, m: &str, args: &[PValue]) -> Result<PValue> {
    let s = st.get("s").map(|v| v.display()).unwrap_or_default();
    let p = std::path::Path::new(&s);
    let opt_str = |o: Option<&std::ffi::OsStr>| match o {
        Some(v) => PValue::some(PValue::str(v.to_string_lossy().into_owned())),
        None => PValue::none(),
    };
    Ok(match m {
        "display" | "to_string_lossy" => PValue::str(s.clone()),
        "to_str" => PValue::some(PValue::str(s.clone())),
        "into_string" | "into_os_string" => PValue::ok(PValue::str(s.clone())),
        "to_owned" | "to_path_buf" | "as_path" | "as_os_str" => make_path(s.clone()),
        "is_dir" => PValue::Bool(p.is_dir()),
        "is_file" => PValue::Bool(p.is_file()),
        "is_absolute" => PValue::Bool(p.is_absolute()),
        "exists" => PValue::Bool(p.exists()),
        "file_name" => match p.file_name() {
            Some(n) => PValue::some(make_path(n.to_string_lossy().into_owned())),
            None => PValue::none(),
        },
        "file_stem" => opt_str(p.file_stem()),
        "extension" => opt_str(p.extension()),
        "parent" => match p.parent() {
            Some(par) => PValue::some(make_path(par.display().to_string())),
            None => PValue::none(),
        },
        "ancestors" => PValue::vec(
            p.ancestors()
                .map(|ancestor| make_path(ancestor.display().to_string()))
                .collect(),
        ),
        "join" | "push" => {
            let joined = p.join(args.first().map(PValue::display).unwrap_or_default());
            make_path(joined.display().to_string())
        }
        _ => bail!("method `{m}` on Path is not supported in tokio mode"),
    })
}

pub(super) fn os_string_method(st: &Arc<PStructData>, m: &str) -> Result<PValue> {
    let value = st.get("s").map(|v| v.display()).unwrap_or_default();
    Ok(match m {
        "into" => make_path(value),
        "to_string_lossy" | "to_str" => PValue::str(value),
        "is_empty" => PValue::Bool(value.is_empty()),
        _ => bail!("method `{m}` on OsString is not supported in tokio mode"),
    })
}

pub(super) fn dir_entry_method(st: &Arc<PStructData>, m: &str) -> Result<PValue> {
    let path = st.get("path").map(|v| v.display()).unwrap_or_default();
    Ok(match m {
        "path" => make_path(path),
        "file_name" => make_path(st.get("name").map(|v| v.display()).unwrap_or_default()),
        "file_type" => PValue::ok(make_file_type(std::path::Path::new(&path))),
        _ => bail!("method `{m}` on DirEntry is not supported in tokio mode"),
    })
}

pub(super) fn file_type_method(st: &Arc<PStructData>, m: &str) -> Result<PValue> {
    Ok(match m {
        "is_dir" | "is_file" | "is_symlink" => st.get(m).unwrap_or(PValue::Bool(false)),
        _ => bail!("method `{m}` on FileType is not supported in tokio mode"),
    })
}

pub(super) fn metadata_method(st: &Arc<PStructData>, m: &str) -> Result<PValue> {
    Ok(match m {
        "len" | "is_dir" | "is_file" | "is_symlink" | "readonly" => {
            st.get(m).unwrap_or(PValue::Unit)
        }
        _ => bail!("method `{m}` on Metadata is not supported in tokio mode"),
    })
}

pub(super) fn std_stream_method(st: &Arc<PStructData>, m: &str) -> Result<PValue> {
    use std::io::IsTerminal;
    Ok(match m {
        "is_terminal" => {
            let kind = st.get("kind").map(|v| v.display()).unwrap_or_default();
            PValue::Bool(match kind.as_str() {
                "stdin" => std::io::stdin().is_terminal(),
                "stderr" => std::io::stderr().is_terminal(),
                _ => std::io::stdout().is_terminal(),
            })
        }
        "lock" | "by_ref" => PValue::Struct(st.clone()),
        // A redraw loop prints without a newline and then flushes, so without
        // this the frame sits in the buffer and the screen never updates.
        "flush" => {
            use std::io::Write;
            let kind = st.get("kind").map(|v| v.display()).unwrap_or_default();
            let flushed = if kind == "stderr" {
                std::io::stderr().flush()
            } else {
                std::io::stdout().flush()
            };
            match flushed {
                Ok(()) => PValue::ok(PValue::Unit),
                Err(e) => PValue::err(PValue::str(e.to_string())),
            }
        }
        _ => bail!("method `{m}` on a std stream is not supported in tokio mode"),
    })
}

// -- helpers ----------------------------------------------------------------

/// Turn a value into a path string. A `Path`/`PathBuf`/`OsString` value carries
/// the path in its `s` field; anything else uses its display form.
fn path_like(v: &PValue) -> String {
    match v {
        PValue::Struct(st) if matches!(&**st.name(), "Path" | "PathBuf" | "OsString") => {
            st.get("s").map(|s| s.display()).unwrap_or_default()
        }
        other => other.display(),
    }
}

fn wrap_io(r: std::io::Result<String>) -> PValue {
    match r {
        Ok(s) => PValue::ok(PValue::str(s)),
        Err(e) => PValue::err(PValue::str(e.to_string())),
    }
}

fn wrap_bytes(r: std::io::Result<Vec<u8>>) -> PValue {
    match r {
        Ok(bytes) => PValue::ok(PValue::vec(
            bytes
                .into_iter()
                .map(|b| PValue::Int(i64::from(b)))
                .collect(),
        )),
        Err(e) => PValue::err(PValue::str(e.to_string())),
    }
}

fn wrap_unit(r: std::io::Result<()>) -> PValue {
    match r {
        Ok(()) => PValue::ok(PValue::Unit),
        Err(e) => PValue::err(PValue::str(e.to_string())),
    }
}

fn bytes_to_string(arg: Option<&PValue>) -> String {
    match arg {
        Some(PValue::Str(s)) => s.to_string(),
        Some(PValue::Vec(v)) => {
            let bytes: Vec<u8> = v
                .lock()
                .iter()
                .filter_map(|x| match x {
                    PValue::Int(i) => Some(*i as u8),
                    _ => None,
                })
                .collect();
            String::from_utf8_lossy(&bytes).into_owned()
        }
        _ => String::new(),
    }
}

fn int_from_arg(ty: &str, v: Option<&PValue>) -> Result<i64> {
    match v {
        Some(PValue::Int(n)) => Ok(*n),
        Some(PValue::Bool(b)) => Ok(i64::from(*b)),
        Some(PValue::Char(c)) => Ok(*c as i64),
        _ => bail!("`{ty}` conversion needs an integer"),
    }
}

/// `T::from_le_bytes([..])` and its be and ne siblings.
fn int_from_bytes(ty: &str, func: &str, args: &[PValue]) -> Result<PValue> {
    let (Some(width), Some(order)) = (IntWidth::parse(ty), from_bytes_order(func)) else {
        bail!("`{ty}::{func}` is not a byte conversion");
    };
    let bytes = byte_array(ty, func, args.first())?;
    Ok(PValue::int_of_width(
        from_bytes(width, order, &bytes)?,
        width,
    ))
}

/// The `[u8; N]` argument of a byte conversion. An array literal is a vec at
/// runtime, so the shape real Rust guarantees in its type is read back here.
fn byte_array(ty: &str, func: &str, arg: Option<&PValue>) -> Result<Vec<i128>> {
    let Some(PValue::Vec(items)) = arg else {
        bail!("`{ty}::{func}` needs a byte array");
    };
    let items = items.lock();
    let mut out = Vec::with_capacity(items.len());
    for item in items.iter() {
        let Some((value, _)) = item.int_parts() else {
            bail!("`{ty}::{func}` needs a byte array");
        };
        out.push(value);
    }
    Ok(out)
}

/// Whether `n` lands inside the target integer type range.
fn int_fits(ty: &str, n: i64) -> bool {
    match ty {
        "i8" => i8::try_from(n).is_ok(),
        "i16" => i16::try_from(n).is_ok(),
        "i32" => i32::try_from(n).is_ok(),
        "u8" => u8::try_from(n).is_ok(),
        "u16" => u16::try_from(n).is_ok(),
        "u32" => u32::try_from(n).is_ok(),
        "u64" | "u128" | "usize" => n >= 0,
        _ => true,
    }
}