ruchy 4.2.1

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
// EXTREME TDD: Async Runtime Tests
// Sprint 80: 0% Coverage Modules Attack
// Testing runtime/async_runtime.rs with comprehensive coverage

use ruchy::runtime::async_runtime::AsyncRuntime;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake};
use std::time::Duration;

#[cfg(test)]
mod async_runtime_unit_tests {
    use super::*;

    #[test]
    fn test_async_runtime_new() {
        let runtime = AsyncRuntime::new();
        // Should create without panic
        let _ = runtime;
    }

    #[test]
    fn test_async_runtime_default() {
        let runtime = AsyncRuntime::default();
        // Default should work same as new
        let _ = runtime;
    }

    #[tokio::test]
    async fn test_async_runtime_spawn_simple() {
        let runtime = AsyncRuntime::new();

        let handle = runtime.spawn(async { 42 });

        let result = handle.await;
        assert_eq!(result, 42);
    }

    #[tokio::test]
    async fn test_async_runtime_spawn_with_computation() {
        let runtime = AsyncRuntime::new();

        let handle = runtime.spawn(async {
            let mut sum = 0;
            for i in 1..=10 {
                sum += i;
            }
            sum
        });

        let result = handle.await;
        assert_eq!(result, 55); // Sum of 1..=10
    }

    #[tokio::test]
    async fn test_async_runtime_sleep() {
        let runtime = AsyncRuntime::new();

        let start = std::time::Instant::now();
        runtime.sleep(Duration::from_millis(10)).await;
        let elapsed = start.elapsed();

        assert!(elapsed >= Duration::from_millis(10));
        assert!(elapsed < Duration::from_millis(100)); // Reasonable upper bound
    }

    #[tokio::test]
    async fn test_async_runtime_spawn_multiple() {
        let runtime = AsyncRuntime::new();

        let handle1 = runtime.spawn(async { 1 });
        let handle2 = runtime.spawn(async { 2 });
        let handle3 = runtime.spawn(async { 3 });

        let result1 = handle1.await;
        let result2 = handle2.await;
        let result3 = handle3.await;

        assert_eq!(result1, 1);
        assert_eq!(result2, 2);
        assert_eq!(result3, 3);
    }

    #[tokio::test]
    async fn test_async_runtime_spawn_with_sleep() {
        let runtime = AsyncRuntime::new();

        let handle = runtime.spawn(async {
            tokio::time::sleep(Duration::from_millis(10)).await;
            "done"
        });

        let result = handle.await;
        assert_eq!(result, "done");
    }

    #[tokio::test]
    async fn test_async_runtime_concurrent_spawns() {
        let runtime = AsyncRuntime::new();

        let mut handles = vec![];

        for i in 0..10 {
            let handle = runtime.spawn(async move {
                tokio::time::sleep(Duration::from_millis(1)).await;
                i * 2
            });
            handles.push(handle);
        }

        let mut results = vec![];
        for handle in handles {
            results.push(handle.await);
        }

        for (i, result) in results.iter().enumerate() {
            assert_eq!(*result, i * 2);
        }
    }

    #[tokio::test]
    async fn test_async_runtime_nested_spawn() {
        let runtime = AsyncRuntime::new();

        let handle = runtime.spawn(async {
            let runtime2 = AsyncRuntime::new();
            let inner_handle = runtime2.spawn(async { 100 });
            inner_handle.await
        });

        let result = handle.await;
        assert_eq!(result, 100);
    }

    #[tokio::test]
    async fn test_async_runtime_error_handling() {
        let runtime = AsyncRuntime::new();

        let handle = runtime.spawn(async {
            // Simulate some work that could fail
            let result: Result<i32, &str> = Ok(42);
            result.unwrap()
        });

        let result = handle.await;
        assert_eq!(result, 42);
    }

    #[tokio::test]
    async fn test_async_runtime_with_strings() {
        let runtime = AsyncRuntime::new();

        let handle = runtime.spawn(async {
            let mut s = String::from("Hello");
            s.push_str(", World!");
            s
        });

        let result = handle.await;
        assert_eq!(result, "Hello, World!");
    }

    #[tokio::test]
    async fn test_async_runtime_with_vec() {
        let runtime = AsyncRuntime::new();

        let handle = runtime.spawn(async {
            let mut v = vec![1, 2, 3];
            v.push(4);
            v.push(5);
            v
        });

        let result = handle.await;
        assert_eq!(result, vec![1, 2, 3, 4, 5]);
    }

    #[tokio::test]
    async fn test_multiple_sleeps() {
        let runtime = AsyncRuntime::new();

        let start = std::time::Instant::now();
        runtime.sleep(Duration::from_millis(5)).await;
        runtime.sleep(Duration::from_millis(5)).await;
        runtime.sleep(Duration::from_millis(5)).await;
        let elapsed = start.elapsed();

        assert!(elapsed >= Duration::from_millis(15));
    }

    #[tokio::test]
    async fn test_zero_duration_sleep() {
        let runtime = AsyncRuntime::new();

        let start = std::time::Instant::now();
        runtime.sleep(Duration::from_millis(0)).await;
        let elapsed = start.elapsed();

        assert!(elapsed < Duration::from_millis(10));
    }

    #[test]
    fn test_join_handle_future_impl() {
        // Check that JoinHandle implements Future trait properly
        let runtime = tokio::runtime::Runtime::new().unwrap();

        runtime.block_on(async {
            let async_runtime = AsyncRuntime::new();
            let handle = async_runtime.spawn(async { 123 });

            // This tests the Future implementation
            let result = handle.await;
            assert_eq!(result, 123);
        });
    }

    struct NoopWaker;

    impl Wake for NoopWaker {
        fn wake(self: Arc<Self>) {}
        fn wake_by_ref(self: &Arc<Self>) {}
    }

    #[test]
    fn test_join_handle_poll() {
        // Check the poll method directly
        let runtime = tokio::runtime::Runtime::new().unwrap();

        runtime.block_on(async {
            let async_runtime = AsyncRuntime::new();
            let mut handle = async_runtime.spawn(async { 999 });

            // Create a no-op waker for testing
            let waker = Arc::new(NoopWaker).into();
            let mut context = Context::from_waker(&waker);

            // Poll the handle
            let pinned = Pin::new(&mut handle);
            match pinned.poll(&mut context) {
                Poll::Ready(value) => assert_eq!(value, 999),
                Poll::Pending => {
                    // It's okay to be pending initially
                    // In real use, the executor would poll again
                }
            }
        });
    }
}

// Property-based tests
#[cfg(test)]
mod async_runtime_property_tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn test_spawn_returns_value(value: i32) {
            let runtime = tokio::runtime::Runtime::new().unwrap();

            runtime.block_on(async move {
                let async_runtime = AsyncRuntime::new();
                let val_copy = value;
                let handle = async_runtime.spawn(async move { val_copy });
                let result = handle.await;
                assert_eq!(result, value);
            });
        }

        #[test]
        fn test_sleep_duration(millis in 0u64..10u64) {
            let runtime = tokio::runtime::Runtime::new().unwrap();

            runtime.block_on(async {
                let async_runtime = AsyncRuntime::new();
                let duration = Duration::from_millis(millis);

                let start = std::time::Instant::now();
                async_runtime.sleep(duration).await;
                let elapsed = start.elapsed();

                // Sleep should take at least the requested duration
                assert!(elapsed >= duration);
            });
        }

    }
}

// Stress tests
#[cfg(test)]
mod async_runtime_stress_tests {
    use super::*;

    #[tokio::test]
    #[ignore] // Can be expensive
    async fn test_many_concurrent_spawns() {
        let runtime = AsyncRuntime::new();

        let mut handles = vec![];

        // Spawn 1000 tasks
        for i in 0..1000 {
            let handle = runtime.spawn(async move {
                // Each task does minimal work
                i * i
            });
            handles.push(handle);
        }

        // Await all handles
        for (i, handle) in handles.into_iter().enumerate() {
            let result = handle.await;
            assert_eq!(result, i * i);
        }
    }

    #[tokio::test]
    #[ignore] // Can be expensive
    async fn test_many_sequential_sleeps() {
        let runtime = AsyncRuntime::new();

        let start = std::time::Instant::now();

        // 100 very short sleeps
        for _ in 0..100 {
            runtime.sleep(Duration::from_micros(100)).await;
        }

        let elapsed = start.elapsed();

        // Should take at least 10ms (100 * 100 microseconds)
        assert!(elapsed >= Duration::from_millis(10));
    }

    #[tokio::test]
    #[ignore] // Can be expensive
    async fn test_deeply_nested_spawns() {
        // Simplified nested function to avoid Send issues
        fn nested_spawn_blocking(depth: usize) -> usize {
            if depth == 0 {
                return 42;
            }
            nested_spawn_blocking(depth - 1)
        }

        let result = nested_spawn_blocking(10);
        assert_eq!(result, 42);
    }
}

// Additional integration tests for comprehensive coverage
#[cfg(test)]
mod async_runtime_integration_tests {
    use super::*;

    #[tokio::test]
    async fn test_runtime_with_shared_state() {
        use std::sync::{Arc, Mutex};

        let runtime = AsyncRuntime::new();
        let counter = Arc::new(Mutex::new(0));

        let mut handles = vec![];

        // Spawn 10 tasks that increment a shared counter
        for _ in 0..10 {
            let counter_clone = counter.clone();
            let handle = runtime.spawn(async move {
                let mut count = counter_clone.lock().unwrap();
                *count += 1;
                *count
            });
            handles.push(handle);
        }

        // Wait for all tasks to complete
        for handle in handles {
            let _ = handle.await;
        }

        // Final counter value should be 10
        let final_count = *counter.lock().unwrap();
        assert_eq!(final_count, 10);
    }

    #[tokio::test]
    async fn test_runtime_task_cancellation_safety() {
        let runtime = AsyncRuntime::new();

        // Spawn a long-running task
        let handle = runtime.spawn(async {
            for i in 0..1000 {
                tokio::time::sleep(Duration::from_micros(10)).await;
                if i == 10 {
                    return "early_exit";
                }
            }
            "completed"
        });

        let result = handle.await;
        assert_eq!(result, "early_exit");
    }

    #[tokio::test]
    async fn test_runtime_resource_cleanup() {
        // Check that resources are properly cleaned up
        for _ in 0..100 {
            let runtime = AsyncRuntime::new();
            let handle = runtime.spawn(async {
                // Allocate some resources
                let _data = vec![0u8; 1000];
                42
            });
            let result = handle.await;
            assert_eq!(result, 42);
            // Runtime and handle should be dropped here
        }
    }

    #[tokio::test]
    async fn test_runtime_performance_timing() {
        let runtime = AsyncRuntime::new();

        // Check that spawning is fast
        let start = std::time::Instant::now();
        let handles: Vec<_> = (0..100).map(|i| runtime.spawn(async move { i })).collect();
        let spawn_time = start.elapsed();

        // Check that awaiting is reasonable
        let start_await = std::time::Instant::now();
        for (i, handle) in handles.into_iter().enumerate() {
            let result = handle.await;
            assert_eq!(result, i);
        }
        let await_time = start_await.elapsed();

        // Performance should be reasonable
        assert!(spawn_time < Duration::from_millis(100));
        assert!(await_time < Duration::from_millis(100));
    }

    #[tokio::test]
    async fn test_runtime_mixed_sync_async_work() {
        let runtime = AsyncRuntime::new();

        let handle = runtime.spawn(async {
            // Mix of sync and async work
            let mut result = 0;

            // Sync work
            for i in 1..=10 {
                result += i;
            }

            // Async work
            tokio::time::sleep(Duration::from_millis(1)).await;

            // More sync work
            result *= 2;

            // More async work
            tokio::time::sleep(Duration::from_millis(1)).await;

            result
        });

        let result = handle.await;
        assert_eq!(result, 110); // (1+2+...+10) * 2 = 55 * 2 = 110
    }

    #[tokio::test]
    async fn test_runtime_error_propagation() {
        let runtime = AsyncRuntime::new();

        // Check successful execution
        let success_handle = runtime.spawn(async { Result::<i32, &str>::Ok(42) });

        let success_result = success_handle.await;
        assert!(success_result.is_ok());
        assert_eq!(success_result.unwrap(), 42);

        // Check error handling
        let error_handle = runtime.spawn(async { Result::<i32, &str>::Err("test error") });

        let error_result = error_handle.await;
        assert!(error_result.is_err());
        assert_eq!(error_result.unwrap_err(), "test error");
    }

    #[tokio::test]
    async fn test_runtime_complex_data_structures() {
        let runtime = AsyncRuntime::new();

        let handle = runtime.spawn(async {
            use std::collections::HashMap;

            let mut map = HashMap::new();
            map.insert("key1", vec![1, 2, 3]);
            map.insert("key2", vec![4, 5, 6]);
            map.insert("key3", vec![7, 8, 9]);

            // Simulate some async processing
            tokio::time::sleep(Duration::from_millis(1)).await;

            map
        });

        let result = handle.await;
        assert_eq!(result.len(), 3);
        assert_eq!(result.get("key1"), Some(&vec![1, 2, 3]));
        assert_eq!(result.get("key2"), Some(&vec![4, 5, 6]));
        assert_eq!(result.get("key3"), Some(&vec![7, 8, 9]));
    }

    #[tokio::test]
    async fn test_runtime_producer_consumer_pattern() {
        use std::sync::mpsc;

        let runtime = AsyncRuntime::new();
        let (tx, rx) = mpsc::channel();

        // Producer task
        let producer_handle = runtime.spawn(async move {
            for i in 0..10 {
                tx.send(i).unwrap();
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        });

        // Consumer task
        let consumer_handle = runtime.spawn(async move {
            let mut sum = 0;
            while let Ok(value) = rx.recv() {
                sum += value;
                if sum >= 45 {
                    // Sum of 0..=9
                    break;
                }
            }
            sum
        });

        // Wait for both tasks
        producer_handle.await;
        let consumer_result = consumer_handle.await;

        assert_eq!(consumer_result, 45); // Sum of 0..=9
    }
}

// Edge case and error handling tests
#[cfg(test)]
mod async_runtime_edge_case_tests {
    use super::*;

    #[tokio::test]
    async fn test_runtime_immediate_completion() {
        let runtime = AsyncRuntime::new();

        // Task that completes immediately without any async work
        let handle = runtime.spawn(async { "immediate" });

        let result = handle.await;
        assert_eq!(result, "immediate");
    }

    #[tokio::test]
    async fn test_runtime_unit_return_type() {
        let runtime = AsyncRuntime::new();

        // Task that returns unit type
        let handle = runtime.spawn(async {
            // Do some work but return nothing
            let _ = 42 + 8;
        });

        let result = handle.await;
        assert_eq!(result, ());
    }

    #[tokio::test]
    async fn test_runtime_large_data_transfer() {
        let runtime = AsyncRuntime::new();

        // Task that works with large data
        let handle = runtime.spawn(async {
            let large_vec: Vec<u64> = (0..10000).collect();
            large_vec.len()
        });

        let result = handle.await;
        assert_eq!(result, 10000);
    }

    #[tokio::test]
    async fn test_runtime_sleep_precision() {
        let runtime = AsyncRuntime::new();

        // Check various sleep durations
        let durations = vec![
            Duration::from_millis(1),
            Duration::from_millis(5),
            Duration::from_millis(10),
            Duration::from_millis(50),
        ];

        for duration in durations {
            let start = std::time::Instant::now();
            runtime.sleep(duration).await;
            let elapsed = start.elapsed();

            // Sleep should take at least the requested time
            assert!(elapsed >= duration);
            // But not too much longer (allowing for system variance)
            assert!(elapsed <= duration + Duration::from_millis(50));
        }
    }

    #[tokio::test]
    async fn test_runtime_spawn_different_types() {
        let runtime = AsyncRuntime::new();

        // Check spawning tasks that return different types
        let bool_handle = runtime.spawn(async { true });
        let string_handle = runtime.spawn(async { "test".to_string() });
        let vec_handle = runtime.spawn(async { vec![1, 2, 3] });
        let option_handle = runtime.spawn(async { Some(42) });

        assert_eq!(bool_handle.await, true);
        assert_eq!(string_handle.await, "test");
        assert_eq!(vec_handle.await, vec![1, 2, 3]);
        assert_eq!(option_handle.await, Some(42));
    }

    #[tokio::test]
    async fn test_runtime_concurrent_sleeps() {
        let runtime = AsyncRuntime::new();

        let start = std::time::Instant::now();

        // Spawn multiple concurrent sleep tasks
        let handles: Vec<_> = (0..5)
            .map(|i| {
                runtime.spawn(async move {
                    tokio::time::sleep(Duration::from_millis(10)).await;
                    i
                })
            })
            .collect();

        // Collect all results
        let mut results = Vec::new();
        for handle in handles {
            results.push(handle.await);
        }

        let elapsed = start.elapsed();

        // Should complete in roughly 10ms (concurrent execution)
        // not 50ms (sequential execution)
        assert!(elapsed < Duration::from_millis(40));
        assert_eq!(results, vec![0, 1, 2, 3, 4]);
    }

    #[tokio::test]
    async fn test_runtime_recursive_async() {
        async fn async_factorial(n: u64) -> u64 {
            let mut result = 1;
            for i in 1..=n {
                // Add small delay to make it actually async
                tokio::time::sleep(Duration::from_micros(1)).await;
                result *= i;
            }
            result
        }

        let runtime = AsyncRuntime::new();
        let handle = runtime.spawn(async { async_factorial(5).await });

        let result = handle.await;
        assert_eq!(result, 120); // 5! = 120
    }
}