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
//! MATLAB-compatible `error` builtin with structured exception handling semantics.

use std::convert::TryFrom;

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

use crate::builtins::common::format::format_variadic;
use crate::builtins::common::spec::{
    BroadcastSemantics, BuiltinFusionSpec, BuiltinGpuSpec, ConstantStrategy, GpuOpKind,
    ReductionNaN, ResidencyPolicy, ShapeRequirements,
};
use crate::builtins::diagnostics::type_resolvers::error_type;
use crate::{build_runtime_error, RuntimeError};

const BUILTIN_NAME: &str = "error";

const ERROR_OUTPUT: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "out",
    ty: BuiltinParamType::Any,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "Never returned because error always throws.",
}];

const ERROR_INPUTS_MESSAGE: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "message",
    ty: BuiltinParamType::StringScalar,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "Error message text.",
}];

const ERROR_INPUTS_MESSAGE_VARIADIC: [BuiltinParamDescriptor; 2] = [
    BuiltinParamDescriptor {
        name: "message",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Error message template text.",
    },
    BuiltinParamDescriptor {
        name: "A",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Variadic,
        default: None,
        description: "Formatting values for the message template.",
    },
];

const ERROR_INPUTS_IDENTIFIER_MESSAGE: [BuiltinParamDescriptor; 2] = [
    BuiltinParamDescriptor {
        name: "message_id",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Required,
        default: Some("\"RunMat:error\""),
        description: "Message identifier.",
    },
    BuiltinParamDescriptor {
        name: "message",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Error message text.",
    },
];

const ERROR_INPUTS_IDENTIFIER_MESSAGE_VARIADIC: [BuiltinParamDescriptor; 3] = [
    BuiltinParamDescriptor {
        name: "message_id",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Required,
        default: Some("\"RunMat:error\""),
        description: "Message identifier.",
    },
    BuiltinParamDescriptor {
        name: "message",
        ty: BuiltinParamType::StringScalar,
        arity: BuiltinParamArity::Required,
        default: None,
        description: "Error message template text.",
    },
    BuiltinParamDescriptor {
        name: "A",
        ty: BuiltinParamType::Any,
        arity: BuiltinParamArity::Variadic,
        default: None,
        description: "Formatting values for the message template.",
    },
];

const ERROR_INPUTS_MEXCEPTION: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "mex",
    ty: BuiltinParamType::Any,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "MException value to rethrow.",
}];

const ERROR_INPUTS_STRUCT: [BuiltinParamDescriptor; 1] = [BuiltinParamDescriptor {
    name: "msg_struct",
    ty: BuiltinParamType::Any,
    arity: BuiltinParamArity::Required,
    default: None,
    description: "Struct containing identifier/message fields.",
}];

const ERROR_SIGNATURES: [BuiltinSignatureDescriptor; 6] = [
    BuiltinSignatureDescriptor {
        label: "out = error(message)",
        inputs: &ERROR_INPUTS_MESSAGE,
        outputs: &ERROR_OUTPUT,
    },
    BuiltinSignatureDescriptor {
        label: "out = error(message, A...)",
        inputs: &ERROR_INPUTS_MESSAGE_VARIADIC,
        outputs: &ERROR_OUTPUT,
    },
    BuiltinSignatureDescriptor {
        label: "out = error(message_id, message)",
        inputs: &ERROR_INPUTS_IDENTIFIER_MESSAGE,
        outputs: &ERROR_OUTPUT,
    },
    BuiltinSignatureDescriptor {
        label: "out = error(message_id, message, A...)",
        inputs: &ERROR_INPUTS_IDENTIFIER_MESSAGE_VARIADIC,
        outputs: &ERROR_OUTPUT,
    },
    BuiltinSignatureDescriptor {
        label: "out = error(mex)",
        inputs: &ERROR_INPUTS_MEXCEPTION,
        outputs: &ERROR_OUTPUT,
    },
    BuiltinSignatureDescriptor {
        label: "out = error(msg_struct)",
        inputs: &ERROR_INPUTS_STRUCT,
        outputs: &ERROR_OUTPUT,
    },
];

const ERROR_ERROR_MISSING_MESSAGE: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.ERROR.MISSING_MESSAGE",
    identifier: Some("RunMat:error"),
    when: "No arguments are supplied.",
    message: "error: missing message argument",
};

const ERROR_ERROR_EXTRA_ARGS_MEXCEPTION: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.ERROR.MEXCEPTION_EXTRA_ARGS",
    identifier: Some("RunMat:error"),
    when: "Additional arguments are supplied after an MException input.",
    message: "error: additional arguments are not allowed when passing an MException",
};

const ERROR_ERROR_EXTRA_ARGS_STRUCT: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.ERROR.STRUCT_EXTRA_ARGS",
    identifier: Some("RunMat:error"),
    when: "Additional arguments are supplied after a message-struct input.",
    message: "error: additional arguments are not allowed when passing a message struct",
};

const ERROR_ERROR_STRUCT_MISSING_IDENTIFIER: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.ERROR.STRUCT_MISSING_IDENTIFIER",
    identifier: Some("RunMat:error"),
    when: "Message struct does not contain an identifier field.",
    message: "error: message struct must contain an 'identifier' field",
};

const ERROR_ERROR_STRUCT_MISSING_MESSAGE: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.ERROR.STRUCT_MISSING_MESSAGE",
    identifier: Some("RunMat:error"),
    when: "Message struct does not contain a message field.",
    message: "error: message struct must contain a 'message' field",
};

const ERROR_ERROR_INVALID_INPUT: BuiltinErrorDescriptor = BuiltinErrorDescriptor {
    code: "RM.ERROR.INVALID_INPUT",
    identifier: Some("RunMat:error"),
    when: "Identifier/message inputs or format arguments are not string-compatible.",
    message: "error: invalid input argument",
};

const ERROR_ERRORS: [BuiltinErrorDescriptor; 6] = [
    ERROR_ERROR_MISSING_MESSAGE,
    ERROR_ERROR_EXTRA_ARGS_MEXCEPTION,
    ERROR_ERROR_EXTRA_ARGS_STRUCT,
    ERROR_ERROR_STRUCT_MISSING_IDENTIFIER,
    ERROR_ERROR_STRUCT_MISSING_MESSAGE,
    ERROR_ERROR_INVALID_INPUT,
];

pub const ERROR_DESCRIPTOR: BuiltinDescriptor = BuiltinDescriptor {
    signatures: &ERROR_SIGNATURES,
    output_mode: BuiltinOutputMode::Fixed,
    completion_policy: BuiltinCompletionPolicy::Public,
    errors: &ERROR_ERRORS,
};

#[runmat_macros::register_gpu_spec(builtin_path = "crate::builtins::diagnostics::error")]
pub const GPU_SPEC: BuiltinGpuSpec = BuiltinGpuSpec {
    name: "error",
    op_kind: GpuOpKind::Custom("control"),
    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: "Control-flow builtin; never dispatched to GPU backends.",
};

#[runmat_macros::register_fusion_spec(builtin_path = "crate::builtins::diagnostics::error")]
pub const FUSION_SPEC: BuiltinFusionSpec = BuiltinFusionSpec {
    name: "error",
    shape: ShapeRequirements::Any,
    constant_strategy: ConstantStrategy::InlineLiteral,
    elementwise: None,
    reduction: None,
    emits_nan: false,
    notes: "Control-flow builtin; excluded from fusion planning.",
};

fn error_flow(identifier: &str, message: impl Into<String>) -> RuntimeError {
    build_runtime_error(message)
        .with_builtin(BUILTIN_NAME)
        .with_identifier(normalize_identifier(identifier))
        .build()
}

fn error_default_identifier() -> &'static str {
    ERROR_ERROR_MISSING_MESSAGE
        .identifier
        .expect("error default identifier must be defined")
}

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

fn error_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(normalize_identifier(identifier));
    }
    builder.build()
}

fn remap_error_flow(err: RuntimeError, error: &'static BuiltinErrorDescriptor) -> RuntimeError {
    let mut builder = build_runtime_error(err.message().to_string())
        .with_builtin(BUILTIN_NAME)
        .with_source(err);
    if let Some(identifier) = error.identifier {
        builder = builder.with_identifier(normalize_identifier(identifier));
    }
    builder.build()
}

#[runtime_builtin(
    name = "error",
    category = "diagnostics",
    summary = "Throw exceptions with identifiers and formatted messages.",
    keywords = "error,exception,diagnostics,throw",
    accel = "metadata",
    type_resolver(error_type),
    descriptor(crate::builtins::diagnostics::error::ERROR_DESCRIPTOR),
    builtin_path = "crate::builtins::diagnostics::error"
)]
fn error_builtin(args: Vec<Value>) -> crate::BuiltinResult<Value> {
    if args.is_empty() {
        return Err(error_error(&ERROR_ERROR_MISSING_MESSAGE));
    }

    let mut iter = args.into_iter();
    let first = iter.next().expect("checked above");
    let rest: Vec<Value> = iter.collect();

    match first {
        Value::MException(mex) => {
            if !rest.is_empty() {
                return Err(error_error(&ERROR_ERROR_EXTRA_ARGS_MEXCEPTION));
            }
            Err(error_flow(&mex.identifier, &mex.message))
        }
        Value::Struct(ref st) => {
            if !rest.is_empty() {
                return Err(error_error(&ERROR_ERROR_EXTRA_ARGS_STRUCT));
            }
            let (identifier, message) = extract_struct_error_fields(st)?;
            Err(error_flow(&identifier, &message))
        }
        other => handle_message_arguments(other, rest),
    }
}

fn handle_message_arguments(first: Value, rest: Vec<Value>) -> crate::BuiltinResult<Value> {
    let first_string = value_to_string("error", &first)?;

    if rest.is_empty() {
        return Err(error_flow(error_default_identifier(), first_string));
    }

    let mut identifier = error_default_identifier().to_string();
    let mut format_string = first_string;
    let mut format_args: &[Value] = &rest;

    if !rest.is_empty()
        && (is_message_identifier(&format_string)
            || looks_like_unqualified_identifier(&format_string))
    {
        identifier = normalize_identifier(&format_string);
        let (message_value, extra_args) = rest.split_first().expect("rest not empty");
        format_string = value_to_string("error", message_value)?;
        format_args = extra_args;
    }

    let message = if format_args.is_empty() {
        format_string
    } else {
        format_variadic(&format_string, format_args)
            .map_err(|flow| remap_error_flow(flow, &ERROR_ERROR_INVALID_INPUT))?
    };

    Err(error_flow(&identifier, message))
}

fn extract_struct_error_fields(
    struct_value: &StructValue,
) -> crate::BuiltinResult<(String, String)> {
    let identifier_value = struct_value
        .fields
        .get("identifier")
        .or_else(|| struct_value.fields.get("messageid"))
        .ok_or_else(|| error_error(&ERROR_ERROR_STRUCT_MISSING_IDENTIFIER))?;
    let message_value = struct_value
        .fields
        .get("message")
        .or_else(|| struct_value.fields.get("msg"))
        .ok_or_else(|| error_error(&ERROR_ERROR_STRUCT_MISSING_MESSAGE))?;

    let identifier = value_to_string("error", identifier_value)?;
    let message = value_to_string("error", message_value)?;
    Ok((identifier, message))
}

fn value_to_string(context: &str, value: &Value) -> crate::BuiltinResult<String> {
    String::try_from(value).map_err(|e| {
        error_error_with_message(format!("{context}: {e}"), &ERROR_ERROR_INVALID_INPUT)
    })
}

fn normalize_identifier(raw: &str) -> String {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        error_default_identifier().to_string()
    } else if trimmed.contains(':') {
        trimmed.to_string()
    } else {
        format!("RunMat:{trimmed}")
    }
}

fn is_message_identifier(text: &str) -> bool {
    let trimmed = text.trim();
    if trimmed.is_empty() || !trimmed.contains(':') {
        return false;
    }
    trimmed
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, ':' | '_' | '.'))
}

fn looks_like_unqualified_identifier(text: &str) -> bool {
    let trimmed = text.trim();
    if trimmed.is_empty() || trimmed.contains(char::is_whitespace) {
        return false;
    }
    trimmed
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.'))
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use runmat_builtins::{IntValue, MException, ResolveContext, Type};

    fn unwrap_error(err: crate::RuntimeError) -> crate::RuntimeError {
        err
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn error_requires_message() {
        let err = unwrap_error(error_builtin(Vec::new()).expect_err("should error"));
        assert_eq!(err.identifier(), Some(error_default_identifier()));
        assert!(err.message().contains("missing message"));
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn default_identifier_is_applied() {
        let err =
            unwrap_error(error_builtin(vec![Value::from("Failure!")]).expect_err("should error"));
        assert_eq!(err.identifier(), Some(error_default_identifier()));
        assert_eq!(err.message(), "Failure!");
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn custom_identifier_is_preserved() {
        let err = unwrap_error(
            error_builtin(vec![
                Value::from("runmat:tests:badValue"),
                Value::from("Value %d is not allowed."),
                Value::from(5.0),
            ])
            .expect_err("should error"),
        );
        assert_eq!(err.identifier(), Some("runmat:tests:badValue"));
        assert_eq!(err.message(), "Value 5 is not allowed.");
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn identifier_is_normalised_when_namespace_missing() {
        let err = unwrap_error(
            error_builtin(vec![
                Value::from("missingNamespace"),
                Value::from("Message"),
            ])
            .expect_err("should error"),
        );
        assert_eq!(err.identifier(), Some("RunMat:missingNamespace"));
        assert_eq!(err.message(), "Message");
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn format_string_with_colon_not_treated_as_identifier() {
        let err = unwrap_error(
            error_builtin(vec![
                Value::from("Value: %d."),
                Value::Int(IntValue::I32(7)),
            ])
            .expect_err("should error"),
        );
        assert_eq!(err.identifier(), Some(error_default_identifier()));
        assert_eq!(err.message(), "Value: 7.");
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn error_accepts_mexception() {
        let mex = MException::new("RunMat:demo:test".to_string(), "broken".to_string());
        let err =
            unwrap_error(error_builtin(vec![Value::MException(mex)]).expect_err("should error"));
        assert_eq!(err.identifier(), Some("RunMat:demo:test"));
        assert_eq!(err.message(), "broken");
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn error_rejects_extra_args_after_mexception() {
        let mex = MException::new("RunMat:demo:test".to_string(), "broken".to_string());
        let err = unwrap_error(
            error_builtin(vec![Value::MException(mex), Value::from(1.0)])
                .expect_err("should error"),
        );
        assert_eq!(err.identifier(), Some(error_default_identifier()));
        assert!(err.message().contains("additional arguments"));
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn error_accepts_message_struct() {
        let mut st = StructValue::new();
        st.fields
            .insert("identifier".to_string(), Value::from("pkg:demo:failure"));
        st.fields
            .insert("message".to_string(), Value::from("Struct message."));
        let err = unwrap_error(error_builtin(vec![Value::Struct(st)]).expect_err("should error"));
        assert_eq!(err.identifier(), Some("pkg:demo:failure"));
        assert_eq!(err.message(), "Struct message.");
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
    #[test]
    fn error_struct_requires_message_field() {
        let mut st = StructValue::new();
        st.fields
            .insert("identifier".to_string(), Value::from("pkg:demo:oops"));
        let err = unwrap_error(error_builtin(vec![Value::Struct(st)]).expect_err("should error"));
        assert_eq!(err.identifier(), Some(error_default_identifier()));
        assert!(err
            .message()
            .contains("message struct must contain a 'message' field"));
    }

    #[test]
    fn error_type_is_unknown() {
        assert_eq!(
            error_type(&[Type::String], &ResolveContext::new(Vec::new())),
            Type::Unknown
        );
    }
}