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
/// Extract code blocks from lines
fn extract_blocks(
lines: &[&str],
path: &Path,
min_lines: usize,
max_tokens: usize,
detection_type: crate::cli::DuplicateType,
) -> Vec<(String, String, usize, usize, String)> {
let mut blocks = Vec::new();
let file_str = path.to_string_lossy().to_string();
// Exhaustive on purpose. This match used to end in `_ => {}`, which
// silently swallowed `All` -- the DOCUMENTED DEFAULT. So the default
// invocation extracted zero blocks and reported "total_duplicates: 0,
// duplication_percentage: 0.0" for byte-identical files, while
// `--detection-type exact` on the same input found 124. Reporting
// duplicated code as clean is worse than reporting nothing at all.
//
// Keeping it exhaustive means a new DuplicateType variant is a compile
// error here rather than another silent zero.
match detection_type {
crate::cli::DuplicateType::Exact => {
extract_exact_blocks(&mut blocks, lines, &file_str, min_lines, max_tokens);
}
crate::cli::DuplicateType::Fuzzy | crate::cli::DuplicateType::Gapped => {
extract_fuzzy_blocks(&mut blocks, lines, &file_str, min_lines, max_tokens);
}
// `All` must be a superset of every sub-mode, never a subset. Both
// extractors run and their blocks are unioned; the hashes cannot
// collide across modes because `extract_fuzzy_blocks` hashes a
// structural signature while `extract_exact_blocks` hashes normalised
// source, and identical content legitimately matching under both is a
// genuine duplicate either way.
crate::cli::DuplicateType::All => {
extract_exact_blocks(&mut blocks, lines, &file_str, min_lines, max_tokens);
extract_fuzzy_blocks(&mut blocks, lines, &file_str, min_lines, max_tokens);
}
// Type-2 (renamed) and Type-4 (semantic) have no implementation here.
// They extract nothing rather than pretending: the caller reports the
// honest zero for an explicitly requested mode, which is different from
// the default silently reporting zero for everything.
crate::cli::DuplicateType::Renamed | crate::cli::DuplicateType::Semantic => {}
}
blocks
}
/// Extract exact match blocks using sliding window
fn extract_exact_blocks(
blocks: &mut Vec<(String, String, usize, usize, String)>,
lines: &[&str],
file_str: &str,
min_lines: usize,
max_tokens: usize,
) {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
// Sliding window for exact matches
for i in 0..lines.len().saturating_sub(min_lines) {
let block_lines = &lines[i..i + min_lines];
let content = normalize_block(block_lines);
if count_tokens(&content) <= max_tokens {
let mut hasher = DefaultHasher::new();
content.hash(&mut hasher);
let hash = format!("{:x}", hasher.finish());
blocks.push((hash, file_str.to_string(), i + 1, i + min_lines, content));
}
}
}
/// Extract fuzzy match blocks based on code structure
fn extract_fuzzy_blocks(
blocks: &mut Vec<(String, String, usize, usize, String)>,
lines: &[&str],
file_str: &str,
min_lines: usize,
max_tokens: usize,
) {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut i = 0;
while i < lines.len() {
if is_block_start(lines[i]) {
// Clamped: `find_block_end` returning None falls back to
// `min_lines`, and `i + min_lines` can run past the end of the
// file — `&lines[i..end]` then panics with "range end index 131 out
// of range for slice of length 130".
//
// This was latent: `All` used to fall into a `_ => {}` arm so this
// extractor was never reached on the DEFAULT detection type. Making
// `All` a real superset turned a dormant panic into a crash on
// `pmat analyze duplicates` over any ordinary source tree,
// including pmat's own (SIGABRT, rc=134).
let end = (find_block_end(&lines[i..]).unwrap_or(min_lines) + i).min(lines.len());
if end - i >= min_lines {
let block_lines = &lines[i..end];
let content = normalize_block(block_lines);
if count_tokens(&content) <= max_tokens {
let mut hasher = DefaultHasher::new();
content.hash(&mut hasher);
let hash = format!("{:x}", hasher.finish());
blocks.push((hash, file_str.to_string(), i + 1, end, content));
}
}
i = end;
} else {
i += 1;
}
}
}
/// Normalize code block (remove whitespace variations)
fn normalize_block(lines: &[&str]) -> String {
lines
.iter()
.map(|line| line.trim())
.filter(|line| !line.is_empty() && !line.starts_with("//") && !line.starts_with('#'))
.collect::<Vec<_>>()
.join("\n")
}
/// Count tokens in content
fn count_tokens(content: &str) -> usize {
content.split_whitespace().count()
}
/// Check if line starts a code block - refactored to reduce complexity
fn is_block_start(line: &str) -> bool {
let trimmed = line.trim();
// Check for function/method declarations
if is_function_declaration(trimmed) {
return true;
}
// Check for class/type declarations
if is_type_declaration(trimmed) {
return true;
}
// Check for block opening
if is_block_opening(trimmed) {
return true;
}
false
}
/// Check if line is a function declaration
fn is_function_declaration(line: &str) -> bool {
line.contains("fn ") || line.contains("function") || line.contains("def ")
}
/// Check if line is a type declaration
fn is_type_declaration(line: &str) -> bool {
line.contains("class ") || line.contains("struct ") || line.contains("impl ")
}
/// Check if line is a block opening
fn is_block_opening(line: &str) -> bool {
line.ends_with('{') && !line.starts_with('{')
}
/// Find end of code block
fn find_block_end(lines: &[&str]) -> Option<usize> {
let mut brace_count = 0;
let mut in_block = false;
for (i, line) in lines.iter().enumerate() {
for ch in line.chars() {
match ch {
'{' => {
brace_count += 1;
in_block = true;
}
'}' => {
brace_count -= 1;
if brace_count == 0 && in_block {
return Some(i + 1);
}
}
_ => {}
}
}
}
None
}
/// Find duplicate blocks from all blocks
fn find_duplicate_blocks(
all_blocks: Vec<(String, String, usize, usize, String)>,
_threshold: f32,
) -> Vec<DuplicateBlock> {
let mut hash_groups: HashMap<String, Vec<(String, usize, usize, String)>> = HashMap::new();
// Group by hash
for (hash, file, start, end, content) in all_blocks {
hash_groups
.entry(hash)
.or_default()
.push((file, start, end, content));
}
// Find duplicates
let mut duplicates = Vec::new();
for (hash, mut locations) in hash_groups {
// Collapse OVERLAPPING windows within a file before deciding anything is
// duplicated. Detection slides a window one line at a time, so a single
// 5-line function yields windows at 2-6, 3-7 and 4-8 whose normalised
// text can hash identically. Counting those as three "locations" made a
// file of four entirely distinct functions report four duplicates at
// 211.5% duplication. Overlapping windows are the same code, not copies
// of it.
//
// Greedy sweep per file: keep a window, skip every later one that starts
// before the kept one ends.
locations.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
let mut kept: Vec<(String, usize, usize, String)> = Vec::new();
for loc in locations {
let overlaps_kept = kept
.last()
.is_some_and(|last| last.0 == loc.0 && loc.1 <= last.2);
if !overlaps_kept {
kept.push(loc);
}
}
let locations = kept;
// Two or more NON-OVERLAPPING sites is what makes it a duplicate.
if locations.len() > 1 {
let lines = locations[0].2 - locations[0].1 + 1;
let tokens = count_tokens(&locations[0].3);
let duplicate_locations: Vec<DuplicateLocation> = locations
.into_iter()
.map(|(file, start, end, content)| {
let preview = content.lines().take(3).collect::<Vec<_>>().join("\n");
DuplicateLocation {
file,
start_line: start,
end_line: end,
content_preview: if content.lines().count() > 3 {
format!("{preview}...")
} else {
preview
},
}
})
.collect();
duplicates.push(DuplicateBlock {
hash,
locations: duplicate_locations,
lines,
tokens,
similarity: 1.0, // Exact match for now
});
}
}
// Sort by lines descending.
//
// DETERMINISM (round-3 sweep): `hash_groups` is a `HashMap`, so the vector
// above was built in a per-process random order, and `sort_by_key` is
// stable — every block of the same `lines` therefore kept that random
// order. `analyze duplicates --format json` on a fixed two-file fixture
// produced 5 DIFFERENT md5 sums over 5 runs, with the same 14 block hashes
// merely reordered. The (file, start_line, hash) suffix is a total order
// over blocks: `locations` is already sorted by (file, start) above, and no
// two surviving blocks share a hash.
duplicates.sort_by(|a, b| {
b.lines
.cmp(&a.lines)
.then_with(|| {
let a_first = a.locations.first();
let b_first = b.locations.first();
match (a_first, b_first) {
(Some(x), Some(y)) => (&x.file, x.start_line).cmp(&(&y.file, y.start_line)),
(None, Some(_)) => std::cmp::Ordering::Less,
(Some(_), None) => std::cmp::Ordering::Greater,
(None, None) => std::cmp::Ordering::Equal,
}
})
.then_with(|| a.hash.cmp(&b.hash))
});
duplicates
}
/// Check if file should be processed
fn should_process_file(path: &Path, include: &Option<String>, exclude: &Option<String>) -> bool {
let path_str = path.to_string_lossy();
if let Some(excl) = exclude {
if path_str.contains(excl) {
return false;
}
}
if let Some(incl) = include {
return path_str.contains(incl);
}
true
}
/// Check if file is source code
fn is_source_file(path: &Path) -> bool {
matches!(
path.extension().and_then(|s| s.to_str()),
Some("rs" | "js" | "ts" | "py" | "java" | "cpp" | "c" | "kt" | "kts")
)
}