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
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
//! Unified quality scoring system for Ruchy code (RUCHY-0810)
//! Incremental scoring architecture (RUCHY-0813)
use crate::frontend::ast::ExprKind;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
/// Analysis depth for quality scoring
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum AnalysisDepth {
    /// <100ms - AST metrics only
    Shallow,
    /// <1s - AST + type checking + basic flow
    Standard,
    /// <30s - Full property/mutation testing
    Deep,
}
/// Unified quality score with components
#[derive(Debug, Clone)]
pub struct QualityScore {
    pub value: f64, // 0.0-1.0 normalized score
    pub components: ScoreComponents,
    pub grade: Grade,        // Human-readable grade
    pub confidence: f64,     // Confidence in score accuracy
    pub cache_hit_rate: f64, // Percentage from cached analysis
}
/// Individual score components
#[derive(Debug, Clone)]
pub struct ScoreComponents {
    pub correctness: f64,     // 35% - Semantic correctness
    pub performance: f64,     // 25% - Runtime efficiency
    pub maintainability: f64, // 20% - Change resilience
    pub safety: f64,          // 15% - Memory/type safety
    pub idiomaticity: f64,    // 5%  - Language conventions
}
/// Human-readable grade boundaries
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Grade {
    APlus,  // [0.97, 1.00] - Ship to production
    A,      // [0.93, 0.97) - Ship with confidence
    AMinus, // [0.90, 0.93) - Ship with review
    BPlus,  // [0.87, 0.90) - Acceptable
    B,      // [0.83, 0.87) - Needs work
    BMinus, // [0.80, 0.83) - Minimum viable
    CPlus,  // [0.77, 0.80) - Technical debt
    C,      // [0.73, 0.77) - Refactor advised
    CMinus, // [0.70, 0.73) - Refactor required
    D,      // [0.60, 0.70) - Major issues
    F,      // [0.00, 0.60) - Fundamental problems
}
impl Grade {
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::scoring::Grade;
    ///
    /// let mut instance = Grade::new();
    /// let result = instance.from_score();
    /// // Verify behavior
    /// ```
    pub fn from_score(value: f64) -> Self {
        match value {
            v if v >= 0.97 => Grade::APlus,
            v if v >= 0.93 => Grade::A,
            v if v >= 0.90 => Grade::AMinus,
            v if v >= 0.87 => Grade::BPlus,
            v if v >= 0.83 => Grade::B,
            v if v >= 0.80 => Grade::BMinus,
            v if v >= 0.77 => Grade::CPlus,
            v if v >= 0.73 => Grade::C,
            v if v >= 0.70 => Grade::CMinus,
            v if v >= 0.60 => Grade::D,
            _ => Grade::F,
        }
    }

    /// Extract method: Convert grade to numeric rank for ordering - complexity: 6
    /// Reduces complexity of cmp function from 25 to 2
    pub fn to_rank(&self) -> u8 {
        use Grade::{AMinus, APlus, BMinus, BPlus, CMinus, CPlus, A, B, C, D, F};
        match self {
            F => 0,
            D => 1,
            CMinus => 2,
            C => 3,
            CPlus => 4,
            BMinus => 5,
            B => 6,
            BPlus => 7,
            AMinus => 8,
            A => 9,
            APlus => 10,
        }
    }
}
impl std::fmt::Display for Grade {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Grade::APlus => write!(f, "A+"),
            Grade::A => write!(f, "A"),
            Grade::AMinus => write!(f, "A-"),
            Grade::BPlus => write!(f, "B+"),
            Grade::B => write!(f, "B"),
            Grade::BMinus => write!(f, "B-"),
            Grade::CPlus => write!(f, "C+"),
            Grade::C => write!(f, "C"),
            Grade::CMinus => write!(f, "C-"),
            Grade::D => write!(f, "D"),
            Grade::F => write!(f, "F"),
        }
    }
}
/// Configuration for score weights
#[derive(Debug, Clone)]
pub struct ScoreConfig {
    pub correctness_weight: f64,
    pub performance_weight: f64,
    pub maintainability_weight: f64,
    pub safety_weight: f64,
    pub idiomaticity_weight: f64,
}
impl Default for ScoreConfig {
    fn default() -> Self {
        Self {
            correctness_weight: 0.35,
            performance_weight: 0.25,
            maintainability_weight: 0.20,
            safety_weight: 0.15,
            idiomaticity_weight: 0.05,
        }
    }
}
/// Cache key for scoring results
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct CacheKey {
    pub file_path: PathBuf,
    pub content_hash: u64,
    pub depth: AnalysisDepth,
}
/// Cached scoring result with metadata
#[derive(Debug, Clone)]
pub struct CacheEntry {
    pub score: QualityScore,
    pub timestamp: SystemTime,
    pub dependencies: Vec<PathBuf>,
}
/// File dependency tracker
#[derive(Debug)]
pub struct DependencyTracker {
    /// Map of file -> files it depends on
    dependencies: HashMap<PathBuf, Vec<PathBuf>>,
    /// Map of file -> last modified time
    file_times: HashMap<PathBuf, SystemTime>,
}
impl Default for DependencyTracker {
    fn default() -> Self {
        Self::new()
    }
}
impl DependencyTracker {
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::scoring::DependencyTracker;
    ///
    /// let instance = DependencyTracker::new();
    /// // Verify behavior
    /// ```
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::scoring::DependencyTracker;
    ///
    /// let instance = DependencyTracker::new();
    /// // Verify behavior
    /// ```
    pub fn new() -> Self {
        Self {
            dependencies: HashMap::new(),
            file_times: HashMap::new(),
        }
    }
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::track_dependency;
    ///
    /// let result = track_dependency(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn track_dependency(&mut self, file: PathBuf, dependency: PathBuf) {
        self.dependencies.entry(file).or_default().push(dependency);
    }
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::scoring::DependencyTracker;
    ///
    /// let mut instance = DependencyTracker::new();
    /// let result = instance.is_stale();
    /// // Verify behavior
    /// ```
    pub fn is_stale(&self, file: &PathBuf) -> bool {
        if let Some(dependencies) = self.dependencies.get(file) {
            for dep in dependencies {
                if self.is_file_modified(dep) {
                    return true;
                }
            }
        }
        false
    }
    fn is_file_modified(&self, file: &PathBuf) -> bool {
        let Ok(metadata) = fs::metadata(file) else {
            return true;
        };
        let Ok(modified) = metadata.modified() else {
            return true;
        };
        if let Some(&cached_time) = self.file_times.get(file) {
            modified > cached_time
        } else {
            true
        }
    }
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::update_file_time;
    ///
    /// let result = update_file_time(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn update_file_time(&mut self, file: PathBuf) {
        if let Ok(metadata) = fs::metadata(&file) {
            if let Ok(modified) = metadata.modified() {
                self.file_times.insert(file, modified);
            }
        }
    }
}
/// Incremental scoring engine with caching
pub struct ScoreEngine {
    config: ScoreConfig,
    cache: HashMap<CacheKey, CacheEntry>,
    dependency_tracker: DependencyTracker,
}
impl ScoreEngine {
    pub fn new(config: ScoreConfig) -> Self {
        Self {
            config,
            cache: HashMap::new(),
            dependency_tracker: DependencyTracker::new(),
        }
    }
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::score;
    ///
    /// let result = score(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn score(&self, ast: &crate::frontend::ast::Expr, depth: AnalysisDepth) -> QualityScore {
        let components = match depth {
            AnalysisDepth::Shallow => Self::score_shallow(ast),
            AnalysisDepth::Standard => Self::score_standard(ast),
            AnalysisDepth::Deep => Self::score_deep(ast),
        };
        let value = self.calculate_weighted_score(&components);
        let grade = Grade::from_score(value);
        let confidence = Self::calculate_confidence(depth);
        QualityScore {
            value,
            components,
            grade,
            confidence,
            cache_hit_rate: 0.0, // No file path in legacy API
        }
    }
    /// Incremental scoring with file-based caching (RUCHY-0813)
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::score_incremental;
    ///
    /// let result = score_incremental("example");
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn score_incremental(
        &mut self,
        ast: &crate::frontend::ast::Expr,
        file_path: PathBuf,
        content: &str,
        depth: AnalysisDepth,
    ) -> QualityScore {
        let content_hash = Self::hash_content(content);
        let cache_key = CacheKey {
            file_path: file_path.clone(),
            content_hash,
            depth,
        };
        // Check cache first
        if let Some(entry) = self.cache.get(&cache_key) {
            if !self.dependency_tracker.is_stale(&file_path) {
                let mut score = entry.score.clone();
                score.cache_hit_rate = 1.0;
                return score;
            }
        }
        // Fast path for small files - skip complex analysis
        let start = std::time::Instant::now();
        let is_small_file = content.len() < 1024;
        let effective_depth = if is_small_file && depth != AnalysisDepth::Deep {
            AnalysisDepth::Shallow
        } else {
            depth
        };
        let components = match effective_depth {
            AnalysisDepth::Shallow => Self::score_shallow(ast),
            AnalysisDepth::Standard => Self::score_standard(ast),
            AnalysisDepth::Deep => Self::score_deep(ast),
        };
        let value = self.calculate_weighted_score(&components);
        let grade = Grade::from_score(value);
        let confidence = if is_small_file && depth != effective_depth {
            Self::calculate_confidence(effective_depth) * 0.9 // Slightly reduced confidence for fast path
        } else {
            Self::calculate_confidence(depth)
        };
        let elapsed = start.elapsed();
        let score = QualityScore {
            value,
            components,
            grade,
            confidence,
            cache_hit_rate: 0.0,
        };
        // Cache the result only if worth caching
        let is_worth_caching = elapsed > Duration::from_millis(10) || !is_small_file;
        if is_worth_caching {
            let entry = CacheEntry {
                score: score.clone(),
                timestamp: SystemTime::now(),
                dependencies: Self::extract_dependencies(ast),
            };
            self.cache.insert(cache_key, entry);
        }
        self.dependency_tracker.update_file_time(file_path);
        // Maintain cache if scoring took too long or cache is getting large
        if elapsed > Duration::from_millis(100) || self.cache.len() > 1000 {
            self.optimize_cache();
        }
        score
    }
    /// Progressive scoring that refines analysis depth based on time budget
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::score_progressive;
    ///
    /// let result = score_progressive("example");
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn score_progressive(
        &mut self,
        ast: &crate::frontend::ast::Expr,
        file_path: PathBuf,
        content: &str,
        time_budget: Duration,
    ) -> QualityScore {
        let start = std::time::Instant::now();
        // Start with shallow analysis
        let mut score =
            self.score_incremental(ast, file_path.clone(), content, AnalysisDepth::Shallow);
        if start.elapsed() < time_budget / 3 {
            // Upgrade to standard analysis
            score =
                self.score_incremental(ast, file_path.clone(), content, AnalysisDepth::Standard);
            if start.elapsed() < time_budget * 2 / 3 {
                // Upgrade to deep analysis
                score = self.score_incremental(ast, file_path, content, AnalysisDepth::Deep);
            }
        }
        score
    }
    fn hash_content(content: &str) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        content.hash(&mut hasher);
        hasher.finish()
    }
    fn extract_dependencies(_ast: &crate::frontend::ast::Expr) -> Vec<PathBuf> {
        // Extract import/use dependencies from AST
        // Implementation in RUCHY-0814 with type checker integration
        Vec::new()
    }
    fn optimize_cache(&mut self) {
        // Remove old cache entries to maintain <100ms performance
        let now = SystemTime::now();
        let cutoff = Duration::from_secs(300); // 5 minutes
        let max_entries = 500; // Maximum cache entries for performance
                               // First pass: Remove old entries
        self.cache.retain(|_, entry| {
            if let Ok(age) = now.duration_since(entry.timestamp) {
                age < cutoff
            } else {
                false
            }
        });
        // Second pass: If still too many entries, remove least recently used
        if self.cache.len() > max_entries {
            let mut entries: Vec<_> = self
                .cache
                .iter()
                .map(|(k, v)| (k.clone(), v.timestamp))
                .collect();
            entries.sort_by_key(|(_, timestamp)| *timestamp);
            let to_remove = self.cache.len() - max_entries;
            let keys_to_remove: Vec<_> = entries
                .iter()
                .take(to_remove)
                .map(|(k, _)| k.clone())
                .collect();
            for key in keys_to_remove {
                self.cache.remove(&key);
            }
        }
    }
    /// Clear all caches - useful for memory management
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::clear_cache;
    ///
    /// let result = clear_cache(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn clear_cache(&mut self) {
        self.cache.clear();
        self.dependency_tracker = DependencyTracker::new();
    }
    /// Get cache statistics
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::cache_stats;
    ///
    /// let result = cache_stats(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn cache_stats(&self) -> CacheStats {
        CacheStats {
            entries: self.cache.len(),
            memory_usage_estimate: self.cache.len() * 1024, // Rough estimate
        }
    }
    fn score_shallow(ast: &crate::frontend::ast::Expr) -> ScoreComponents {
        // Fast AST-only analysis (<100ms)
        let metrics = analyze_ast_metrics(ast);
        let correctness = 1.0;
        let mut performance = 1.0;
        let mut maintainability = 1.0;
        let safety = 1.0;
        let idiomaticity = 1.0;
        // Penalize high complexity
        if metrics.max_depth > 10 {
            maintainability *= 0.9;
        }
        if metrics.function_count > 50 {
            maintainability *= 0.95;
        }
        // Penalize deep nesting
        if metrics.max_nesting > 5 {
            performance *= 0.9;
            maintainability *= 0.9;
        }
        // Penalize excessive lines
        if metrics.line_count > 1000 {
            maintainability *= 0.95;
        }
        ScoreComponents {
            correctness,
            performance,
            maintainability,
            safety,
            idiomaticity,
        }
    }
    fn score_standard(ast: &crate::frontend::ast::Expr) -> ScoreComponents {
        // Standard analysis with type checking (<1s)
        let mut components = Self::score_shallow(ast);
        // Additional type-based analysis
        // Type checker integration in RUCHY-0814
        components.correctness *= 0.95;
        components.safety *= 0.95;
        components
    }
    fn score_deep(ast: &crate::frontend::ast::Expr) -> ScoreComponents {
        // Deep analysis with property testing (<30s)
        let mut components = Self::score_standard(ast);
        // Additional deep analysis
        // Property testing and mutation testing in RUCHY-0816
        components.correctness *= 0.98;
        components
    }
    fn calculate_weighted_score(&self, components: &ScoreComponents) -> f64 {
        components.correctness * self.config.correctness_weight
            + components.performance * self.config.performance_weight
            + components.maintainability * self.config.maintainability_weight
            + components.safety * self.config.safety_weight
            + components.idiomaticity * self.config.idiomaticity_weight
    }
    fn calculate_confidence(depth: AnalysisDepth) -> f64 {
        match depth {
            AnalysisDepth::Shallow => 0.6,
            AnalysisDepth::Standard => 0.8,
            AnalysisDepth::Deep => 0.95,
        }
    }
}
/// AST metrics for analysis
#[derive(Debug)]
struct AstMetrics {
    function_count: usize,
    max_depth: usize,
    max_nesting: usize,
    line_count: usize,
    cyclomatic_complexity: usize,
}
fn analyze_ast_metrics(ast: &crate::frontend::ast::Expr) -> AstMetrics {
    let mut metrics = AstMetrics {
        function_count: 0,
        max_depth: 0,
        max_nesting: 0,
        line_count: 0,
        cyclomatic_complexity: 1, // Base complexity
    };
    analyze_expr(ast, &mut metrics, 0, 0);
    metrics
}
fn analyze_expr(
    expr: &crate::frontend::ast::Expr,
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    metrics.max_depth = metrics.max_depth.max(depth);
    metrics.max_nesting = metrics.max_nesting.max(nesting);
    match &expr.kind {
        ExprKind::Function { body, .. } => analyze_function(body, metrics, depth),
        ExprKind::Block(exprs) => analyze_block(exprs, metrics, depth, nesting),
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => analyze_if(
            condition,
            then_branch,
            else_branch.as_deref(),
            metrics,
            depth,
            nesting,
        ),
        ExprKind::While {
            condition, body, ..
        } => analyze_while(condition, body, metrics, depth, nesting),
        ExprKind::For { iter, body, .. } => analyze_for(iter, body, metrics, depth, nesting),
        ExprKind::Match {
            expr: match_expr,
            arms,
        } => analyze_match(match_expr, arms, metrics, depth, nesting),
        _ => {}
    }
}

fn analyze_function(body: &crate::frontend::ast::Expr, metrics: &mut AstMetrics, depth: usize) {
    metrics.function_count += 1;
    analyze_expr(body, metrics, depth + 1, 0);
}

fn analyze_block(
    exprs: &[crate::frontend::ast::Expr],
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    for e in exprs {
        analyze_expr(e, metrics, depth + 1, nesting);
    }
}

fn analyze_if(
    condition: &crate::frontend::ast::Expr,
    then_branch: &crate::frontend::ast::Expr,
    else_branch: Option<&crate::frontend::ast::Expr>,
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    metrics.cyclomatic_complexity += 1;
    analyze_expr(condition, metrics, depth + 1, nesting + 1);
    analyze_expr(then_branch, metrics, depth + 1, nesting + 1);
    if let Some(else_expr) = else_branch {
        analyze_expr(else_expr, metrics, depth + 1, nesting + 1);
    }
}

fn analyze_while(
    condition: &crate::frontend::ast::Expr,
    body: &crate::frontend::ast::Expr,
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    metrics.cyclomatic_complexity += 1;
    analyze_expr(condition, metrics, depth + 1, nesting + 1);
    analyze_expr(body, metrics, depth + 1, nesting + 1);
}

fn analyze_for(
    iter: &crate::frontend::ast::Expr,
    body: &crate::frontend::ast::Expr,
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    metrics.cyclomatic_complexity += 1;
    analyze_expr(iter, metrics, depth + 1, nesting + 1);
    analyze_expr(body, metrics, depth + 1, nesting + 1);
}

fn analyze_match(
    match_expr: &crate::frontend::ast::Expr,
    arms: &[crate::frontend::ast::MatchArm],
    metrics: &mut AstMetrics,
    depth: usize,
    nesting: usize,
) {
    analyze_expr(match_expr, metrics, depth + 1, nesting);
    for arm in arms {
        metrics.cyclomatic_complexity += 1;
        analyze_expr(&arm.body, metrics, depth + 1, nesting + 1);
    }
}
impl QualityScore {
    /// Explain changes from a baseline score
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::scoring::explain_delta;
    ///
    /// let result = explain_delta(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn explain_delta(&self, baseline: &QualityScore) -> ScoreExplanation {
        let delta = self.value - baseline.value;
        let mut changes = Vec::new();
        let mut tradeoffs = Vec::new();
        // Track component changes
        let components = [
            (
                "Correctness",
                self.components.correctness,
                baseline.components.correctness,
            ),
            (
                "Performance",
                self.components.performance,
                baseline.components.performance,
            ),
            (
                "Maintainability",
                self.components.maintainability,
                baseline.components.maintainability,
            ),
            ("Safety", self.components.safety, baseline.components.safety),
            (
                "Idiomaticity",
                self.components.idiomaticity,
                baseline.components.idiomaticity,
            ),
        ];
        for (name, current, baseline) in components {
            let diff = current - baseline;
            if diff.abs() > 0.01 {
                changes.push(format!(
                    "{}: {}{:.1}%",
                    name,
                    if diff > 0.0 { "+" } else { "" },
                    diff * 100.0
                ));
            }
        }
        // Detect tradeoffs
        if self.components.performance > baseline.components.performance
            && self.components.maintainability < baseline.components.maintainability
        {
            tradeoffs.push("Performance improved at the cost of maintainability".to_string());
        }
        if self.components.safety > baseline.components.safety
            && self.components.performance < baseline.components.performance
        {
            tradeoffs.push("Safety improved at the cost of performance".to_string());
        }
        ScoreExplanation {
            delta,
            changes,
            tradeoffs,
            grade_change: format!("{} → {}", baseline.grade, self.grade),
        }
    }
}
/// Explanation of score changes
pub struct ScoreExplanation {
    pub delta: f64,
    pub changes: Vec<String>,
    pub tradeoffs: Vec<String>,
    pub grade_change: String,
}
/// Cache performance statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    pub entries: usize,
    pub memory_usage_estimate: usize,
}
/// Score correctness component (35% weight)
/// # Examples
///
/// ```ignore
/// use ruchy::quality::scoring::score_correctness;
///
/// let result = score_correctness(());
/// assert_eq!(result, Ok(()));
/// ```
pub fn score_correctness(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut score = 1.0;
    // Pattern match exhaustiveness check
    let pattern_completeness = analyze_pattern_completeness(ast);
    score *= pattern_completeness;
    // Error handling coverage
    let error_handling_quality = analyze_error_handling(ast);
    score *= error_handling_quality;
    // Type consistency analysis
    let type_consistency = analyze_type_consistency(ast);
    score *= type_consistency;
    // Logical soundness (basic checks)
    let logical_soundness = analyze_logical_soundness(ast);
    score *= logical_soundness;
    score.clamp(0.0, 1.0)
}
/// Analyze pattern match completeness
fn analyze_pattern_completeness(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut total_matches = 0;
    let mut complete_matches = 0;
    analyze_pattern_completeness_recursive(ast, &mut total_matches, &mut complete_matches);
    if total_matches == 0 {
        1.0 // No matches, assume complete
    } else {
        #[allow(clippy::cast_precision_loss)]
        let score = (complete_matches as f64) / (total_matches as f64);
        score
    }
}
fn check_match_completeness(
    arms: &[crate::frontend::ast::MatchArm],
    complete_matches: &mut usize,
) {
    let has_wildcard = arms
        .iter()
        .any(|arm| matches!(arm.pattern, crate::frontend::ast::Pattern::Wildcard));
    if has_wildcard || arms.len() >= 2 {
        *complete_matches += 1;
    }
}

fn analyze_pattern_completeness_recursive(
    expr: &crate::frontend::ast::Expr,
    total_matches: &mut usize,
    complete_matches: &mut usize,
) {
    let recurse =
        |e: &crate::frontend::ast::Expr, tm: &mut usize, cm: &mut usize| {
            analyze_pattern_completeness_recursive(e, tm, cm);
        };

    match &expr.kind {
        ExprKind::Match {
            expr: match_expr,
            arms,
        } => {
            *total_matches += 1;
            check_match_completeness(arms, complete_matches);
            recurse(match_expr, total_matches, complete_matches);
            for arm in arms {
                recurse(&arm.body, total_matches, complete_matches);
            }
        }
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => {
            recurse(condition, total_matches, complete_matches);
            recurse(then_branch, total_matches, complete_matches);
            if let Some(else_expr) = else_branch {
                recurse(else_expr, total_matches, complete_matches);
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                recurse(e, total_matches, complete_matches);
            }
        }
        ExprKind::Function { body, .. } => {
            recurse(body, total_matches, complete_matches);
        }
        _ => {}
    }
}
/// Analyze error handling quality
fn analyze_error_handling(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut total_fallible_ops = 0;
    let mut handled_ops = 0;
    analyze_error_handling_recursive(ast, &mut total_fallible_ops, &mut handled_ops);
    if total_fallible_ops == 0 {
        1.0 // No fallible operations
    } else {
        #[allow(clippy::cast_precision_loss)]
        let base_score = (handled_ops as f64) / (total_fallible_ops as f64);
        // Boost score if some error handling is present
        if handled_ops > 0 {
            (base_score + 0.3).min(1.0)
        } else {
            0.7 // Penalty for no error handling
        }
    }
}
fn analyze_error_handling_recursive(
    expr: &crate::frontend::ast::Expr,
    total_fallible_ops: &mut usize,
    handled_ops: &mut usize,
) {
    match &expr.kind {
        ExprKind::Match {
            expr: match_expr,
            arms,
        } => {
            // Check if matching on Result type (heuristic)
            if arms.len() >= 2 {
                *total_fallible_ops += 1;
                *handled_ops += 1;
            }
            analyze_error_handling_recursive(match_expr, total_fallible_ops, handled_ops);
            for arm in arms {
                analyze_error_handling_recursive(&arm.body, total_fallible_ops, handled_ops);
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                analyze_error_handling_recursive(e, total_fallible_ops, handled_ops);
            }
        }
        ExprKind::Function { body, .. } => {
            analyze_error_handling_recursive(body, total_fallible_ops, handled_ops);
        }
        _ => {}
    }
}
/// Analyze type consistency
fn analyze_type_consistency(_ast: &crate::frontend::ast::Expr) -> f64 {
    // For now, assume good consistency since we have type checking
    // Future: integrate with type checker for real analysis
    0.95
}
/// Analyze logical soundness
fn analyze_logical_soundness(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut score = 1.0;
    // Check for obvious logical issues
    let has_unreachable = has_unreachable_code(ast);
    if has_unreachable {
        score *= 0.8; // Penalty for unreachable code
    }
    let has_infinite_loops = has_potential_infinite_loops(ast);
    if has_infinite_loops {
        score *= 0.9; // Penalty for potential infinite loops
    }
    score
}
fn has_unreachable_code(ast: &crate::frontend::ast::Expr) -> bool {
    match &ast.kind {
        ExprKind::Block(exprs) => check_block_unreachable(exprs),
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => check_if_unreachable(condition, then_branch, else_branch.as_deref()),
        _ => false,
    }
}

fn check_block_unreachable(exprs: &[crate::frontend::ast::Expr]) -> bool {
    for (i, expr) in exprs.iter().enumerate() {
        if i < exprs.len() - 1 && is_diverging_expr(expr) {
            return true; // Code after diverging expression
        }
        if has_unreachable_code(expr) {
            return true;
        }
    }
    false
}

fn check_if_unreachable(
    condition: &crate::frontend::ast::Expr,
    then_branch: &crate::frontend::ast::Expr,
    else_branch: Option<&crate::frontend::ast::Expr>,
) -> bool {
    has_unreachable_code(condition)
        || has_unreachable_code(then_branch)
        || else_branch
            .as_ref()
            .is_some_and(|e| has_unreachable_code(e))
}
fn is_diverging_expr(expr: &crate::frontend::ast::Expr) -> bool {
    match &expr.kind {
        ExprKind::Call { func, .. } => {
            // Check for known diverging functions (heuristic)
            if let ExprKind::Identifier(name) = &func.kind {
                matches!(name.as_str(), "panic" | "unreachable" | "exit")
            } else {
                false
            }
        }
        _ => false,
    }
}
fn has_potential_infinite_loops(ast: &crate::frontend::ast::Expr) -> bool {
    match &ast.kind {
        ExprKind::While {
            condition, body, ..
        } => {
            // Check for trivial infinite loops: while true { ... }
            if let ExprKind::Literal(crate::frontend::ast::Literal::Bool(true)) = &condition.kind {
                // Check if body has break statement
                !has_break_statement(body)
            } else {
                has_potential_infinite_loops(condition) || has_potential_infinite_loops(body)
            }
        }
        ExprKind::Block(exprs) => exprs.iter().any(has_potential_infinite_loops),
        ExprKind::Function { body, .. } => has_potential_infinite_loops(body),
        _ => false,
    }
}
fn has_break_statement(ast: &crate::frontend::ast::Expr) -> bool {
    match &ast.kind {
        ExprKind::Break { .. } => true,
        ExprKind::Block(exprs) => exprs.iter().any(has_break_statement),
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => {
            has_break_statement(condition)
                || has_break_statement(then_branch)
                || else_branch.as_ref().is_some_and(|e| has_break_statement(e))
        }
        _ => false,
    }
}
/// Score performance component (25% weight)
/// # Examples
///
/// ```ignore
/// use ruchy::quality::scoring::score_performance;
///
/// let result = score_performance(());
/// assert_eq!(result, Ok(()));
/// ```
pub fn score_performance(ast: &crate::frontend::ast::Expr) -> f64 {
    let metrics = analyze_ast_metrics(ast);
    let mut score = 1.0;
    // Complexity analysis (BigO implications)
    let complexity_score = analyze_algorithmic_complexity(ast);
    score *= complexity_score;
    // Penalize high cyclomatic complexity (affects branch prediction)
    if metrics.cyclomatic_complexity > 10 {
        #[allow(clippy::cast_precision_loss)]
        let penalty = ((metrics.cyclomatic_complexity - 10) as f64 * 0.02).min(0.3);
        score *= 1.0 - penalty;
    }
    // Penalize deep nesting (affects cache performance)
    if metrics.max_nesting > 3 {
        #[allow(clippy::cast_precision_loss)]
        let penalty = ((metrics.max_nesting - 3) as f64 * 0.05).min(0.2);
        score *= 1.0 - penalty;
    }
    // Allocation analysis
    let allocation_score = analyze_allocation_patterns(ast);
    score *= allocation_score;
    // Memory access patterns (simplified for current AST)
    // Future enhancement when Index/Dict variants are added
    score.clamp(0.0, 1.0)
}
/// Analyze algorithmic complexity patterns
fn analyze_algorithmic_complexity(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut nested_loops = 0;
    let mut recursive_calls = 0;
    analyze_complexity_recursive(ast, &mut nested_loops, &mut recursive_calls, 0);
    let mut score = 1.0;
    // Penalize nested loops (O(n^k) complexity)
    if nested_loops > 0 {
        #[allow(clippy::cast_precision_loss)]
        let penalty = (f64::from(nested_loops) * 0.15).min(0.5);
        score *= 1.0 - penalty;
    }
    // Penalize recursive calls without obvious base case
    if recursive_calls > 2 {
        score *= 0.8; // May indicate exponential complexity
    }
    score
}
fn analyze_complexity_recursive(
    expr: &crate::frontend::ast::Expr,
    nested_loops: &mut i32,
    recursive_calls: &mut i32,
    current_nesting: i32,
) {
    match &expr.kind {
        ExprKind::For { iter, body, .. }
        | ExprKind::While {
            condition: iter,
            body,
            ..
        } => analyze_loop_complexity(iter, body, nested_loops, recursive_calls, current_nesting),
        ExprKind::Call { func, args } => {
            analyze_call_complexity(func, args, nested_loops, recursive_calls, current_nesting);
        }
        ExprKind::Block(exprs) => {
            analyze_block_complexity(exprs, nested_loops, recursive_calls, current_nesting);
        }
        ExprKind::Function { body, .. } => {
            analyze_complexity_recursive(body, nested_loops, recursive_calls, 0);
        }
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => analyze_if_complexity(
            condition,
            then_branch,
            else_branch.as_deref(),
            nested_loops,
            recursive_calls,
            current_nesting,
        ),
        _ => {}
    }
}

fn analyze_loop_complexity(
    iter: &crate::frontend::ast::Expr,
    body: &crate::frontend::ast::Expr,
    nested_loops: &mut i32,
    recursive_calls: &mut i32,
    current_nesting: i32,
) {
    if current_nesting > 0 {
        *nested_loops += 1;
    }
    analyze_complexity_recursive(iter, nested_loops, recursive_calls, current_nesting);
    analyze_complexity_recursive(body, nested_loops, recursive_calls, current_nesting + 1);
}

fn analyze_call_complexity(
    func: &crate::frontend::ast::Expr,
    args: &[crate::frontend::ast::Expr],
    nested_loops: &mut i32,
    recursive_calls: &mut i32,
    current_nesting: i32,
) {
    if let ExprKind::Identifier(_) = &func.kind {
        *recursive_calls += 1;
    }
    analyze_complexity_recursive(func, nested_loops, recursive_calls, current_nesting);
    for arg in args {
        analyze_complexity_recursive(arg, nested_loops, recursive_calls, current_nesting);
    }
}

fn analyze_block_complexity(
    exprs: &[crate::frontend::ast::Expr],
    nested_loops: &mut i32,
    recursive_calls: &mut i32,
    current_nesting: i32,
) {
    for e in exprs {
        analyze_complexity_recursive(e, nested_loops, recursive_calls, current_nesting);
    }
}

fn analyze_if_complexity(
    condition: &crate::frontend::ast::Expr,
    then_branch: &crate::frontend::ast::Expr,
    else_branch: Option<&crate::frontend::ast::Expr>,
    nested_loops: &mut i32,
    recursive_calls: &mut i32,
    current_nesting: i32,
) {
    analyze_complexity_recursive(condition, nested_loops, recursive_calls, current_nesting);
    analyze_complexity_recursive(then_branch, nested_loops, recursive_calls, current_nesting);
    if let Some(else_expr) = else_branch {
        analyze_complexity_recursive(else_expr, nested_loops, recursive_calls, current_nesting);
    }
}
/// Analyze allocation patterns (GC pressure)
fn analyze_allocation_patterns(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut allocations = 0;
    let mut large_allocations = 0;
    count_allocations_recursive(ast, &mut allocations, &mut large_allocations);
    let mut score = 1.0;
    // Penalize excessive allocations
    if allocations > 10 {
        #[allow(clippy::cast_precision_loss)]
        let penalty = (f64::from(allocations - 10) * 0.01).min(0.3);
        score *= 1.0 - penalty;
    }
    // Penalize large allocations in loops
    if large_allocations > 0 {
        #[allow(clippy::cast_precision_loss)]
        let penalty = (f64::from(large_allocations) * 0.1).min(0.4);
        score *= 1.0 - penalty;
    }
    score
}
fn count_allocations_recursive(
    expr: &crate::frontend::ast::Expr,
    allocations: &mut i32,
    large_allocations: &mut i32,
) {
    match &expr.kind {
        ExprKind::List(items) => {
            *allocations += 1;
            if items.len() > 100 {
                *large_allocations += 1;
            }
            for item in items {
                count_allocations_recursive(item, allocations, large_allocations);
            }
        }
        // Dictionary literals not yet implemented in AST
        // ExprKind::Dict { pairs } => { ... }
        ExprKind::StringInterpolation { parts } => {
            *allocations += 1; // String concatenation
            for part in parts {
                if let crate::frontend::ast::StringPart::Expr(e) = part {
                    count_allocations_recursive(e, allocations, large_allocations);
                }
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                count_allocations_recursive(e, allocations, large_allocations);
            }
        }
        ExprKind::Function { body, .. } => {
            count_allocations_recursive(body, allocations, large_allocations);
        }
        _ => {}
    }
}
// Memory access pattern analysis will be added when
// AST supports indexing and dictionary operations
/// Score maintainability component (20% weight)
/// # Examples
///
/// ```ignore
/// use ruchy::quality::scoring::score_maintainability;
///
/// let result = score_maintainability(());
/// assert_eq!(result, Ok(()));
/// ```
pub fn score_maintainability(ast: &crate::frontend::ast::Expr) -> f64 {
    let metrics = analyze_ast_metrics(ast);
    let mut score = 1.0;
    // Coupling analysis
    let coupling_score = analyze_coupling(ast);
    score *= coupling_score;
    // Cohesion analysis
    let cohesion_score = analyze_cohesion(ast, &metrics);
    score *= cohesion_score;
    // Code duplication detection (simplified)
    let duplication_score = analyze_duplication(ast);
    score *= duplication_score;
    // Naming quality (basic heuristics)
    let naming_score = analyze_naming_quality(ast);
    score *= naming_score;
    score.clamp(0.0, 1.0)
}
/// Analyze coupling between functions/modules
fn analyze_coupling(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut external_calls = 0;
    let mut total_functions = 0;
    count_coupling_metrics(ast, &mut external_calls, &mut total_functions);
    if total_functions == 0 {
        return 1.0;
    }
    #[allow(clippy::cast_precision_loss)]
    let coupling_ratio = f64::from(external_calls) / f64::from(total_functions);
    // Lower coupling is better
    if coupling_ratio > 5.0 {
        0.7 // High coupling penalty
    } else if coupling_ratio > 2.0 {
        0.85
    } else {
        1.0 // Good coupling
    }
}
fn count_coupling_metrics(
    expr: &crate::frontend::ast::Expr,
    external_calls: &mut i32,
    total_functions: &mut i32,
) {
    match &expr.kind {
        ExprKind::Function { body, .. } => {
            *total_functions += 1;
            count_coupling_metrics(body, external_calls, total_functions);
        }
        ExprKind::Call { func, args } => {
            *external_calls += 1;
            count_coupling_metrics(func, external_calls, total_functions);
            for arg in args {
                count_coupling_metrics(arg, external_calls, total_functions);
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                count_coupling_metrics(e, external_calls, total_functions);
            }
        }
        _ => {}
    }
}
/// Analyze cohesion within functions
fn analyze_cohesion(_ast: &crate::frontend::ast::Expr, metrics: &AstMetrics) -> f64 {
    let mut score = 1.0;
    // Penalize functions that are too large (low cohesion indicator)
    if metrics.line_count > 100 {
        score *= 0.8;
    }
    // Penalize excessive depth (indicates mixed concerns)
    if metrics.max_depth > 15 {
        score *= 0.85;
    }
    // Penalize too many functions (possible low cohesion)
    if metrics.function_count > 30 {
        score *= 0.9;
    }
    score
}
/// Analyze code duplication (simplified heuristic)
fn analyze_duplication(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut expression_patterns = std::collections::HashMap::new();
    collect_expression_patterns(ast, &mut expression_patterns);
    let duplicated_patterns = expression_patterns
        .values()
        .filter(|&&count| count > 1)
        .count();
    if duplicated_patterns > 5 {
        0.8 // Significant duplication penalty
    } else if duplicated_patterns > 2 {
        0.9 // Some duplication
    } else {
        1.0 // Little to no duplication
    }
}
fn collect_expression_patterns(
    expr: &crate::frontend::ast::Expr,
    patterns: &mut std::collections::HashMap<String, i32>,
) {
    // Simplified pattern matching - use expression kind as pattern
    let pattern = format!("{:?}", std::mem::discriminant(&expr.kind));
    *patterns.entry(pattern).or_insert(0) += 1;
    match &expr.kind {
        ExprKind::Block(exprs) => {
            for e in exprs {
                collect_expression_patterns(e, patterns);
            }
        }
        ExprKind::Function { body, .. } => {
            collect_expression_patterns(body, patterns);
        }
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => {
            collect_expression_patterns(condition, patterns);
            collect_expression_patterns(then_branch, patterns);
            if let Some(else_expr) = else_branch {
                collect_expression_patterns(else_expr, patterns);
            }
        }
        _ => {}
    }
}
/// Analyze naming quality (basic heuristics)
fn analyze_naming_quality(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut good_names = 0;
    let mut total_names = 0;
    analyze_names_recursive(ast, &mut good_names, &mut total_names);
    if total_names == 0 {
        return 1.0;
    }
    #[allow(clippy::cast_precision_loss)]
    let good_ratio = f64::from(good_names) / f64::from(total_names);
    good_ratio.max(0.5) // Minimum score for naming
}
fn analyze_names_recursive(
    expr: &crate::frontend::ast::Expr,
    good_names: &mut i32,
    total_names: &mut i32,
) {
    match &expr.kind {
        ExprKind::Function { name, .. } => {
            *total_names += 1;
            if is_good_name(name) {
                *good_names += 1;
            }
        }
        ExprKind::Let { name, body, .. } => {
            *total_names += 1;
            if is_good_name(name) {
                *good_names += 1;
            }
            analyze_names_recursive(body, good_names, total_names);
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                analyze_names_recursive(e, good_names, total_names);
            }
        }
        _ => {}
    }
}
fn is_good_name(name: &str) -> bool {
    // Basic heuristics for good naming
    if name.len() < 2 || name.starts_with('_') {
        return false;
    }
    // Check for descriptive names (not single letters or abbreviations)
    name.len() >= 3 && !name.chars().all(|c| c.is_ascii_uppercase())
}
/// Score safety component (15% weight)
/// # Examples
///
/// ```ignore
/// use ruchy::quality::scoring::score_safety;
///
/// let result = score_safety(());
/// assert_eq!(result, Ok(()));
/// ```
pub fn score_safety(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut score = 1.0;
    // Error handling coverage (reuse from correctness)
    let error_handling_quality = analyze_error_handling(ast);
    score *= error_handling_quality;
    // Null safety analysis
    let null_safety_score = analyze_null_safety(ast);
    score *= null_safety_score;
    // Resource management analysis
    let resource_score = analyze_resource_management(ast);
    score *= resource_score;
    // Bounds checking (implicit in type system, give good score)
    score *= 0.95; // Slight penalty for not having explicit bounds checks
    score.clamp(0.0, 1.0)
}
/// Analyze null safety patterns
fn analyze_null_safety(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut option_uses = 0;
    let mut unsafe_accesses = 0;
    analyze_null_safety_recursive(ast, &mut option_uses, &mut unsafe_accesses);
    if option_uses + unsafe_accesses == 0 {
        return 1.0; // No nullable types used
    }
    // Prefer Option types over unsafe accesses
    if unsafe_accesses == 0 {
        1.0 // All nullable accesses are safe
    } else {
        #[allow(clippy::cast_precision_loss)]
        let safety_ratio = f64::from(option_uses) / f64::from(option_uses + unsafe_accesses);
        safety_ratio.max(0.5) // Minimum safety score
    }
}
fn analyze_null_safety_recursive(
    expr: &crate::frontend::ast::Expr,
    option_uses: &mut i32,
    unsafe_accesses: &mut i32,
) {
    match &expr.kind {
        ExprKind::Some { .. } | ExprKind::None => {
            *option_uses += 1;
        }
        ExprKind::Match { arms, .. } => {
            // Check if matching on Option (heuristic)
            if arms.len() >= 2 {
                *option_uses += 1;
            }
            for arm in arms {
                analyze_null_safety_recursive(&arm.body, option_uses, unsafe_accesses);
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                analyze_null_safety_recursive(e, option_uses, unsafe_accesses);
            }
        }
        ExprKind::Function { body, .. } => {
            analyze_null_safety_recursive(body, option_uses, unsafe_accesses);
        }
        _ => {}
    }
}
/// Analyze resource management patterns
fn analyze_resource_management(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut resource_allocations = 0;
    let mut proper_cleanup = 0;
    analyze_resources_recursive(ast, &mut resource_allocations, &mut proper_cleanup);
    if resource_allocations == 0 {
        return 1.0; // No resources to manage
    }
    #[allow(clippy::cast_precision_loss)]
    let cleanup_ratio = f64::from(proper_cleanup) / f64::from(resource_allocations);
    cleanup_ratio.max(0.7) // Minimum score for resource management
}
fn analyze_resources_recursive(
    expr: &crate::frontend::ast::Expr,
    allocations: &mut i32,
    cleanup: &mut i32,
) {
    match &expr.kind {
        ExprKind::Block(exprs) => {
            for e in exprs {
                analyze_resources_recursive(e, allocations, cleanup);
            }
        }
        ExprKind::Function { body, .. } => {
            analyze_resources_recursive(body, allocations, cleanup);
        }
        _ => {}
    }
}
/// Score idiomaticity component (5% weight)
/// # Examples
///
/// ```ignore
/// use ruchy::quality::scoring::score_idiomaticity;
///
/// let result = score_idiomaticity(());
/// assert_eq!(result, Ok(()));
/// ```
pub fn score_idiomaticity(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut score = 1.0;
    // Pattern matching usage (idiomatic in Ruchy)
    let pattern_score = analyze_pattern_usage(ast);
    score *= pattern_score;
    // Iterator usage (functional style)
    let iterator_score = analyze_iterator_usage(ast);
    score *= iterator_score;
    // Lambda usage (functional programming)
    let lambda_score = analyze_lambda_usage(ast);
    score *= lambda_score;
    score.clamp(0.0, 1.0)
}
/// Analyze usage of pattern matching (idiomatic)
fn analyze_pattern_usage(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut matches = 0;
    let mut conditionals = 0;
    count_pattern_vs_conditional(ast, &mut matches, &mut conditionals);
    let total = matches + conditionals;
    if total == 0 {
        return 1.0;
    }
    #[allow(clippy::cast_precision_loss)]
    let pattern_ratio = f64::from(matches) / f64::from(total);
    // Higher ratio of matches vs if-else is more idiomatic
    if pattern_ratio > 0.7 {
        1.0
    } else if pattern_ratio > 0.4 {
        0.9
    } else {
        0.8
    }
}
fn count_pattern_vs_conditional(
    expr: &crate::frontend::ast::Expr,
    matches: &mut i32,
    conditionals: &mut i32,
) {
    match &expr.kind {
        ExprKind::Match { arms, .. } => {
            *matches += 1;
            for arm in arms {
                count_pattern_vs_conditional(&arm.body, matches, conditionals);
            }
        }
        ExprKind::If {
            condition,
            then_branch,
            else_branch,
        } => {
            *conditionals += 1;
            count_pattern_vs_conditional(condition, matches, conditionals);
            count_pattern_vs_conditional(then_branch, matches, conditionals);
            if let Some(else_expr) = else_branch {
                count_pattern_vs_conditional(else_expr, matches, conditionals);
            }
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                count_pattern_vs_conditional(e, matches, conditionals);
            }
        }
        ExprKind::Function { body, .. } => {
            count_pattern_vs_conditional(body, matches, conditionals);
        }
        _ => {}
    }
}
/// Analyze iterator usage patterns
fn analyze_iterator_usage(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut iterators = 0;
    let mut loops = 0;
    count_iterator_vs_loops(ast, &mut iterators, &mut loops);
    let total = iterators + loops;
    if total == 0 {
        return 1.0;
    }
    #[allow(clippy::cast_precision_loss)]
    let iterator_ratio = f64::from(iterators) / f64::from(total);
    // Higher ratio of iterators vs manual loops is more idiomatic
    if iterator_ratio > 0.6 {
        1.0
    } else if iterator_ratio > 0.3 {
        0.9
    } else {
        0.8
    }
}
fn count_iterator_vs_loops(
    expr: &crate::frontend::ast::Expr,
    iterators: &mut i32,
    loops: &mut i32,
) {
    match &expr.kind {
        ExprKind::For { .. } => {
            *iterators += 1; // For loops in Ruchy are iterator-based
        }
        ExprKind::While { .. } => {
            *loops += 1;
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                count_iterator_vs_loops(e, iterators, loops);
            }
        }
        ExprKind::Function { body, .. } => {
            count_iterator_vs_loops(body, iterators, loops);
        }
        _ => {}
    }
}
/// Analyze lambda/closure usage
fn analyze_lambda_usage(ast: &crate::frontend::ast::Expr) -> f64 {
    let mut lambdas = 0;
    let mut total_functions = 0;
    count_lambda_usage(ast, &mut lambdas, &mut total_functions);
    if total_functions == 0 {
        return 1.0;
    }
    #[allow(clippy::cast_precision_loss)]
    let lambda_ratio = f64::from(lambdas) / f64::from(total_functions);
    // Some lambda usage indicates functional style
    if lambda_ratio > 0.3 {
        1.0
    } else if lambda_ratio > 0.1 {
        0.95
    } else {
        0.9 // Still good if other patterns are used
    }
}
fn count_lambda_usage(
    expr: &crate::frontend::ast::Expr,
    lambdas: &mut i32,
    total_functions: &mut i32,
) {
    match &expr.kind {
        ExprKind::Lambda { .. } => {
            *lambdas += 1;
            *total_functions += 1;
        }
        ExprKind::Function { body, .. } => {
            *total_functions += 1;
            count_lambda_usage(body, lambdas, total_functions);
        }
        ExprKind::Block(exprs) => {
            for e in exprs {
                count_lambda_usage(e, lambdas, total_functions);
            }
        }
        _ => {}
    }
}


#[cfg(test)]
#[path = "scoring_tests.rs"]
mod tests;

#[cfg(test)]
#[allow(clippy::expect_used)]
#[path = "scoring_prop_tests.rs"]
mod property_tests_scoring;

#[cfg(test)]
#[path = "scoring_tests_r162.rs"]
mod scoring_tests_r162;