brrr-lint 0.1.0

A fast linter and language server for F* (FStar) with autofix capabilities
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
//! FST012: Refinement type simplifier.
//!
//! Detects refinement types that can be simplified or are problematic:
//!
//! 1. `x:nat{x >= 0}` - redundant, `nat` already implies `>= 0` (SAFE AUTO-FIX)
//! 2. `x:int{x >= 0}` - can be simplified to `nat` (SUGGESTION ONLY - type change!)
//! 3. `x:int{x > 0}` - can be simplified to `pos` (SUGGESTION ONLY - type change!)
//! 4. `x:pos{x > 0}` - redundant, `pos` already implies `> 0` (SAFE AUTO-FIX)
//! 5. `x:T{True}` - useless refinement (SAFE AUTO-FIX)
//! 6. `x:int{x > 5 /\ x < 3}` - unsatisfiable refinement (ERROR, no fix)
//!
//! ## Semantic Equivalence and Safety
//!
//! This rule is CONSERVATIVE by design. Type simplifications (int->nat, int->pos)
//! are marked as UNSAFE for auto-fix because:
//! - Changing types can break type inference in dependent code
//! - The verbose form might be intentional for documentation/clarity
//! - F* type unification may behave differently with aliased types
//!
//! Redundant refinement removals (nat{x >= 0} -> nat) are SAFE because:
//! - The base type remains unchanged
//! - The removed constraint is already implied by the type
//! - No semantic change occurs
//!
//! ## Semantic Equivalence Validation
//!
//! We use EXACT STRING MATCHING for refinement bodies, NOT substring matching:
//! - `x >= 0` matches ONLY the exact constraint (after whitespace trimming)
//! - `x >= 0 /\ x < 100` does NOT match (compound constraint, not equivalent to nat)
//! - `0 <= x` does NOT match (different syntactic form, even if semantically equal)
//!
//! This prevents false positives on compound refinements where simplification
//! would lose constraints.
//!
//! ## Guards Against False Positives
//!
//! - Matches inside string literals (`"..."`) are skipped.
//! - Matches inside inline block comments (`(* ... *)`) are skipped.
//! - Unsatisfiable detection only fires inside refinement braces.
//! - The old `nat{x < pow2 32}` -> `UInt32.t` suggestion was REMOVED because
//!   `nat` and machine integers have fundamentally different semantics in F*.

use lazy_static::lazy_static;
use regex::Regex;
use std::path::PathBuf;

use super::rules::{Diagnostic, DiagnosticSeverity, Edit, Fix, FixConfidence, FixSafetyLevel, Range, Rule, RuleCode};

lazy_static! {
    /// General refinement pattern: captures (var_name, base_type, refinement_body)
    static ref REFINEMENT: Regex = Regex::new(
        r"(\w+)\s*:\s*(\w+)\s*\{([^}]+)\}"
    ).unwrap();

    /// Useless: T{True} refinement
    static ref TRUE_REFINEMENT: Regex = Regex::new(
        r"(\w+)\s*:\s*(\w+)\s*\{\s*True\s*\}"
    ).unwrap();

    /// Unsatisfiable: var > N /\ var < M inside a refinement
    static ref UNSAT_GT_LT: Regex = Regex::new(
        r"(\w+)\s*>\s*(\d+)\s*/\\\s*(\w+)\s*<\s*(\d+)"
    ).unwrap();

    /// Unsatisfiable: var < N /\ var > M inside a refinement (reversed order)
    static ref UNSAT_LT_GT: Regex = Regex::new(
        r"(\w+)\s*<\s*(\d+)\s*/\\\s*(\w+)\s*>\s*(\d+)"
    ).unwrap();
}

/// Convert byte offset to character column (1-indexed).
///
/// This is necessary because regex matches return byte offsets, but LSP
/// and editor columns are character-based. For ASCII this is the same,
/// but for UTF-8 multi-byte characters they differ.
fn byte_to_char_col(s: &str, byte_offset: usize) -> usize {
    s[..byte_offset.min(s.len())].chars().count() + 1
}

/// Check if a byte offset falls inside a string literal or inline block comment.
///
/// Scans the line left-to-right tracking whether we are inside `"..."` or `(* ... *)`.
/// Returns `true` if the given byte position is inside either construct, meaning
/// any regex match at that position should be suppressed as a false positive.
fn is_inside_string_or_comment(line: &str, byte_offset: usize) -> bool {
    let bytes = line.as_bytes();
    let mut in_string = false;
    let mut in_block_comment = false;
    let mut i = 0;

    while i < bytes.len() && i < byte_offset {
        if in_string {
            if bytes[i] == b'\\' {
                // Skip escaped character inside string
                i += 2;
                continue;
            }
            if bytes[i] == b'"' {
                in_string = false;
            }
        } else if in_block_comment {
            if bytes[i] == b'*' && i + 1 < bytes.len() && bytes[i + 1] == b')' {
                in_block_comment = false;
                i += 2;
                continue;
            }
        } else {
            if bytes[i] == b'"' {
                in_string = true;
            } else if bytes[i] == b'(' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
                in_block_comment = true;
                i += 2;
                continue;
            }
        }
        i += 1;
    }

    in_string || in_block_comment
}

/// FST012: Refinement Type Simplifier
///
/// Analyzes F* refinement types and suggests simplifications or
/// detects unsatisfiable constraints.
pub struct RefinementSimplifierRule;

impl RefinementSimplifierRule {
    pub fn new() -> Self {
        Self
    }

    /// Check if refinement body is just "var >= 0"
    fn is_gte_zero_refinement(var_name: &str, body: &str) -> bool {
        let trimmed = body.trim();
        let pattern = format!("{} >= 0", var_name);
        trimmed == pattern || trimmed == format!("{}>=0", var_name)
    }

    /// Check if refinement body is just "var > 0"
    fn is_gt_zero_refinement(var_name: &str, body: &str) -> bool {
        let trimmed = body.trim();
        let pattern = format!("{} > 0", var_name);
        trimmed == pattern || trimmed == format!("{}>0", var_name)
    }

    /// Check for redundant nat{x >= 0} refinements.
    fn check_redundant_nat(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for (line_idx, line) in content.lines().enumerate() {
            let line_num = line_idx + 1;

            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") {
                continue;
            }

            for caps in REFINEMENT.captures_iter(line) {
                let full_match = caps.get(0).unwrap();
                if is_inside_string_or_comment(line, full_match.start()) {
                    continue;
                }

                let var_name = caps.get(1).map(|m| m.as_str()).unwrap_or("");
                let base_type = caps.get(2).map(|m| m.as_str()).unwrap_or("");
                let body = caps.get(3).map(|m| m.as_str()).unwrap_or("");

                if base_type == "nat" && Self::is_gte_zero_refinement(var_name, body) {
                    let start_col = byte_to_char_col(line, full_match.start());
                    let end_col = byte_to_char_col(line, full_match.end());

                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST012,
                        severity: DiagnosticSeverity::Warning,
                        file: file.clone(),
                        range: Range::new(line_num, start_col, line_num, end_col),
                        message: format!(
                            "Redundant refinement: `nat` is defined as `x:int{{x >= 0}}`, \
                             so `{} >= 0` adds no constraint. Use `{}:nat` instead.",
                            var_name, var_name
                        ),
                        // SAFE: Removing redundant constraint, type stays the same.
                        // No semantic change - nat already implies >= 0.
                        fix: Some(Fix::safe(
                            "Remove redundant refinement (safe: type unchanged)",
                            vec![Edit {
                                file: file.clone(),
                                range: Range::new(line_num, start_col, line_num, end_col),
                                new_text: format!("{}:nat", var_name),
                            }],
                        )
                        .with_safety_level(FixSafetyLevel::Safe)  // Type unchanged
                        .with_reversible(true)  // Can add refinement back
                        .with_requires_review(false)),  // Safe transformation
                    });
                }
            }
        }

        diagnostics
    }

    /// Check for redundant pos{x > 0} refinements.
    fn check_redundant_pos(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for (line_idx, line) in content.lines().enumerate() {
            let line_num = line_idx + 1;

            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") {
                continue;
            }

            for caps in REFINEMENT.captures_iter(line) {
                let full_match = caps.get(0).unwrap();
                if is_inside_string_or_comment(line, full_match.start()) {
                    continue;
                }

                let var_name = caps.get(1).map(|m| m.as_str()).unwrap_or("");
                let base_type = caps.get(2).map(|m| m.as_str()).unwrap_or("");
                let body = caps.get(3).map(|m| m.as_str()).unwrap_or("");

                if base_type == "pos" && Self::is_gt_zero_refinement(var_name, body) {
                    let start_col = byte_to_char_col(line, full_match.start());
                    let end_col = byte_to_char_col(line, full_match.end());

                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST012,
                        severity: DiagnosticSeverity::Warning,
                        file: file.clone(),
                        range: Range::new(line_num, start_col, line_num, end_col),
                        message: format!(
                            "Redundant refinement: `pos` is defined as `x:int{{x > 0}}`, \
                             so `{} > 0` adds no constraint. Use `{}:pos` instead.",
                            var_name, var_name
                        ),
                        // SAFE: Removing redundant constraint, type stays the same.
                        // No semantic change - pos already implies > 0.
                        fix: Some(Fix::safe(
                            "Remove redundant refinement (safe: type unchanged)",
                            vec![Edit {
                                file: file.clone(),
                                range: Range::new(line_num, start_col, line_num, end_col),
                                new_text: format!("{}:pos", var_name),
                            }],
                        )
                        .with_safety_level(FixSafetyLevel::Safe)  // Type unchanged
                        .with_reversible(true)  // Can add refinement back
                        .with_requires_review(false)),  // Safe transformation
                    });
                }
            }
        }

        diagnostics
    }

    /// Check for useless {True} refinements.
    fn check_true_refinement(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for (line_idx, line) in content.lines().enumerate() {
            let line_num = line_idx + 1;

            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") {
                continue;
            }

            // Use captures_iter to catch ALL occurrences on a line, not just the first.
            for caps in TRUE_REFINEMENT.captures_iter(line) {
                let full_match = caps.get(0).unwrap();
                if is_inside_string_or_comment(line, full_match.start()) {
                    continue;
                }

                let var_name = caps.get(1).map(|m| m.as_str()).unwrap_or("x");
                let type_name = caps.get(2).map(|m| m.as_str()).unwrap_or("T");
                let start_col = byte_to_char_col(line, full_match.start());
                let end_col = byte_to_char_col(line, full_match.end());

                diagnostics.push(Diagnostic {
                    rule: RuleCode::FST012,
                    severity: DiagnosticSeverity::Warning,
                    file: file.clone(),
                    range: Range::new(line_num, start_col, line_num, end_col),
                    message: format!(
                        "Useless refinement: `{{True}}` is always satisfied, adding no constraint. \
                         Use `{}:{}` instead.",
                        var_name, type_name
                    ),
                    // SAFE: True is always satisfied, removing it changes nothing.
                    fix: Some(Fix::safe(
                        "Remove useless {True} refinement (safe: True is tautology)",
                        vec![Edit {
                            file: file.clone(),
                            range: Range::new(line_num, start_col, line_num, end_col),
                            new_text: format!("{}:{}", var_name, type_name),
                        }],
                    )
                    .with_safety_level(FixSafetyLevel::Safe)  // True is tautology
                    .with_reversible(true)  // Can add {True} back
                    .with_requires_review(false)),  // Safe transformation
                });
            }
        }

        diagnostics
    }

    /// Check for int{x >= 0} that could be nat.
    fn check_int_to_nat(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for (line_idx, line) in content.lines().enumerate() {
            let line_num = line_idx + 1;

            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") {
                continue;
            }

            for caps in REFINEMENT.captures_iter(line) {
                let full_match = caps.get(0).unwrap();
                if is_inside_string_or_comment(line, full_match.start()) {
                    continue;
                }

                let var_name = caps.get(1).map(|m| m.as_str()).unwrap_or("");
                let base_type = caps.get(2).map(|m| m.as_str()).unwrap_or("");
                let body = caps.get(3).map(|m| m.as_str()).unwrap_or("");

                if base_type == "int" && Self::is_gte_zero_refinement(var_name, body) {
                    let start_col = byte_to_char_col(line, full_match.start());
                    let end_col = byte_to_char_col(line, full_match.end());

                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST012,
                        severity: DiagnosticSeverity::Info,
                        file: file.clone(),
                        range: Range::new(line_num, start_col, line_num, end_col),
                        message: format!(
                            "Consider using `nat` instead of `int{{{} >= 0}}`. \
                             The `nat` type is defined as `x:int{{x >= 0}}` in Prims. \
                             NOTE: This changes the type, which may affect type inference. \
                             Keep the verbose form if it aids documentation or if dependent \
                             code expects the explicit refinement.",
                            var_name
                        ),
                        // UNSAFE: This CHANGES THE TYPE from int{...} to nat.
                        // While semantically equivalent, this can affect:
                        // - Type inference in dependent code
                        // - Code that pattern-matches on the type
                        // - Documentation intent (verbose form may be clearer)
                        fix: Some(Fix::unsafe_fix(
                            "Use nat instead of int{x >= 0} (CAUTION: changes type)",
                            vec![Edit {
                                file: file.clone(),
                                range: Range::new(line_num, start_col, line_num, end_col),
                                new_text: format!("{}:nat", var_name),
                            }],
                            FixConfidence::Low,
                            "Type change from int{...} to nat may affect type inference",
                        )
                        .with_safety_level(FixSafetyLevel::Caution)  // Type changes require review
                        .with_reversible(true)  // Can change back to int{x >= 0}
                        .with_requires_review(true)),  // Always review type changes
                    });
                }
            }
        }

        diagnostics
    }

    /// Check for int{x > 0} that could be pos.
    fn check_int_to_pos(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for (line_idx, line) in content.lines().enumerate() {
            let line_num = line_idx + 1;

            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") {
                continue;
            }

            for caps in REFINEMENT.captures_iter(line) {
                let full_match = caps.get(0).unwrap();
                if is_inside_string_or_comment(line, full_match.start()) {
                    continue;
                }

                let var_name = caps.get(1).map(|m| m.as_str()).unwrap_or("");
                let base_type = caps.get(2).map(|m| m.as_str()).unwrap_or("");
                let body = caps.get(3).map(|m| m.as_str()).unwrap_or("");

                if base_type == "int" && Self::is_gt_zero_refinement(var_name, body) {
                    let start_col = byte_to_char_col(line, full_match.start());
                    let end_col = byte_to_char_col(line, full_match.end());

                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST012,
                        severity: DiagnosticSeverity::Info,
                        file: file.clone(),
                        range: Range::new(line_num, start_col, line_num, end_col),
                        message: format!(
                            "Consider using `pos` instead of `int{{{} > 0}}`. \
                             The `pos` type is defined as `x:int{{x > 0}}` in Prims. \
                             NOTE: This changes the type, which may affect type inference. \
                             Keep the verbose form if it aids documentation or if dependent \
                             code expects the explicit refinement.",
                            var_name
                        ),
                        // UNSAFE: This CHANGES THE TYPE from int{...} to pos.
                        // While semantically equivalent, this can affect:
                        // - Type inference in dependent code
                        // - Code that pattern-matches on the type
                        // - Documentation intent (verbose form may be clearer)
                        fix: Some(Fix::unsafe_fix(
                            "Use pos instead of int{x > 0} (CAUTION: changes type)",
                            vec![Edit {
                                file: file.clone(),
                                range: Range::new(line_num, start_col, line_num, end_col),
                                new_text: format!("{}:pos", var_name),
                            }],
                            FixConfidence::Low,
                            "Type change from int{...} to pos may affect type inference",
                        )
                        .with_safety_level(FixSafetyLevel::Caution)  // Type changes require review
                        .with_reversible(true)  // Can change back to int{x > 0}
                        .with_requires_review(true)),  // Always review type changes
                    });
                }
            }
        }

        diagnostics
    }

    /// Check for unsatisfiable refinements like x > 5 /\ x < 3.
    ///
    /// Only fires when the contradictory pattern is found inside a refinement
    /// brace `{...}`, preventing false positives on bare assertions or comments.
    /// Uses pre-compiled regexes from `lazy_static!`.
    fn check_unsatisfiable(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for (line_idx, line) in content.lines().enumerate() {
            let line_num = line_idx + 1;

            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") {
                continue;
            }

            // Only search inside refinement bodies to avoid false positives
            // on assertions like `assert (x > 5 /\ x < 3)`.
            for ref_caps in REFINEMENT.captures_iter(line) {
                let ref_match = ref_caps.get(0).unwrap();
                if is_inside_string_or_comment(line, ref_match.start()) {
                    continue;
                }
                let body = ref_caps.get(3).map(|m| m.as_str()).unwrap_or("");
                let body_start_byte = ref_caps.get(3).unwrap().start();

                // Check "var > N /\ var < M" inside the refinement body
                for caps in UNSAT_GT_LT.captures_iter(body) {
                    let var1 = caps.get(1).map(|m| m.as_str()).unwrap_or("");
                    let var2 = caps.get(3).map(|m| m.as_str()).unwrap_or("");
                    if var1 != var2 {
                        continue;
                    }
                    if let (Ok(lower), Ok(upper)) = (
                        caps.get(2).unwrap().as_str().parse::<i64>(),
                        caps.get(4).unwrap().as_str().parse::<i64>(),
                    ) {
                        if lower >= upper {
                            let inner = caps.get(0).unwrap();
                            let start_col =
                                byte_to_char_col(line, body_start_byte + inner.start());
                            let end_col =
                                byte_to_char_col(line, body_start_byte + inner.end());

                            diagnostics.push(Diagnostic {
                                rule: RuleCode::FST012,
                                severity: DiagnosticSeverity::Error,
                                file: file.clone(),
                                range: Range::new(line_num, start_col, line_num, end_col),
                                message: format!(
                                    "UNSATISFIABLE REFINEMENT: No value can satisfy \
                                     `{} > {} /\\ {} < {}`. \
                                     This constraint is logically impossible.",
                                    var1, lower, var2, upper
                                ),
                                fix: None,
                            });
                        }
                    }
                }

                // Check "var < N /\ var > M" (reversed order) inside the body
                for caps in UNSAT_LT_GT.captures_iter(body) {
                    let var1 = caps.get(1).map(|m| m.as_str()).unwrap_or("");
                    let var2 = caps.get(3).map(|m| m.as_str()).unwrap_or("");
                    if var1 != var2 {
                        continue;
                    }
                    if let (Ok(upper), Ok(lower)) = (
                        caps.get(2).unwrap().as_str().parse::<i64>(),
                        caps.get(4).unwrap().as_str().parse::<i64>(),
                    ) {
                        if lower >= upper {
                            let inner = caps.get(0).unwrap();
                            let start_col =
                                byte_to_char_col(line, body_start_byte + inner.start());
                            let end_col =
                                byte_to_char_col(line, body_start_byte + inner.end());

                            diagnostics.push(Diagnostic {
                                rule: RuleCode::FST012,
                                severity: DiagnosticSeverity::Error,
                                file: file.clone(),
                                range: Range::new(line_num, start_col, line_num, end_col),
                                message: format!(
                                    "UNSATISFIABLE REFINEMENT: No value can satisfy \
                                     `{} < {} /\\ {} > {}`. \
                                     This constraint is logically impossible.",
                                    var1, upper, var2, lower
                                ),
                                fix: None,
                            });
                        }
                    }
                }
            }
        }

        diagnostics
    }
}

impl Default for RefinementSimplifierRule {
    fn default() -> Self {
        Self::new()
    }
}

impl Rule for RefinementSimplifierRule {
    fn code(&self) -> RuleCode {
        RuleCode::FST012
    }

    fn check(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        diagnostics.extend(self.check_redundant_nat(file, content));
        diagnostics.extend(self.check_redundant_pos(file, content));
        diagnostics.extend(self.check_true_refinement(file, content));
        diagnostics.extend(self.check_int_to_nat(file, content));
        diagnostics.extend(self.check_int_to_pos(file, content));
        diagnostics.extend(self.check_unsatisfiable(file, content));

        diagnostics
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_path() -> PathBuf {
        PathBuf::from("test.fst")
    }

    #[test]
    fn test_redundant_nat_refinement() {
        let rule = RefinementSimplifierRule::new();
        let content = "let foo (x:nat{x >= 0}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("Redundant refinement"));
        assert!(diags[0].message.contains("nat"));
        assert!(diags[0].fix.is_some());
    }

    #[test]
    fn test_redundant_pos_refinement() {
        let rule = RefinementSimplifierRule::new();
        let content = "let bar (n:pos{n > 0}) = n";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("Redundant refinement"));
        assert!(diags[0].message.contains("pos"));
    }

    #[test]
    fn test_true_refinement() {
        let rule = RefinementSimplifierRule::new();
        let content = "let baz (x:int{True}) = x + 1";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("Useless refinement"));
    }

    #[test]
    fn test_int_to_nat() {
        let rule = RefinementSimplifierRule::new();
        let content = "let len (n:int{n >= 0}) = n";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("Consider using `nat`"));
        assert_eq!(diags[0].severity, DiagnosticSeverity::Info);
    }

    #[test]
    fn test_int_to_pos() {
        let rule = RefinementSimplifierRule::new();
        let content = "let positive (n:int{n > 0}) = n";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("Consider using `pos`"));
    }

    #[test]
    fn test_unsatisfiable_gt_lt() {
        let rule = RefinementSimplifierRule::new();
        let content = "let impossible (x:int{x > 5 /\\ x < 3}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("UNSATISFIABLE"));
        assert_eq!(diags[0].severity, DiagnosticSeverity::Error);
    }

    #[test]
    fn test_unsatisfiable_equal_bounds() {
        let rule = RefinementSimplifierRule::new();
        let content = "let also_impossible (x:int{x > 3 /\\ x < 3}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("UNSATISFIABLE"));
    }

    #[test]
    fn test_satisfiable_range() {
        let rule = RefinementSimplifierRule::new();
        // This is satisfiable (x could be 4)
        let content = "let valid_range (x:int{x > 3 /\\ x < 5}) = x";
        let diags = rule.check(&make_path(), content);
        // Should not produce unsatisfiable error
        assert!(!diags.iter().any(|d| d.message.contains("UNSATISFIABLE")));
    }

    #[test]
    fn test_valid_nat_refinement() {
        let rule = RefinementSimplifierRule::new();
        // nat with additional constraint (not just >= 0) is valid
        let content = "let bounded (x:nat{x < 100}) = x";
        let diags = rule.check(&make_path(), content);
        // Should not produce any diagnostics
        assert!(diags.is_empty());
    }

    #[test]
    fn test_comment_lines_skipped() {
        let rule = RefinementSimplifierRule::new();
        let content = "// let foo (x:nat{x >= 0}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(diags.is_empty());
    }

    // ========== Autofix verification tests ==========

    #[test]
    fn test_nat_refinement_fix_content() {
        let rule = RefinementSimplifierRule::new();
        let content = "let foo (x:nat{x >= 0}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        let fix = diags[0].fix.as_ref().unwrap();
        assert_eq!(fix.edits.len(), 1);
        assert_eq!(fix.edits[0].new_text, "x:nat");
        // Message now indicates safety
        assert!(fix.message.contains("Remove redundant refinement"));
        assert!(fix.message.contains("safe"));
    }

    #[test]
    fn test_pos_refinement_fix_content() {
        let rule = RefinementSimplifierRule::new();
        let content = "let bar (n:pos{n > 0}) = n";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        let fix = diags[0].fix.as_ref().unwrap();
        assert_eq!(fix.edits[0].new_text, "n:pos");
    }

    #[test]
    fn test_true_refinement_fix_content() {
        let rule = RefinementSimplifierRule::new();
        let content = "let baz (x:int{True}) = x + 1";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        let fix = diags[0].fix.as_ref().unwrap();
        assert_eq!(fix.edits[0].new_text, "x:int");
        // Message now indicates safety
        assert!(fix.message.contains("Remove useless {True} refinement"));
        assert!(fix.message.contains("safe"));
    }

    #[test]
    fn test_int_to_nat_fix_content() {
        let rule = RefinementSimplifierRule::new();
        let content = "let len (n:int{n >= 0}) = n";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        let fix = diags[0].fix.as_ref().unwrap();
        assert_eq!(fix.edits[0].new_text, "n:nat");
    }

    #[test]
    fn test_int_to_pos_fix_content() {
        let rule = RefinementSimplifierRule::new();
        let content = "let positive (n:int{n > 0}) = n";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        let fix = diags[0].fix.as_ref().unwrap();
        assert_eq!(fix.edits[0].new_text, "n:pos");
    }

    // ========== UInt suggestion REMOVED tests ==========
    // The old UInt32/UInt64 suggestions were false positives because
    // nat{x < pow2 32} and FStar.UInt32.t have fundamentally different
    // semantics (mathematical nat vs machine word with modular arithmetic).

    #[test]
    fn test_nat_pow2_32_no_longer_triggers() {
        let rule = RefinementSimplifierRule::new();
        let content = "let bounded32 (x:nat{x < pow2 32}) = x";
        let diags = rule.check(&make_path(), content);
        // Must produce ZERO diagnostics -- this is valid F* code.
        assert!(diags.is_empty());
    }

    #[test]
    fn test_nat_pow2_64_no_longer_triggers() {
        let rule = RefinementSimplifierRule::new();
        let content = "let bounded64 (n:nat{n < pow2 64}) = n";
        let diags = rule.check(&make_path(), content);
        assert!(diags.is_empty());
    }

    // ========== Column calculation tests ==========

    #[test]
    fn test_column_calculation_simple() {
        let rule = RefinementSimplifierRule::new();
        // "let foo " is 8 chars, x starts at column 9
        let content = "let foo (x:nat{x >= 0}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        // x:nat{x >= 0} starts at position 9
        assert_eq!(diags[0].range.start_col, 10);
    }

    #[test]
    fn test_column_calculation_with_leading_spaces() {
        let rule = RefinementSimplifierRule::new();
        let content = "    let foo (x:nat{x >= 0}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        // 4 spaces + "let foo " = 13 chars, x starts at column 14
        assert_eq!(diags[0].range.start_col, 14);
    }

    #[test]
    fn test_byte_to_char_col_ascii() {
        // Pure ASCII: byte offset == char offset
        let s = "hello world";
        assert_eq!(byte_to_char_col(s, 0), 1); // Column 1
        assert_eq!(byte_to_char_col(s, 5), 6); // Column 6
        assert_eq!(byte_to_char_col(s, 11), 12); // Column 12
    }

    #[test]
    fn test_byte_to_char_col_utf8() {
        // UTF-8 with multi-byte chars: byte offset != char offset
        let s = "hi there";
        assert_eq!(byte_to_char_col(s, 0), 1);
        assert_eq!(byte_to_char_col(s, 2), 3);
    }

    #[test]
    fn test_byte_to_char_col_edge_cases() {
        let s = "abc";
        // Beyond string length should clamp
        assert_eq!(byte_to_char_col(s, 100), 4);
        // Empty prefix
        assert_eq!(byte_to_char_col(s, 0), 1);
    }

    // ========== Whitespace variation tests ==========

    #[test]
    fn test_no_space_in_refinement() {
        let rule = RefinementSimplifierRule::new();
        let content = "let foo (x:nat{x>=0}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("Redundant refinement"));
    }

    #[test]
    fn test_extra_spaces_in_refinement() {
        let rule = RefinementSimplifierRule::new();
        let content = "let foo (x:nat{  x >= 0  }) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("Redundant refinement"));
    }

    #[test]
    fn test_multiline_not_detected() {
        let rule = RefinementSimplifierRule::new();
        let content = "let foo (x:nat{\nx >= 0\n}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(diags.is_empty());
    }

    // ========== Multiple diagnostics tests ==========

    #[test]
    fn test_multiple_refinements_same_line() {
        let rule = RefinementSimplifierRule::new();
        let content = "let foo (x:nat{x >= 0}) (y:pos{y > 0}) = x + y";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 2);
    }

    #[test]
    fn test_multiple_refinements_different_lines() {
        let rule = RefinementSimplifierRule::new();
        let content = "let foo (x:nat{x >= 0}) = x\nlet bar (y:int{y >= 0}) = y";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 2);
        assert_eq!(diags[0].range.start_line, 1);
        assert_eq!(diags[1].range.start_line, 2);
    }

    // ========== Block comment tests ==========

    #[test]
    fn test_block_comment_skipped() {
        let rule = RefinementSimplifierRule::new();
        let content = "(* let foo (x:nat{x >= 0}) = x *)";
        let diags = rule.check(&make_path(), content);
        assert!(diags.is_empty());
    }

    // ========== Unsatisfiable edge cases ==========

    #[test]
    fn test_unsatisfiable_reversed_order() {
        let rule = RefinementSimplifierRule::new();
        let content = "let impossible (x:int{x < 3 /\\ x > 5}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("UNSATISFIABLE"));
    }

    #[test]
    fn test_unsatisfiable_no_fix_provided() {
        let rule = RefinementSimplifierRule::new();
        let content = "let impossible (x:int{x > 5 /\\ x < 3}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].fix.is_none());
    }

    #[test]
    fn test_different_variables_not_unsatisfiable() {
        let rule = RefinementSimplifierRule::new();
        let content = "let valid (x:int{x > 5 /\\ y < 3}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(!diags.iter().any(|d| d.message.contains("UNSATISFIABLE")));
    }

    // ========== No false positive tests ==========

    #[test]
    fn test_no_false_positive_nat_with_constraint() {
        let rule = RefinementSimplifierRule::new();
        let content = "let bounded (x:nat{x < 10}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(diags.is_empty());
    }

    #[test]
    fn test_no_false_positive_pos_with_constraint() {
        let rule = RefinementSimplifierRule::new();
        let content = "let bounded (x:pos{x <= 100}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(diags.is_empty());
    }

    #[test]
    fn test_no_false_positive_int_with_other_constraint() {
        let rule = RefinementSimplifierRule::new();
        let content = "let bounded (x:int{x < 100}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(diags.is_empty());
    }

    // ========== NEW: False positive regression tests ==========

    #[test]
    fn test_no_false_positive_string_literal() {
        let rule = RefinementSimplifierRule::new();
        // Refinement pattern inside a string literal must NOT trigger
        let content = r#"let msg = "x:nat{x >= 0}" in msg"#;
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Should not flag refinement patterns inside string literals"
        );
    }

    #[test]
    fn test_no_false_positive_inline_block_comment() {
        let rule = RefinementSimplifierRule::new();
        // Refinement inside inline (* ... *) comment must NOT trigger
        let content = "let f = (* x:nat{x >= 0} *) 42";
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Should not flag refinement patterns inside inline block comments"
        );
    }

    #[test]
    fn test_no_false_positive_unsatisfiable_outside_refinement() {
        let rule = RefinementSimplifierRule::new();
        // Unsatisfiable pattern in a bare assert, NOT inside a refinement brace.
        // The old code would flag this; the new code should not.
        let content = "let _ = assert (x > 5 /\\ x < 3)";
        let diags = rule.check(&make_path(), content);
        assert!(
            !diags.iter().any(|d| d.message.contains("UNSATISFIABLE")),
            "Should not flag unsatisfiable patterns outside refinement braces"
        );
    }

    #[test]
    fn test_no_false_positive_compound_refinement_nat() {
        let rule = RefinementSimplifierRule::new();
        // int{x >= 0 /\ x < 256} should NOT suggest nat -- the refinement
        // has additional constraints beyond just >= 0.
        let content = r"let byte (x:int{x >= 0 /\ x < 256}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Should not suggest nat for compound refinements"
        );
    }

    #[test]
    fn test_no_false_positive_compound_refinement_pos() {
        let rule = RefinementSimplifierRule::new();
        // int{x > 0 /\ x <= 255} should NOT suggest pos.
        let content = r"let positive_byte (x:int{x > 0 /\ x <= 255}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Should not suggest pos for compound refinements"
        );
    }

    #[test]
    fn test_no_false_positive_string_literal_unsatisfiable() {
        let rule = RefinementSimplifierRule::new();
        let content = r#"let msg = "x:int{x > 5 /\ x < 3}" in msg"#;
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Should not flag unsatisfiable patterns inside string literals"
        );
    }

    #[test]
    fn test_no_false_positive_true_in_string() {
        let rule = RefinementSimplifierRule::new();
        let content = r#"let msg = "x:int{True}" in msg"#;
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Should not flag {{True}} inside string literals"
        );
    }

    #[test]
    fn test_is_inside_string_or_comment_basic() {
        // After opening quote, offset 5 is inside the string
        assert!(is_inside_string_or_comment(r#"foo "bar" baz"#, 5));
        // Before opening quote, offset 0 is outside
        assert!(!is_inside_string_or_comment(r#"foo "bar" baz"#, 0));
        // After closing quote, offset 10 is outside
        assert!(!is_inside_string_or_comment(r#"foo "bar" baz"#, 10));
    }

    #[test]
    fn test_is_inside_block_comment() {
        assert!(is_inside_string_or_comment("foo (* bar *) baz", 7));
        assert!(!is_inside_string_or_comment("foo (* bar *) baz", 0));
        assert!(!is_inside_string_or_comment("foo (* bar *) baz", 14));
    }

    #[test]
    fn test_is_inside_escaped_string() {
        // Escaped quote inside a string should not end the string
        let line = r#"let s = "x:nat{x >= 0}\"more" in s"#;
        // Position of the opening `"` is byte 8, so byte 10 is inside
        assert!(is_inside_string_or_comment(line, 10));
    }

    #[test]
    fn test_hacl_star_pattern_no_false_positive() {
        let rule = RefinementSimplifierRule::new();
        // Real pattern from hacl-star: d:int{r * d % n = 1}
        // Should NOT trigger any diagnostic (complex refinement, not >= 0 or > 0)
        let content = "val lemma_mont_one: n:pos -> r:pos -> d:int{r * d % n = 1} -> a:nat";
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Should not flag complex refinements from real hacl-star code"
        );
    }

    // ========== Fix Safety Tests ==========
    // These tests verify the critical safety features for auto-fix.

    #[test]
    fn test_redundant_nat_fix_is_safe_and_auto_applicable() {
        let rule = RefinementSimplifierRule::new();
        let content = "let foo (x:nat{x >= 0}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);

        let fix = diags[0].fix.as_ref().expect("Should have a fix");
        assert!(fix.is_safe, "Redundant nat removal should be marked safe");
        assert!(
            fix.can_auto_apply(),
            "Safe high-confidence fix should be auto-applicable"
        );
        assert!(
            fix.message.contains("safe"),
            "Fix message should indicate safety"
        );
    }

    #[test]
    fn test_redundant_pos_fix_is_safe_and_auto_applicable() {
        let rule = RefinementSimplifierRule::new();
        let content = "let bar (n:pos{n > 0}) = n";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);

        let fix = diags[0].fix.as_ref().expect("Should have a fix");
        assert!(fix.is_safe, "Redundant pos removal should be marked safe");
        assert!(
            fix.can_auto_apply(),
            "Safe high-confidence fix should be auto-applicable"
        );
    }

    #[test]
    fn test_true_refinement_fix_is_safe_and_auto_applicable() {
        let rule = RefinementSimplifierRule::new();
        let content = "let baz (x:int{True}) = x + 1";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);

        let fix = diags[0].fix.as_ref().expect("Should have a fix");
        assert!(fix.is_safe, "True refinement removal should be marked safe");
        assert!(
            fix.can_auto_apply(),
            "Safe high-confidence fix should be auto-applicable"
        );
    }

    #[test]
    fn test_int_to_nat_fix_is_unsafe_not_auto_applicable() {
        let rule = RefinementSimplifierRule::new();
        let content = "let len (n:int{n >= 0}) = n";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);

        let fix = diags[0].fix.as_ref().expect("Should have a fix");
        assert!(
            !fix.is_safe,
            "int->nat type change should be marked UNSAFE"
        );
        assert!(
            !fix.can_auto_apply(),
            "Unsafe fix should NOT be auto-applicable"
        );
        assert!(
            fix.unsafe_reason.is_some(),
            "Unsafe fix should have a reason"
        );
        assert!(
            fix.message.contains("CAUTION"),
            "Fix message should warn about type change"
        );
    }

    #[test]
    fn test_int_to_pos_fix_is_unsafe_not_auto_applicable() {
        let rule = RefinementSimplifierRule::new();
        let content = "let positive (n:int{n > 0}) = n";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);

        let fix = diags[0].fix.as_ref().expect("Should have a fix");
        assert!(
            !fix.is_safe,
            "int->pos type change should be marked UNSAFE"
        );
        assert!(
            !fix.can_auto_apply(),
            "Unsafe fix should NOT be auto-applicable"
        );
        assert!(
            fix.unsafe_reason.is_some(),
            "Unsafe fix should have a reason"
        );
    }

    #[test]
    fn test_int_to_nat_message_warns_about_type_change() {
        let rule = RefinementSimplifierRule::new();
        let content = "let len (n:int{n >= 0}) = n";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);

        // Message should warn about the implications
        assert!(
            diags[0].message.contains("NOTE"),
            "Message should have a NOTE about implications"
        );
        assert!(
            diags[0].message.contains("type inference"),
            "Message should mention type inference impact"
        );
    }

    #[test]
    fn test_unsatisfiable_has_no_fix() {
        let rule = RefinementSimplifierRule::new();
        let content = "let impossible (x:int{x > 5 /\\ x < 3}) = x";
        let diags = rule.check(&make_path(), content);
        assert_eq!(diags.len(), 1);

        assert!(
            diags[0].fix.is_none(),
            "Unsatisfiable refinement should have no fix"
        );
        assert_eq!(
            diags[0].severity,
            DiagnosticSeverity::Error,
            "Unsatisfiable should be an error"
        );
    }

    // ========== Additional Edge Case Tests ==========

    #[test]
    fn test_reversed_gte_not_matched() {
        let rule = RefinementSimplifierRule::new();
        // "0 <= x" is semantically the same as "x >= 0", but we do EXACT matching
        // to be conservative. This should NOT trigger.
        let content = "let foo (x:int{0 <= x}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Reversed comparison form should not trigger (conservative)"
        );
    }

    #[test]
    fn test_not_int_base_type_no_simplification() {
        let rule = RefinementSimplifierRule::new();
        // Base type is "integer" not "int" - should not trigger
        let content = "let foo (x:integer{x >= 0}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Only exact 'int' base type should trigger simplification"
        );
    }

    #[test]
    fn test_qualified_int_not_matched() {
        let rule = RefinementSimplifierRule::new();
        // FStar.Int.int is different from bare int - should not trigger
        // Note: Our regex only matches single-word types
        let content = "let foo (x:FStar.Int.int{x >= 0}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Qualified types should not trigger simplification"
        );
    }

    #[test]
    fn test_conjunction_with_gte_zero_not_nat() {
        let rule = RefinementSimplifierRule::new();
        // int{x >= 0 /\ x <> 5} has additional constraint - NOT equivalent to nat
        let content = r"let foo (x:int{x >= 0 /\ x <> 5}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "int{{x >= 0 /\\ extra}} should NOT suggest nat"
        );
    }

    #[test]
    fn test_disjunction_with_gte_zero_not_nat() {
        let rule = RefinementSimplifierRule::new();
        // int{x >= 0 \/ x < -10} is NOT equivalent to nat
        let content = r"let foo (x:int{x >= 0 \/ x < -10}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "int{{x >= 0 \\/ extra}} should NOT suggest nat"
        );
    }

    #[test]
    fn test_negation_with_gte_zero_not_nat() {
        let rule = RefinementSimplifierRule::new();
        // int{~(x >= 0)} is the opposite of nat
        let content = r"let foo (x:int{~(x >= 0)}) = x";
        let diags = rule.check(&make_path(), content);
        assert!(
            diags.is_empty(),
            "Negated constraint should NOT suggest nat"
        );
    }
}