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
#![cfg_attr(coverage_nightly, coverage(off))]
//! FIXED Phase Implementation for PMAT-070-002: JSON Parser
//!
//! Parses cargo-mutants JSON output and converts to PMAT mutation report format.
//!
//! ## Actual cargo-mutants v25.3.1 Format
//!
//! cargo-mutants writes to `mutants.out/` directory:
//! - `mutants.json`: List of mutant definitions (no outcomes)
//! - `outcomes.json`: Execution results with outcomes
//!
//! ## Outcome Mapping
//!
//! cargo-mutants summary → PMAT MutantStatus:
//! - `CaughtMutant` → `Killed` (test suite detected the mutant)
//! - `MissedMutant` → `Survived` (test suite missed the mutant)
//! - `Timeout` → `Timeout` (test suite timed out)
//! - `Unviable` → `CompileError` (mutant failed to compile)
//!
//! ## Example
//!
//! ```rust
//! use pmat::services::mutation::json_parser::CargoMutantsReport;
//! use std::path::PathBuf;
//!
//! let output_dir = PathBuf::from("mutants.out");
//! let report = CargoMutantsReport::from_output_dir(&output_dir)?;
//! let pmat_report = report.to_pmat_report();
//! ```
use serde::{Deserialize, Serialize};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use super::types::{Mutant, MutantStatus, MutationOperatorType, SourceLocation};
/// Type alias for Result with boxed error
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
/// cargo-mutants JSON report structure
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CargoMutantsReport {
/// List of mutants from cargo-mutants
pub mutants: Vec<CargoMutant>,
}
/// Individual mutant from cargo-mutants
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CargoMutant {
/// Mutation outcome (caught, missed, timeout, unviable)
pub outcome: MutantOutcome,
/// Source file path
pub file: String,
/// Function name (optional)
#[serde(skip_serializing_if = "Option::is_none")]
pub function: Option<String>,
/// Line number where mutation occurred
pub line: usize,
/// Replacement text (optional - cargo-mutants may include this)
#[serde(skip_serializing_if = "Option::is_none")]
pub replacement: Option<String>,
}
/// Mutation outcome from cargo-mutants
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MutantOutcome {
/// Test suite detected the mutant (good!)
Caught,
/// Test suite missed the mutant (test gap!)
Missed,
/// Test suite timed out
Timeout,
/// Mutant failed to compile
Unviable,
}
// ============================================================================
// Actual cargo-mutants v25.3.1 JSON Format Structs
// ============================================================================
/// Actual outcomes.json structure from cargo-mutants
#[derive(Debug, Deserialize)]
struct OutcomesFile {
outcomes: Vec<Outcome>,
}
/// Individual outcome entry
#[derive(Debug, Deserialize)]
struct Outcome {
scenario: ScenarioType,
summary: String,
}
/// Scenario can be either "Baseline" or {"Mutant": {...}}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
#[allow(dead_code)]
enum ScenarioType {
Baseline(String),
Mutant {
#[serde(rename = "Mutant")]
mutant: MutantDefinition,
},
}
/// Mutant definition from outcomes.json (embedded in scenario)
#[derive(Debug, Deserialize)]
struct MutantDefinition {
#[allow(dead_code)]
package: String,
file: String,
function: FunctionInfo,
span: SpanInfo,
replacement: String,
#[allow(dead_code)]
genre: String,
}
/// Function information
#[derive(Debug, Deserialize)]
struct FunctionInfo {
function_name: String,
}
/// Span information (line/column range)
#[derive(Debug, Deserialize)]
struct SpanInfo {
start: Position,
}
/// Position in file
#[derive(Debug, Deserialize)]
struct Position {
line: usize,
}
impl CargoMutantsReport {
/// Parse cargo-mutants output from directory (ACTUAL v25.3.1 format)
///
/// Reads `outcomes.json` from the cargo-mutants output directory and
/// converts it to PMAT mutation report format.
///
/// # Arguments
/// * `dir` - Path to `mutants.out/` directory
///
/// # Returns
/// * `Ok(CargoMutantsReport)` - Successfully parsed report
/// * `Err(...)` - Parse error with description
///
/// # Example
/// ```rust
/// use std::path::PathBuf;
/// let output_dir = PathBuf::from("mutants.out");
/// let report = CargoMutantsReport::from_output_dir(&output_dir)?;
/// ```
pub fn from_output_dir(dir: &std::path::Path) -> Result<Self> {
// Read outcomes.json
let outcomes_path = dir.join("outcomes.json");
let outcomes_json = std::fs::read_to_string(&outcomes_path)
.map_err(|e| format!("Failed to read outcomes.json: {}", e))?;
// Parse outcomes file
let outcomes_file: OutcomesFile = serde_json::from_str(&outcomes_json)
.map_err(|e| format!("Failed to parse outcomes.json: {}", e))?;
// Extract mutants from outcomes
let mut mutants = Vec::new();
for outcome in outcomes_file.outcomes {
// Skip baseline scenario
if let ScenarioType::Mutant { mutant } = outcome.scenario {
// Map cargo-mutants summary to our outcome enum
let outcome_type = match outcome.summary.as_str() {
"CaughtMutant" => MutantOutcome::Caught,
"MissedMutant" => MutantOutcome::Missed,
"Timeout" => MutantOutcome::Timeout,
_ => MutantOutcome::Unviable, // Includes "Unviable" and unknown
};
mutants.push(CargoMutant {
outcome: outcome_type,
file: mutant.file,
function: Some(mutant.function.function_name),
line: mutant.span.start.line,
replacement: Some(mutant.replacement),
});
}
}
Ok(CargoMutantsReport { mutants })
}
/// Parse cargo-mutants JSON output (DEPRECATED - for backward compatibility)
///
/// # Arguments
/// * `json` - JSON string from cargo-mutants output
///
/// # Returns
/// * `Ok(CargoMutantsReport)` - Successfully parsed report
/// * `Err(...)` - Parse error with description
///
/// # Example
/// ```rust
/// let json = r#"{"mutants": []}"#;
/// let report = CargoMutantsReport::from_json(json)?;
/// assert_eq!(report.mutants.len(), 0);
/// ```
#[deprecated(
note = "Use from_output_dir() instead - matches actual cargo-mutants v25.3.1 format"
)]
pub fn from_json(json: &str) -> Result<Self> {
serde_json::from_str(json)
.map_err(|e| format!("Failed to parse cargo-mutants JSON: {}", e).into())
}
/// Convert cargo-mutants report to PMAT mutation report
///
/// Maps cargo-mutants outcomes to PMAT MutantStatus:
/// - caught → Killed
/// - missed → Survived
/// - timeout → Timeout
/// - unviable → CompileError
///
/// # Returns
/// Vector of PMAT Mutant structs
///
/// # Example
/// ```rust
/// let json = r#"{"mutants": [{"outcome": "caught", "file": "src/lib.rs", "line": 10}]}"#;
/// let report = CargoMutantsReport::from_json(json)?;
/// let pmat_report = report.to_pmat_report();
/// assert_eq!(pmat_report[0].status, MutantStatus::Killed);
/// ```
pub fn to_pmat_report(&self) -> Vec<Mutant> {
self.mutants
.iter()
.enumerate()
.map(|(idx, cargo_mutant)| Self::convert_mutant(cargo_mutant, idx))
.collect()
}
/// Calculate mutation score (percentage of caught mutants)
///
/// # Returns
/// Mutation score as a percentage (0.0 - 100.0)
///
/// # Example
/// ```rust
/// let json = r#"{"mutants": [
/// {"outcome": "caught", "file": "src/lib.rs", "line": 10},
/// {"outcome": "missed", "file": "src/lib.rs", "line": 20}
/// ]}"#;
/// let report = CargoMutantsReport::from_json(json)?;
/// assert_eq!(report.mutation_score(), 50.0);
/// ```
pub fn mutation_score(&self) -> f64 {
if self.mutants.is_empty() {
return 0.0;
}
let caught = self.count_by_outcome(MutantOutcome::Caught);
(caught as f64 / self.mutants.len() as f64) * 100.0
}
/// Count mutants by outcome
///
/// # Arguments
/// * `outcome` - The outcome to count
///
/// # Returns
/// Number of mutants with the given outcome
pub fn count_by_outcome(&self, outcome: MutantOutcome) -> usize {
self.mutants.iter().filter(|m| m.outcome == outcome).count()
}
/// Convert a single cargo mutant to PMAT format
///
/// # Arguments
/// * `cargo_mutant` - The cargo-mutants mutant to convert
/// * `idx` - Index for generating unique ID
///
/// # Returns
/// PMAT Mutant struct
fn convert_mutant(cargo_mutant: &CargoMutant, idx: usize) -> Mutant {
let status = Self::map_outcome(&cargo_mutant.outcome);
let id = Self::generate_id(cargo_mutant, idx);
let location = Self::create_location(cargo_mutant);
let mutated_source = Self::format_mutated_source(cargo_mutant);
let hash = Self::generate_hash(cargo_mutant);
Mutant {
id,
original_file: PathBuf::from(&cargo_mutant.file),
mutated_source,
location,
operator: MutationOperatorType::Custom("cargo-mutants".to_string()),
hash,
status,
}
}
/// Map cargo-mutants outcome to PMAT status
fn map_outcome(outcome: &MutantOutcome) -> MutantStatus {
match outcome {
MutantOutcome::Caught => MutantStatus::Killed,
MutantOutcome::Missed => MutantStatus::Survived,
MutantOutcome::Timeout => MutantStatus::Timeout,
MutantOutcome::Unviable => MutantStatus::CompileError,
}
}
/// Generate unique ID for mutant
fn generate_id(cargo_mutant: &CargoMutant, idx: usize) -> String {
format!(
"cargo-mutants-{}-{}-{}",
cargo_mutant.file.replace('/', "_").replace(".rs", ""),
cargo_mutant.line,
idx
)
}
/// Create source location from cargo mutant
fn create_location(cargo_mutant: &CargoMutant) -> SourceLocation {
SourceLocation {
line: cargo_mutant.line,
column: 0, // cargo-mutants doesn't provide column
end_line: cargo_mutant.line,
end_column: 0,
}
}
/// Format mutated source description
fn format_mutated_source(cargo_mutant: &CargoMutant) -> String {
if let Some(ref replacement) = cargo_mutant.replacement {
format!("Replacement: {}", replacement)
} else {
"Unknown mutation".to_string()
}
}
/// Generate hash for mutant
fn generate_hash(cargo_mutant: &CargoMutant) -> String {
let mut hasher = DefaultHasher::new();
cargo_mutant.file.hash(&mut hasher);
cargo_mutant.line.hash(&mut hasher);
format!("{:?}", cargo_mutant.outcome).hash(&mut hasher);
format!("{:x}", hasher.finish())
}
}
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[allow(deprecated)]
fn test_parse_simple_json() {
let json = r#"{"mutants": []}"#;
let report = CargoMutantsReport::from_json(json).unwrap();
assert_eq!(report.mutants.len(), 0);
}
#[test]
#[allow(deprecated)]
fn test_outcome_deserialization() {
let json = r#"{"mutants": [
{"outcome": "caught", "file": "src/lib.rs", "line": 10},
{"outcome": "missed", "file": "src/lib.rs", "line": 15},
{"outcome": "timeout", "file": "src/lib.rs", "line": 20},
{"outcome": "unviable", "file": "src/lib.rs", "line": 25}
]}"#;
let report = CargoMutantsReport::from_json(json).unwrap();
assert_eq!(report.mutants.len(), 4);
assert_eq!(report.mutants[0].outcome, MutantOutcome::Caught);
assert_eq!(report.mutants[1].outcome, MutantOutcome::Missed);
assert_eq!(report.mutants[2].outcome, MutantOutcome::Timeout);
assert_eq!(report.mutants[3].outcome, MutantOutcome::Unviable);
}
#[test]
#[allow(deprecated)]
fn test_to_pmat_conversion() {
let json = r#"{"mutants": [
{"outcome": "caught", "file": "src/lib.rs", "line": 10}
]}"#;
let report = CargoMutantsReport::from_json(json).unwrap();
let pmat_report = report.to_pmat_report();
assert_eq!(pmat_report.len(), 1);
assert_eq!(pmat_report[0].status, MutantStatus::Killed);
assert_eq!(pmat_report[0].original_file, PathBuf::from("src/lib.rs"));
assert_eq!(pmat_report[0].location.line, 10);
}
}