runmat-runtime 0.6.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
//! MATLAB-compatible `uigetdir` builtin.

use std::path::PathBuf;

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

use super::file_dialog::scalar_text;
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 NAME: &str = "uigetdir";

const UIGETDIR_OUTPUT_DIR: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "folder",
    ty: BuiltinParamType::Any,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "Selected folder path as a character vector, or 0 when cancelled.",
}];

const UIGETDIR_INPUTS_NONE: [BuiltinParamDescriptor; 0] = [];

const UIGETDIR_INPUTS_START_PATH: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "startPath",
    ty: BuiltinParamType::StringScalar,
    arity: BuiltinParamArity::Optional,
    default: None,
    description: "Initial folder shown by the dialog.",
}];

const UIGETDIR_INPUTS_START_PATH_TITLE: [BuiltinParamDescriptor; 2] = [
    BuiltinParamDescriptor {
        name: "startPath",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Optional,
        default: None,
        description: "Initial folder shown by the dialog.",
    },
    BuiltinParamDescriptor {
        name: "title",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Optional,
        default: None,
        description: "Dialog title.",
    },
];

const UIGETDIR_SIGNATURES: [BuiltinSignatureDescriptor; 3] = [
    BuiltinSignatureDescriptor {
        label: "folder = uigetdir()",
        inputs: &UIGETDIR_INPUTS_NONE,
        outputs: &UIGETDIR_OUTPUT_DIR,
    },
    BuiltinSignatureDescriptor {
        label: "folder = uigetdir(startPath)",
        inputs: &UIGETDIR_INPUTS_START_PATH,
        outputs: &UIGETDIR_OUTPUT_DIR,
    },
    BuiltinSignatureDescriptor {
        label: "folder = uigetdir(startPath, title)",
        inputs: &UIGETDIR_INPUTS_START_PATH_TITLE,
        outputs: &UIGETDIR_OUTPUT_DIR,
    },
];

const UIGETDIR_ERROR_INVALID_ARGUMENT: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.UIGETDIR.INVALID_ARGUMENT",
    identifier: Some("RunMat:uigetdir:InvalidArgument"),
    when: "The start path or title has an unsupported type or shape.",
    message: "uigetdir: invalid argument",
};

const UIGETDIR_ERROR_TOO_MANY_OUTPUTS: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.UIGETDIR.TOO_MANY_OUTPUTS",
    identifier: Some("RunMat:uigetdir:TooManyOutputs"),
    when: "More than one output argument is requested.",
    message: "uigetdir: too many output arguments",
};

const UIGETDIR_ERROR_HOST: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.UIGETDIR.HOST",
    identifier: Some("RunMat:uigetdir:HostError"),
    when: "The active filesystem provider fails while opening the host folder-selection UI.",
    message: "uigetdir: folder selection failed",
};

const UIGETDIR_ERROR_INVALID_SELECTION: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.UIGETDIR.INVALID_SELECTION",
    identifier: Some("RunMat:uigetdir:InvalidSelection"),
    when: "The active filesystem provider returns a malformed folder selection.",
    message: "uigetdir: invalid folder selection",
};

const UIGETDIR_ERRORS: [BuiltinErrorDescriptor; 4] = [
    UIGETDIR_ERROR_INVALID_ARGUMENT,
    UIGETDIR_ERROR_TOO_MANY_OUTPUTS,
    UIGETDIR_ERROR_HOST,
    UIGETDIR_ERROR_INVALID_SELECTION,
];

pub const UIGETDIR_DESCRIPTOR: BuiltinDescriptor = BuiltinDescriptor {
    signatures: &UIGETDIR_SIGNATURES,
    output_mode: BuiltinOutputMode::ByRequestedOutputCount,
    completion_policy: BuiltinCompletionPolicy::Public,
    errors: &UIGETDIR_ERRORS,
};

#[runmat_macros::register_gpu_spec(builtin_path = "crate::builtins::io::repl_fs::uigetdir")]
pub const GPU_SPEC: BuiltinGpuSpec = BuiltinGpuSpec {
    name: NAME,
    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: "`uigetdir` is a host UI/filesystem interaction. GPU-resident textual arguments are gathered before dispatching to the provider.",
};

#[runmat_macros::register_fusion_spec(builtin_path = "crate::builtins::io::repl_fs::uigetdir")]
pub const FUSION_SPEC: BuiltinFusionSpec = BuiltinFusionSpec {
    name: NAME,
    shape: ShapeRequirements::Any,
    constant_strategy: ConstantStrategy::InlineLiteral,
    elementwise: None,
    reduction: None,
    emits_nan: false,
    notes: "`uigetdir` depends on host UI state and terminates fusion plans.",
};

#[derive(Clone, Debug)]
struct UigetdirOptions {
    request: DirectoryDialogRequest,
}

fn uigetdir_error(error: &'static BuiltinErrorDescriptor, detail: impl AsRef<str>) -> RuntimeError {
    let detail = detail.as_ref();
    let message = if detail.is_empty() {
        error.message.to_string()
    } else {
        format!("{}: {detail}", error.message)
    };
    let mut builder = build_runtime_error(message).with_builtin(NAME);
    if let Some(identifier) = error.identifier {
        builder = builder.with_identifier(identifier);
    }
    builder.build()
}

fn invalid_argument(detail: impl AsRef<str>) -> RuntimeError {
    uigetdir_error(&UIGETDIR_ERROR_INVALID_ARGUMENT, detail)
}

fn invalid_selection(detail: impl AsRef<str>) -> RuntimeError {
    uigetdir_error(&UIGETDIR_ERROR_INVALID_SELECTION, detail)
}

fn too_many_outputs() -> RuntimeError {
    uigetdir_error(&UIGETDIR_ERROR_TOO_MANY_OUTPUTS, "")
}

fn host_error(detail: impl AsRef<str>) -> RuntimeError {
    uigetdir_error(&UIGETDIR_ERROR_HOST, detail)
}

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

#[runtime_builtin(
    name = "uigetdir",
    category = "io/repl_fs",
    summary = "Open a host folder-selection dialog and return the selected folder path.",
    keywords = "uigetdir,folder picker,directory picker,file dialog,filesystem,ui",
    accel = "sink",
    type_resolver(crate::builtins::io::type_resolvers::uigetdir_type),
    descriptor(crate::builtins::io::repl_fs::uigetdir::UIGETDIR_DESCRIPTOR),
    builtin_path = "crate::builtins::io::repl_fs::uigetdir"
)]
async fn uigetdir_builtin(args: Vec<Value>) -> BuiltinResult<Value> {
    let gathered = gather_arguments(&args).await?;
    let options = parse_options(&gathered)?;
    let selection = runmat_filesystem::select_directory_async(&options.request)
        .await
        .map_err(|err| host_error(err.to_string()))?;
    outputs_for_selection(selection)
}

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

fn parse_options(args: &[Value]) -> BuiltinResult<UigetdirOptions> {
    if args.len() > 2 {
        return Err(invalid_argument("expected startPath and title"));
    }
    let default_path = if !args.is_empty() {
        Some(PathBuf::from(scalar_text(
            &args[0],
            "startPath",
            invalid_argument,
        )?))
    } else {
        None
    };
    let title = if args.len() >= 2 {
        Some(scalar_text(&args[1], "title", invalid_argument)?)
    } else {
        None
    };

    Ok(UigetdirOptions {
        request: DirectoryDialogRequest {
            title,
            default_path,
        },
    })
}

fn outputs_for_selection(selection: Option<DirectoryDialogSelection>) -> BuiltinResult<Value> {
    let output = match selection {
        Some(selection) => selected_output(selection)?,
        None => Value::Num(0.0),
    };

    if let Some(out_count) = crate::output_count::current_output_count() {
        if out_count > 1 {
            return Err(too_many_outputs());
        }
        return Ok(crate::output_count::output_list_with_padding(
            out_count,
            vec![output],
        ));
    }

    Ok(output)
}

fn selected_output(selection: DirectoryDialogSelection) -> BuiltinResult<Value> {
    if selection.path.as_os_str().is_empty() {
        return Err(invalid_selection("provider returned an empty folder path"));
    }
    Ok(Value::CharArray(CharArray::new_row(
        &selection.path.to_string_lossy(),
    )))
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use runmat_builtins::Tensor;
    use runmat_filesystem::{DirEntry, FileHandle, FsMetadata, FsProvider, OpenFlags};
    use std::io::{self, ErrorKind};
    use std::path::Path;
    use std::sync::{Arc, Mutex};

    fn call(args: Vec<Value>, outputs: Option<usize>) -> BuiltinResult<Value> {
        let _guard = crate::output_count::push_output_count(outputs);
        futures::executor::block_on(uigetdir_builtin(args))
    }

    fn text(value: &Value) -> String {
        match value {
            Value::CharArray(chars) => chars.data.iter().collect(),
            other => panic!("expected char array, got {other:?}"),
        }
    }

    fn output_list(value: Value) -> Vec<Value> {
        match value {
            Value::OutputList(values) => values,
            other => panic!("expected output list, got {other:?}"),
        }
    }

    #[derive(Clone)]
    struct DialogProvider {
        selection: Option<DirectoryDialogSelection>,
        request: Arc<Mutex<Option<DirectoryDialogRequest>>>,
    }

    #[async_trait(?Send)]
    impl FsProvider for DialogProvider {
        fn open(&self, _path: &Path, _flags: &OpenFlags) -> io::Result<Box<dyn FileHandle>> {
            Err(unsupported())
        }

        async fn read(&self, _path: &Path) -> io::Result<Vec<u8>> {
            Err(unsupported())
        }

        async fn write(&self, _path: &Path, _data: &[u8]) -> io::Result<()> {
            Err(unsupported())
        }

        async fn remove_file(&self, _path: &Path) -> io::Result<()> {
            Err(unsupported())
        }

        async fn metadata(&self, _path: &Path) -> io::Result<FsMetadata> {
            Err(unsupported())
        }

        async fn symlink_metadata(&self, _path: &Path) -> io::Result<FsMetadata> {
            Err(unsupported())
        }

        async fn read_dir(&self, _path: &Path) -> io::Result<Vec<DirEntry>> {
            Err(unsupported())
        }

        async fn canonicalize(&self, _path: &Path) -> io::Result<PathBuf> {
            Err(unsupported())
        }

        async fn create_dir(&self, _path: &Path) -> io::Result<()> {
            Err(unsupported())
        }

        async fn create_dir_all(&self, _path: &Path) -> io::Result<()> {
            Err(unsupported())
        }

        async fn remove_dir(&self, _path: &Path) -> io::Result<()> {
            Err(unsupported())
        }

        async fn remove_dir_all(&self, _path: &Path) -> io::Result<()> {
            Err(unsupported())
        }

        async fn rename(&self, _from: &Path, _to: &Path) -> io::Result<()> {
            Err(unsupported())
        }

        async fn set_readonly(&self, _path: &Path, _readonly: bool) -> io::Result<()> {
            Err(unsupported())
        }

        async fn select_directory(
            &self,
            request: &DirectoryDialogRequest,
        ) -> io::Result<Option<DirectoryDialogSelection>> {
            *self.request.lock().unwrap() = Some(request.clone());
            Ok(self.selection.clone())
        }
    }

    fn unsupported() -> io::Error {
        io::Error::new(ErrorKind::Unsupported, "unsupported")
    }

    fn rooted_tmp_path() -> PathBuf {
        let mut path = PathBuf::from(std::path::MAIN_SEPARATOR.to_string());
        path.push("tmp");
        path
    }

    fn rooted_tmp_path_text() -> String {
        rooted_tmp_path().to_string_lossy().into_owned()
    }

    fn with_dialog_provider(
        selection: Option<DirectoryDialogSelection>,
        body: impl FnOnce(Arc<Mutex<Option<DirectoryDialogRequest>>>),
    ) {
        let _lock = runmat_filesystem::provider_override_lock();
        let request = Arc::new(Mutex::new(None));
        let provider = Arc::new(DialogProvider {
            selection,
            request: request.clone(),
        });
        let _guard = runmat_filesystem::replace_provider(provider);
        body(request);
    }

    #[test]
    fn cancel_returns_zero() {
        with_dialog_provider(None, |_| {
            assert_eq!(call(vec![], None).expect("uigetdir"), Value::Num(0.0));
            let outputs = output_list(call(vec![], Some(1)).expect("uigetdir"));
            assert_eq!(outputs, vec![Value::Num(0.0)]);
        });
    }

    #[test]
    fn parses_start_path_title_and_returns_selected_folder() {
        let selection = DirectoryDialogSelection {
            path: rooted_tmp_path(),
        };
        with_dialog_provider(Some(selection), |request| {
            let output = call(
                vec![
                    Value::CharArray(CharArray::new_row(&rooted_tmp_path_text())),
                    Value::CharArray(CharArray::new_row("Select input folder")),
                ],
                None,
            )
            .expect("uigetdir");
            assert_eq!(text(&output), rooted_tmp_path_text());

            let request = request.lock().unwrap().clone().expect("request");
            assert_eq!(request.title.as_deref(), Some("Select input folder"));
            assert_eq!(request.default_path, Some(rooted_tmp_path()));
        });
    }

    #[test]
    fn accepts_backslash_separated_provider_path() {
        let selection = DirectoryDialogSelection {
            path: PathBuf::from(r"C:\data\images"),
        };
        with_dialog_provider(Some(selection), |_| {
            let output = call(vec![], None).expect("uigetdir");
            assert_eq!(text(&output), r"C:\data\images");
        });
    }

    #[test]
    fn rejects_empty_provider_path() {
        let selection = DirectoryDialogSelection {
            path: PathBuf::new(),
        };
        with_dialog_provider(Some(selection), |_| {
            let err = call(vec![], None).expect_err("expected invalid selection");
            assert_eq!(err.identifier(), Some("RunMat:uigetdir:InvalidSelection"));
            assert!(err.message().contains("empty folder path"));
        });
    }

    #[test]
    fn rejects_numeric_tensor_text_arguments() {
        with_dialog_provider(None, |_| {
            let tensor = Tensor::new(vec![42.0], vec![1, 1]).expect("tensor");
            let err =
                call(vec![Value::Tensor(tensor)], Some(1)).expect_err("expected invalid argument");
            assert_eq!(err.identifier(), Some("RunMat:uigetdir:InvalidArgument"));
        });
    }

    #[test]
    fn rejects_too_many_inputs_and_outputs() {
        with_dialog_provider(None, |_| {
            let err = call(
                vec![
                    Value::CharArray(CharArray::new_row("a")),
                    Value::CharArray(CharArray::new_row("b")),
                    Value::CharArray(CharArray::new_row("c")),
                ],
                None,
            )
            .expect_err("expected too many inputs");
            assert_eq!(err.identifier(), Some("RunMat:uigetdir:InvalidArgument"));

            let err = call(vec![], Some(2)).expect_err("expected too many outputs");
            assert_eq!(err.identifier(), Some("RunMat:uigetdir:TooManyOutputs"));
        });
    }
}