ruchy 4.2.0

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
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
//! Performance optimizations for the Ruchy compiler
//!
//! PMAT A+ Quality Standards:
//! - Maximum cyclomatic complexity: 10
//! - No TODO/FIXME/HACK comments
//! - 100% test coverage for new functions

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// AST-based compilation cache with LRU eviction
pub struct CompilationCache {
    /// Cache entries with access tracking
    cache: HashMap<String, CacheEntry>,
    /// Maximum cache size in entries
    max_size: usize,
    /// Cache statistics
    hits: u64,
    misses: u64,
    evictions: u64,
}

#[derive(Clone)]
struct CacheEntry {
    /// Compiled output
    pub output: String,
    /// Last access time for LRU tracking
    pub last_access: Instant,
    /// Compilation time
    pub compile_time: Duration,
    /// Memory usage
    pub memory_bytes: usize,
}

impl CompilationCache {
    /// Create new compilation cache with specified capacity
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::performance_optimizations::CompilationCache;
    ///
    /// let cache = CompilationCache::new(1000);
    /// assert_eq!(cache.len(), 0);
    /// assert_eq!(cache.capacity(), 1000);
    /// ```
    #[must_use]
    pub fn new(max_size: usize) -> Self {
        Self {
            cache: HashMap::new(),
            max_size,
            hits: 0,
            misses: 0,
            evictions: 0,
        }
    }

    /// Get cached compilation result
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::performance_optimizations::CompilationCache;
    ///
    /// let mut cache = CompilationCache::new(100);
    /// cache.insert("test".to_string(), "output".to_string(), std::time::Duration::from_millis(100), 512);
    ///
    /// let result = cache.get("test");
    /// assert!(result.is_some());
    /// assert_eq!(result.unwrap(), "output");
    /// ```
    pub fn get(&mut self, key: &str) -> Option<String> {
        if let Some(entry) = self.cache.get_mut(key) {
            entry.last_access = Instant::now();
            self.hits += 1;
            Some(entry.output.clone())
        } else {
            self.misses += 1;
            None
        }
    }

    /// Insert compilation result into cache
    pub fn insert(
        &mut self,
        key: String,
        output: String,
        compile_time: Duration,
        memory_bytes: usize,
    ) {
        // Evict least recently used entries if at capacity
        if self.cache.len() >= self.max_size {
            self.evict_lru();
        }

        let entry = CacheEntry {
            output,
            last_access: Instant::now(),
            compile_time,
            memory_bytes,
        };

        self.cache.insert(key, entry);
    }

    /// Evict least recently used entry
    fn evict_lru(&mut self) {
        if self.cache.is_empty() {
            return;
        }

        // Find LRU entry
        let (lru_key, _) = self
            .cache
            .iter()
            .min_by_key(|(_, entry)| entry.last_access)
            .map(|(k, v)| (k.clone(), v.clone()))
            .expect("Cache not empty");

        self.cache.remove(&lru_key);
        self.evictions += 1;
    }

    /// Get cache statistics
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::performance_optimizations::CompilationCache;
    ///
    /// let mut cache = CompilationCache::new(100);
    /// cache.insert("test".to_string(), "output".to_string(), std::time::Duration::from_millis(100), 512);
    /// cache.get("test");
    /// cache.get("missing");
    ///
    /// let stats = cache.stats();
    /// assert_eq!(stats.total_requests(), 2);
    /// assert_eq!(stats.hit_rate(), 0.5);
    /// ```
    #[must_use]
    pub fn stats(&self) -> CacheStats {
        CacheStats {
            hits: self.hits,
            misses: self.misses,
            evictions: self.evictions,
            size: self.cache.len(),
            capacity: self.max_size,
        }
    }

    /// Current number of cached entries
    #[must_use]
    pub fn len(&self) -> usize {
        self.cache.len()
    }

    /// Whether cache is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.cache.is_empty()
    }

    /// Maximum cache capacity
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.max_size
    }

    /// Clear all cache entries
    pub fn clear(&mut self) {
        self.cache.clear();
    }

    /// Get memory usage of cached entries
    #[must_use]
    pub fn memory_usage(&self) -> usize {
        self.cache.values().map(|entry| entry.memory_bytes).sum()
    }
}

/// Cache performance statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    pub hits: u64,
    pub misses: u64,
    pub evictions: u64,
    pub size: usize,
    pub capacity: usize,
}

impl CacheStats {
    /// Total cache requests
    #[must_use]
    pub fn total_requests(&self) -> u64 {
        self.hits + self.misses
    }

    /// Cache hit rate (0.0 to 1.0)
    #[must_use]
    pub fn hit_rate(&self) -> f64 {
        let total = self.total_requests();
        if total == 0 {
            0.0
        } else {
            self.hits as f64 / total as f64
        }
    }

    /// Cache utilization (0.0 to 1.0)
    #[must_use]
    pub fn utilization(&self) -> f64 {
        if self.capacity == 0 {
            0.0
        } else {
            self.size as f64 / self.capacity as f64
        }
    }
}

/// Thread-safe parser pool for reuse
///
/// Note: This is a simplified version that focuses on cache management.
/// For a full implementation, consider parser state management.
pub struct ParserPool {
    /// Parser cache size
    max_size: usize,
    /// Pool statistics
    stats: Arc<Mutex<PoolStats>>,
}

#[derive(Debug, Default)]
struct PoolStats {
    /// Total parsers created
    created: u64,
    /// Total parsers borrowed
    borrowed: u64,
    /// Total parsers returned
    returned: u64,
    /// Current pool size
    current_size: usize,
}

impl ParserPool {
    /// Create new parser pool
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::performance_optimizations::ParserPool;
    ///
    /// let pool = ParserPool::new(10);
    /// assert_eq!(pool.capacity(), 10);
    /// ```
    #[must_use]
    pub fn new(max_size: usize) -> Self {
        Self {
            stats: Arc::new(Mutex::new(PoolStats::default())),
            max_size,
        }
    }

    /// Create a new parser (simplified implementation)
    ///
    /// In a full implementation, this would manage a pool of reusable parsers
    pub fn create_parser<'a>(&self, input: &'a str) -> crate::frontend::Parser<'a> {
        let mut stats = self.stats.lock().expect("Lock poisoned");
        stats.created += 1;
        stats.borrowed += 1;
        crate::frontend::Parser::new(input)
    }

    /// Get pool capacity
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.max_size
    }

    /// Get current pool size (simplified implementation)
    #[must_use]
    pub fn size(&self) -> usize {
        let stats = self.stats.lock().expect("Lock poisoned");
        stats.current_size
    }

    /// Get pool statistics
    #[must_use]
    pub fn stats(&self) -> PoolStatsSummary {
        let stats = self.stats.lock().expect("Lock poisoned");
        PoolStatsSummary {
            created: stats.created,
            borrowed: stats.borrowed,
            returned: stats.returned,
            current_size: stats.current_size,
        }
    }
}

/// Summary of pool statistics
#[derive(Debug, Clone)]
pub struct PoolStatsSummary {
    pub created: u64,
    pub borrowed: u64,
    pub returned: u64,
    pub current_size: usize,
}

/// Memory-efficient string interning
pub struct StringInterner {
    /// Interned strings
    strings: HashMap<String, usize>,
    /// String storage by ID
    storage: Vec<String>,
    /// Next available ID
    next_id: usize,
}

impl StringInterner {
    /// Create new string interner
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::performance_optimizations::StringInterner;
    ///
    /// let mut interner = StringInterner::new();
    /// let id1 = interner.intern("hello");
    /// let id2 = interner.intern("hello");
    /// assert_eq!(id1, id2); // Same string gets same ID
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            strings: HashMap::new(),
            storage: Vec::new(),
            next_id: 0,
        }
    }

    /// Intern a string and return its ID
    pub fn intern(&mut self, s: &str) -> usize {
        if let Some(&id) = self.strings.get(s) {
            id
        } else {
            let id = self.next_id;
            self.strings.insert(s.to_string(), id);
            self.storage.push(s.to_string());
            self.next_id += 1;
            id
        }
    }

    /// Get string by ID
    #[must_use]
    pub fn get(&self, id: usize) -> Option<&str> {
        self.storage.get(id).map(String::as_str)
    }

    /// Get number of interned strings
    #[must_use]
    pub fn len(&self) -> usize {
        self.storage.len()
    }

    /// Check if interner is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.storage.is_empty()
    }

    /// Clear all interned strings
    pub fn clear(&mut self) {
        self.strings.clear();
        self.storage.clear();
        self.next_id = 0;
    }
}

impl Default for StringInterner {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_compilation_cache_basic() {
        let mut cache = CompilationCache::new(2);

        // Test insertion and retrieval
        cache.insert(
            "test1".to_string(),
            "output1".to_string(),
            Duration::from_millis(100),
            512,
        );
        assert_eq!(cache.get("test1"), Some("output1".to_string()));
        assert_eq!(cache.len(), 1);

        // Test miss
        assert_eq!(cache.get("missing"), None);
    }

    #[test]
    fn test_compilation_cache_lru_eviction() {
        let mut cache = CompilationCache::new(2);

        // Fill cache
        cache.insert(
            "a".to_string(),
            "output_a".to_string(),
            Duration::from_millis(100),
            256,
        );
        cache.insert(
            "b".to_string(),
            "output_b".to_string(),
            Duration::from_millis(100),
            256,
        );
        assert_eq!(cache.len(), 2);

        // Access 'a' to make it more recently used
        cache.get("a");

        // Insert 'c' should evict 'b' (least recently used)
        cache.insert(
            "c".to_string(),
            "output_c".to_string(),
            Duration::from_millis(100),
            256,
        );
        assert_eq!(cache.len(), 2);
        assert!(cache.get("a").is_some());
        assert!(cache.get("c").is_some());
        assert!(cache.get("b").is_none());
    }

    #[test]
    fn test_cache_stats() {
        let mut cache = CompilationCache::new(100);

        // Add some data
        cache.insert(
            "test".to_string(),
            "output".to_string(),
            Duration::from_millis(100),
            512,
        );

        // Generate some hits and misses
        cache.get("test");
        cache.get("missing");

        let stats = cache.stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.total_requests(), 2);
        assert_eq!(stats.hit_rate(), 0.5);
    }

    #[test]
    fn test_string_interner() {
        let mut interner = StringInterner::new();

        // Test basic interning
        let id1 = interner.intern("hello");
        let id2 = interner.intern("world");
        let id3 = interner.intern("hello"); // Same string

        assert_ne!(id1, id2);
        assert_eq!(id1, id3); // Same string gets same ID

        // Test retrieval
        assert_eq!(interner.get(id1), Some("hello"));
        assert_eq!(interner.get(id2), Some("world"));
        assert_eq!(interner.len(), 2); // Only 2 unique strings
    }

    #[test]
    fn test_parser_pool_basic() {
        let pool = ParserPool::new(5);

        // Create parser
        let _parser1 = pool.create_parser("42");

        // Pool should work
        assert_eq!(pool.capacity(), 5);

        // Should be able to create another
        let _parser2 = pool.create_parser("true");

        let stats = pool.stats();
        assert_eq!(stats.created, 2);
        assert_eq!(stats.borrowed, 2);
    }

    #[test]
    fn test_cache_memory_usage() {
        let mut cache = CompilationCache::new(10);

        cache.insert(
            "small".to_string(),
            "x".to_string(),
            Duration::from_millis(50),
            100,
        );
        cache.insert(
            "large".to_string(),
            "y".repeat(1000),
            Duration::from_millis(200),
            2000,
        );

        let total_memory = cache.memory_usage();
        assert_eq!(total_memory, 2100); // 100 + 2000
    }

    #[test]
    fn test_cache_clear() {
        let mut cache = CompilationCache::new(10);
        cache.insert(
            "test".to_string(),
            "output".to_string(),
            Duration::from_millis(100),
            512,
        );
        assert_eq!(cache.len(), 1);

        cache.clear();
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
    }

    #[test]
    fn test_cache_stats_hit_rate_empty() {
        let stats = CacheStats {
            hits: 0,
            misses: 0,
            evictions: 0,
            size: 0,
            capacity: 100,
        };
        assert_eq!(stats.hit_rate(), 0.0);
    }

    #[test]
    fn test_cache_stats_utilization_empty() {
        let stats = CacheStats {
            hits: 0,
            misses: 0,
            evictions: 0,
            size: 0,
            capacity: 100,
        };
        assert_eq!(stats.utilization(), 0.0);
    }

    #[test]
    fn test_cache_stats_utilization_zero_capacity() {
        let stats = CacheStats {
            hits: 0,
            misses: 0,
            evictions: 0,
            size: 0,
            capacity: 0,
        };
        assert_eq!(stats.utilization(), 0.0);
    }

    #[test]
    fn test_cache_stats_utilization_half() {
        let stats = CacheStats {
            hits: 5,
            misses: 3,
            evictions: 1,
            size: 50,
            capacity: 100,
        };
        assert_eq!(stats.utilization(), 0.5);
    }

    #[test]
    fn test_cache_is_empty() {
        let cache = CompilationCache::new(10);
        assert!(cache.is_empty());
    }

    #[test]
    fn test_cache_capacity() {
        let cache = CompilationCache::new(42);
        assert_eq!(cache.capacity(), 42);
    }

    #[test]
    fn test_string_interner_default() {
        let interner = StringInterner::default();
        assert!(interner.is_empty());
        assert_eq!(interner.len(), 0);
    }

    #[test]
    fn test_string_interner_is_empty() {
        let mut interner = StringInterner::new();
        assert!(interner.is_empty());
        interner.intern("test");
        assert!(!interner.is_empty());
    }

    #[test]
    fn test_string_interner_clear() {
        let mut interner = StringInterner::new();
        interner.intern("hello");
        interner.intern("world");
        assert_eq!(interner.len(), 2);

        interner.clear();
        assert!(interner.is_empty());
        assert_eq!(interner.len(), 0);
    }

    #[test]
    fn test_string_interner_get_invalid() {
        let interner = StringInterner::new();
        assert!(interner.get(999).is_none());
    }

    #[test]
    fn test_cache_stats_debug() {
        let stats = CacheStats {
            hits: 10,
            misses: 5,
            evictions: 2,
            size: 8,
            capacity: 20,
        };
        let debug_str = format!("{:?}", stats);
        assert!(debug_str.contains("CacheStats"));
        assert!(debug_str.contains("10")); // hits
    }

    #[test]
    fn test_cache_stats_clone() {
        let stats = CacheStats {
            hits: 10,
            misses: 5,
            evictions: 2,
            size: 8,
            capacity: 20,
        };
        let cloned = stats.clone();
        assert_eq!(stats.hits, cloned.hits);
        assert_eq!(stats.misses, cloned.misses);
    }

    #[test]
    fn test_pool_stats_summary_debug() {
        let summary = PoolStatsSummary {
            created: 5,
            borrowed: 4,
            returned: 3,
            current_size: 2,
        };
        let debug_str = format!("{:?}", summary);
        assert!(debug_str.contains("PoolStatsSummary"));
    }

    #[test]
    fn test_pool_stats_summary_clone() {
        let summary = PoolStatsSummary {
            created: 5,
            borrowed: 4,
            returned: 3,
            current_size: 2,
        };
        let cloned = summary.clone();
        assert_eq!(summary.created, cloned.created);
    }

    #[test]
    fn test_parser_pool_size() {
        let pool = ParserPool::new(10);
        assert_eq!(pool.size(), 0);
    }

    #[test]
    fn test_cache_stats_total_requests() {
        let stats = CacheStats {
            hits: 7,
            misses: 3,
            evictions: 0,
            size: 10,
            capacity: 100,
        };
        assert_eq!(stats.total_requests(), 10);
    }

    #[test]
    fn test_cache_eviction_counter() {
        let mut cache = CompilationCache::new(1);
        cache.insert(
            "a".to_string(),
            "1".to_string(),
            Duration::from_millis(10),
            100,
        );
        cache.insert(
            "b".to_string(),
            "2".to_string(),
            Duration::from_millis(10),
            100,
        );

        let stats = cache.stats();
        assert_eq!(stats.evictions, 1);
    }

    #[test]
    fn test_string_interner_multiple_same() {
        let mut interner = StringInterner::new();
        let id1 = interner.intern("foo");
        let id2 = interner.intern("foo");
        let id3 = interner.intern("foo");
        assert_eq!(id1, id2);
        assert_eq!(id2, id3);
        assert_eq!(interner.len(), 1);
    }
}