1use serde::Serialize;
4use std::path::{Component, Path};
5
6#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
7pub struct Finding {
8 pub file: String,
9 pub line: usize,
10 pub pattern: &'static str,
11 pub text: String,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
15pub struct FallbackRecord {
16 pub file: String,
17 pub line: usize,
18 pub pattern: &'static str,
19 pub text: String,
20 #[serde(skip_serializing_if = "Option::is_none")]
21 pub verdict: Option<String>,
22 #[serde(skip_serializing_if = "Option::is_none")]
23 pub reason: Option<String>,
24}
25
26pub fn added_fallbacks(diff: &str) -> Vec<Finding> {
30 let lines: Vec<&str> = diff.lines().collect();
31
32 let mut findings = Vec::new();
33
34 let mut current_file: Option<(&str, &str)> = None; let mut current_line: usize = 0;
36 let mut in_hunk = false;
37 let mut ignore_hunk = false;
38 let mut after_cfg_test = false;
39
40 for (idx, &raw_line) in lines.iter().enumerate() {
41 if let Some(rest) = raw_line.strip_prefix("+++ ") {
42 in_hunk = false;
43 ignore_hunk = false;
44 after_cfg_test = false;
45 current_line = 0;
46 if rest == "/dev/null" {
47 current_file = None;
48 } else {
49 let path = rest.strip_prefix("b/").unwrap_or(rest);
50 if is_test_file(path) {
51 current_file = None;
52 } else {
53 let ext = Path::new(path)
54 .extension()
55 .and_then(|s| s.to_str())
56 .unwrap_or("");
57 if is_supported_ext(ext) {
58 current_file = Some((path, ext));
59 } else {
60 current_file = None;
61 }
62 }
63 }
64 continue;
65 }
66
67 if let Some(after_at) = raw_line.strip_prefix("@@ ") {
68 if let Some((coords, _)) = after_at.split_once("@@") {
69 if let Some(plus_part) = coords.split_whitespace().find_map(|t| t.strip_prefix('+'))
70 {
71 let c_str = plus_part.split(',').next().unwrap_or(plus_part);
72 if let Ok(c) = c_str.parse::<usize>() {
73 current_line = c;
74 in_hunk = true;
75 let is_rust = current_file.map(|(_, ext)| ext == "rs").unwrap_or(false);
76 ignore_hunk = is_rust && raw_line.contains("mod tests");
77 }
78 }
79 }
80 continue;
81 }
82
83 let Some((file_path, ext)) = current_file else {
84 continue;
85 };
86 if !in_hunk {
87 continue;
88 }
89
90 if let Some(content) = raw_line.strip_prefix(' ') {
91 current_line += 1;
92 if ext == "rs" && content.contains("#[cfg(test)]") {
93 after_cfg_test = true;
94 }
95 continue;
96 }
97
98 if raw_line.starts_with('-') {
99 continue;
100 }
101
102 if let Some(content) = raw_line.strip_prefix('+') {
103 let line_no = current_line;
104 current_line += 1;
105
106 if ext == "rs" && content.contains("#[cfg(test)]") {
107 after_cfg_test = true;
108 }
109
110 if ignore_hunk || after_cfg_test || is_comment(content, ext) {
111 continue;
112 }
113
114 let patterns = match_line(content, ext, &lines, idx);
115 if !patterns.is_empty() {
116 let trimmed = content.trim();
117 let text: String = trimmed.chars().take(200).collect();
118 for pattern in patterns {
119 findings.push(Finding {
120 file: file_path.to_string(),
121 line: line_no,
122 pattern,
123 text: text.clone(),
124 });
125 }
126 }
127 }
128 }
129
130 findings
131}
132
133pub fn flag(findings: &[Finding]) -> Option<String> {
135 flags_for_review(findings, None).into_iter().next()
136}
137
138pub fn flags_for_review(
140 candidates: &[Finding],
141 model_review: Option<&crate::model_review::ModelReviewResult>,
142) -> Vec<String> {
143 if candidates.is_empty() {
144 return Vec::new();
145 }
146 let Some(mr) = model_review else {
147 return vec![format_not_judged_why(candidates.len(), "no review")];
148 };
149 if mr.is_failed() {
150 let why = mr.error.as_deref().unwrap_or("unknown error");
151 return vec![format_not_judged_why(candidates.len(), why)];
152 }
153
154 let mut confirmed = Vec::new();
155 let mut not_judged = Vec::new();
156 for c in candidates {
157 match mr
158 .fallbacks
159 .iter()
160 .find(|v| v.file == c.file && v.line == c.line)
161 {
162 Some(v) if v.verdict == "fallback" => {
163 confirmed.push(format!("{}:{}", c.file, c.line));
164 }
165 Some(v) if v.verdict == "not_fallback" => {}
166 _ => {
167 not_judged.push(format!("{}:{}", c.file, c.line));
168 }
169 }
170 }
171
172 let mut out = Vec::new();
173 if !confirmed.is_empty() {
174 out.push(format_fallback_list("fallbacks added", &confirmed));
175 }
176 if !not_judged.is_empty() {
177 out.push(format_fallback_list(
178 "fallback candidates not judged",
179 ¬_judged,
180 ));
181 }
182 out
183}
184
185pub fn annotate_fallbacks(
187 candidates: &[Finding],
188 model_review: Option<&crate::model_review::ModelReviewResult>,
189) -> Vec<FallbackRecord> {
190 let ok_review = model_review.filter(|mr| !mr.is_failed());
191 candidates
192 .iter()
193 .map(|c| {
194 let matched = ok_review.and_then(|mr| {
195 mr.fallbacks
196 .iter()
197 .find(|v| v.file == c.file && v.line == c.line)
198 });
199 FallbackRecord {
200 file: c.file.clone(),
201 line: c.line,
202 pattern: c.pattern,
203 text: c.text.clone(),
204 verdict: matched.map(|v| v.verdict.clone()),
205 reason: matched.map(|v| v.reason.clone()),
206 }
207 })
208 .collect()
209}
210
211fn format_not_judged_why(n: usize, why: &str) -> String {
212 let why_one_line: String = why
213 .lines()
214 .map(str::trim)
215 .filter(|s| !s.is_empty())
216 .collect::<Vec<_>>()
217 .join(" ");
218 let prefix = format!("possible fallbacks added: {n} (not judged: ");
219 let full = format!("{prefix}{why_one_line})");
220 if full.chars().count() <= 200 {
221 return full;
222 }
223 let avail = 200usize.saturating_sub(prefix.chars().count() + 2);
224 let truncated: String = why_one_line.chars().take(avail).collect();
225 format!("{prefix}{truncated}…)")
226}
227
228fn format_fallback_list(prefix: &str, items: &[String]) -> String {
229 let clean: Vec<String> = items.iter().map(|s| s.replace(['\r', '\n'], " ")).collect();
230 let n = clean.len();
231 let head = format!("{prefix}: {n} (");
232 let full = format!("{head}{})", clean.join(", "));
233 if full.chars().count() <= 200 {
234 return full;
235 }
236 for m in (1..n).rev() {
237 let k = n - m;
238 let cand = format!("{head}{}, … and {k} more)", clean[..m].join(", "));
239 if cand.chars().count() <= 200 {
240 return cand;
241 }
242 }
243 if n > 1 {
244 let suffix = format!(", … and {} more)", n - 1);
245 let avail = 200usize.saturating_sub(head.chars().count() + suffix.chars().count());
246 if avail > 0 {
247 let first: String = clean[0].chars().take(avail).collect();
248 return format!("{head}{first}{suffix}");
249 }
250 return sanitize_flag(format!("{head}… and {n} more)"));
251 }
252 let avail = 200usize.saturating_sub(head.chars().count() + 1);
253 let first: String = clean[0].chars().take(avail).collect();
254 format!("{head}{first})")
255}
256
257fn sanitize_flag(flag: String) -> String {
258 let single_line = flag.lines().next().unwrap_or("").to_string();
259 if single_line.chars().count() > 200 {
260 single_line.chars().take(200).collect()
261 } else {
262 single_line
263 }
264}
265
266fn is_supported_ext(ext: &str) -> bool {
267 matches!(
268 ext,
269 "rs" | "py" | "js" | "jsx" | "mjs" | "ts" | "tsx" | "sh" | "bash" | "yml" | "yaml"
270 )
271}
272
273fn is_test_file(path: &str) -> bool {
274 let p = Path::new(path);
275 for comp in p.components() {
276 if let Component::Normal(os) = comp {
277 if let Some(s) = os.to_str() {
278 if matches!(
279 s,
280 "tests"
281 | "test"
282 | "__tests__"
283 | "benches"
284 | "examples"
285 | "fixtures"
286 | "testdata"
287 ) {
288 return true;
289 }
290 }
291 }
292 }
293 if let Some(file_name) = p.file_name().and_then(|s| s.to_str()) {
294 if file_name.starts_with("test_") || file_name == "conftest.py" {
295 return true;
296 }
297 if let (Some(stem), Some(ext)) = (
298 p.file_stem().and_then(|s| s.to_str()),
299 p.extension().and_then(|s| s.to_str()),
300 ) {
301 if !ext.is_empty()
302 && (stem.ends_with("_test") || stem.ends_with(".test") || stem.ends_with(".spec"))
303 {
304 return true;
305 }
306 }
307 }
308 false
309}
310
311fn is_comment(content: &str, ext: &str) -> bool {
312 let trimmed = content.trim_start();
313 if trimmed.starts_with("//") || trimmed.starts_with('*') || trimmed.starts_with("--") {
314 return true;
315 }
316 if trimmed.starts_with('#') {
317 if ext == "rs" && (trimmed.starts_with("#[") || trimmed.starts_with("#!")) {
318 return false;
319 }
320 return true;
321 }
322 false
323}
324
325fn match_line(content: &str, ext: &str, diff_lines: &[&str], idx: usize) -> Vec<&'static str> {
326 let mut out = Vec::new();
327 match ext {
328 "rs" => {
329 if content.contains(".unwrap_or(") {
330 out.push("unwrap_or");
331 }
332 if content.contains(".unwrap_or_default(") {
333 out.push("unwrap_or_default");
334 }
335 if content.contains(".unwrap_or_else(") {
336 out.push("unwrap_or_else");
337 }
338 }
339 "py" => {
340 if matches_py_except_pass(content, diff_lines, idx) {
341 out.push("except-pass");
342 }
343 if matches_py_get_default(content) {
344 out.push("get-default");
345 }
346 if matches_py_or_literal(content) {
347 out.push("or-literal");
348 }
349 }
350 "js" | "jsx" | "mjs" | "ts" | "tsx" => {
351 if content.contains("??") {
352 out.push("nullish");
353 }
354 if matches_js_or_literal(content) {
355 out.push("or-literal");
356 }
357 if matches_js_empty_catch(content) {
358 out.push("empty-catch");
359 }
360 }
361 "sh" | "bash" | "yml" | "yaml" => {
362 if content.contains("|| true") || content.contains("|| :") {
363 out.push("or-true");
364 }
365 if matches_shell_param_default(content) {
366 out.push("param-default");
367 }
368 }
369 _ => {}
370 }
371 out
372}
373
374fn matches_py_except_pass(content: &str, diff_lines: &[&str], idx: usize) -> bool {
375 let trimmed = content.trim_start();
376 let after_except = if let Some(rest) = trimmed.strip_prefix("except:") {
377 Some(rest)
378 } else if let Some(rest) = trimmed.strip_prefix("except Exception") {
379 if rest.starts_with(':') || rest.starts_with(char::is_whitespace) {
380 rest.split_once(':').map(|(_, r)| r)
381 } else {
382 None
383 }
384 } else if let Some(rest) = trimmed.strip_prefix("except BaseException") {
385 if rest.starts_with(':') || rest.starts_with(char::is_whitespace) {
386 rest.split_once(':').map(|(_, r)| r)
387 } else {
388 None
389 }
390 } else {
391 None
392 };
393
394 let Some(after_colon) = after_except else {
395 return false;
396 };
397
398 let inline = after_colon.split('#').next().unwrap_or(after_colon).trim();
399 if !inline.is_empty() {
400 return is_pass_continue_or_return(inline);
401 }
402
403 for &next_raw in &diff_lines[idx + 1..] {
404 if next_raw.starts_with("+++ ")
405 || next_raw.starts_with("@@ ")
406 || next_raw.starts_with("diff --git ")
407 || next_raw.starts_with(' ')
408 {
409 break;
410 }
411 if let Some(added) = next_raw.strip_prefix('+') {
412 let added_trim = added.trim();
413 if added_trim.is_empty() {
414 continue;
415 }
416 let stmt = added_trim.split('#').next().unwrap_or(added_trim).trim();
417 return is_pass_continue_or_return(stmt);
418 }
419 }
420 false
421}
422
423fn is_pass_continue_or_return(s: &str) -> bool {
424 s == "pass" || s == "continue" || s.starts_with("return")
425}
426
427fn matches_py_get_default(content: &str) -> bool {
428 let bytes = content.as_bytes();
429 for i in 0..bytes.len() {
430 let rest = &content[i..];
431 let args_start = if let Some(after) = rest.strip_prefix(".get(") {
432 Some(after)
433 } else if let Some(after) = rest.strip_prefix("getenv(") {
434 let prev_ok = i == 0 || {
435 let b = bytes[i - 1];
436 !b.is_ascii_alphanumeric() && b != b'_'
437 };
438 if prev_ok {
439 Some(after)
440 } else {
441 None
442 }
443 } else {
444 None
445 };
446 if let Some(after_open) = args_start {
447 if has_top_level_comma(after_open) {
448 return true;
449 }
450 }
451 }
452 false
453}
454
455fn has_top_level_comma(s: &str) -> bool {
456 let mut depth = 0usize;
457 let mut in_str: Option<char> = None;
458 let mut chars = s.chars();
459 while let Some(c) = chars.next() {
460 if let Some(q) = in_str {
461 if c == '\\' {
462 let _ = chars.next();
463 } else if c == q {
464 in_str = None;
465 }
466 continue;
467 }
468 match c {
469 '"' | '\'' => in_str = Some(c),
470 '(' | '[' | '{' => depth += 1,
471 ')' => {
472 if depth == 0 {
473 return false;
474 }
475 depth -= 1;
476 }
477 ']' | '}' => {
478 depth = depth.saturating_sub(1);
479 }
480 ',' if depth == 0 => return true,
481 _ => {}
482 }
483 }
484 false
485}
486
487fn matches_py_or_literal(content: &str) -> bool {
488 let mut search = content;
489 while let Some(pos) = search.find(" or ") {
490 let after = &search[pos + 4..];
491 let after_trimmed = after.trim_start_matches([' ', '\t']);
492 if let Some(c) = after_trimmed.chars().next() {
493 if matches!(c, '"' | '\'' | '[' | '{' | '(' | '0'..='9') {
494 return true;
495 }
496 }
497 search = after;
498 }
499 false
500}
501
502fn matches_js_or_literal(content: &str) -> bool {
503 let mut search = content;
504 while let Some(pos) = search.find("||") {
505 let after = &search[pos + 2..];
506 let after_trimmed = after.trim_start_matches([' ', '\t']);
507 if let Some(c) = after_trimmed.chars().next() {
508 if matches!(c, '"' | '\'' | '`' | '[' | '{' | '0'..='9') {
509 return true;
510 }
511 }
512 search = after;
513 }
514 false
515}
516
517fn matches_js_empty_catch(content: &str) -> bool {
518 let bytes = content.as_bytes();
519 for i in 0..bytes.len() {
520 let Some(after_catch) = content[i..].strip_prefix("catch") else {
521 continue;
522 };
523 let prev_ok = i == 0 || {
524 let b = bytes[i - 1];
525 !b.is_ascii_alphanumeric() && b != b'_' && b != b'$'
526 };
527 let next_ok = after_catch
528 .chars()
529 .next()
530 .map(|c| !c.is_ascii_alphanumeric() && c != '_' && c != '$')
531 .unwrap_or(false);
532 if !prev_ok || !next_ok {
533 continue;
534 }
535 let mut rest = after_catch.trim_start();
536 if let Some(after_open_paren) = rest.strip_prefix('(') {
537 let mut depth = 1usize;
538 let mut end_idx = None;
539 for (idx, ch) in after_open_paren.char_indices() {
540 match ch {
541 '(' => depth += 1,
542 ')' => {
543 depth -= 1;
544 if depth == 0 {
545 end_idx = Some(idx + 1);
546 break;
547 }
548 }
549 _ => {}
550 }
551 }
552 let Some(end) = end_idx else {
553 continue;
554 };
555 rest = after_open_paren[end..].trim_start();
556 }
557 if let Some(after_brace) = rest.strip_prefix('{') {
558 if after_brace == "}"
559 || after_brace == " }"
560 || after_brace.trim_start().starts_with('}')
561 {
562 return true;
563 }
564 }
565 }
566 false
567}
568
569fn matches_shell_param_default(content: &str) -> bool {
570 let mut search = content;
571 while let Some(pos) = search.find("${") {
572 let after = &search[pos + 2..];
573 let inside = after.split('}').next().unwrap_or(after);
574 if inside.contains(":-") {
575 return true;
576 }
577 search = after;
578 }
579 false
580}