runmat-runtime 0.4.1

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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
//! MATLAB-compatible `delete` builtin for RunMat.

use runmat_filesystem as vfs;
use std::io;
use std::path::{Path, PathBuf};

use glob::{Pattern, PatternError};
use runmat_builtins::{CellArray, CharArray, StringArray, Value};
use runmat_macros::runtime_builtin;

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

const MESSAGE_ID_FILE_NOT_FOUND: &str = "RunMat:DELETE:FileNotFound";
const MESSAGE_ID_IS_DIRECTORY: &str = "RunMat:delete:Directories";
const MESSAGE_ID_OS_ERROR: &str = "RunMat:DELETE:PermissionDenied";
const MESSAGE_ID_INVALID_PATTERN: &str = "RunMat:delete:InvalidPattern";
const MESSAGE_ID_INVALID_INPUT: &str = "RunMat:delete:InvalidInput";
const MESSAGE_ID_EMPTY_FILENAME: &str = "RunMat:delete:EmptyFilename";
const MESSAGE_ID_INVALID_HANDLE: &str = "RunMat:delete:InvalidHandle";

const ERR_FILENAME_ARG: &str =
    "delete: filename must be a character vector, string scalar, string array, or cell array of character vectors";

#[runmat_macros::register_gpu_spec(builtin_path = "crate::builtins::io::repl_fs::delete")]
pub const GPU_SPEC: BuiltinGpuSpec = BuiltinGpuSpec {
    name: "delete",
    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:
        "Host-only filesystem operation. GPU-resident path values are gathered automatically before deletion.",
};

#[runmat_macros::register_fusion_spec(builtin_path = "crate::builtins::io::repl_fs::delete")]
pub const FUSION_SPEC: BuiltinFusionSpec = BuiltinFusionSpec {
    name: "delete",
    shape: ShapeRequirements::Any,
    constant_strategy: ConstantStrategy::InlineLiteral,
    elementwise: None,
    reduction: None,
    emits_nan: false,
    notes:
        "Filesystem side-effects are executed immediately; metadata registered for completeness.",
};

const BUILTIN_NAME: &str = "delete";

fn delete_error(message_id: &'static str, message: impl Into<String>) -> RuntimeError {
    build_runtime_error(message)
        .with_builtin(BUILTIN_NAME)
        .with_identifier(message_id)
        .build()
}

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 = "delete",
    category = "io/repl_fs",
    summary = "Remove files using MATLAB-compatible wildcard expansion, array inputs, and error diagnostics.",
    keywords = "delete,remove file,wildcard delete,cleanup,temporary files,MATLAB delete",
    accel = "cpu",
    sink = true,
    suppress_auto_output = true,
    type_resolver(crate::builtins::io::type_resolvers::delete_type),
    builtin_path = "crate::builtins::io::repl_fs::delete"
)]
async fn delete_builtin(args: Vec<Value>) -> crate::BuiltinResult<Value> {
    if args.is_empty() {
        return Err(delete_error(
            MESSAGE_ID_INVALID_INPUT,
            "delete: missing filename input",
        ));
    }
    let gathered = gather_arguments(&args).await?;

    if gathered.iter().all(is_handle_input) {
        return delete_handles(&gathered);
    }

    if gathered.iter().any(contains_handle_input) {
        return Err(delete_error(
            MESSAGE_ID_INVALID_HANDLE,
            "delete: cannot mix handle and filename inputs",
        ));
    }

    let mut raw_targets = Vec::new();
    for value in &gathered {
        collect_targets(value, &mut raw_targets)?;
    }

    if raw_targets.is_empty() {
        return Ok(Value::Num(0.0));
    }

    for raw in raw_targets {
        delete_target(&raw).await?;
    }

    Ok(Value::Num(0.0))
}

async fn delete_target(raw: &str) -> BuiltinResult<()> {
    let expanded = expand_user_path(raw, "delete")
        .map_err(|msg| delete_error(MESSAGE_ID_INVALID_INPUT, msg))?;
    if expanded.is_empty() {
        return Err(delete_error(
            MESSAGE_ID_EMPTY_FILENAME,
            "delete: filename cannot be empty",
        ));
    }

    if contains_wildcards(&expanded) {
        delete_with_pattern(&expanded, raw).await
    } else {
        delete_single_path_async(&PathBuf::from(&expanded), raw).await
    }
}

async fn delete_with_pattern(pattern: &str, display: &str) -> BuiltinResult<()> {
    validate_wildcard_pattern(pattern, display)?;

    if let Err(PatternError { msg, .. }) = Pattern::new(pattern) {
        return Err(delete_error(
            MESSAGE_ID_INVALID_PATTERN,
            format!("delete: invalid wildcard pattern '{display}' ({msg})"),
        ));
    }

    let paths = match glob::glob(pattern) {
        Ok(iter) => iter,
        Err(PatternError { msg, .. }) => {
            return Err(delete_error(
                MESSAGE_ID_INVALID_PATTERN,
                format!("delete: invalid wildcard pattern '{display}' ({msg})"),
            ))
        }
    };

    let mut matches = Vec::new();
    for entry in paths {
        match entry {
            Ok(path) => matches.push(path),
            Err(err) => {
                let problem_path = path_to_string(err.path());
                return Err(delete_error(
                    MESSAGE_ID_OS_ERROR,
                    format!(
                        "delete: unable to delete '{}' ({})",
                        problem_path,
                        err.error()
                    ),
                ));
            }
        }
    }

    if matches.is_empty() {
        return Err(delete_error(
            MESSAGE_ID_FILE_NOT_FOUND,
            format!(
                "delete: cannot delete '{}' because it does not exist",
                display
            ),
        ));
    }

    for path in matches {
        let display_path = path_to_string(&path);
        delete_single_path_async(&path, &display_path).await?;
    }
    Ok(())
}

async fn delete_single_path_async(path: &Path, display: &str) -> BuiltinResult<()> {
    match vfs::metadata_async(path).await {
        Ok(meta) => {
            if meta.is_dir() {
                return Err(delete_error(
                    MESSAGE_ID_IS_DIRECTORY,
                    format!(
                        "delete: cannot delete '{}' because it is a directory (use rmdir instead)",
                        display
                    ),
                ));
            }
            vfs::remove_file_async(path).await.map_err(|err| {
                delete_error(
                    MESSAGE_ID_OS_ERROR,
                    format!("delete: unable to delete '{}' ({})", display, err),
                )
            })
        }
        Err(err) => {
            if err.kind() == io::ErrorKind::NotFound {
                Err(delete_error(
                    MESSAGE_ID_FILE_NOT_FOUND,
                    format!(
                        "delete: cannot delete '{}' because it does not exist",
                        display
                    ),
                ))
            } else {
                Err(delete_error(
                    MESSAGE_ID_OS_ERROR,
                    format!("delete: unable to delete '{}' ({})", display, err),
                ))
            }
        }
    }
}

#[cfg(test)]
fn delete_single_path(path: &Path, display: &str) -> BuiltinResult<()> {
    futures::executor::block_on(delete_single_path_async(path, display))
}

fn validate_wildcard_pattern(pattern: &str, display: &str) -> BuiltinResult<()> {
    if has_unbalanced(pattern, '[', ']') || has_unbalanced(pattern, '{', '}') {
        return Err(delete_error(
            MESSAGE_ID_INVALID_PATTERN,
            format!("delete: invalid wildcard pattern '{display}'"),
        ));
    }
    Ok(())
}

fn has_unbalanced(pattern: &str, open: char, close: char) -> bool {
    let mut depth = 0usize;
    let mut chars = pattern.chars();
    while let Some(ch) = chars.next() {
        if ch == '\\' {
            // Skip escaped characters to avoid false positives
            let _ = chars.next();
            continue;
        }
        if ch == open {
            depth += 1;
        } else if ch == close {
            if depth == 0 {
                return true;
            }
            depth -= 1;
        }
    }
    depth != 0
}

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)
}

fn collect_targets(value: &Value, targets: &mut Vec<String>) -> BuiltinResult<()> {
    match value {
        Value::String(text) => push_nonempty_target(text, targets),
        Value::CharArray(array) => collect_char_array_targets(array, targets),
        Value::StringArray(array) => collect_string_array_targets(array, targets),
        Value::Cell(cell) => collect_cell_targets(cell, targets),
        _ => Err(delete_error(MESSAGE_ID_INVALID_INPUT, ERR_FILENAME_ARG)),
    }
}

fn collect_char_array_targets(array: &CharArray, targets: &mut Vec<String>) -> BuiltinResult<()> {
    if array.rows == 0 || array.cols == 0 {
        return Ok(());
    }
    for row in 0..array.rows {
        let mut text = String::with_capacity(array.cols);
        for col in 0..array.cols {
            text.push(array.data[row * array.cols + col]);
        }
        let trimmed = text.trim_end().to_string();
        if trimmed.is_empty() {
            return Err(delete_error(
                MESSAGE_ID_EMPTY_FILENAME,
                "delete: filename cannot be empty",
            ));
        }
        targets.push(trimmed);
    }
    Ok(())
}

fn collect_string_array_targets(
    array: &StringArray,
    targets: &mut Vec<String>,
) -> BuiltinResult<()> {
    for text in &array.data {
        if text.is_empty() {
            return Err(delete_error(
                MESSAGE_ID_EMPTY_FILENAME,
                "delete: filename cannot be empty",
            ));
        }
        targets.push(text.clone());
    }
    Ok(())
}

fn collect_cell_targets(cell: &CellArray, targets: &mut Vec<String>) -> BuiltinResult<()> {
    for handle in &cell.data {
        let value = unsafe { &*handle.as_raw() };
        collect_targets(value, targets)?;
    }
    Ok(())
}

fn delete_handles(values: &[Value]) -> BuiltinResult<Value> {
    let mut mutated_last: Option<Value> = None;
    let mut total = 0usize;
    for value in values {
        total += process_handle_value(value, &mut mutated_last)?;
    }
    if total == 1 {
        Ok(mutated_last.unwrap_or(Value::Num(0.0)))
    } else {
        Ok(Value::Num(0.0))
    }
}

fn process_handle_value(value: &Value, mutated_last: &mut Option<Value>) -> BuiltinResult<usize> {
    match value {
        Value::HandleObject(handle) => {
            let mut invalid = handle.clone();
            invalid.valid = false;
            *mutated_last = Some(Value::HandleObject(invalid));
            Ok(1)
        }
        Value::Listener(listener) => {
            let mut invalid = listener.clone();
            invalid.valid = false;
            invalid.enabled = false;
            *mutated_last = Some(Value::Listener(invalid));
            Ok(1)
        }
        Value::Cell(cell) => {
            let mut total = 0usize;
            for handle in &cell.data {
                let inner = unsafe { &*handle.as_raw() };
                total += process_handle_value(inner, mutated_last)?;
            }
            Ok(total)
        }
        other => Err(delete_error(
            MESSAGE_ID_INVALID_HANDLE,
            format!("delete: unsupported handle input {other:?}"),
        )),
    }
}

fn is_handle_input(value: &Value) -> bool {
    match value {
        Value::HandleObject(_) | Value::Listener(_) => true,
        Value::Cell(cell) => cell
            .data
            .iter()
            .all(|ptr| is_handle_input(unsafe { &*ptr.as_raw() })),
        _ => false,
    }
}

fn contains_handle_input(value: &Value) -> bool {
    match value {
        Value::HandleObject(_) | Value::Listener(_) => true,
        Value::Cell(cell) => cell
            .data
            .iter()
            .any(|ptr| contains_handle_input(unsafe { &*ptr.as_raw() })),
        _ => false,
    }
}

fn push_nonempty_target(text: &str, targets: &mut Vec<String>) -> BuiltinResult<()> {
    if text.is_empty() {
        Err(delete_error(
            MESSAGE_ID_EMPTY_FILENAME,
            "delete: filename cannot be empty",
        ))
    } else {
        targets.push(text.to_string());
        Ok(())
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::super::REPL_FS_TEST_LOCK;
    use super::*;
    use runmat_builtins::{CharArray, StringArray, Value};
    use std::fs::File;
    use tempfile::tempdir;

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

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

        let temp = tempdir().expect("temp dir");
        let target = temp.path().join("single.txt");
        File::create(&target).expect("create");

        let result = delete_builtin(vec![Value::from(target.to_string_lossy().to_string())])
            .expect("delete");
        assert_eq!(result, Value::Num(0.0));
        assert!(!target.exists());
    }

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

        let temp = tempdir().expect("temp dir");
        let file_a = temp.path().join("log-01.txt");
        let file_b = temp.path().join("log-02.txt");
        File::create(&file_a).expect("create a");
        File::create(&file_b).expect("create b");

        let pattern = temp.path().join("log-*.txt");
        delete_builtin(vec![Value::from(pattern.to_string_lossy().to_string())]).expect("delete");
        assert!(!file_a.exists());
        assert!(!file_b.exists());
    }

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

        let temp = tempdir().expect("temp dir");
        let file_a = temp.path().join("stageA.dat");
        let file_b = temp.path().join("stageB.dat");
        File::create(&file_a).expect("create a");
        File::create(&file_b).expect("create b");

        let array = StringArray::new(
            vec![
                file_a.to_string_lossy().to_string(),
                file_b.to_string_lossy().to_string(),
            ],
            vec![2],
        )
        .expect("string array");

        delete_builtin(vec![Value::StringArray(array)]).expect("delete");
        assert!(!file_a.exists());
        assert!(!file_b.exists());
    }

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

        let temp = tempdir().expect("temp dir");
        let paths: Vec<_> = ["stageA.tmp", "stageB.tmp"]
            .into_iter()
            .map(|name| temp.path().join(name))
            .collect();
        let path_strings: Vec<String> = paths
            .iter()
            .map(|p| p.to_string_lossy().to_string())
            .collect();
        let max_len = path_strings.iter().map(|s| s.len()).max().unwrap();
        let mut data: Vec<char> = Vec::with_capacity(path_strings.len() * max_len);

        for (path, path_string) in paths.iter().zip(path_strings.iter()) {
            File::create(path).expect("create file");
            let mut chars: Vec<char> = path_string.chars().collect();
            while chars.len() < max_len {
                chars.push(' ');
            }
            data.extend(&chars);
        }

        let char_array = CharArray::new(data, path_strings.len(), max_len).expect("char array");
        delete_builtin(vec![Value::CharArray(char_array)]).expect("delete");

        for path in paths {
            assert!(!path.exists(), "{path:?} should be removed");
        }
    }

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

        let temp = tempdir().expect("temp dir");
        let file_a = temp.path().join("cellA.dat");
        let file_b = temp.path().join("cellB.dat");
        File::create(&file_a).expect("create cellA");
        File::create(&file_b).expect("create cellB");

        let cell_value = crate::make_cell(
            vec![
                Value::from(file_a.to_string_lossy().to_string()),
                Value::from(file_b.to_string_lossy().to_string()),
            ],
            1,
            2,
        )
        .expect("cell");

        delete_builtin(vec![cell_value]).expect("delete");
        assert!(!file_a.exists());
        assert!(!file_b.exists());
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn delete_empty_string_array_is_noop() {
        let array = StringArray::new(Vec::<String>::new(), vec![0]).expect("empty array");
        let result = delete_builtin(vec![Value::StringArray(array)]).expect("delete");
        assert_eq!(result, Value::Num(0.0));
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn delete_errors_on_empty_string_argument() {
        let err = delete_builtin(vec![Value::from(String::new())]).expect_err("empty string");
        assert_eq!(err.identifier(), Some(MESSAGE_ID_EMPTY_FILENAME));
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn delete_errors_on_string_array_empty_element() {
        let array =
            StringArray::new(vec![String::new()], vec![1]).expect("single empty string element");
        let err = delete_builtin(vec![Value::StringArray(array)]).expect_err("empty element");
        assert_eq!(err.identifier(), Some(MESSAGE_ID_EMPTY_FILENAME));
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn delete_errors_on_char_array_blank_row() {
        let data = vec![' '; 4];
        let char_array = CharArray::new(data, 1, 4).expect("char matrix");
        let err = delete_builtin(vec![Value::CharArray(char_array)]).expect_err("blank row");
        assert_eq!(err.identifier(), Some(MESSAGE_ID_EMPTY_FILENAME));
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn delete_errors_on_invalid_pattern() {
        let pattern = "{invalid*";
        let err = futures::executor::block_on(delete_target(pattern))
            .expect_err("invalid pattern should error");
        assert_eq!(err.identifier(), Some(MESSAGE_ID_INVALID_PATTERN));
    }

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

        let temp = tempdir().expect("temp dir");
        let missing = temp.path().join("missing.txt");
        let missing_str = missing.to_string_lossy().to_string();
        let err = futures::executor::block_on(delete_target(&missing_str)).expect_err("error");
        assert_eq!(err.identifier(), Some(MESSAGE_ID_FILE_NOT_FOUND));
    }

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

        let temp = tempdir().expect("temp dir");
        let dir = temp.path().join("dir");
        std::fs::create_dir(&dir).expect("create dir");
        let dir_display = dir.to_string_lossy().to_string();
        let err = delete_single_path(&dir, &dir_display).expect_err("error");
        assert_eq!(err.identifier(), Some(MESSAGE_ID_IS_DIRECTORY));
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn delete_handle_returns_invalid_handle() {
        let handle = futures::executor::block_on(crate::new_handle_object_builtin(
            "ReplFsDeleteTestHandle".to_string(),
        ))
        .expect("handle");
        let result = delete_builtin(vec![handle]).expect("delete handle");
        match result {
            Value::HandleObject(h) => {
                assert!(!h.valid, "handle should be marked invalid");
                let valid_value = futures::executor::block_on(crate::isvalid_builtin(
                    Value::HandleObject(h.clone()),
                ))
                .expect("isvalid");
                match valid_value {
                    Value::Bool(flag) => assert!(!flag, "isvalid should report false after delete"),
                    other => panic!("expected bool from isvalid, got {other:?}"),
                }
            }
            other => panic!("expected handle result, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn delete_rejects_mixed_handle_and_filename() {
        let handle = futures::executor::block_on(crate::new_handle_object_builtin(
            "ReplFsDeleteTestHandle".to_string(),
        ))
        .expect("handle");
        let err = delete_builtin(vec![
            handle,
            Value::from("mixed-handle-path.txt".to_string()),
        ])
        .expect_err("expected mixed error");
        assert_eq!(err.identifier(), Some(MESSAGE_ID_INVALID_HANDLE));
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn delete_accepts_cell_of_handles() {
        let handle_a = futures::executor::block_on(crate::new_handle_object_builtin(
            "ReplFsDeleteTestHandle".to_string(),
        ))
        .expect("handle");
        let handle_b = futures::executor::block_on(crate::new_handle_object_builtin(
            "ReplFsDeleteTestHandle".to_string(),
        ))
        .expect("handle");
        let cell = crate::make_cell(vec![handle_a, handle_b], 1, 2).expect("cell of handles");
        let result = delete_builtin(vec![cell]).expect("delete handles");
        assert_eq!(result, Value::Num(0.0));
    }

    #[cfg(feature = "wgpu")]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn delete_runs_with_wgpu_provider_registered() {
        let _lock = REPL_FS_TEST_LOCK
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());

        let _ = runmat_accelerate::backend::wgpu::provider::register_wgpu_provider(
            runmat_accelerate::backend::wgpu::provider::WgpuProviderOptions::default(),
        );

        let temp = tempdir().expect("temp dir");
        let path = temp.path().join("wgpu-file.txt");
        File::create(&path).expect("create file");

        delete_builtin(vec![Value::from(path.to_string_lossy().to_string())]).expect("delete");
        assert!(!path.exists());
    }
}