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
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! MATLAB-compatible `which` builtin for RunMat.
//!
//! Resolves the entity associated with a name, mirroring MATLAB search
//! semantics (workspace variables, builtins, classes, scripts, and folders)
//! and supporting `-all`, `-builtin`, `-var`, and `-file` options.

use std::collections::HashSet;
use std::path::Path;

use runmat_builtins::{
    builtin_functions, BuiltinCompletionPolicy, BuiltinDescriptor, BuiltinErrorDescriptor,
    BuiltinOutputMode, BuiltinParamArity, BuiltinParamDescriptor, BuiltinParamType,
    BuiltinSignatureDescriptor, CharArray, Value,
};
use runmat_filesystem as vfs;
use runmat_macros::runtime_builtin;

use crate::builtins::common::fs::path_to_string;
use crate::builtins::common::path_search::{
    class_file_paths, class_folder_candidates, directory_candidates,
    find_all_files_with_extensions, CLASS_M_FILE_EXTENSIONS, GENERAL_FILE_EXTENSIONS,
};
use crate::builtins::common::spec::{
    BroadcastSemantics, BuiltinFusionSpec, BuiltinGpuSpec, ConstantStrategy, GpuOpKind,
    ReductionNaN, ResidencyPolicy, ShapeRequirements,
};
use crate::builtins::introspection::type_resolvers::which_type;
use crate::{
    build_runtime_error, dispatcher::gather_if_needed_async, make_cell, BuiltinResult, RuntimeError,
};

const WHICH_OUTPUT_SINGLE: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "result",
    ty: BuiltinParamType::StringScalar,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "Single resolution result string.",
}];

const WHICH_OUTPUT_ALL: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "results",
    ty: BuiltinParamType::Any,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "All matching resolution strings (cell array of char rows).",
}];

const WHICH_SIG_NAME_INPUTS: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "name",
    ty: BuiltinParamType::StringScalar,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "Name to resolve.",
}];

const WHICH_SIG_NAME_OPTION_INPUTS: [BuiltinParamDescriptor; 2] = [
    BuiltinParamDescriptor {
        name: "name",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Name to resolve.",
    },
    BuiltinParamDescriptor {
        name: "option",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Optional,
        default: Some("\"-all\""),
        description: "Optional mode filter (-all|-builtin|-var|-file).",
    },
];

const WHICH_SIG_OPTION_NAME_INPUTS: [BuiltinParamDescriptor; 2] = [
    BuiltinParamDescriptor {
        name: "option",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Mode filter (-all|-builtin|-var|-file).",
    },
    BuiltinParamDescriptor {
        name: "name",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Name to resolve.",
    },
];

const WHICH_SIGNATURES: [BuiltinSignatureDescriptor; 4] = [
    BuiltinSignatureDescriptor {
        label: "result = which(name)",
        inputs: &WHICH_SIG_NAME_INPUTS,
        outputs: &WHICH_OUTPUT_SINGLE,
    },
    BuiltinSignatureDescriptor {
        label: "result = which(name, option)",
        inputs: &WHICH_SIG_NAME_OPTION_INPUTS,
        outputs: &WHICH_OUTPUT_SINGLE,
    },
    BuiltinSignatureDescriptor {
        label: "result = which(option, name)",
        inputs: &WHICH_SIG_OPTION_NAME_INPUTS,
        outputs: &WHICH_OUTPUT_SINGLE,
    },
    BuiltinSignatureDescriptor {
        label: "results = which(\"-all\", name)",
        inputs: &WHICH_SIG_OPTION_NAME_INPUTS,
        outputs: &WHICH_OUTPUT_ALL,
    },
];

const WHICH_ERROR_ARG_COUNT_MIN: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.WHICH.ARG_COUNT_MIN",
    identifier: None,
    when: "No input arguments are provided.",
    message: "which: not enough input arguments",
};

const WHICH_ERROR_ARG_COUNT_MAX: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.WHICH.ARG_COUNT_MAX",
    identifier: None,
    when: "More than one name argument is provided.",
    message: "which: too many input arguments",
};

const WHICH_ERROR_NAME_ARG_TYPE: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.WHICH.NAME_ARG_TYPE",
    identifier: None,
    when: "Name argument is not a char row or string scalar.",
    message: "which: name must be a character vector or string scalar",
};

const WHICH_ERROR_OPTION_ARG_TYPE: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.WHICH.OPTION_ARG_TYPE",
    identifier: None,
    when: "Option argument is not a char row or string scalar.",
    message: "which: option must be a character vector or string scalar",
};

const WHICH_ERROR_OPTION_CONFLICT: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.WHICH.OPTION_CONFLICT",
    identifier: None,
    when: "Conflicting mode options are combined.",
    message: "which: conflicting option",
};

const WHICH_ERROR_OPTION_UNRECOGNIZED: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.WHICH.OPTION_UNRECOGNIZED",
    identifier: None,
    when: "An unrecognized mode option is provided.",
    message: "which: unrecognized option",
};

const WHICH_ERRORS: [BuiltinErrorDescriptor; 6] = [
    WHICH_ERROR_ARG_COUNT_MIN,
    WHICH_ERROR_ARG_COUNT_MAX,
    WHICH_ERROR_NAME_ARG_TYPE,
    WHICH_ERROR_OPTION_ARG_TYPE,
    WHICH_ERROR_OPTION_CONFLICT,
    WHICH_ERROR_OPTION_UNRECOGNIZED,
];

pub const WHICH_DESCRIPTOR: BuiltinDescriptor = BuiltinDescriptor {
    signatures: &WHICH_SIGNATURES,
    output_mode: BuiltinOutputMode::Fixed,
    completion_policy: BuiltinCompletionPolicy::Public,
    errors: &WHICH_ERRORS,
};

#[runmat_macros::register_gpu_spec(builtin_path = "crate::builtins::introspection::which")]
pub const GPU_SPEC: BuiltinGpuSpec = BuiltinGpuSpec {
    name: "which",
    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:
        "Lookup runs on the host. Arguments are gathered from the GPU before evaluating the search.",
};

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

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

fn which_error_with_detail(
    error: &'static BuiltinErrorDescriptor,
    detail: impl std::fmt::Display,
) -> RuntimeError {
    which_error_with_message(format!("{} {detail}", error.message), error)
}

fn which_runtime_error(message: impl Into<String>) -> RuntimeError {
    build_runtime_error(message).with_builtin("which").build()
}

fn which_flow(err: RuntimeError) -> RuntimeError {
    let identifier = err.identifier().map(|id| id.to_string());
    let mut builder = build_runtime_error(err.message().to_string())
        .with_builtin("which")
        .with_source(err);
    if let Some(identifier) = identifier {
        builder = builder.with_identifier(identifier);
    }
    builder.build()
}

fn which_path<T>(result: Result<T, String>) -> BuiltinResult<T> {
    result.map_err(which_runtime_error)
}

#[runmat_macros::register_fusion_spec(builtin_path = "crate::builtins::introspection::which")]
pub const FUSION_SPEC: BuiltinFusionSpec = BuiltinFusionSpec {
    name: "which",
    shape: ShapeRequirements::Any,
    constant_strategy: ConstantStrategy::InlineLiteral,
    elementwise: None,
    reduction: None,
    emits_nan: false,
    notes: "I/O lookup; not eligible for fusion. Metadata registered for diagnostics.",
};

#[runtime_builtin(
    name = "which",
    category = "introspection",
    summary = "Resolve which variable, builtin, file, or class matches a given name.",
    keywords = "which,search path,builtin lookup,script path,variable shadowing",
    accel = "cpu",
    type_resolver(which_type),
    descriptor(crate::builtins::introspection::which::WHICH_DESCRIPTOR),
    builtin_path = "crate::builtins::introspection::which"
)]
async fn which_builtin(args: Vec<Value>) -> crate::BuiltinResult<Value> {
    if args.is_empty() {
        return Err(which_error(&WHICH_ERROR_ARG_COUNT_MIN));
    }

    let mut name: Option<String> = None;
    let mut options = WhichOptions::default();

    for arg in args {
        let gathered = gather_if_needed_async(&arg).await.map_err(which_flow)?;
        let text = value_to_string_scalar(&gathered).ok_or_else(|| {
            if name.is_none() {
                which_error(&WHICH_ERROR_NAME_ARG_TYPE)
            } else {
                which_error(&WHICH_ERROR_OPTION_ARG_TYPE)
            }
        })?;

        if looks_like_option(&text) {
            options.apply(&text)?;
        } else if name.is_none() {
            name = Some(text);
        } else {
            return Err(which_error(&WHICH_ERROR_ARG_COUNT_MAX));
        }
    }

    let name = name.ok_or_else(|| which_error(&WHICH_ERROR_ARG_COUNT_MIN))?;
    let matches = search_matches(&name, &options).await?;
    if matches.is_empty() {
        return Ok(Value::CharArray(CharArray::new_row(&format!(
            "'{name}' not found."
        ))));
    }

    if options.all {
        let mut cell_values = Vec::with_capacity(matches.len());
        for entry in &matches {
            cell_values.push(Value::CharArray(CharArray::new_row(entry)));
        }
        return make_cell(cell_values, matches.len(), 1).map_err(|err| {
            build_runtime_error(err)
                .with_builtin("which")
                .build()
                .into()
        });
    }

    Ok(Value::CharArray(CharArray::new_row(
        matches.first().expect("non-empty result"),
    )))
}

#[derive(Default, Debug)]
struct WhichOptions {
    all: bool,
    builtin_only: bool,
    var_only: bool,
    file_only: bool,
}

impl WhichOptions {
    fn apply(&mut self, option: &str) -> BuiltinResult<()> {
        let lowered = option.trim().to_ascii_lowercase();
        match lowered.as_str() {
            "-all" => {
                self.all = true;
                Ok(())
            }
            "-builtin" | "-built-in" => {
                let mut conflicts = Vec::new();
                if self.var_only {
                    conflicts.push("-var");
                }
                if self.file_only {
                    conflicts.push("-file");
                }
                if !conflicts.is_empty() {
                    return Err(which_error_with_detail(
                        &WHICH_ERROR_OPTION_CONFLICT,
                        conflict_message("-builtin", &conflicts),
                    ));
                }
                self.builtin_only = true;
                Ok(())
            }
            "-var" | "-variable" => {
                let mut conflicts = Vec::new();
                if self.builtin_only {
                    conflicts.push("-builtin");
                }
                if self.file_only {
                    conflicts.push("-file");
                }
                if !conflicts.is_empty() {
                    return Err(which_error_with_detail(
                        &WHICH_ERROR_OPTION_CONFLICT,
                        conflict_message("-var", &conflicts),
                    ));
                }
                self.var_only = true;
                Ok(())
            }
            "-file" => {
                let mut conflicts = Vec::new();
                if self.builtin_only {
                    conflicts.push("-builtin");
                }
                if self.var_only {
                    conflicts.push("-var");
                }
                if !conflicts.is_empty() {
                    return Err(which_error_with_detail(
                        &WHICH_ERROR_OPTION_CONFLICT,
                        conflict_message("-file", &conflicts),
                    ));
                }
                self.file_only = true;
                Ok(())
            }
            other => Err(which_error_with_detail(
                &WHICH_ERROR_OPTION_UNRECOGNIZED,
                format!("'{other}'"),
            )),
        }
    }
}

fn conflict_message(option: &str, conflicts: &[&str]) -> String {
    debug_assert!(!conflicts.is_empty());
    let joined = match conflicts.len() {
        1 => conflicts[0].to_string(),
        2 => format!("{} or {}", conflicts[0], conflicts[1]),
        _ => {
            let mut text = conflicts[..conflicts.len() - 1].join(", ");
            text.push_str(", or ");
            text.push_str(conflicts.last().unwrap());
            text
        }
    };
    format!("'{option}'; cannot combine with {joined}")
}

async fn search_matches(name: &str, options: &WhichOptions) -> BuiltinResult<Vec<String>> {
    if options.var_only {
        return Ok(variable_match(name).into_iter().collect());
    }
    if options.builtin_only {
        return Ok(builtin_matches(name));
    }
    if options.file_only {
        return search_file_like_matches(name, options.all).await;
    }

    let mut seen = HashSet::new();
    let mut results = Vec::new();

    if let Some(var_msg) = variable_match(name) {
        push_unique(&mut results, &mut seen, var_msg.clone());
        if !options.all {
            return Ok(results);
        }
    }

    for entry in builtin_matches(name) {
        push_unique(&mut results, &mut seen, entry.clone());
        if !options.all && !results.is_empty() {
            return Ok(results);
        }
    }

    let mut class_entries = class_matches(name).await?;
    for entry in class_entries.drain(..) {
        push_unique(&mut results, &mut seen, entry.clone());
        if !options.all && !results.is_empty() {
            return Ok(results);
        }
    }

    let mut file_entries = file_matches(name).await?;
    for entry in file_entries.drain(..) {
        push_unique(&mut results, &mut seen, entry.clone());
        if !options.all && !results.is_empty() {
            return Ok(results);
        }
    }

    let mut directory_entries = directory_matches(name).await?;
    for entry in directory_entries.drain(..) {
        push_unique(&mut results, &mut seen, entry.clone());
        if !options.all && !results.is_empty() {
            return Ok(results);
        }
    }

    Ok(results)
}

async fn search_file_like_matches(name: &str, gather_all: bool) -> BuiltinResult<Vec<String>> {
    let mut seen = HashSet::new();
    let mut results = Vec::new();

    for entry in class_matches(name).await? {
        push_unique(&mut results, &mut seen, entry);
    }

    for entry in file_matches(name).await? {
        push_unique(&mut results, &mut seen, entry);
        if !gather_all && !results.is_empty() {
            return Ok(results);
        }
    }

    for entry in directory_matches(name).await? {
        push_unique(&mut results, &mut seen, entry);
        if !gather_all && !results.is_empty() {
            return Ok(results);
        }
    }

    Ok(results)
}

fn variable_match(name: &str) -> Option<String> {
    crate::workspace::lookup(name).map(|_| format!("'{name}' is a variable."))
}

fn builtin_matches(name: &str) -> Vec<String> {
    let lowered = name.to_ascii_lowercase();
    builtin_functions()
        .into_iter()
        .filter(|b| b.name.eq_ignore_ascii_case(&lowered))
        .map(|b| format!("built-in (RunMat builtin: {})", b.name))
        .collect()
}

async fn class_matches(name: &str) -> BuiltinResult<Vec<String>> {
    let mut results = Vec::new();
    let mut seen = HashSet::new();

    for folder in which_path(class_folder_candidates(name, "which"))? {
        if vfs::metadata_async(&folder)
            .await
            .map(|meta| meta.is_dir())
            .unwrap_or(false)
        {
            let text = format!("class folder: {}", canonical_path(&folder).await);
            push_unique(&mut results, &mut seen, text);
        }
    }

    for file in
        which_path(class_file_paths(name, CLASS_M_FILE_EXTENSIONS, "classdef", "which").await)?
    {
        let text = format!("classdef file: {}", canonical_path(&file).await);
        push_unique(&mut results, &mut seen, text);
    }

    Ok(results)
}

async fn file_matches(name: &str) -> BuiltinResult<Vec<String>> {
    let mut results = Vec::new();
    let mut seen = HashSet::new();
    for file in
        which_path(find_all_files_with_extensions(name, GENERAL_FILE_EXTENSIONS, "which").await)?
    {
        if vfs::metadata_async(&file)
            .await
            .map(|meta| meta.is_file())
            .unwrap_or(false)
        {
            push_unique(&mut results, &mut seen, canonical_path(&file).await);
        }
    }
    Ok(results)
}

async fn directory_matches(name: &str) -> BuiltinResult<Vec<String>> {
    let mut results = Vec::new();
    let mut seen = HashSet::new();
    for dir in which_path(directory_candidates(name, "which"))? {
        if vfs::metadata_async(&dir)
            .await
            .map(|meta| meta.is_dir())
            .unwrap_or(false)
        {
            push_unique(&mut results, &mut seen, canonical_path(&dir).await);
        }
    }
    Ok(results)
}

async fn canonical_path(path: &Path) -> String {
    vfs::canonicalize_async(path)
        .await
        .map(|p| path_to_string(&p))
        .unwrap_or_else(|_| path_to_string(path))
}

fn value_to_string_scalar(value: &Value) -> Option<String> {
    match value {
        Value::String(text) => Some(text.clone()),
        Value::CharArray(array) if array.rows == 1 => Some(array.data.iter().collect()),
        Value::StringArray(array) if array.data.len() == 1 => Some(array.data[0].clone()),
        _ => None,
    }
}

fn looks_like_option(text: &str) -> bool {
    text.trim_start().starts_with('-')
}

fn push_unique(results: &mut Vec<String>, seen: &mut HashSet<String>, entry: String) {
    if seen.insert(entry.clone()) {
        results.push(entry);
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use futures::executor::block_on;
    use once_cell::sync::Lazy;
    use runmat_builtins::{CharArray, StringArray, Value};
    use runmat_thread_local::runmat_thread_local;
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::fs::File;
    use std::io::Write;
    use std::path::PathBuf;
    use std::sync::Mutex;
    use tempfile::tempdir;

    static WHICH_TEST_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));

    fn workspace_guard() -> std::sync::MutexGuard<'static, ()> {
        crate::workspace::test_guard()
    }

    fn test_guard() -> (
        std::sync::MutexGuard<'static, ()>,
        std::sync::MutexGuard<'static, ()>,
    ) {
        let workspace = workspace_guard();
        let which = WHICH_TEST_LOCK
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        (workspace, which)
    }

    fn which_builtin(args: Vec<Value>) -> BuiltinResult<Value> {
        block_on(super::which_builtin(args))
    }

    runmat_thread_local! {
        static TEST_WORKSPACE: RefCell<HashMap<String, Value>> = RefCell::new(HashMap::new());
    }

    fn ensure_test_resolver() {
        crate::workspace::register_workspace_resolver(crate::workspace::WorkspaceResolver {
            lookup: |name| TEST_WORKSPACE.with(|slot| slot.borrow().get(name).cloned()),
            snapshot: || {
                let mut entries: Vec<(String, Value)> =
                    TEST_WORKSPACE.with(|slot| slot.borrow().clone().into_iter().collect());
                entries.sort_by(|a, b| a.0.cmp(&b.0));
                entries
            },
            globals: || Vec::new(),
            assign: None,
            clear: None,
            remove: None,
        });
    }

    fn set_workspace(entries: &[(&str, Value)]) {
        TEST_WORKSPACE.with(|slot| {
            let mut map = slot.borrow_mut();
            map.clear();
            for (name, value) in entries {
                map.insert((*name).to_string(), value.clone());
            }
        });
    }

    fn error_message(err: crate::RuntimeError) -> String {
        err.message().to_string()
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_reports_builtin() {
        let (_guard, _lock) = test_guard();
        let value = which_builtin(vec![Value::from("sin")]).expect("which");
        let text = String::try_from(&value).expect("string result");
        assert!(
            text.contains("built-in"),
            "expected builtin output, got {text}"
        );
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_variable_search_respects_workspace() {
        let (_guard, _lock) = test_guard();
        ensure_test_resolver();
        set_workspace(&[("answer", Value::Num(42.0))]);

        let value = which_builtin(vec![Value::from("answer")]).expect("which");
        assert_eq!(String::try_from(&value).unwrap(), "'answer' is a variable.");
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_finds_files() {
        let (_guard, _lock) = test_guard();
        let temp = tempdir().expect("tempdir");
        let script_path = temp.path().join("script.m");
        File::create(&script_path)
            .and_then(|mut file| writeln!(file, "disp('hi');"))
            .expect("write script");

        let guard = DirGuard::new();
        std::env::set_current_dir(temp.path()).expect("set temp dir");

        let value = which_builtin(vec![Value::from("script")]).expect("which");
        let text = String::try_from(&value).expect("string");
        assert!(
            text.ends_with("script.m"),
            "expected to end with script.m, got {text}"
        );

        drop(guard);
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_all_returns_cell_array() {
        let (_guard, _lock) = test_guard();
        let value = which_builtin(vec![Value::from("sin"), Value::from("-all")]).expect("which");
        match value {
            Value::Cell(cell) => assert!(!cell.data.is_empty()),
            other => panic!("expected cell array, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_not_found_message() {
        let (_guard, _lock) = test_guard();
        let value = which_builtin(vec![Value::from("definitely_missing")]).expect("which");
        let text = String::try_from(&value).expect("string");
        assert_eq!(text, "'definitely_missing' not found.");
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_parses_leading_option() {
        let (_guard, _lock) = test_guard();
        let value = which_builtin(vec![Value::from("-all"), Value::from("sin")]).expect("which");
        match value {
            Value::Cell(cell) => assert!(!cell.data.is_empty()),
            other => panic!("expected cell array, got {other:?}"),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_allows_uppercase_and_repeated_flags() {
        let (_guard, _lock) = test_guard();
        let value = which_builtin(vec![
            Value::from("-BUILTIN"),
            Value::from("-builtin"),
            Value::from("sin"),
        ])
        .expect("which");
        let text = String::try_from(&value).expect("string");
        assert!(
            text.contains("built-in"),
            "expected builtin output, got {text}"
        );
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_conflicting_flags_error() {
        let (_guard, _lock) = test_guard();
        let err = which_builtin(vec![
            Value::from("-var"),
            Value::from("-builtin"),
            Value::from("sin"),
        ])
        .unwrap_err();
        let message = error_message(err);
        assert!(
            message.contains("conflicting option '-builtin'"),
            "unexpected error: {message}"
        );
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_invalid_flag_error() {
        let (_guard, _lock) = test_guard();
        let err = which_builtin(vec![Value::from("-nope"), Value::from("sin")]).unwrap_err();
        let message = error_message(err);
        assert!(
            message.contains("unrecognized option '-nope'"),
            "unexpected error: {message}"
        );
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_requires_name_argument() {
        let (_guard, _lock) = test_guard();
        let err = which_builtin(vec![]).unwrap_err();
        let message = error_message(err);
        assert_eq!(message, WHICH_ERROR_ARG_COUNT_MIN.message);
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_errors_on_non_string_name() {
        let (_guard, _lock) = test_guard();
        let err = which_builtin(vec![Value::Num(4.0)]).unwrap_err();
        let message = error_message(err);
        assert_eq!(message, WHICH_ERROR_NAME_ARG_TYPE.message);
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_errors_on_too_many_arguments() {
        let (_guard, _lock) = test_guard();
        let err = which_builtin(vec![
            Value::from("sin"),
            Value::from("cos"),
            Value::from("tan"),
        ])
        .unwrap_err();
        let message = error_message(err);
        assert_eq!(message, WHICH_ERROR_ARG_COUNT_MAX.message);
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_accepts_char_and_string_array_inputs() {
        let (_guard, _lock) = test_guard();
        let char_value = Value::CharArray(CharArray::new_row("sin"));
        let char_result = which_builtin(vec![char_value]).expect("which char");
        let char_text = String::try_from(&char_result).expect("string");
        assert!(
            char_text.contains("built-in"),
            "expected builtin output, got {char_text}"
        );

        let string_array = StringArray::new(vec!["sin".to_string()], vec![1]).unwrap();
        let string_result =
            which_builtin(vec![Value::StringArray(string_array)]).expect("which string array");
        let string_text = String::try_from(&string_result).expect("string");
        assert!(
            string_text.contains("built-in"),
            "expected builtin output, got {string_text}"
        );
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn which_file_option_finds_directories() {
        let (_guard, _lock) = test_guard();
        let temp = tempdir().expect("tempdir");
        let subdir = temp.path().join("helpers");
        std::fs::create_dir_all(&subdir).expect("create dir");
        let guard = DirGuard::new();
        std::env::set_current_dir(temp.path()).expect("set temp dir");

        let value =
            which_builtin(vec![Value::from("-file"), Value::from("helpers")]).expect("which");
        let text = String::try_from(&value).expect("string");
        assert!(
            text.ends_with("helpers") || text.contains("/helpers") || text.contains("\\helpers"),
            "expected directory path, got {text}"
        );

        drop(guard);
    }

    struct DirGuard {
        original: PathBuf,
    }

    impl DirGuard {
        fn new() -> Self {
            let original = std::env::current_dir().expect("current dir");
            Self { original }
        }
    }

    impl Drop for DirGuard {
        fn drop(&mut self) {
            let _ = std::env::set_current_dir(&self.original);
        }
    }
}