-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathllm_response.rs
More file actions
1297 lines (1173 loc) · 46.9 KB
/
llm_response.rs
File metadata and controls
1297 lines (1173 loc) · 46.9 KB
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
use anyhow::Result;
use once_cell::sync::Lazy;
use regex::Regex;
use std::path::Path;
use crate::core;
pub fn parse_llm_response(
content: &str,
file_path: &Path,
) -> Result<Vec<core::comment::RawComment>> {
// Strategy 1: Structured JSON output (preferred contract)
let comments = parse_json_format(content, file_path);
if !comments.is_empty() {
return Ok(comments);
}
// Strategy 2: Primary parser (existing regex + code suggestion blocks)
let comments = parse_primary(content, file_path)?;
if !comments.is_empty() {
return Ok(comments);
}
// Strategy 3: Numbered list format (e.g. "1. **src/lib.rs:42** - Issue text")
let comments = parse_numbered_list(content, file_path);
if !comments.is_empty() {
return Ok(comments);
}
// Strategy 4: Markdown bullet format (e.g. "- Line 42: Issue text")
let comments = parse_markdown_bullets(content, file_path);
if !comments.is_empty() {
return Ok(comments);
}
// Strategy 5: file:line format (e.g. "src/lib.rs:42 - Issue text")
let comments = parse_file_line_format(content, file_path);
if !comments.is_empty() {
return Ok(comments);
}
// All strategies failed — return empty
Ok(Vec::new())
}
/// Strategy 1: Primary parser — `Line <num>: <text>` with code suggestion blocks.
fn parse_primary(content: &str, file_path: &Path) -> Result<Vec<core::comment::RawComment>> {
let mut comments = Vec::new();
static LINE_PATTERN: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"(?i)line\s+(\d+)((?:\s*(?:\[[^\]]+\]|\([^)]+\)))*)\s*:\s*(.+)").unwrap()
});
// State machine for tracking <<<ORIGINAL ... === ... >>>SUGGESTED blocks
let mut in_original = false;
let mut in_suggested = false;
let mut original_lines: Vec<String> = Vec::new();
let mut suggested_lines: Vec<String> = Vec::new();
for line in content.lines() {
let trimmed = line.trim();
// Handle code suggestion block markers
if trimmed == "<<<ORIGINAL" {
in_original = true;
in_suggested = false;
original_lines.clear();
suggested_lines.clear();
continue;
}
if in_original && trimmed == "===" {
in_original = false;
in_suggested = true;
continue;
}
if in_suggested && trimmed == ">>>SUGGESTED" {
in_suggested = false;
// Attach the code suggestion to the most recent comment
if let Some(last_comment) = comments.last_mut() {
let original_code = original_lines.join("\n");
let suggested_code = suggested_lines.join("\n");
let diff = build_suggestion_diff(&original_code, &suggested_code);
let last_comment: &mut core::comment::RawComment = last_comment;
last_comment.code_suggestion = Some(core::comment::CodeSuggestion {
original_code,
suggested_code,
explanation: last_comment
.suggestion
.clone()
.or_else(|| Some(last_comment.content.clone()))
.unwrap_or_default(),
diff,
});
}
original_lines.clear();
suggested_lines.clear();
continue;
}
// Accumulate lines inside the code suggestion block
if in_original {
original_lines.push(line.to_string());
continue;
}
if in_suggested {
suggested_lines.push(line.to_string());
continue;
}
// Normal line-by-line comment parsing
// Skip empty lines and common non-issue lines
if trimmed.is_empty()
|| trimmed.starts_with("```")
|| trimmed.starts_with('#')
|| trimmed.starts_with('<')
|| trimmed.contains("Here are")
|| trimmed.contains("Here is")
|| trimmed.contains("review of")
{
continue;
}
if let Some(caps) = LINE_PATTERN.captures(line) {
let Some(line_number) = capture_usize(&caps, 1)? else {
continue;
};
let metadata = caps.get(2).map(|value| value.as_str()).unwrap_or("");
let Some(comment_text) = capture_text(&caps, 3) else {
continue;
};
let comment_text = comment_text.trim();
let (inline_rule_id, comment_text) = extract_rule_id_from_text(comment_text);
let metadata_rule_id = extract_rule_id_from_metadata(metadata);
let rule_id = inline_rule_id.or(metadata_rule_id);
// Extract suggestion if present
let (content, suggestion) = if let Some(sugg_idx) = comment_text.rfind(". Consider ") {
(
comment_text[..sugg_idx + 1].to_string(),
Some(
comment_text[sugg_idx + 11..]
.trim_end_matches('.')
.to_string(),
),
)
} else if let Some(sugg_idx) = comment_text.rfind(". Use ") {
(
comment_text[..sugg_idx + 1].to_string(),
Some(
comment_text[sugg_idx + 6..]
.trim_end_matches('.')
.to_string(),
),
)
} else {
(comment_text.to_string(), None)
};
comments.push(core::comment::RawComment {
file_path: file_path.to_path_buf(),
line_number,
content,
rule_id,
suggestion,
severity: None,
category: None,
confidence: None,
fix_effort: None,
tags: Vec::new(),
code_suggestion: None,
});
}
}
Ok(comments)
}
/// Strategy 2: Numbered list format.
/// Matches patterns like:
/// 1. **src/lib.rs:42** - Missing null check
/// 2. src/lib.rs:15 - SQL injection
fn parse_numbered_list(content: &str, file_path: &Path) -> Vec<core::comment::RawComment> {
static NUMBERED_PATTERN: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"^\s*\d+\.\s*\*{0,2}(?:.*?):?(\d+)\*{0,2}\s*[-\u{2013}\u{2014}:]\s*(.+)")
.unwrap()
});
let mut comments = Vec::new();
for line in content.lines() {
if let Some(caps) = NUMBERED_PATTERN.captures(line) {
if let Some(line_number) = capture_usize_lossy(&caps, 1) {
let Some(text) = capture_text(&caps, 2) else {
continue;
};
let text = text.trim().to_string();
comments.push(make_raw_comment(file_path, line_number, text));
}
}
}
comments
}
/// Strategy 3: Markdown bullet format.
/// Matches patterns like:
/// - Line 42: Missing null check
/// * **Line 42**: Missing null check
fn parse_markdown_bullets(content: &str, file_path: &Path) -> Vec<core::comment::RawComment> {
static BULLET_PATTERN: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"^\s*[-*]\s*\*{0,2}[Ll]ine\s+(\d+)\*{0,2}\s*[:–—-]\s*(.+)").unwrap()
});
let mut comments = Vec::new();
for line in content.lines() {
if let Some(caps) = BULLET_PATTERN.captures(line) {
if let Some(line_number) = capture_usize_lossy(&caps, 1) {
let Some(text) = capture_text(&caps, 2) else {
continue;
};
let text = text.trim().to_string();
comments.push(make_raw_comment(file_path, line_number, text));
}
}
}
comments
}
/// Strategy 4: file:line format.
/// Matches patterns like:
/// src/lib.rs:42 - Missing null check
/// file.py:15: SQL injection vulnerability
fn parse_file_line_format(content: &str, file_path: &Path) -> Vec<core::comment::RawComment> {
static FILE_LINE_PATTERN: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"^\s*\*{0,2}(?:[\w./]+):(\d+)\*{0,2}\s*[-\u{2013}\u{2014}:]\s*(.+)").unwrap()
});
let mut comments = Vec::new();
for line in content.lines() {
if let Some(caps) = FILE_LINE_PATTERN.captures(line) {
if let Some(line_number) = capture_usize_lossy(&caps, 1) {
let Some(text) = capture_text(&caps, 2) else {
continue;
};
let text = text.trim().to_string();
comments.push(make_raw_comment(file_path, line_number, text));
}
}
}
comments
}
/// Strategy 1: Structured JSON extraction.
/// Tries to find and parse JSON arrays/objects from the response content.
/// Handles JSON in code blocks, bare arrays, and wrapped result objects.
fn parse_json_format(content: &str, file_path: &Path) -> Vec<core::comment::RawComment> {
let json_str = extract_json_from_code_block(content)
.or_else(|| find_json_array(content))
.or_else(|| find_json_object(content));
if let Some(json_str) = json_str {
for candidate in repair_json_candidates(&json_str) {
let Ok(value) = serde_json::from_str::<serde_json::Value>(&candidate) else {
continue;
};
let items = extract_structured_items(value);
let comments = items
.into_iter()
.filter_map(|item| structured_value_to_comment(file_path, &item))
.collect::<Vec<_>>();
if !comments.is_empty() {
return comments;
}
}
}
Vec::new()
}
/// Extract JSON array content from markdown code blocks (```json ... ``` or ``` ... ```).
fn extract_json_from_code_block(content: &str) -> Option<String> {
static CODE_BLOCK: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?s)```(?:json)?\s*\n(.*?)```").unwrap());
for caps in CODE_BLOCK.captures_iter(content) {
let Some(block) = capture_text(&caps, 1) else {
continue;
};
let block = block.trim();
if block.starts_with('[') || block.starts_with('{') {
return Some(block.to_string());
}
}
None
}
/// Find a bare JSON array in the content (not in a code block).
///
/// Uses bracket-depth counting to find the matching `]` for each `[`,
/// then validates with serde. This correctly handles multiple separate
/// arrays and nested brackets inside JSON strings.
fn find_json_array(content: &str) -> Option<String> {
find_balanced_json(content, '[', ']')
}
fn find_json_object(content: &str) -> Option<String> {
find_balanced_json(content, '{', '}')
}
fn find_balanced_json(content: &str, open: char, close: char) -> Option<String> {
for (start, _) in content.char_indices().filter(|&(_, ch)| ch == open) {
let mut depth = 0i32;
let mut in_string = false;
let mut escape_next = false;
for (offset, ch) in content[start..].char_indices() {
if escape_next {
escape_next = false;
continue;
}
if ch == '\\' && in_string {
escape_next = true;
continue;
}
if ch == '"' {
in_string = !in_string;
continue;
}
if !in_string {
if ch == open {
depth += 1;
} else if ch == close {
depth -= 1;
if depth == 0 {
let end = start + offset;
let candidate = &content[start..=end];
if serde_json::from_str::<serde_json::Value>(candidate).is_ok() {
return Some(candidate.to_string());
}
break;
}
}
}
}
}
None
}
fn repair_json_candidates(candidate: &str) -> Vec<String> {
static TRAILING_COMMAS: Lazy<Regex> = Lazy::new(|| Regex::new(r",\s*([}\]])").unwrap());
let trimmed = candidate.trim();
let mut candidates = vec![trimmed.to_string()];
let without_trailing_commas = TRAILING_COMMAS.replace_all(trimmed, "$1").to_string();
if without_trailing_commas != trimmed {
candidates.push(without_trailing_commas);
}
// When LLM echoes JSON with diff-style line prefixes (leading "+"), strip them (issue #28).
let without_diff_prefix: String = trimmed
.lines()
.map(|line| line.strip_prefix('+').map(str::trim).unwrap_or(line))
.collect::<Vec<_>>()
.join("\n");
let without_diff_prefix = without_diff_prefix.trim();
if without_diff_prefix != trimmed
&& (without_diff_prefix.starts_with('[') || without_diff_prefix.starts_with('{'))
{
candidates.push(without_diff_prefix.to_string());
}
candidates
}
fn extract_structured_items(value: serde_json::Value) -> Vec<serde_json::Value> {
if let Some(items) = value.as_array() {
return items.clone();
}
for key in ["findings", "comments", "issues", "results"] {
if let Some(items) = value.get(key).and_then(|value| value.as_array()) {
return items.clone();
}
}
Vec::new()
}
fn structured_value_to_comment(
file_path: &Path,
item: &serde_json::Value,
) -> Option<core::comment::RawComment> {
let line = json_line_number(item)?;
let content = json_issue_text(item);
if content.trim().is_empty() {
return None;
}
let suggestion = item
.get("suggestion")
.or_else(|| item.get("fix"))
.or_else(|| item.get("recommendation"))
.and_then(|value| value.as_str())
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty());
let tags = item
.get("tags")
.and_then(|value| value.as_array())
.map(|values| {
values
.iter()
.filter_map(|value| value.as_str().map(|value| value.to_string()))
.collect::<Vec<_>>()
})
.unwrap_or_default();
Some(core::comment::RawComment {
file_path: file_path.to_path_buf(),
line_number: line,
content,
rule_id: item
.get("rule_id")
.or_else(|| item.get("ruleId"))
.and_then(|value| value.as_str())
.map(|value| value.to_string()),
suggestion,
severity: item
.get("severity")
.and_then(|value| value.as_str())
.and_then(parse_severity_label),
category: item
.get("category")
.and_then(|value| value.as_str())
.and_then(parse_category_label),
confidence: item.get("confidence").and_then(json_confidence),
fix_effort: item
.get("fix_effort")
.or_else(|| item.get("fixEffort"))
.and_then(|value| value.as_str())
.and_then(parse_fix_effort_label),
tags,
code_suggestion: build_code_suggestion(item),
})
}
fn json_line_number(item: &serde_json::Value) -> Option<usize> {
let direct = item
.get("line")
.or_else(|| item.get("line_number"))
.or_else(|| item.get("lineNumber"))
.or_else(|| item.get("start_line"))
.or_else(|| item.get("startLine"));
if let Some(line) = direct.and_then(parse_usize_value) {
return Some(line);
}
item.get("location")
.and_then(|location| {
location
.get("line")
.or_else(|| location.get("start_line"))
.or_else(|| location.get("startLine"))
})
.and_then(parse_usize_value)
}
fn json_issue_text(item: &serde_json::Value) -> String {
let issue = item
.get("issue")
.or_else(|| item.get("description"))
.or_else(|| item.get("message"))
.or_else(|| item.get("content"))
.or_else(|| item.get("text"))
.or_else(|| item.get("title"))
.and_then(|value| value.as_str())
.unwrap_or("Issue found")
.trim()
.to_string();
let impact = item
.get("impact")
.and_then(|value| value.as_str())
.map(|value| value.trim())
.filter(|value| !value.is_empty());
match impact {
Some(impact) if !issue.contains(impact) => format!("{issue} Impact: {impact}"),
_ => issue,
}
}
fn parse_usize_value(value: &serde_json::Value) -> Option<usize> {
value.as_u64().map(|value| value as usize).or_else(|| {
value
.as_str()
.and_then(|value| value.trim().parse::<usize>().ok())
})
}
fn json_confidence(value: &serde_json::Value) -> Option<f32> {
if let Some(number) = value.as_f64() {
let confidence = number as f32;
return Some(if confidence > 1.0 {
(confidence / 100.0).clamp(0.0, 1.0)
} else {
confidence.clamp(0.0, 1.0)
});
}
value
.as_str()
.and_then(|value| value.parse::<f32>().ok())
.map(|confidence| {
if confidence > 1.0 {
(confidence / 100.0).clamp(0.0, 1.0)
} else {
confidence.clamp(0.0, 1.0)
}
})
}
fn parse_severity_label(label: &str) -> Option<core::comment::Severity> {
match label.trim().to_ascii_lowercase().as_str() {
"error" | "critical" => Some(core::comment::Severity::Error),
"warning" | "warn" | "medium" => Some(core::comment::Severity::Warning),
"info" | "low" => Some(core::comment::Severity::Info),
"suggestion" | "nit" => Some(core::comment::Severity::Suggestion),
_ => None,
}
}
fn parse_category_label(label: &str) -> Option<core::comment::Category> {
match label.trim().to_ascii_lowercase().as_str() {
"bug" | "correctness" => Some(core::comment::Category::Bug),
"security" => Some(core::comment::Category::Security),
"performance" => Some(core::comment::Category::Performance),
"style" => Some(core::comment::Category::Style),
"documentation" | "docs" => Some(core::comment::Category::Documentation),
"bestpractice" | "best_practice" | "best-practice" | "best practice" => {
Some(core::comment::Category::BestPractice)
}
"maintainability" => Some(core::comment::Category::Maintainability),
"testing" | "test" => Some(core::comment::Category::Testing),
"architecture" => Some(core::comment::Category::Architecture),
_ => None,
}
}
fn parse_fix_effort_label(label: &str) -> Option<core::comment::FixEffort> {
match label.trim().to_ascii_lowercase().as_str() {
"low" | "small" => Some(core::comment::FixEffort::Low),
"medium" | "moderate" => Some(core::comment::FixEffort::Medium),
"high" | "large" => Some(core::comment::FixEffort::High),
_ => None,
}
}
fn build_code_suggestion(item: &serde_json::Value) -> Option<core::comment::CodeSuggestion> {
let code_suggestion = item
.get("code_suggestion")
.or_else(|| item.get("codeSuggestion"));
let original_code = code_suggestion
.and_then(|value| {
value
.get("original_code")
.or_else(|| value.get("originalCode"))
})
.and_then(|value| value.as_str())
.or_else(|| item.get("original_code").and_then(|value| value.as_str()))?
.to_string();
let suggested_code = code_suggestion
.and_then(|value| {
value
.get("suggested_code")
.or_else(|| value.get("suggestedCode"))
})
.and_then(|value| value.as_str())
.or_else(|| item.get("suggested_code").and_then(|value| value.as_str()))?
.to_string();
let explanation = code_suggestion
.and_then(|value| value.get("explanation"))
.and_then(|value| value.as_str())
.or_else(|| item.get("fix").and_then(|value| value.as_str()))
.unwrap_or("Suggested code change")
.to_string();
Some(core::comment::CodeSuggestion {
diff: build_suggestion_diff(&original_code, &suggested_code),
original_code,
suggested_code,
explanation,
})
}
/// Helper to construct a RawComment with default fields.
fn make_raw_comment(
file_path: &Path,
line_number: usize,
content: String,
) -> core::comment::RawComment {
core::comment::RawComment {
file_path: file_path.to_path_buf(),
line_number,
content,
rule_id: None,
suggestion: None,
severity: None,
category: None,
confidence: None,
fix_effort: None,
tags: Vec::new(),
code_suggestion: None,
}
}
fn capture_text<'a>(captures: &'a regex::Captures<'_>, group: usize) -> Option<&'a str> {
captures.get(group).map(|value| value.as_str())
}
fn capture_usize(captures: ®ex::Captures<'_>, group: usize) -> Result<Option<usize>> {
capture_text(captures, group)
.map(|value| value.parse::<usize>())
.transpose()
.map_err(Into::into)
}
fn capture_usize_lossy(captures: ®ex::Captures<'_>, group: usize) -> Option<usize> {
capture_text(captures, group).and_then(|value| value.parse::<usize>().ok())
}
/// Build a unified-diff-style string from original and suggested code.
fn build_suggestion_diff(original: &str, suggested: &str) -> String {
let mut diff = String::new();
for line in original.lines() {
diff.push_str(&format!("- {line}\n"));
}
for line in suggested.lines() {
diff.push_str(&format!("+ {line}\n"));
}
// Remove trailing newline for consistency
if diff.ends_with('\n') {
diff.truncate(diff.len() - 1);
}
diff
}
pub fn extract_rule_id_from_text(text: &str) -> (Option<String>, String) {
static BRACKET_RULE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?i)\[\s*rule\s*:\s*([a-z0-9_.-]+)\s*\]").unwrap());
static PREFIX_RULE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?i)^rule[\s:#-]+([a-z0-9_.-]+)\s*[-:]\s*(.+)$").unwrap());
if let Some(caps) = BRACKET_RULE.captures(text) {
let rule_id = caps
.get(1)
.map(|m| m.as_str().trim().to_string())
.filter(|value| !value.is_empty());
let stripped = BRACKET_RULE.replace(text, "").trim().to_string();
return (rule_id, stripped);
}
if let Some(caps) = PREFIX_RULE.captures(text) {
let rule_id = caps
.get(1)
.map(|m| m.as_str().trim().to_string())
.filter(|value| !value.is_empty());
let stripped = caps
.get(2)
.map(|m| m.as_str().trim().to_string())
.unwrap_or_else(|| text.trim().to_string());
return (rule_id, stripped);
}
(None, text.trim().to_string())
}
pub fn extract_rule_id_from_metadata(metadata: &str) -> Option<String> {
static META_RULE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?i)rule\s*[:=]\s*([a-z0-9_.-]+)").unwrap());
META_RULE
.captures(metadata)
.and_then(|captures| {
captures
.get(1)
.map(|value| value.as_str().trim().to_string())
})
.filter(|value| !value.is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn parse_llm_response_extracts_basic_comment() {
let input = "Line 10: This is a basic issue.";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 1);
assert_eq!(comments[0].line_number, 10);
assert!(comments[0].content.contains("This is a basic issue"));
}
#[test]
fn parse_llm_response_prefers_structured_json_array() {
let input = r#"[
{
"line": 14,
"category": "security",
"issue": "SQL query interpolates user input",
"impact": "Attackers can inject arbitrary SQL",
"fix": "Use bound parameters",
"rule_id": "sec.sql.injection",
"severity": "warning",
"confidence": 0.92,
"fix_effort": "low",
"tags": ["security", "sql"],
"original_code": "db.query(sql)",
"suggested_code": "db.query(sql, [user_id])"
}
]"#;
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 1);
assert_eq!(comments[0].line_number, 14);
assert_eq!(comments[0].rule_id.as_deref(), Some("sec.sql.injection"));
assert_eq!(comments[0].severity, Some(core::comment::Severity::Warning));
assert!(comments[0]
.content
.contains("Attackers can inject arbitrary SQL"));
assert!(comments[0].code_suggestion.is_some());
}
#[test]
fn parse_llm_response_handles_json_object_wrapper_and_trailing_commas() {
let input = r#"```json
{
"findings": [
{
"location": { "line": 7 },
"description": "Missing authorization check",
"fix": "Validate ownership before returning the record",
"category": "security",
"severity": "error",
},
]
}
```"#;
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 1);
assert_eq!(comments[0].line_number, 7);
assert_eq!(comments[0].severity, Some(core::comment::Severity::Error));
assert_eq!(
comments[0].category,
Some(core::comment::Category::Security)
);
assert_eq!(
comments[0].suggestion.as_deref(),
Some("Validate ownership before returning the record")
);
}
#[test]
fn parse_llm_response_extracts_rule_from_line_metadata() {
let input = "Line 12 [rule:sec.sql.injection]: Security - Raw SQL with user input.";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 1);
assert_eq!(comments[0].line_number, 12);
assert_eq!(comments[0].rule_id.as_deref(), Some("sec.sql.injection"));
}
#[test]
fn parse_llm_response_extracts_suggestion_with_consider() {
let input = "Line 5: Missing null check. Consider adding a guard clause.";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 1);
assert_eq!(comments[0].content, "Missing null check.");
assert_eq!(
comments[0].suggestion.as_deref(),
Some("adding a guard clause")
);
}
#[test]
fn parse_llm_response_extracts_suggestion_with_use() {
let input = "Line 8: Deprecated API call. Use the new v2 API instead.";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 1);
assert_eq!(comments[0].content, "Deprecated API call.");
assert_eq!(
comments[0].suggestion.as_deref(),
Some("the new v2 API instead")
);
}
#[test]
fn parse_llm_response_skips_empty_and_noise_lines() {
// The parser skips lines starting with ```, #, <, and noise phrases,
// but does NOT track code-block state — content between ``` markers is still parsed.
let input = "\n\n# Review\nHere are the issues:\n```\nLine 3: Real issue.\n```\n";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 1);
assert_eq!(comments[0].line_number, 3);
// Verify noise-only input produces no comments
let noise = "\n\n# Summary\nHere are the results:\n";
let comments = parse_llm_response(noise, &file_path).unwrap();
assert_eq!(comments.len(), 0);
}
#[test]
fn parse_llm_response_handles_multiple_comments() {
let input = "Line 1: First issue.\nLine 20: Second issue.";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 2);
assert_eq!(comments[0].line_number, 1);
assert_eq!(comments[1].line_number, 20);
}
#[test]
fn extract_rule_id_from_text_bracket_syntax() {
let (rule_id, text) = extract_rule_id_from_text("Something [rule: sec.auth] is wrong");
assert_eq!(rule_id.as_deref(), Some("sec.auth"));
assert_eq!(text, "Something is wrong");
}
#[test]
fn extract_rule_id_from_text_prefix_syntax() {
let (rule_id, text) = extract_rule_id_from_text("rule: sec.auth - Missing auth check");
assert_eq!(rule_id.as_deref(), Some("sec.auth"));
assert_eq!(text, "Missing auth check");
}
#[test]
fn extract_rule_id_from_text_no_rule() {
let (rule_id, text) = extract_rule_id_from_text("Just a regular comment");
assert!(rule_id.is_none());
assert_eq!(text, "Just a regular comment");
}
#[test]
fn extract_rule_id_from_metadata_finds_rule() {
let rule = extract_rule_id_from_metadata(" [rule:sec.xss] (Warning)");
assert_eq!(rule.as_deref(), Some("sec.xss"));
}
#[test]
fn extract_rule_id_from_metadata_empty() {
let rule = extract_rule_id_from_metadata("(Warning)");
assert!(rule.is_none());
}
#[test]
fn parse_llm_response_extracts_code_suggestion() {
let input = r#"Line 42: Security - User input passed directly to SQL query. Use parameterized queries.
<<<ORIGINAL
query = "SELECT * FROM users WHERE id = " + user_id
===
query = "SELECT * FROM users WHERE id = ?"
cursor.execute(query, (user_id,))
>>>SUGGESTED"#;
let file_path = PathBuf::from("src/db.py");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 1);
let cs = comments[0].code_suggestion.as_ref().unwrap();
assert_eq!(
cs.original_code,
"query = \"SELECT * FROM users WHERE id = \" + user_id"
);
assert_eq!(
cs.suggested_code,
"query = \"SELECT * FROM users WHERE id = ?\"\ncursor.execute(query, (user_id,))"
);
assert!(cs
.diff
.contains("- query = \"SELECT * FROM users WHERE id = \" + user_id"));
assert!(cs
.diff
.contains("+ query = \"SELECT * FROM users WHERE id = ?\""));
}
#[test]
fn parse_llm_response_code_suggestion_attaches_to_correct_comment() {
let input = r#"Line 10: Bug - Missing null check.
Line 20: Security - SQL injection risk.
<<<ORIGINAL
db.query(user_input)
===
db.query(sanitize(user_input))
>>>SUGGESTED"#;
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 2);
// First comment should have no code suggestion
assert!(comments[0].code_suggestion.is_none());
// Second comment should have the code suggestion
let cs = comments[1].code_suggestion.as_ref().unwrap();
assert_eq!(cs.original_code, "db.query(user_input)");
assert_eq!(cs.suggested_code, "db.query(sanitize(user_input))");
}
#[test]
fn parse_llm_response_multiple_code_suggestions() {
let input = r#"Line 5: Bug - Off by one error.
<<<ORIGINAL
for i in 0..len + 1 {
===
for i in 0..len {
>>>SUGGESTED
Line 15: Performance - Unnecessary clone.
<<<ORIGINAL
let data = input.clone();
===
let data = &input;
>>>SUGGESTED"#;
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 2);
let cs0 = comments[0].code_suggestion.as_ref().unwrap();
assert_eq!(cs0.original_code, "for i in 0..len + 1 {");
assert_eq!(cs0.suggested_code, "for i in 0..len {");
let cs1 = comments[1].code_suggestion.as_ref().unwrap();
assert_eq!(cs1.original_code, "let data = input.clone();");
assert_eq!(cs1.suggested_code, "let data = &input;");
}
#[test]
fn parse_llm_response_no_code_suggestion_when_markers_absent() {
let input = "Line 7: Style - Variable name is unclear.";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 1);
assert!(comments[0].code_suggestion.is_none());
}
#[test]
fn build_suggestion_diff_formats_correctly() {
let diff = build_suggestion_diff("old_line", "new_line");
assert_eq!(diff, "- old_line\n+ new_line");
}
#[test]
fn build_suggestion_diff_multiline() {
let diff = build_suggestion_diff("line1\nline2", "line1\nline2_fixed\nline3");
assert_eq!(diff, "- line1\n- line2\n+ line1\n+ line2_fixed\n+ line3");
}
// === Fallback strategy tests ===
#[test]
fn parse_fallback_numbered_list() {
let input = "Here are the issues found:\n\n1. **src/lib.rs:42** - Missing null check on user input\n2. **src/lib.rs:15** - SQL injection vulnerability in query builder";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 2);
assert_eq!(comments[0].line_number, 42);
assert_eq!(comments[1].line_number, 15);
}
#[test]
fn parse_fallback_numbered_list_no_bold() {
let input = "1. src/lib.rs:42 - Missing null check\n2. src/lib.rs:15 - SQL injection";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 2);
}
#[test]
fn parse_fallback_markdown_bullets() {
let input =
"- Line 42: Missing null check on user input\n- Line 15: SQL injection vulnerability";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 2);
assert_eq!(comments[0].line_number, 42);
assert_eq!(comments[1].line_number, 15);
}
#[test]
fn parse_fallback_markdown_bullets_bold() {
let input = "* **Line 42**: Missing null check\n* **Line 15**: SQL injection";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 2);
}
#[test]
fn parse_fallback_file_line_format() {
let input = "src/lib.rs:42 - Missing null check\nsrc/lib.rs:15: SQL injection";
let file_path = PathBuf::from("src/lib.rs");
let comments = parse_llm_response(input, &file_path).unwrap();
assert_eq!(comments.len(), 2);
assert_eq!(comments[0].line_number, 42);
assert_eq!(comments[1].line_number, 15);