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
use crate::analyzer::{CodeIssue, Severity};
use std::collections::HashMap;
/// Code quality rating system
/// Score range: 0-100, the higher the score, the worse the code quality
/// 0-20: Excellent
/// 21-40: Good
/// 41-60: Average
/// 61-80: Poor
/// 81-100: Terrible
#[derive(Debug, Clone)]
pub struct CodeQualityScore {
pub total_score: f64,
pub category_scores: HashMap<String, f64>,
pub file_count: usize,
pub total_lines: usize,
pub issue_density: f64,
pub severity_distribution: SeverityDistribution,
pub quality_level: QualityLevel,
}
/// Breakdown of issues by severity level.
#[derive(Debug, Clone)]
pub struct SeverityDistribution {
pub nuclear: usize,
pub spicy: usize,
pub mild: usize,
}
/// Overall code quality rating derived from the score.
#[derive(Debug, Clone, PartialEq)]
pub enum QualityLevel {
Excellent, // 0-20
Good, // 21-40
Average, // 41-60
Poor, // 61-80
Terrible, // 81-100
}
impl QualityLevel {
pub fn from_score(score: f64) -> Self {
match score as u32 {
0..=20 => QualityLevel::Excellent,
21..=40 => QualityLevel::Good,
41..=60 => QualityLevel::Average,
61..=80 => QualityLevel::Poor,
_ => QualityLevel::Terrible,
}
}
pub fn description(&self, lang: &str) -> &'static str {
match (self, lang) {
(QualityLevel::Excellent, "zh-CN") => "优秀",
(QualityLevel::Good, "zh-CN") => "良好",
(QualityLevel::Average, "zh-CN") => "一般",
(QualityLevel::Poor, "zh-CN") => "较差",
(QualityLevel::Terrible, "zh-CN") => "糟糕",
(QualityLevel::Excellent, _) => "Excellent",
(QualityLevel::Good, _) => "Good",
(QualityLevel::Average, _) => "Average",
(QualityLevel::Poor, _) => "Poor",
(QualityLevel::Terrible, _) => "Terrible",
}
}
pub fn emoji(&self) -> &'static str {
match self {
QualityLevel::Excellent => "🏆",
QualityLevel::Good => "👍",
QualityLevel::Average => "😐",
QualityLevel::Poor => "😞",
QualityLevel::Terrible => "💀",
}
}
}
/// Calculates severity-weighted, category-based code quality scores.
pub struct CodeScorer;
impl CodeScorer {
pub fn new() -> Self {
Self
}
/// calculate code quality score using normalized category-based approach
pub fn calculate_score(
&self,
issues: &[CodeIssue],
file_count: usize,
total_lines: usize,
) -> CodeQualityScore {
if issues.is_empty() {
return CodeQualityScore {
total_score: 0.0, // Perfect score when no issues (0 = best)
category_scores: HashMap::new(),
file_count,
total_lines,
issue_density: 0.0,
severity_distribution: SeverityDistribution {
nuclear: 0,
spicy: 0,
mild: 0,
},
quality_level: QualityLevel::Excellent,
};
}
// calculate severity distribution
let severity_distribution = self.calculate_severity_distribution(issues);
// calculate category scores (0-100 for each category)
let category_scores = self.calculate_normalized_category_scores(issues, total_lines);
// calculate weighted final score
let total_score = self.calculate_weighted_final_score(&category_scores);
let issue_density = if total_lines > 0 {
issues.len() as f64 / total_lines as f64 * 1000.0 // issues per 1000 lines
} else {
0.0
};
CodeQualityScore {
total_score,
category_scores,
file_count,
total_lines,
issue_density,
severity_distribution,
quality_level: QualityLevel::from_score(total_score),
}
}
fn calculate_severity_distribution(&self, issues: &[CodeIssue]) -> SeverityDistribution {
let mut nuclear = 0;
let mut spicy = 0;
let mut mild = 0;
for issue in issues {
match issue.severity {
Severity::Nuclear => nuclear += 1,
Severity::Spicy => spicy += 1,
Severity::Mild => mild += 1,
}
}
SeverityDistribution {
nuclear,
spicy,
mild,
}
}
/// Calculate normalized category scores (0-100 for each category)
fn calculate_normalized_category_scores(
&self,
issues: &[CodeIssue],
total_lines: usize,
) -> HashMap<String, f64> {
let mut category_scores = HashMap::new();
let mut category_weighted_counts: HashMap<String, f64> = HashMap::new();
// Define categories with their rule mappings
let categories = [
(
"naming",
vec![
"terrible-naming",
"single-letter-variable",
"meaningless-naming",
"hungarian-notation",
"abbreviation-abuse",
"c-naming",
],
),
(
"complexity",
vec![
"deep-nesting",
"long-function",
"cyclomatic-complexity",
"c-nesting",
"c-long-function",
],
),
("duplication", vec!["code-duplication"]),
(
"rust-basics",
vec![
"unwrap-abuse",
"unnecessary-clone",
"string-abuse",
"vec-abuse",
],
),
(
"advanced-rust",
vec![
"complex-closure",
"lifetime-abuse",
"trait-complexity",
"generic-abuse",
],
),
(
"rust-features",
vec![
"channel-abuse",
"async-abuse",
"dyn-trait-abuse",
"unsafe-abuse",
"ffi-abuse",
"macro-abuse",
],
),
(
"structure",
vec![
"module-complexity",
"pattern-matching-abuse",
"reference-abuse",
"box-abuse",
"slice-abuse",
"file-too-long",
"duplicate-imports",
"deep-module-nesting",
"c-include-chaos",
],
),
(
"code-smells",
vec![
"magic-number",
"god-function",
"commented-code",
"dead-code",
"c-magic-number",
"c-god-function",
"c-commented-code",
"c-dead-code",
],
),
(
"student-code",
vec!["println-debugging", "panic-abuse", "todo-comment"],
),
("c-safety", vec!["c-goto-abuse", "c-malloc-leak"]),
];
// Severity weights: Nuclear issues count 6x as much as Mild
let severity_weight = |severity: &Severity| -> f64 {
match severity {
Severity::Nuclear => 3.0,
Severity::Spicy => 1.5,
Severity::Mild => 0.5,
}
};
// Accumulate severity-weighted counts per category
for issue in issues {
let weight = severity_weight(&issue.severity);
for (category_name, rules) in &categories {
if rules.contains(&issue.rule_name.as_str()) {
*category_weighted_counts
.entry(category_name.to_string())
.or_insert(0.0) += weight;
}
}
}
// Calculate normalized scores for each category (0-100)
for (category_name, _) in &categories {
let weighted_count = category_weighted_counts.get(*category_name).unwrap_or(&0.0);
let score = self.calculate_category_score(*weighted_count, total_lines, category_name);
category_scores.insert(category_name.to_string(), score);
}
category_scores
}
/// Calculate score for a specific category (0-100, where 0 is perfect, 100 is terrible, maximum 90)
fn calculate_category_score(
&self,
weighted_count: f64,
total_lines: usize,
category: &str,
) -> f64 {
if total_lines == 0 {
return 0.0; // Perfect score when no code
}
// Calculate weighted issues per 1000 lines for this category
let issues_per_1k_lines = (weighted_count / total_lines as f64) * 1000.0;
// Different thresholds for different categories
let (excellent_threshold, good_threshold, average_threshold, poor_threshold) =
match category {
"naming" => (0.0, 2.0, 5.0, 10.0), // Naming should be very clean
"complexity" => (0.0, 1.0, 3.0, 6.0), // Complexity should be low
"duplication" => (0.0, 0.5, 2.0, 4.0), // Duplication should be minimal
"rust-basics" => (0.0, 1.0, 3.0, 6.0), // Basic Rust issues
"advanced-rust" => (0.0, 0.5, 2.0, 4.0), // Advanced features should be used carefully
"rust-features" => (0.0, 0.5, 1.5, 3.0), // Special features should be rare
"structure" => (0.0, 1.0, 3.0, 6.0), // Structure issues
"code-smells" => (0.0, 1.5, 4.0, 8.0), // Code smells are common
"student-code" => (0.0, 1.0, 3.0, 6.0), // Student patterns
"c-safety" => (0.0, 0.5, 2.0, 4.0), // C safety issues are serious
_ => (0.0, 1.0, 3.0, 6.0), // Default thresholds
};
// Calculate score based on thresholds (0 = excellent, 100 = terrible)
if issues_per_1k_lines <= excellent_threshold {
0.0 // Perfect score
} else if issues_per_1k_lines <= good_threshold {
(issues_per_1k_lines - excellent_threshold) / (good_threshold - excellent_threshold)
* 20.0
} else if issues_per_1k_lines <= average_threshold {
20.0 + (issues_per_1k_lines - good_threshold) / (average_threshold - good_threshold)
* 20.0
} else if issues_per_1k_lines <= poor_threshold {
40.0 + (issues_per_1k_lines - average_threshold) / (poor_threshold - average_threshold)
* 20.0
} else {
// Beyond poor threshold, score increases rapidly but caps at 90
let excess = issues_per_1k_lines - poor_threshold;
(60.0 + excess * 2.0).min(90.0) // Cap at 90 to avoid perfect 100
}
}
/// Calculate weighted final score from category scores
fn calculate_weighted_final_score(&self, category_scores: &HashMap<String, f64>) -> f64 {
// Category weights (sum to ~0.95, normalized by total_weight)
let weights = [
("naming", 0.15), // 15% - Very important (includes garbage-naming + c-naming)
("complexity", 0.15), // 15% - Very important
("duplication", 0.10), // 10% - Important
("rust-basics", 0.10), // 10% - Important (includes string/vec abuse)
("advanced-rust", 0.08), // 8% - Moderate
("rust-features", 0.05), // 5% - Moderate
("structure", 0.07), // 7% - Structure issues (includes include-chaos)
("code-smells", 0.15), // 15% - Common issues (shared by Rust + C/C++)
("student-code", 0.05), // 5% - Beginner patterns
("c-safety", 0.10), // 10% - C/C++ safety (goto, malloc leaks)
];
let mut weighted_sum = 0.0;
let mut total_weight = 0.0;
for (category, weight) in &weights {
if let Some(score) = category_scores.get(*category) {
weighted_sum += score * weight;
total_weight += weight;
}
}
if total_weight > 0.0 {
weighted_sum / total_weight
} else {
100.0 // Default to perfect score if no categories found
}
}
}
impl Default for CodeScorer {
fn default() -> Self {
Self::new()
}
}