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
//! FST003: Comment syntax verification rule.
//!
//! Port of verify_comments.py's FStarCommentVerifier class.
//!
//! Detects common comment syntax issues in F* files:
//! 1. Unclosed (* comments that swallow code
//! 2. Premature *) that close comments too early
//! 3. Nested comment issues
//! 4. Common gotchas:
//! - (*) asterisk operator descriptions
//! - (-*) magic wand operator (separation logic)
//! - (char*), (void*) C-style pointer casts
//! - Any identifier*) pattern inside comments
//!
//! F* Comment Rules:
//! - (* text *) - regular block comment
//! - (** text *) - docstring
//! - Nested comments ARE allowed: (* outer (* inner *) outer *)
//! - DANGER: *) anywhere closes a comment level!
use lazy_static::lazy_static;
use regex::Regex;
use std::path::PathBuf;
use super::rules::{Diagnostic, DiagnosticSeverity, Range, Rule, RuleCode};
/// Convert byte offset to character column (1-indexed).
///
/// Regex matches return byte offsets, but LSP column positions must be
/// character offsets for correct behavior with multibyte UTF-8 characters
/// (e.g., "Martínez" where 'í' is 2 bytes).
fn byte_to_char_col(s: &str, byte_offset: usize) -> usize {
s[..byte_offset.min(s.len())].chars().count() + 1
}
lazy_static! {
// Pattern for (*) which F* parses as unit value followed by star
static ref UNIT_STAR_PATTERN: Regex = Regex::new(r"\(\*\)").unwrap();
// Pattern for (-*) magic wand operator from separation logic
static ref MAGIC_WAND_PATTERN: Regex = Regex::new(r"\(-\*\)").unwrap();
// Pattern for C-style pointer casts like (char*), (void*), (int*)
// Excludes F* operator definitions like (let*), (and*)
static ref C_POINTER_PATTERN: Regex = Regex::new(r"\(([a-zA-Z_][a-zA-Z0-9_]*)\s*\*\)").unwrap();
// F* operator names that look like pointer casts but aren't
static ref FSTAR_OPERATORS: &'static [&'static str] = &[
"let", "and", "or", "fun", "match", "if", "then", "else"
];
// Pattern for suspicious close: word character followed by *)
static ref SUSPICIOUS_CLOSE: Regex = Regex::new(r"[a-zA-Z0-9_]\*\)").unwrap();
// Pattern for empty comment blocks - requires whitespace to exclude (**)
// (**) is a standard F* proof annotation idiom (empty doc comment) used
// extensively in real-world F* code (e.g., 800+ occurrences in hacl-star)
// to mark proof steps. Only flag (* *), (* *), etc. with actual whitespace.
static ref EMPTY_COMMENT: Regex = Regex::new(r"\(\*\s+\*\)").unwrap();
// Pattern for *) inside string literals
static ref STRING_WITH_CLOSE: Regex = Regex::new(r#""[^"]*\*\)[^"]*""#).unwrap();
// Code keywords to detect "all commented" syndrome
static ref CODE_KEYWORDS: &'static [&'static str] = &[
"let ", "val ", "type ", "module ", "open ", "include "
];
// FIX: Move patterns that were compiled in hot loops to lazy_static
// Pattern to detect operator definition lookahead: (identifier*)
static ref OPERATOR_DEF_LOOKAHEAD: Regex = Regex::new(r"^\([a-zA-Z_][a-zA-Z0-9_]*\*\)").unwrap();
// Pattern to detect operator definition lookback: (identifier
static ref OPERATOR_DEF_LOOKBACK: Regex = Regex::new(r"\([a-zA-Z_][a-zA-Z0-9_]*$").unwrap();
// Pattern for suspicious close with context
static ref SUSPICIOUS_CLOSE_WITH_CONTEXT: Regex = Regex::new(r"\([a-zA-Z_][a-zA-Z0-9_]*\*\)$").unwrap();
}
/// Issue found during comment analysis.
#[derive(Debug, Clone)]
pub struct CommentIssue {
pub line: usize,
pub col: usize,
pub issue_type: CommentIssueType,
pub message: String,
pub severity: IssueSeverity,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommentIssueType {
ReadError,
UnclosedComment,
PrematureClose,
AsteriskOperatorPattern,
MagicWandPattern,
CPointerCastPattern,
SuspiciousClosePattern,
EmptyComment,
AllCommented,
CloseInString,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueSeverity {
Critical,
High,
Medium,
Low,
}
impl IssueSeverity {
fn to_diagnostic_severity(self) -> DiagnosticSeverity {
match self {
// FIX: Critical should map to Error, not Warning
// Critical issues like unclosed comments or premature closes
// can break the entire file parsing
IssueSeverity::Critical => DiagnosticSeverity::Error,
IssueSeverity::High => DiagnosticSeverity::Warning,
IssueSeverity::Medium => DiagnosticSeverity::Info,
IssueSeverity::Low => DiagnosticSeverity::Hint,
}
}
}
/// FST003: Comment syntax verification.
pub struct CommentRule;
impl CommentRule {
pub fn new() -> Self {
Self
}
/// Analyze content for comment issues.
pub fn analyze(&self, content: &str) -> Vec<CommentIssue> {
let mut issues = Vec::new();
let lines: Vec<&str> = content.lines().collect();
// Count comment delimiters and check balance
self.count_and_check_comments(content, &mut issues);
// Compute per-line comment depth so pattern checks know context
let line_depths = self.compute_line_comment_depths(content);
// Check for problematic patterns (only inside comments where they matter)
self.check_problematic_patterns(content, &lines, &line_depths, &mut issues);
issues
}
/// Compute comment nesting depth at the START of each line.
///
/// Returns a Vec where `result[i]` is the comment depth at the beginning
/// of line `i` (0-indexed). Depth 0 means the line starts in code context.
/// Depth > 0 means the line starts inside a nested block comment.
fn compute_line_comment_depths(&self, content: &str) -> Vec<i32> {
let chars: Vec<char> = content.chars().collect();
let n = chars.len();
let mut depths = Vec::new();
let mut i = 0;
let mut depth: i32 = 0;
let mut in_string = false;
let mut in_line_comment = false;
// Depth at the start of line 1
depths.push(depth);
while i < n {
let c = chars[i];
if c == '\n' {
in_line_comment = false;
i += 1;
// Record depth at start of next line
depths.push(depth);
continue;
}
if in_line_comment {
i += 1;
continue;
}
// String handling (mirrors count_and_check_comments logic)
if c == '"' && !in_string {
in_string = true;
i += 1;
continue;
} else if c == '"' && in_string {
let backslash_count = {
let mut count = 0;
let mut j = i;
while j > 0 {
j -= 1;
if chars[j] == '\\' {
count += 1;
} else {
break;
}
}
count
};
if backslash_count % 2 == 1 {
i += 1;
continue;
}
in_string = false;
i += 1;
continue;
} else if in_string {
i += 1;
continue;
}
// Line comment (only outside block comments)
if depth == 0 && c == '/' && i + 1 < n && chars[i + 1] == '/' {
in_line_comment = true;
i += 2;
continue;
}
// Comment open (*
if c == '(' && i + 1 < n && chars[i + 1] == '*' {
// Skip (*) pattern
if i + 2 < n && chars[i + 2] == ')' {
i += 3;
continue;
}
depth += 1;
i += 2;
continue;
}
// Comment close *)
if c == '*' && i + 1 < n && chars[i + 1] == ')' {
if depth > 0 {
depth -= 1;
}
i += 2;
continue;
}
i += 1;
}
depths
}
/// Count comment delimiters accounting for strings and line comments.
fn count_and_check_comments(&self, content: &str, issues: &mut Vec<CommentIssue>) {
let chars: Vec<char> = content.chars().collect();
let n = chars.len();
let mut i = 0;
let mut line = 1;
let mut col = 1;
let mut in_string = false;
let mut in_line_comment = false;
let mut depth: i32 = 0;
// Track where unclosed comments start
let mut unclosed_starts: Vec<(usize, usize)> = Vec::new();
while i < n {
let c = chars[i];
// Track line/column
if c == '\n' {
line += 1;
col = 1;
in_line_comment = false;
i += 1;
continue;
}
// Inside line comment - skip
if in_line_comment {
i += 1;
col += 1;
continue;
}
// String handling
if c == '"' && !in_string {
in_string = true;
i += 1;
col += 1;
continue;
} else if c == '"' && in_string {
// Check for escaped quote
// FIX: Count consecutive backslashes to handle "\\" correctly
// "path\\" followed by (* should NOT treat the (* as inside string
// because \\ is an escaped backslash, not an escape for the quote
let backslash_count = {
let mut count = 0;
let mut j = i;
while j > 0 {
j -= 1;
if chars[j] == '\\' {
count += 1;
} else {
break;
}
}
count
};
// Quote is escaped only if preceded by odd number of backslashes
if backslash_count % 2 == 1 {
i += 1;
col += 1;
continue;
}
in_string = false;
i += 1;
col += 1;
continue;
} else if in_string {
i += 1;
col += 1;
continue;
}
// Line comment - only when outside block comments
// In F* (like OCaml), // inside (* *) is just text
if depth == 0 && c == '/' && i + 1 < n && chars[i + 1] == '/' {
in_line_comment = true;
i += 2;
col += 2;
continue;
}
// Comment open (*
if c == '(' && i + 1 < n && chars[i + 1] == '*' {
// Check for (*) pattern
if i + 2 < n && chars[i + 2] == ')' {
// This is (*) - skip, will be caught by pattern check
i += 3;
col += 3;
continue;
}
// Check for operator definition like (let*), (and*)
let lookback: String = chars[i.saturating_sub(10)..i].iter().collect();
let lookback = lookback.trim();
if lookback.ends_with("let") || lookback.ends_with('=') {
// Look ahead for (identifier*)
let lookahead: String = chars[i..std::cmp::min(i + 15, n)].iter().collect();
// FIX: Use precompiled pattern instead of compiling in hot loop
if OPERATOR_DEF_LOOKAHEAD.is_match(&lookahead) {
// Operator definition, find end and skip
if let Some(end) = lookahead.find("*)") {
i += end + 2;
col += end + 2;
continue;
}
}
}
depth += 1;
unclosed_starts.push((line, col));
i += 2;
col += 2;
continue;
}
// Comment close *)
if c == '*' && i + 1 < n && chars[i + 1] == ')' {
// Skip if part of operator def
let lookback: String = chars[i.saturating_sub(15)..i].iter().collect();
// FIX: Use precompiled pattern instead of compiling in hot loop
if OPERATOR_DEF_LOOKBACK.is_match(&lookback) {
i += 2;
col += 2;
continue;
}
if depth > 0 {
depth -= 1;
unclosed_starts.pop();
} else {
// Closing without opening!
issues.push(CommentIssue {
line,
col,
issue_type: CommentIssueType::PrematureClose,
message: format!(
"*) closes comment but no comment is open (depth was {})",
depth
),
severity: IssueSeverity::Critical,
});
}
i += 2;
col += 2;
continue;
}
i += 1;
col += 1;
}
// Check for unclosed comments at end
for (start_line, start_col) in unclosed_starts {
issues.push(CommentIssue {
line: start_line,
col: start_col,
issue_type: CommentIssueType::UnclosedComment,
message: format!(
"(* opened at line {}:{} is never closed - swallowing {} lines!",
start_line,
start_col,
line - start_line
),
severity: IssueSeverity::Critical,
});
}
}
/// Check for common problematic patterns.
///
/// `line_depths` contains the comment nesting depth at the START of each
/// line (0-indexed). Patterns like `(*)`, `(-*)`, and C pointer casts are
/// only dangerous inside comments (where `*)` closes a comment level).
/// In code context (depth 0), these are valid F* syntax.
fn check_problematic_patterns(
&self,
content: &str,
lines: &[&str],
line_depths: &[i32],
issues: &mut Vec<CommentIssue>,
) {
// Pattern 1: (*) - only dangerous INSIDE comments where *) closes a level.
// In code, (*) is valid F* syntax (e.g., multiplication operator in parens).
for (line_num, line) in lines.iter().enumerate() {
// Only flag if line starts inside a comment
let depth = line_depths.get(line_num).copied().unwrap_or(0);
if depth == 0 {
// In code context: (*) is valid F* syntax, not a problem.
// However, if (* appears before (*) on this line, it could still
// be inside a comment that opened on this same line.
if let Some(m) = UNIT_STAR_PATTERN.find(line) {
let before = &line[..m.start()];
let opens_before = before.matches("(*").count();
let closes_before = before.matches("*)").count();
if opens_before <= closes_before {
continue; // Truly in code context, skip
}
} else {
continue;
}
}
let line_num = line_num + 1;
if let Some(m) = UNIT_STAR_PATTERN.find(line) {
issues.push(CommentIssue {
line: line_num,
col: byte_to_char_col(line, m.start()),
issue_type: CommentIssueType::AsteriskOperatorPattern,
message: "'(*)' found inside comment - this closes and reopens the comment! May be describing * operator. Use '(star)' instead.".to_string(),
severity: IssueSeverity::High,
});
}
}
// Pattern 2: (-*) - magic wand operator, only dangerous inside comments
for (line_num, line) in lines.iter().enumerate() {
let depth = line_depths.get(line_num).copied().unwrap_or(0);
if depth == 0 {
if let Some(m) = MAGIC_WAND_PATTERN.find(line) {
let before = &line[..m.start()];
let opens_before = before.matches("(*").count();
let closes_before = before.matches("*)").count();
if opens_before <= closes_before {
continue;
}
} else {
continue;
}
}
let line_num = line_num + 1;
if let Some(m) = MAGIC_WAND_PATTERN.find(line) {
issues.push(CommentIssue {
line: line_num,
col: byte_to_char_col(line, m.start()),
issue_type: CommentIssueType::MagicWandPattern,
message: "'(-*)' found inside comment - the '*)' closes a comment level! Use '(wand)' or '(dash-star)' instead.".to_string(),
severity: IssueSeverity::High,
});
}
}
// Pattern 3: C-style pointer casts like (char*), (void*)
// Only dangerous inside comments where *) closes a comment level.
for (line_num, line) in lines.iter().enumerate() {
let depth = line_depths.get(line_num).copied().unwrap_or(0);
let line_num = line_num + 1;
for caps in C_POINTER_PATTERN.captures_iter(line) {
if let Some(ident) = caps.get(1) {
let identifier = ident.as_str();
// Skip F* operator definitions
if FSTAR_OPERATORS
.iter()
.any(|op| *op == identifier)
{
continue;
}
// Skip if it looks like a let binding
let match_start = caps.get(0).unwrap().start();
let context_start = match_start.saturating_sub(10);
let context_before = &line[context_start..match_start];
let context_before = context_before.trim();
if context_before.ends_with("let") || context_before.ends_with('=') {
continue;
}
// Only flag inside comments
if depth == 0 {
let before = &line[..match_start];
let opens_before = before.matches("(*").count();
let closes_before = before.matches("*)").count();
if opens_before <= closes_before {
continue; // In code context, skip
}
}
issues.push(CommentIssue {
line: line_num,
col: byte_to_char_col(line, match_start),
issue_type: CommentIssueType::CPointerCastPattern,
message: format!(
"'{}' found inside comment - C pointer syntax with '*)' closes a comment level! Use 'type pointer' instead.",
caps.get(0).unwrap().as_str()
),
severity: IssueSeverity::High,
});
}
}
}
// Pattern 4: Suspicious close - word char followed by *)
for (line_num, line) in lines.iter().enumerate() {
let line_num = line_num + 1;
// Count (* and *) on this line - if balanced, skip
let line_opens = line.matches("(*").count();
let line_closes = line.matches("*)").count();
if line_opens == line_closes && line_opens > 0 {
continue;
}
for m in SUSPICIOUS_CLOSE.find_iter(line) {
// Skip if already caught by C_POINTER_PATTERN
let context_start = m.start().saturating_sub(15);
let context = &line[context_start..m.end()];
// FIX: Use precompiled pattern instead of compiling in hot loop
if SUSPICIOUS_CLOSE_WITH_CONTEXT.is_match(context) {
continue;
}
// Skip if there's a matching (* before this *) on same line
let before = &line[..m.start()];
let opens_before = before.matches("(*").count();
let closes_before = before.matches("*)").count();
if opens_before > closes_before {
continue;
}
// Check if it looks like it's inside a comment
if before.contains("(*")
|| before.trim().starts_with('*')
|| before.trim().is_empty()
{
issues.push(CommentIssue {
line: line_num,
col: byte_to_char_col(line, m.start()),
issue_type: CommentIssueType::SuspiciousClosePattern,
message: format!(
"'...{}' may close comment prematurely. Check if inside comment block.",
m.as_str()
),
severity: IssueSeverity::Medium,
});
}
}
}
// Pattern 5: Empty comment blocks
for (line_num, line) in lines.iter().enumerate() {
let line_num = line_num + 1;
if EMPTY_COMMENT.is_match(line) {
if let Some(m) = line.find("(*") {
issues.push(CommentIssue {
line: line_num,
col: byte_to_char_col(line, m),
issue_type: CommentIssueType::EmptyComment,
message: "Empty comment block (* *) - intentional?".to_string(),
severity: IssueSeverity::Low,
});
}
}
}
// Pattern 6: Very long runs without any code
if lines.len() > 100 {
let mut has_code = false;
let mut comment_depth: i32 = 0;
for line in lines {
// Track comment state (simplified) - use matches() for UTF-8 safety
let opens = line.matches("(*").count() as i32;
let closes = line.matches("*)").count() as i32;
comment_depth += opens - closes;
comment_depth = std::cmp::max(0, comment_depth);
// Only check for keywords outside comments
if comment_depth == 0 {
for kw in CODE_KEYWORDS.iter() {
if line.contains(kw) && !line.trim().starts_with("//") {
has_code = true;
break;
}
}
}
if has_code {
break;
}
}
if !has_code {
issues.push(CommentIssue {
line: 1,
col: 1,
issue_type: CommentIssueType::AllCommented,
message: format!(
"File has {} lines but no code keywords found outside comments - possibly all commented out!",
lines.len()
),
severity: IssueSeverity::Critical,
});
}
}
// Pattern 7: *) inside string literals
for (line_num, line) in lines.iter().enumerate() {
let line_num = line_num + 1;
if STRING_WITH_CLOSE.is_match(line) {
issues.push(CommentIssue {
line: line_num,
col: 1,
issue_type: CommentIssueType::CloseInString,
message: "String contains '*)', might cause issues if string parsing fails."
.to_string(),
severity: IssueSeverity::Medium,
});
}
}
}
}
impl Default for CommentRule {
fn default() -> Self {
Self::new()
}
}
impl Rule for CommentRule {
fn code(&self) -> RuleCode {
RuleCode::FST003
}
fn check(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
let issues = self.analyze(content);
issues
.into_iter()
.map(|issue| Diagnostic {
rule: RuleCode::FST003,
severity: issue.severity.to_diagnostic_severity(),
file: file.clone(),
range: Range::point(issue.line, issue.col),
message: issue.message,
fix: None,
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_unclosed_comment() {
let rule = CommentRule::new();
let content = "(* this comment is not closed\nlet x = 1";
let issues = rule.analyze(content);
assert!(issues
.iter()
.any(|i| i.issue_type == CommentIssueType::UnclosedComment));
}
#[test]
fn test_premature_close() {
let rule = CommentRule::new();
let content = "let x = 1 *)";
let issues = rule.analyze(content);
assert!(issues
.iter()
.any(|i| i.issue_type == CommentIssueType::PrematureClose));
}
#[test]
fn test_unit_star_pattern() {
let rule = CommentRule::new();
let content = "(* describing (*) operator *)";
let issues = rule.analyze(content);
assert!(issues
.iter()
.any(|i| i.issue_type == CommentIssueType::AsteriskOperatorPattern));
}
#[test]
fn test_nested_comments_ok() {
let rule = CommentRule::new();
let content = "(* outer (* inner *) still outer *)";
let issues = rule.analyze(content);
// Should not have unclosed/premature issues
assert!(!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::UnclosedComment));
assert!(!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::PrematureClose));
}
#[test]
fn test_string_not_comment() {
let rule = CommentRule::new();
let content = r#"let s = "(*) this is a string""#;
let issues = rule.analyze(content);
// Should not report asterisk pattern inside string as critical
assert!(!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::UnclosedComment));
}
#[test]
fn test_escaped_backslash_in_string() {
let rule = CommentRule::new();
// FIX: "path\\" followed by (* should detect the comment correctly
// because \\ is an escaped backslash, not an escape for the quote
let content = r#"let path = "C:\\Users\\" (* this is a real comment *)"#;
let issues = rule.analyze(content);
// Should NOT report unclosed comment
assert!(!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::UnclosedComment));
assert!(!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::PrematureClose));
}
#[test]
fn test_escaped_quote_in_string() {
let rule = CommentRule::new();
// Single backslash escapes the quote - string continues
let content = r#"let s = "escaped \" quote" (* comment *)"#;
let issues = rule.analyze(content);
assert!(!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::UnclosedComment));
}
#[test]
fn test_utf8_column_offset() {
let rule = CommentRule::new();
// Put (*) inside a comment so the pattern check fires.
// "Martínez" has 8 characters but 9 bytes ('í' is 2 bytes in UTF-8)
let content = "(* Martínez (*) *)";
let issues = rule.analyze(content);
let asterisk_issue = issues
.iter()
.find(|i| i.issue_type == CommentIssueType::AsteriskOperatorPattern)
.expect("Should find (*) pattern inside comment");
// "Martínez " inside the comment: "(* " = 3 chars, then "Martínez " = 9 chars
// (*) starts at character position 13 (12 chars before + 1 for 1-indexing)
// Byte offset of (*) = 3 + 9(Martínez) + 1(space) + 1(extra byte for í) = 14
// Character offset = 3 + 9 + 1 = 13, so col = 13 (char-based, 1-indexed)
assert_eq!(
asterisk_issue.col, 13,
"Column should be character offset, not byte offset"
);
}
#[test]
fn test_byte_to_char_col_helper() {
// Test the helper function directly
assert_eq!(byte_to_char_col("hello", 0), 1); // First char is col 1
assert_eq!(byte_to_char_col("hello", 5), 6); // After "hello" (5 chars + 1)
assert_eq!(byte_to_char_col("Martínez", 0), 1); // First char
// "Martí" = bytes 0-5 (6 bytes), 5 chars, so col = 6
assert_eq!(byte_to_char_col("Martínez", 6), 6); // After "Martí" (5 chars + 1)
// Full string "Martínez" = 9 bytes, 8 chars, so col = 9
assert_eq!(byte_to_char_col("Martínez", 9), 9); // After full string (8 chars + 1)
}
// =========================================================================
// FALSE POSITIVE REGRESSION TESTS
// =========================================================================
#[test]
fn test_double_star_proof_annotation_not_flagged() {
// (**) is a standard F* proof annotation idiom (empty doc comment).
// Used extensively in hacl-star (800+ occurrences) to mark proof steps.
// Must NOT be flagged as EmptyComment.
let rule = CommentRule::new();
let content = "(**) let blocks = n * l in\n(**) assert(x > 0);\n(**) Math.Lemmas.foo bar;";
let issues = rule.analyze(content);
assert!(
!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::EmptyComment),
"(**) proof annotation should not be flagged as empty comment"
);
}
#[test]
fn test_empty_comment_with_space_still_flagged() {
// (* *) with actual whitespace should still be flagged (Low severity)
let rule = CommentRule::new();
let content = "let x = 1\n(* *)\nlet y = 2";
let issues = rule.analyze(content);
assert!(
issues
.iter()
.any(|i| i.issue_type == CommentIssueType::EmptyComment),
"(* *) with whitespace should still be flagged"
);
}
#[test]
fn test_asterisk_in_code_not_flagged() {
// (*) in code is valid F* syntax: multiplication operator in parens
let rule = CommentRule::new();
let content = "let mul = (*) in mul 3 4";
let issues = rule.analyze(content);
assert!(
!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::AsteriskOperatorPattern),
"(*) in code context should not be flagged - it's valid F* multiplication"
);
}
#[test]
fn test_asterisk_inside_comment_flagged() {
// (*) inside a comment is dangerous - it closes and reopens
let rule = CommentRule::new();
let content = "(* the (*) operator is multiplication *)";
let issues = rule.analyze(content);
assert!(
issues
.iter()
.any(|i| i.issue_type == CommentIssueType::AsteriskOperatorPattern),
"(*) inside a comment should be flagged"
);
}
#[test]
fn test_asterisk_inside_multiline_comment_flagged() {
// (*) on a line that starts inside a multi-line comment
let rule = CommentRule::new();
let content = "(* this is a multi-line comment\n describing the (*) operator\n*)";
let issues = rule.analyze(content);
assert!(
issues
.iter()
.any(|i| i.issue_type == CommentIssueType::AsteriskOperatorPattern),
"(*) on a line inside multi-line comment should be flagged"
);
}
#[test]
fn test_magic_wand_in_code_not_flagged() {
// (-*) in code context should not be flagged
let rule = CommentRule::new();
let content = "let wand = (-*) in wand p q";
let issues = rule.analyze(content);
assert!(
!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::MagicWandPattern),
"(-*) in code context should not be flagged"
);
}
#[test]
fn test_magic_wand_inside_comment_flagged() {
// (-*) inside a comment is dangerous
let rule = CommentRule::new();
let content = "(* the (-*) magic wand operator *)";
let issues = rule.analyze(content);
assert!(
issues
.iter()
.any(|i| i.issue_type == CommentIssueType::MagicWandPattern),
"(-*) inside a comment should be flagged"
);
}
#[test]
fn test_let_star_operator_not_flagged() {
// let (let*) = ... is a valid F* operator definition
let rule = CommentRule::new();
let content = "let (let*) (#a:Type) (#b:Type) (m:st a) (f:a -> st b) : st b = f m";
let issues = rule.analyze(content);
assert!(
!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::UnclosedComment
|| i.issue_type == CommentIssueType::PrematureClose),
"let (let*) operator definition should not cause nesting errors"
);
}
#[test]
fn test_c_pointer_in_code_not_flagged() {
// (char*) in code context should not be flagged
let rule = CommentRule::new();
let content = "let cast = (char*) ptr";
let issues = rule.analyze(content);
assert!(
!issues
.iter()
.any(|i| i.issue_type == CommentIssueType::CPointerCastPattern),
"(char*) in code context should not be flagged"
);
}
#[test]
fn test_c_pointer_inside_comment_flagged() {
// (char*) inside a comment is dangerous
let rule = CommentRule::new();
let content = "(* cast to (char*) for C interop *)";
let issues = rule.analyze(content);
assert!(
issues
.iter()
.any(|i| i.issue_type == CommentIssueType::CPointerCastPattern),
"(char*) inside a comment should be flagged"
);
}
#[test]
fn test_line_depth_tracking() {
// Verify compute_line_comment_depths works correctly
let rule = CommentRule::new();
let content = "code line\n(* start comment\n inside comment\n*)\nback to code";
let depths = rule.compute_line_comment_depths(content);
assert_eq!(depths[0], 0, "Line 1 should be depth 0 (code)");
assert_eq!(depths[1], 0, "Line 2 starts at depth 0 (comment opens on this line)");
assert_eq!(depths[2], 1, "Line 3 should be depth 1 (inside comment)");
assert_eq!(depths[3], 1, "Line 4 starts at depth 1 (close is on this line)");
assert_eq!(depths[4], 0, "Line 5 should be depth 0 (back to code)");
}
#[test]
fn test_nested_depth_tracking() {
let rule = CommentRule::new();
let content = "(* outer\n(* inner\n*)\nstill outer\n*)";
let depths = rule.compute_line_comment_depths(content);
assert_eq!(depths[0], 0, "Line 1 starts at depth 0");
assert_eq!(depths[1], 1, "Line 2 starts at depth 1");
assert_eq!(depths[2], 2, "Line 3 starts at depth 2 (nested)");
assert_eq!(depths[3], 1, "Line 4 back to depth 1");
assert_eq!(depths[4], 1, "Line 5 starts at depth 1");
}
}