runmat-runtime 0.5.0

Core runtime for RunMat with builtins, BLAS/LAPACK integration, and execution APIs
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
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
//! MATLAB-compatible `rmpath` builtin for manipulating the RunMat search path.

use runmat_builtins::{
    BuiltinCompletionPolicy, BuiltinDescriptor, BuiltinErrorDescriptor, BuiltinOutputMode,
    BuiltinParamArity, BuiltinParamDescriptor, BuiltinParamType, BuiltinSignatureDescriptor,
    CharArray, StringArray, Tensor, Value,
};
use runmat_macros::runtime_builtin;

use crate::builtins::common::fs::{expand_user_path, path_to_string};
use crate::builtins::common::path_state::{
    current_path_segments, current_path_string, set_path_string, PATH_LIST_SEPARATOR,
};
use crate::builtins::common::spec::{
    BroadcastSemantics, BuiltinFusionSpec, BuiltinGpuSpec, ConstantStrategy, GpuOpKind,
    ReductionNaN, ResidencyPolicy, ShapeRequirements,
};
use crate::{build_runtime_error, gather_if_needed_async, BuiltinResult, RuntimeError};

use runmat_filesystem as vfs;
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};

#[runmat_macros::register_gpu_spec(builtin_path = "crate::builtins::io::repl_fs::rmpath")]
pub const GPU_SPEC: BuiltinGpuSpec = BuiltinGpuSpec {
    name: "rmpath",
    op_kind: GpuOpKind::Custom("io"),
    supported_precisions: &[],
    broadcast: BroadcastSemantics::None,
    provider_hooks: &[],
    constant_strategy: ConstantStrategy::InlineLiteral,
    residency: ResidencyPolicy::GatherImmediately,
    nan_mode: ReductionNaN::Include,
    two_pass_threshold: None,
    workgroup_size: None,
    accepts_nan_mode: false,
    notes: "Search-path manipulation is a host-only operation; GPU inputs are gathered before processing.",
};

#[runmat_macros::register_fusion_spec(builtin_path = "crate::builtins::io::repl_fs::rmpath")]
pub const FUSION_SPEC: BuiltinFusionSpec = BuiltinFusionSpec {
    name: "rmpath",
    shape: ShapeRequirements::Any,
    constant_strategy: ConstantStrategy::InlineLiteral,
    elementwise: None,
    reduction: None,
    emits_nan: false,
    notes: "IO builtins are not eligible for fusion; metadata registered for completeness.",
};

const BUILTIN_NAME: &str = "rmpath";

const RMPATH_OUTPUT: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "oldpath",
    ty: BuiltinParamType::StringScalar,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "Previous search path string.",
}];
const RMPATH_INPUTS_FOLDER: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "folder1",
    ty: BuiltinParamType::Any,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "Folder, path-list string, or container of folders to remove.",
}];
const RMPATH_INPUTS_FOLDER_VARIADIC: [BuiltinParamDescriptor; 2] = [
    BuiltinParamDescriptor {
        name: "folder1",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "First folder argument.",
    },
    BuiltinParamDescriptor {
        name: "folderN",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Variadic,
        default: None,
        description: "Additional folder arguments.",
    },
];
const RMPATH_SIGNATURES: [BuiltinSignatureDescriptor; 2] = [
    BuiltinSignatureDescriptor {
        label: "oldpath = rmpath(folder1)",
        inputs: &RMPATH_INPUTS_FOLDER,
        outputs: &RMPATH_OUTPUT,
    },
    BuiltinSignatureDescriptor {
        label: "oldpath = rmpath(folder1, folder2, ...)",
        inputs: &RMPATH_INPUTS_FOLDER_VARIADIC,
        outputs: &RMPATH_OUTPUT,
    },
];

const RMPATH_ERROR_ARG_TYPE: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.RMPATH.ARG_TYPE",
    identifier: None,
    when: "Folder arguments are not character vectors, string scalars/arrays, tensors of character codes, or cell arrays containing those forms.",
    message:
        "rmpath: folder names must be character vectors, string scalars, string arrays, or cell arrays of character vectors",
};
const RMPATH_ERROR_TOO_FEW_ARGS: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.RMPATH.TOO_FEW_ARGS",
    identifier: None,
    when: "No folder arguments are provided, or all provided folder tokens are empty.",
    message: "rmpath: at least one folder must be specified",
};
const RMPATH_ERROR_CWD_RESOLVE: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.RMPATH.CWD_RESOLVE",
    identifier: None,
    when: "Current directory cannot be resolved while normalizing a relative folder.",
    message: "rmpath: unable to resolve current directory",
};
const RMPATH_ERROR_NOT_FOLDER: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.RMPATH.NOT_FOLDER",
    identifier: None,
    when: "The requested path exists but is not a folder.",
    message: "rmpath: path is not a folder",
};
const RMPATH_ERROR_NOT_ON_PATH: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.RMPATH.NOT_ON_PATH",
    identifier: None,
    when: "The requested folder exists but is not on the active search path.",
    message: "rmpath: folder not on search path",
};
const RMPATH_ERROR_FOLDER_NOT_FOUND: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.RMPATH.FOLDER_NOT_FOUND",
    identifier: None,
    when: "The requested folder path does not exist.",
    message: "rmpath: folder not found",
};
const RMPATH_ERRORS: [BuiltinErrorDescriptor; 6] = [
    RMPATH_ERROR_ARG_TYPE,
    RMPATH_ERROR_TOO_FEW_ARGS,
    RMPATH_ERROR_CWD_RESOLVE,
    RMPATH_ERROR_NOT_FOLDER,
    RMPATH_ERROR_NOT_ON_PATH,
    RMPATH_ERROR_FOLDER_NOT_FOUND,
];
pub const RMPATH_DESCRIPTOR: BuiltinDescriptor = BuiltinDescriptor {
    signatures: &RMPATH_SIGNATURES,
    output_mode: BuiltinOutputMode::Fixed,
    completion_policy: BuiltinCompletionPolicy::Public,
    errors: &RMPATH_ERRORS,
};

fn rmpath_error(error: &'static BuiltinErrorDescriptor) -> RuntimeError {
    rmpath_error_with_message(error.message, error)
}

fn rmpath_error_with_message(
    message: impl Into<String>,
    error: &'static BuiltinErrorDescriptor,
) -> RuntimeError {
    let mut builder = build_runtime_error(message).with_builtin(BUILTIN_NAME);
    if let Some(identifier) = error.identifier {
        builder = builder.with_identifier(identifier);
    }
    builder.build()
}

fn rmpath_error_with_detail(
    error: &'static BuiltinErrorDescriptor,
    detail: impl AsRef<str>,
) -> RuntimeError {
    rmpath_error_with_message(format!("{}: {}", error.message, detail.as_ref()), error)
}

fn map_control_flow(err: RuntimeError) -> RuntimeError {
    let identifier = err.identifier().map(str::to_string);
    let mut builder = build_runtime_error(format!("{BUILTIN_NAME}: {}", err.message()))
        .with_builtin(BUILTIN_NAME)
        .with_source(err);
    if let Some(identifier) = identifier {
        builder = builder.with_identifier(identifier);
    }
    builder.build()
}

#[runtime_builtin(
    name = "rmpath",
    category = "io/repl_fs",
    summary = "Remove folders from the active MATLAB search path.",
    keywords = "rmpath,search path,matlab path,remove folder",
    accel = "cpu",
    suppress_auto_output = true,
    type_resolver(crate::builtins::io::type_resolvers::rmpath_type),
    descriptor(crate::builtins::io::repl_fs::rmpath::RMPATH_DESCRIPTOR),
    builtin_path = "crate::builtins::io::repl_fs::rmpath"
)]
async fn rmpath_builtin(args: Vec<Value>) -> crate::BuiltinResult<Value> {
    if args.is_empty() {
        return Err(rmpath_error(&RMPATH_ERROR_TOO_FEW_ARGS));
    }

    let gathered = gather_arguments(&args).await?;
    let directories = parse_directories(&gathered).await?;

    let previous = current_path_string();
    apply_rmpath(directories).await?;
    Ok(char_array_value(&previous))
}

async fn gather_arguments(args: &[Value]) -> BuiltinResult<Vec<Value>> {
    let mut out = Vec::with_capacity(args.len());
    for value in args {
        out.push(
            gather_if_needed_async(value)
                .await
                .map_err(map_control_flow)?,
        );
    }
    Ok(out)
}

async fn parse_directories(args: &[Value]) -> BuiltinResult<Vec<String>> {
    let mut directories = Vec::new();
    for value in args {
        collect_strings(value, &mut directories).await?;
    }

    if directories.is_empty() {
        return Err(rmpath_error(&RMPATH_ERROR_TOO_FEW_ARGS));
    }

    let mut resolved = Vec::new();
    for token in directories {
        let trimmed = token.trim();
        if trimmed.is_empty() {
            continue;
        }
        resolved.extend(split_path_list(trimmed));
    }

    if resolved.is_empty() {
        return Err(rmpath_error(&RMPATH_ERROR_TOO_FEW_ARGS));
    }

    Ok(resolved)
}

#[async_recursion::async_recursion(?Send)]
async fn collect_strings(value: &Value, output: &mut Vec<String>) -> BuiltinResult<()> {
    match value {
        Value::String(text) => {
            output.push(text.clone());
            Ok(())
        }
        Value::StringArray(StringArray { data, .. }) => {
            for entry in data {
                output.push(entry.clone());
            }
            Ok(())
        }
        Value::CharArray(chars) => {
            if chars.rows == 1 {
                output.push(chars.data.iter().collect());
                return Ok(());
            }
            for row in 0..chars.rows {
                let mut line = String::with_capacity(chars.cols);
                for col in 0..chars.cols {
                    line.push(chars.data[row * chars.cols + col]);
                }
                output.push(line.trim_end().to_string());
            }
            Ok(())
        }
        Value::Tensor(tensor) => {
            output.push(tensor_to_string(tensor)?);
            Ok(())
        }
        Value::Cell(cell) => {
            for ptr in &cell.data {
                let inner = (**ptr).clone();
                let gathered = gather_if_needed_async(&inner)
                    .await
                    .map_err(map_control_flow)?;
                collect_strings(&gathered, output).await?;
            }
            Ok(())
        }
        Value::GpuTensor(_) => Err(rmpath_error(&RMPATH_ERROR_ARG_TYPE)),
        _ => Err(rmpath_error(&RMPATH_ERROR_ARG_TYPE)),
    }
}

fn split_path_list(text: &str) -> Vec<String> {
    text.split(PATH_LIST_SEPARATOR)
        .map(|segment| segment.trim())
        .filter(|segment| !segment.is_empty())
        .map(|segment| segment.to_string())
        .collect()
}

async fn apply_rmpath(directories: Vec<String>) -> BuiltinResult<()> {
    let mut segments = current_path_segments();
    let mut changed = false;
    let mut seen = HashSet::new();

    for raw in directories {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            continue;
        }

        let dedup_key = path_identity(trimmed);
        if !seen.insert(dedup_key) {
            continue;
        }

        if remove_directory(&mut segments, trimmed).await? {
            changed = true;
        }
    }

    if changed {
        let new_path = if segments.is_empty() {
            String::new()
        } else {
            join_segments(&segments)
        };
        set_path_string(&new_path);
    }

    Ok(())
}

async fn remove_directory(segments: &mut Vec<String>, raw: &str) -> BuiltinResult<bool> {
    let direct_identity = path_identity(raw);
    let before = segments.len();
    segments.retain(|entry| path_identity(entry) != direct_identity);
    if segments.len() != before {
        return Ok(true);
    }

    let expanded = expand_user_path(raw, "rmpath")
        .map_err(|err| rmpath_error_with_detail(&RMPATH_ERROR_FOLDER_NOT_FOUND, err))?;
    let path = Path::new(&expanded);
    let joined = if path.is_absolute() {
        path.to_path_buf()
    } else {
        vfs::current_dir()
            .map_err(|_| rmpath_error(&RMPATH_ERROR_CWD_RESOLVE))?
            .join(path)
    };
    let normalized = normalize_pathbuf(&joined);
    let canonical = path_to_string(&normalized);

    let canonical_identity = path_identity(&canonical);
    let before = segments.len();
    segments.retain(|entry| path_identity(entry) != canonical_identity);
    if segments.len() != before {
        return Ok(true);
    }

    match vfs::metadata_async(&normalized).await {
        Ok(meta) => {
            if !meta.is_dir() {
                Err(rmpath_error_with_detail(&RMPATH_ERROR_NOT_FOLDER, raw))
            } else {
                Err(rmpath_error_with_detail(&RMPATH_ERROR_NOT_ON_PATH, raw))
            }
        }
        Err(_) => Err(rmpath_error_with_detail(
            &RMPATH_ERROR_FOLDER_NOT_FOUND,
            raw,
        )),
    }
}

fn normalize_pathbuf(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
            Component::RootDir => normalized.push(component.as_os_str()),
            Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
            Component::Normal(part) => normalized.push(part),
        }
    }
    if normalized.as_os_str().is_empty() {
        path.to_path_buf()
    } else {
        normalized
    }
}

fn tensor_to_string(tensor: &Tensor) -> BuiltinResult<String> {
    if tensor.shape.len() > 2 {
        return Err(rmpath_error(&RMPATH_ERROR_ARG_TYPE));
    }
    if tensor.rows() > 1 {
        return Err(rmpath_error(&RMPATH_ERROR_ARG_TYPE));
    }
    let mut text = String::with_capacity(tensor.data.len());
    for &code in &tensor.data {
        if !code.is_finite() {
            return Err(rmpath_error(&RMPATH_ERROR_ARG_TYPE));
        }
        let rounded = code.round();
        if (code - rounded).abs() > 1e-6 {
            return Err(rmpath_error(&RMPATH_ERROR_ARG_TYPE));
        }
        let int_code = rounded as i64;
        if !(0..=0x10FFFF).contains(&int_code) {
            return Err(rmpath_error(&RMPATH_ERROR_ARG_TYPE));
        }
        let ch =
            char::from_u32(int_code as u32).ok_or_else(|| rmpath_error(&RMPATH_ERROR_ARG_TYPE))?;
        text.push(ch);
    }
    Ok(text)
}

fn path_identity(path: &str) -> String {
    #[cfg(windows)]
    {
        path.replace('/', "\\").to_ascii_lowercase()
    }
    #[cfg(not(windows))]
    {
        path.to_string()
    }
}

fn join_segments(segments: &[String]) -> String {
    let mut joined = String::new();
    for (idx, segment) in segments.iter().enumerate() {
        if idx > 0 {
            joined.push(PATH_LIST_SEPARATOR);
        }
        joined.push_str(segment);
    }
    joined
}

fn char_array_value(text: &str) -> Value {
    Value::CharArray(CharArray::new_row(text))
}

#[cfg(test)]
pub(crate) mod tests {
    use super::super::REPL_FS_TEST_LOCK;
    use super::*;
    use crate::builtins::common::path_state::{current_path_segments, set_path_string};
    use runmat_builtins::CellArray;
    use std::convert::TryFrom;
    use tempfile::tempdir;

    fn rmpath_builtin(args: Vec<Value>) -> BuiltinResult<Value> {
        futures::executor::block_on(super::rmpath_builtin(args))
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn rmpath_descriptor_signatures_cover_core_forms() {
        let labels: Vec<&str> = RMPATH_DESCRIPTOR
            .signatures
            .iter()
            .map(|sig| sig.label)
            .collect();
        assert!(labels.contains(&"oldpath = rmpath(folder1)"));
        assert!(labels.contains(&"oldpath = rmpath(folder1, folder2, ...)"));
    }

    struct PathGuard {
        previous: String,
    }

    impl PathGuard {
        fn new() -> Self {
            Self {
                previous: current_path_string(),
            }
        }
    }

    impl Drop for PathGuard {
        fn drop(&mut self) {
            set_path_string(&self.previous);
        }
    }

    fn canonical(dir: &Path) -> String {
        let normalized = normalize_pathbuf(dir);
        path_to_string(&normalized)
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn rmpath_removes_single_entry() {
        let _lock = REPL_FS_TEST_LOCK
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        let _guard = PathGuard::new();

        let target = tempdir().expect("target");
        let keep = tempdir().expect("keep");
        let target_str = canonical(target.path());
        let keep_str = canonical(keep.path());
        let combined = format!(
            "{target}{sep}{keep}",
            target = target_str,
            keep = keep_str,
            sep = PATH_LIST_SEPARATOR
        );
        set_path_string(&combined);

        let returned = rmpath_builtin(vec![Value::String(target_str.clone())]).expect("rmpath");
        let returned_str = String::try_from(&returned).expect("convert");
        assert_eq!(returned_str, combined);

        let segments = current_path_segments();
        assert_eq!(segments, vec![keep_str]);
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn rmpath_splits_path_list_argument() {
        let _lock = REPL_FS_TEST_LOCK
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        let _guard = PathGuard::new();

        let dir1 = tempdir().expect("dir1");
        let dir2 = tempdir().expect("dir2");
        let dir3 = tempdir().expect("dir3");

        let str1 = canonical(dir1.path());
        let str2 = canonical(dir2.path());
        let str3 = canonical(dir3.path());

        let combined = format!(
            "{first}{sep}{second}{sep}{third}",
            first = str1,
            second = str2,
            third = str3,
            sep = PATH_LIST_SEPARATOR
        );
        set_path_string(&combined);

        let to_remove = format!("{str1}{sep}{str2}", sep = PATH_LIST_SEPARATOR);
        rmpath_builtin(vec![Value::String(to_remove)]).expect("rmpath");

        let segments = current_path_segments();
        assert_eq!(segments, vec![str3]);
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn rmpath_accepts_string_containers() {
        let _lock = REPL_FS_TEST_LOCK
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        let _guard = PathGuard::new();

        let dir1 = tempdir().expect("dir1");
        let dir2 = tempdir().expect("dir2");

        let str1 = canonical(dir1.path());
        let str2 = canonical(dir2.path());
        set_path_string(&format!("{str1}{sep}{str2}", sep = PATH_LIST_SEPARATOR));

        let strings = StringArray::new(vec![str1.clone()], vec![1, 1]).expect("string array");
        let chars = CharArray::new_row(str2.as_str());
        let args = vec![Value::StringArray(strings), Value::CharArray(chars)];
        rmpath_builtin(args).expect("rmpath");

        let segments = current_path_segments();
        assert!(segments.is_empty());
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn rmpath_supports_cell_array() {
        let _lock = REPL_FS_TEST_LOCK
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        let _guard = PathGuard::new();

        let dir = tempdir().expect("dir");
        let str = canonical(dir.path());
        set_path_string(&str);

        let cell = CellArray::new(vec![Value::String(str.clone())], 1, 1).expect("cell");
        rmpath_builtin(vec![Value::Cell(cell)]).expect("rmpath");
        let segments = current_path_segments();
        assert!(segments.is_empty());
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn rmpath_errors_on_missing_folder() {
        let _lock = REPL_FS_TEST_LOCK
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        let _guard = PathGuard::new();

        set_path_string("");
        let err = rmpath_builtin(vec![Value::String("this/folder/does/not/exist".into())])
            .expect_err("expected error");
        assert!(err.message().contains("not found"));
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn rmpath_errors_when_folder_not_on_path() {
        let _lock = REPL_FS_TEST_LOCK
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        let _guard = PathGuard::new();

        let dir = tempdir().expect("dir");
        let str = canonical(dir.path());
        set_path_string("");

        let err = rmpath_builtin(vec![Value::String(str.clone())]).expect_err("expected error");
        assert!(err.message().contains("not on search path"));
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn rmpath_returns_previous_path() {
        let _lock = REPL_FS_TEST_LOCK
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        let _guard = PathGuard::new();

        let dir = tempdir().expect("dir");
        let str = canonical(dir.path());
        set_path_string(&str);

        let returned = rmpath_builtin(vec![Value::String(str.clone())]).expect("rmpath");
        let returned_str = String::try_from(&returned).expect("string");
        assert_eq!(returned_str, str);
    }
}