runmat 0.0.17

High-performance MATLAB/Octave runtime with Jupyter kernel support
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
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;

// Helper function to get the binary path
fn get_binary_path() -> PathBuf {
    let mut path = std::env::current_exe().unwrap();
    path.pop(); // Remove test binary name
    if path.ends_with("deps") {
        path.pop(); // Remove deps directory
    }
    path.push("runmat");
    path
}

// Helper function to run runmat with arguments
fn run_runmat(args: &[&str]) -> std::process::Output {
    Command::new(get_binary_path())
        .args(args)
        .output()
        .expect("Failed to execute runmat binary")
}

#[test]
fn test_end_to_end_script_execution() {
    let temp_dir = TempDir::new().unwrap();
    let script_path = temp_dir.path().join("e2e_test.m");

    // Create a comprehensive test script
    fs::write(
        &script_path,
        r#"
% Test script for end-to-end functionality
x = 10 + 5
y = [1, 2; 3, 4]
z = x * 2
result = z + 5
"#,
    )
    .unwrap();

    let output = run_runmat(&["run", script_path.to_str().unwrap()]);
    assert!(
        output.status.success(),
        "End-to-end script execution failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_gc_integration_with_cli() {
    let temp_dir = TempDir::new().unwrap();
    let script_path = temp_dir.path().join("gc_test.m");

    // Create a script that allocates objects
    fs::write(
        &script_path,
        r#"
for i = 1:10
    matrix_i = [i, i+1; i+2, i+3]
end
final_result = 42
"#,
    )
    .unwrap();

    let output = run_runmat(&[
        "--gc-preset",
        "debug",
        "--gc-stats",
        "run",
        script_path.to_str().unwrap(),
    ]);

    assert!(
        output.status.success(),
        "GC integration test failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_jit_vs_interpreter_performance() {
    let temp_dir = TempDir::new().unwrap();
    let script_path = temp_dir.path().join("perf_test.m");

    // Create a script for performance testing
    fs::write(
        &script_path,
        r#"
x = 50;
y = 25;
result = x + y * 2;
"#,
    )
    .unwrap();

    // Test with JIT enabled
    let jit_output = run_runmat(&[
        "--jit-opt-level",
        "speed",
        "benchmark",
        script_path.to_str().unwrap(),
        "--iterations",
        "5",
        "--jit",
    ]);

    // Test with JIT disabled
    let interp_output = run_runmat(&["--no-jit", "run", script_path.to_str().unwrap()]);

    assert!(jit_output.status.success(), "JIT benchmark failed");
    assert!(
        interp_output.status.success(),
        "Interpreter execution failed"
    );

    let jit_stdout = String::from_utf8_lossy(&jit_output.stdout);
    assert!(jit_stdout.contains("Benchmark Results"));
}

#[test]
fn test_configuration_persistence() {
    // Test that configuration options are properly applied
    let output = run_runmat(&[
        "--gc-preset",
        "low-latency",
        "--jit-threshold",
        "5",
        "--gc-young-size",
        "32",
        "info",
    ]);

    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("GC Preset: \"LowLatency\""));
    assert!(stdout.contains("JIT Threshold: 5"));
    assert!(stdout.contains("GC Young Generation: 32MB"));
}

#[test]
fn test_error_handling_and_recovery() {
    let temp_dir = TempDir::new().unwrap();
    let bad_script_path = temp_dir.path().join("bad_script.m");
    let good_script_path = temp_dir.path().join("good_script.m");

    // Create a script with errors
    fs::write(&bad_script_path, "x = [1, 2,").unwrap(); // Syntax error

    // Create a valid script
    fs::write(&good_script_path, "x = 42").unwrap();

    // Bad script should fail
    let bad_output = run_runmat(&["run", bad_script_path.to_str().unwrap()]);
    assert!(!bad_output.status.success());

    // Good script should work after error
    let good_output = run_runmat(&["run", good_script_path.to_str().unwrap()]);
    assert!(good_output.status.success());
}

#[test]
fn test_comprehensive_system_functionality() {
    // Test multiple subsystems working together
    let temp_dir = TempDir::new().unwrap();
    let script_path = temp_dir.path().join("comprehensive.m");

    fs::write(
        &script_path,
        r#"
% Comprehensive test
A = [1, 2; 3, 4];
B = [5, 6; 7, 8];
x = 10;
y = 20;

% Arithmetic
result1 = x + y;

% Matrix operations
result2 = A;

% Simple calculation
result3 = x * 2;

% Loop
sum_val = 0;
for i = 1:5; sum_val = sum_val + i; end;

final_answer = result1 + result3;
"#,
    )
    .unwrap();

    let output = run_runmat(&[
        "--gc-preset",
        "high-throughput",
        "--jit-opt-level",
        "aggressive",
        "--verbose",
        "run",
        script_path.to_str().unwrap(),
    ]);

    assert!(
        output.status.success(),
        "Comprehensive system test failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Should have completed without crashes
    let stdout = String::from_utf8_lossy(&output.stdout);
    // The verbose output or successful completion should be evident
    assert!(!stdout.is_empty() || output.status.success());
}

#[test]
fn test_memory_stress_with_gc() {
    let temp_dir = TempDir::new().unwrap();
    let script_path = temp_dir.path().join("memory_stress.m");

    fs::write(
        &script_path,
        r#"
% Memory stress test
for i = 1:50
    big_matrix = [i, i+1, i+2; i+3, i+4, i+5; i+6, i+7, i+8]
    temp_val = i * 2
end
result = 999
"#,
    )
    .unwrap();

    let output = run_runmat(&[
        "--gc-preset",
        "low-memory",
        "--gc-stats",
        "run",
        script_path.to_str().unwrap(),
    ]);

    assert!(
        output.status.success(),
        "Memory stress test failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_cli_help_and_documentation() {
    // Test that help output is comprehensive and correct
    let output = run_runmat(&["--help"]);
    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should contain key sections
    let required_sections = [
        "RunMat",
        "JIT compilation",
        "Garbage collection",
        "Usage:",
        "Commands:",
        "Options:",
        "Environment Variables:",
    ];

    for section in &required_sections {
        assert!(stdout.contains(section), "Help missing section: {section}");
    }
}

#[test]
fn test_version_information() {
    let output = run_runmat(&["version", "--detailed"]);
    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);

    let required_components = [
        "runmat-lexer",
        "runmat-parser",
        "runmat-hir",
        "runmat-ignition",
        "runmat-turbine",
        "runmat-gc",
        "runmat-runtime",
    ];

    for component in &required_components {
        assert!(
            stdout.contains(component),
            "Version info missing component: {component}"
        );
    }
}

#[test]
fn test_benchmark_functionality() {
    let temp_dir = TempDir::new().unwrap();
    let script_path = temp_dir.path().join("benchmark_test.m");

    fs::write(&script_path, "benchmark_result = 10 + 20").unwrap();

    let output = run_runmat(&[
        "benchmark",
        script_path.to_str().unwrap(),
        "--iterations",
        "3",
    ]);

    assert!(
        output.status.success(),
        "Benchmark test failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("Benchmark Results"));
    assert!(stdout.contains("iterations"));
    assert!(stdout.contains("Average time"));
}

#[test]
fn test_gc_commands() {
    // Test all GC subcommands
    let gc_commands = ["stats", "minor", "major", "config"];

    for cmd in &gc_commands {
        let output = run_runmat(&["gc", cmd]);
        assert!(
            output.status.success() || output.status.success(), // Some might not be implemented yet
            "GC command failed: gc {cmd}"
        );
    }
}

#[test]
fn test_multi_configuration_compatibility() {
    // Test that multiple configuration options work together
    let combinations = [
        vec!["--gc-preset", "low-latency", "--jit-opt-level", "speed"],
        vec!["--gc-preset", "debug", "--no-jit", "--verbose"],
        vec!["--gc-young-size", "64", "--jit-threshold", "20"],
    ];

    for combo in &combinations {
        let mut args = combo.clone();
        args.push("info");

        let output = run_runmat(&args);
        assert!(
            output.status.success(),
            "Configuration combination failed: {combo:?}"
        );
    }
}

#[test]
fn test_script_with_all_language_features() {
    let temp_dir = TempDir::new().unwrap();
    let script_path = temp_dir.path().join("all_features.m");

    fs::write(
        &script_path,
        r#"
% Test all major language features

% Variables and arithmetic
x = 10;
y = 5;
arithmetic_result = x + y * 2 - 3;

% Matrices
matrix_2d = [1, 2; 3, 4];
vector_row = [1, 2, 3];
vector_col = [1; 2; 3];

% Simple calculation instead of conditional
condition_result = 1;

% Loop
loop_sum = 0;
for i = 1:5; loop_sum = loop_sum + i; end;

% Final computation
final_result = arithmetic_result + condition_result + loop_sum;
"#,
    )
    .unwrap();

    let output = run_runmat(&["run", script_path.to_str().unwrap()]);
    assert!(
        output.status.success(),
        "All features test failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn test_concurrent_execution_safety() {
    use std::sync::Arc;
    use std::thread;

    let temp_dir = Arc::new(TempDir::new().unwrap());
    let mut handles = vec![];

    // Spawn multiple threads running different scripts
    for i in 0..3 {
        let temp_dir_clone = Arc::clone(&temp_dir);
        let handle = thread::spawn(move || {
            let script_path = temp_dir_clone.path().join(format!("concurrent_{i}.m"));
            fs::write(&script_path, format!("thread_result_{i} = {i} * 10")).unwrap();

            let output = run_runmat(&["run", script_path.to_str().unwrap()]);
            output.status.success()
        });
        handles.push(handle);
    }

    // Wait for all threads and check results
    for (i, handle) in handles.into_iter().enumerate() {
        let success = handle.join().unwrap();
        assert!(success, "Concurrent execution {i} failed");
    }
}

#[test]
fn test_edge_case_handling() {
    let temp_dir = TempDir::new().unwrap();

    // Test empty file
    let empty_script = temp_dir.path().join("empty.m");
    fs::write(&empty_script, "").unwrap();
    let output = run_runmat(&["run", empty_script.to_str().unwrap()]);
    assert!(output.status.success()); // Should handle gracefully

    // Test whitespace-only file
    let whitespace_script = temp_dir.path().join("whitespace.m");
    fs::write(&whitespace_script, "   \n\t  \n  ").unwrap();
    let output = run_runmat(&["run", whitespace_script.to_str().unwrap()]);
    assert!(output.status.success()); // Should handle gracefully

    // Test very large numbers
    let large_num_script = temp_dir.path().join("large_nums.m");
    fs::write(&large_num_script, "huge = 1e100; result = huge / 1e50;").unwrap();
    let output = run_runmat(&["run", large_num_script.to_str().unwrap()]);
    // Should handle gracefully (success or controlled failure)
    assert!(output.status.success() || !output.status.success());
}