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
//! Lint rule definitions and diagnostic types.

use std::fmt;
use std::path::PathBuf;

/// Rule codes for F* linting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RuleCode {
    /// FST001: Type defined in both .fst and .fsti (duplicate definition).
    FST001,
    /// FST002: Interface declarations don't match implementation order.
    FST002,
    /// FST003: Comment syntax issues (unclosed comments, (*), (-*), etc.).
    FST003,
    /// FST004: Unused open statements that can be removed.
    FST004,
    /// FST005: Dead code detection (unused private bindings, unreachable code).
    FST005,
    /// FST006: Naming convention violations (snake_case, CamelCase).
    FST006,
    /// FST007: Z3 complexity patterns that cause slow verification.
    FST007,
    /// FST008: Import optimization (broad imports, heavy modules, circular deps).
    FST008,
    /// FST009: Proof hint suggester (helpful lemmas and techniques).
    FST009,
    /// FST010: Specification extractor (missing .fsti files).
    FST010,
    /// FST011: Effect checker (admit, magic, unsafe_coerce, ML effect).
    FST011,
    /// FST012: Refinement type simplifier (redundant, promotable, unsatisfiable).
    FST012,
    /// FST013: Documentation checker (missing docs on public declarations).
    FST013,
    /// FST014: Test generator (suggests test cases from type signatures).
    FST014,
    /// FST015: Module dependency analysis (self-deps, too many deps).
    FST015,
    /// FST016: Verification performance profiler (high fuel/ifuel/rlimit, etc.).
    FST016,
    /// FST017: Security checker for cryptographic code.
    FST017,
}

impl RuleCode {
    /// Parse a rule code from string (e.g., "FST001").
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_uppercase().as_str() {
            "FST001" => Some(RuleCode::FST001),
            "FST002" => Some(RuleCode::FST002),
            "FST003" => Some(RuleCode::FST003),
            "FST004" => Some(RuleCode::FST004),
            "FST005" => Some(RuleCode::FST005),
            "FST006" => Some(RuleCode::FST006),
            "FST007" => Some(RuleCode::FST007),
            "FST008" => Some(RuleCode::FST008),
            "FST009" => Some(RuleCode::FST009),
            "FST010" => Some(RuleCode::FST010),
            "FST011" => Some(RuleCode::FST011),
            "FST012" => Some(RuleCode::FST012),
            "FST013" => Some(RuleCode::FST013),
            "FST014" => Some(RuleCode::FST014),
            "FST015" => Some(RuleCode::FST015),
            "FST016" => Some(RuleCode::FST016),
            "FST017" => Some(RuleCode::FST017),
            _ => None,
        }
    }

    /// All available rule codes.
    pub fn all() -> &'static [RuleCode] {
        &[
            RuleCode::FST001,
            RuleCode::FST002,
            RuleCode::FST003,
            RuleCode::FST004,
            RuleCode::FST005,
            RuleCode::FST006,
            RuleCode::FST007,
            RuleCode::FST008,
            RuleCode::FST009,
            RuleCode::FST010,
            RuleCode::FST011,
            RuleCode::FST012,
            RuleCode::FST013,
            RuleCode::FST014,
            RuleCode::FST015,
            RuleCode::FST016,
            RuleCode::FST017,
        ]
    }

    /// Whether this rule can produce automatic fixes.
    pub fn is_fixable(&self) -> bool {
        matches!(
            self,
            RuleCode::FST001
                | RuleCode::FST002
                | RuleCode::FST004
                | RuleCode::FST005
                | RuleCode::FST010
                | RuleCode::FST012
                | RuleCode::FST013
        )
    }

    /// Short name for the rule.
    pub fn name(&self) -> &'static str {
        match self {
            RuleCode::FST001 => "duplicate-types",
            RuleCode::FST002 => "interface-order",
            RuleCode::FST003 => "comment-syntax",
            RuleCode::FST004 => "unused-opens",
            RuleCode::FST005 => "dead-code",
            RuleCode::FST006 => "naming-conventions",
            RuleCode::FST007 => "z3-complexity",
            RuleCode::FST008 => "import-optimizer",
            RuleCode::FST009 => "proof-hints",
            RuleCode::FST010 => "spec-extractor",
            RuleCode::FST011 => "effect-checker",
            RuleCode::FST012 => "refinement-simplifier",
            RuleCode::FST013 => "doc-checker",
            RuleCode::FST014 => "test-generator",
            RuleCode::FST015 => "module-deps",
            RuleCode::FST016 => "perf-profiler",
            RuleCode::FST017 => "security",
        }
    }

    /// Detailed description of what the rule checks.
    pub fn description(&self) -> &'static str {
        match self {
            RuleCode::FST001 => {
                "Detects type definitions that appear in both .fst and .fsti files. \
                 F* only requires type definitions in interface files; duplicating them \
                 in implementation files can cause maintenance issues and confusion."
            }
            RuleCode::FST002 => {
                "Detects when interface (.fsti) declarations are not in the same order \
                 as the implementation (.fst). This can cause F* Error 233: \
                 'Expected the definition of X to precede Y'."
            }
            RuleCode::FST003 => {
                "Detects comment syntax issues including unclosed comments, \
                 premature comment closes, (*) which F* parses as unit value, \
                 and (-*) which is the magic wand operator from separation logic."
            }
            RuleCode::FST004 => {
                "Detects unused open statements that import modules which are never \
                 used in the file. Removing unused opens improves compilation time \
                 and keeps dependencies explicit."
            }
            RuleCode::FST005 => {
                "Detects dead code including unused private bindings, unreachable code \
                 after assert false/admit(), unused function parameters (with autofix), \
                 and unreachable match branches after wildcard patterns."
            }
            RuleCode::FST006 => {
                "Checks naming conventions: types should be snake_case, functions should be \
                 snake_case, effects should be CamelCase. Allows legacy exceptions from F* stdlib."
            }
            RuleCode::FST007 => {
                "Detects Z3 complexity patterns: quantifiers without SMTPat triggers, \
                 non-linear arithmetic, deep quantifier nesting, large match expressions, \
                 recursive functions without decreases, and high z3rlimit settings."
            }
            RuleCode::FST008 => {
                "Detects import optimization opportunities: broad imports when selective would \
                 suffice, heavy modules (Tactics, Reflection) that slow verification, \
                 circular imports, and unnecessary transitive imports."
            }
            RuleCode::FST009 => {
                "Suggests helpful proof hints based on code patterns. Detects list append \
                 length properties, modular arithmetic lemmas, pow2 normalization needs, \
                 sequence operation lemmas, and bitwise operation hints."
            }
            RuleCode::FST010 => {
                "Detects .fst files without corresponding .fsti interface files. \
                 Interface files help with encapsulation, separate compilation, \
                 and documentation of public APIs."
            }
            RuleCode::FST011 => {
                "Detects effect-related issues: admit() bypassing verification, magic() producing \
                 arbitrary values, unsafe_coerce bypassing type safety, overly permissive ML effect, \
                 and assume val axioms."
            }
            RuleCode::FST012 => {
                "Simplifies refinement types: detects redundant refinements (nat{x >= 0}), \
                 promotable types (int{x >= 0} -> nat), useless refinements (T{True}), \
                 and unsatisfiable constraints (x > 5 /\\ x < 3)."
            }
            RuleCode::FST013 => {
                "Checks for missing documentation on public val and type declarations. \
                 Skips private declarations, internal names (starting with _), type abbreviations, \
                 and .fst files that have a corresponding .fsti interface."
            }
            RuleCode::FST014 => {
                "Generates test suggestions from type signatures. Analyzes function parameters \
                 for refinement type boundaries, collection edge cases (empty, singleton), \
                 integer bounds (min/max for U32, U64, etc.), and option type coverage."
            }
            RuleCode::FST015 => {
                "Analyzes module dependencies from open/friend/include statements. \
                 Detects self-dependencies and warns when modules have too many dependencies (>15)."
            }
            RuleCode::FST016 => {
                "Verification performance profiler that detects patterns causing slow verification: \
                 high fuel/ifuel settings, high z3rlimit values, --quake/--retry usage indicating \
                 instability, and high assertion density suggesting proof complexity."
            }
            RuleCode::FST017 => {
                "Security checker for cryptographic F* code. Detects hardcoded secrets, \
                 RawIntTypes usage that may break secret independence, and potential \
                 secret-dependent branches that could enable timing side-channel attacks."
            }
        }
    }
}

impl fmt::Display for RuleCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RuleCode::FST001 => write!(f, "FST001"),
            RuleCode::FST002 => write!(f, "FST002"),
            RuleCode::FST003 => write!(f, "FST003"),
            RuleCode::FST004 => write!(f, "FST004"),
            RuleCode::FST005 => write!(f, "FST005"),
            RuleCode::FST006 => write!(f, "FST006"),
            RuleCode::FST007 => write!(f, "FST007"),
            RuleCode::FST008 => write!(f, "FST008"),
            RuleCode::FST009 => write!(f, "FST009"),
            RuleCode::FST010 => write!(f, "FST010"),
            RuleCode::FST011 => write!(f, "FST011"),
            RuleCode::FST012 => write!(f, "FST012"),
            RuleCode::FST013 => write!(f, "FST013"),
            RuleCode::FST014 => write!(f, "FST014"),
            RuleCode::FST015 => write!(f, "FST015"),
            RuleCode::FST016 => write!(f, "FST016"),
            RuleCode::FST017 => write!(f, "FST017"),
        }
    }
}

/// Severity level for diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSeverity {
    Error,
    Warning,
    Info,
    Hint,
}

impl fmt::Display for DiagnosticSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DiagnosticSeverity::Error => write!(f, "error"),
            DiagnosticSeverity::Warning => write!(f, "warning"),
            DiagnosticSeverity::Info => write!(f, "info"),
            DiagnosticSeverity::Hint => write!(f, "hint"),
        }
    }
}

/// A text range in a file (1-indexed lines and columns).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Range {
    pub start_line: usize,
    pub start_col: usize,
    pub end_line: usize,
    pub end_col: usize,
}

impl Range {
    pub fn new(start_line: usize, start_col: usize, end_line: usize, end_col: usize) -> Self {
        Self {
            start_line,
            start_col,
            end_line,
            end_col,
        }
    }

    /// Create a range for a single point.
    pub fn point(line: usize, col: usize) -> Self {
        Self {
            start_line: line,
            start_col: col,
            end_line: line,
            end_col: col,
        }
    }
}

/// Confidence level for a fix.
/// Higher confidence means the fix is more likely to be correct and safe.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FixConfidence {
    /// Low confidence - the analysis might have missed usages.
    /// Fix should NOT be auto-applied. Requires manual review.
    Low = 0,
    /// Medium confidence - likely correct but some uncertainty remains.
    /// Fix can be suggested but user should verify.
    Medium = 50,
    /// High confidence - analysis is comprehensive and fix is safe.
    /// Fix can be auto-applied with --fix flag.
    High = 100,
}

impl FixConfidence {
    /// Convert to f64 confidence score (0.0 to 1.0).
    pub fn as_f64(&self) -> f64 {
        match self {
            FixConfidence::Low => 0.25,
            FixConfidence::Medium => 0.5,
            FixConfidence::High => 1.0,
        }
    }

    /// Create from f64 confidence score (0.0 to 1.0).
    pub fn from_f64(score: f64) -> Self {
        if score >= 0.75 {
            FixConfidence::High
        } else if score >= 0.4 {
            FixConfidence::Medium
        } else {
            FixConfidence::Low
        }
    }
}

impl Default for FixConfidence {
    fn default() -> Self {
        FixConfidence::Medium
    }
}

impl fmt::Display for FixConfidence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FixConfidence::Low => write!(f, "low"),
            FixConfidence::Medium => write!(f, "medium"),
            FixConfidence::High => write!(f, "high"),
        }
    }
}

/// Safety level for fix application.
///
/// This determines how the fix is presented and applied:
/// - Safe: Can be auto-applied with `--apply`
/// - Caution: Shows warning, applies with `--apply` but warns
/// - Unsafe: Requires `--force` in addition to `--apply`
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FixSafetyLevel {
    /// SAFE: Can auto-apply with --apply flag.
    /// The fix is guaranteed to preserve semantics and cannot break working code.
    /// Examples:
    /// - Removing exactly-matching duplicate type definitions
    /// - Removing redundant refinements (nat{x >= 0} -> nat)
    /// - Adding documentation comments
    Safe,

    /// CAUTION: Show warning, apply with --apply but display caution.
    /// The fix is likely correct but has some risk:
    /// - Reordering declarations (might affect later code)
    /// - Creating new files (spec extraction)
    /// - Type changes that are semantically equivalent
    Caution,

    /// UNSAFE: Requires --force in addition to --apply.
    /// The fix has significant risk and requires explicit confirmation:
    /// - Removing code that might be used (dead code detection)
    /// - Complex refactoring with potential side effects
    /// - Changes in files with circular dependencies
    Unsafe,
}

impl Default for FixSafetyLevel {
    fn default() -> Self {
        FixSafetyLevel::Caution
    }
}

impl fmt::Display for FixSafetyLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FixSafetyLevel::Safe => write!(f, "safe"),
            FixSafetyLevel::Caution => write!(f, "caution"),
            FixSafetyLevel::Unsafe => write!(f, "unsafe"),
        }
    }
}

/// Safety level for dead code removal fixes.
///
/// CRITICAL: Dead code removal is HIGH RISK in F* because:
/// - "Unused" bindings may be used via SMTPat (auto-triggered by solver)
/// - Private bindings may be used by `friend` modules
/// - Ghost bindings exist for proofs only
/// - Lemmas prove properties without explicit call sites
///
/// This enum classifies the risk level of removing code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DeadCodeSafetyLevel {
    /// SAFE: Can auto-apply with --fix flag.
    /// Examples:
    /// - Unused parameter in non-proof function (can prefix with _)
    /// - Obviously dead code after `assert false`
    Safe,

    /// CAUTION: Show warning, require explicit confirmation.
    /// The code APPEARS unused but might be used in ways we cannot detect:
    /// - Private binding in file without SMTPat (might have friend users)
    /// - Code after admit() (might be intentional placeholder)
    Caution,

    /// UNSAFE: Do NOT offer automatic fix, only warn.
    /// The code has patterns suggesting it IS used:
    /// - Binding has attributes like `[@"opaque_to_smt"]`
    /// - Binding is in a .fsti file (part of public interface)
    /// - Binding has SMTPat (even if not detected as private)
    /// - Binding is a Lemma (proofs don't need call sites)
    Unsafe,
}

impl Default for DeadCodeSafetyLevel {
    fn default() -> Self {
        // Default to CAUTION - we're paranoid about removing F* code
        DeadCodeSafetyLevel::Caution
    }
}

impl fmt::Display for DeadCodeSafetyLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DeadCodeSafetyLevel::Safe => write!(f, "safe"),
            DeadCodeSafetyLevel::Caution => write!(f, "caution"),
            DeadCodeSafetyLevel::Unsafe => write!(f, "unsafe"),
        }
    }
}

/// A suggested fix for a diagnostic.
#[derive(Debug, Clone)]
pub struct Fix {
    /// Description of what the fix does.
    pub message: String,
    /// The edits to apply (may span multiple ranges).
    pub edits: Vec<Edit>,
    /// Confidence level for this fix.
    /// Affects whether the fix can be auto-applied.
    pub confidence: FixConfidence,
    /// Whether the fix is considered safe for auto-application.
    /// A fix is safe if:
    /// - The analysis is comprehensive (not missing edge cases)
    /// - Applying the fix cannot break working code
    /// - The module is not in the "never auto-remove" list
    pub is_safe: bool,
    /// Reason if the fix is marked unsafe.
    pub unsafe_reason: Option<String>,
    /// Safety level for the fix (Safe, Caution, Unsafe).
    /// Determines how the fix is presented and what flags are needed to apply it.
    pub safety_level: FixSafetyLevel,
    /// Whether this fix can be easily reversed.
    /// True for additive changes (adding comments, creating files).
    /// False for destructive changes (removing code, reordering).
    pub reversible: bool,
    /// Whether this fix requires human review before application.
    /// True for changes that might affect semantics or require context.
    pub requires_review: bool,
}

impl Fix {
    /// Create a new fix with default medium confidence and safe=true.
    pub fn new(message: impl Into<String>, edits: Vec<Edit>) -> Self {
        Self {
            message: message.into(),
            edits,
            confidence: FixConfidence::Medium,
            is_safe: true,
            unsafe_reason: None,
            safety_level: FixSafetyLevel::Caution,
            reversible: true,
            requires_review: false,
        }
    }

    /// Create a fix marked as unsafe with a reason.
    pub fn unsafe_fix(
        message: impl Into<String>,
        edits: Vec<Edit>,
        confidence: FixConfidence,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            message: message.into(),
            edits,
            confidence,
            is_safe: false,
            unsafe_reason: Some(reason.into()),
            safety_level: FixSafetyLevel::Unsafe,
            reversible: false,
            requires_review: true,
        }
    }

    /// Create a high-confidence safe fix.
    pub fn safe(message: impl Into<String>, edits: Vec<Edit>) -> Self {
        Self {
            message: message.into(),
            edits,
            confidence: FixConfidence::High,
            is_safe: true,
            unsafe_reason: None,
            safety_level: FixSafetyLevel::Safe,
            reversible: true,
            requires_review: false,
        }
    }

    /// Create a fix with Caution safety level.
    pub fn caution(message: impl Into<String>, edits: Vec<Edit>) -> Self {
        Self {
            message: message.into(),
            edits,
            confidence: FixConfidence::Medium,
            is_safe: true,
            unsafe_reason: None,
            safety_level: FixSafetyLevel::Caution,
            reversible: true,
            requires_review: true,
        }
    }

    /// Set the confidence level.
    pub fn with_confidence(mut self, confidence: FixConfidence) -> Self {
        self.confidence = confidence;
        self
    }

    /// Set the safety level.
    pub fn with_safety_level(mut self, level: FixSafetyLevel) -> Self {
        self.safety_level = level;
        // Update is_safe to match
        self.is_safe = level == FixSafetyLevel::Safe;
        self
    }

    /// Mark as reversible or not.
    pub fn with_reversible(mut self, reversible: bool) -> Self {
        self.reversible = reversible;
        self
    }

    /// Mark as requiring review or not.
    pub fn with_requires_review(mut self, requires_review: bool) -> Self {
        self.requires_review = requires_review;
        self
    }

    /// Mark as unsafe with a reason.
    pub fn mark_unsafe(mut self, reason: impl Into<String>) -> Self {
        self.is_safe = false;
        self.unsafe_reason = Some(reason.into());
        self.safety_level = FixSafetyLevel::Unsafe;
        self.requires_review = true;
        self
    }

    /// Check if this fix should be auto-applied.
    /// Only high-confidence safe fixes can be auto-applied.
    pub fn can_auto_apply(&self) -> bool {
        self.is_safe && self.confidence == FixConfidence::High
    }

    /// Check if this fix can be applied with just --apply.
    /// Safe and Caution fixes can be applied, Unsafe requires --force.
    pub fn can_apply_without_force(&self) -> bool {
        self.safety_level != FixSafetyLevel::Unsafe
    }

    /// Check if this fix requires the --force flag.
    pub fn requires_force(&self) -> bool {
        self.safety_level == FixSafetyLevel::Unsafe
    }
}

/// A single text edit.
#[derive(Debug, Clone)]
pub struct Edit {
    /// File to edit.
    pub file: PathBuf,
    /// Range to replace (or point to insert at).
    pub range: Range,
    /// New text to insert (empty string for deletion).
    pub new_text: String,
}

/// A lint diagnostic.
#[derive(Debug, Clone)]
pub struct Diagnostic {
    /// The rule that produced this diagnostic.
    pub rule: RuleCode,
    /// Severity level.
    pub severity: DiagnosticSeverity,
    /// File path.
    pub file: PathBuf,
    /// Location in the file.
    pub range: Range,
    /// Human-readable message.
    pub message: String,
    /// Optional fix suggestion.
    pub fix: Option<Fix>,
}

/// A lint rule trait.
pub trait Rule: Send + Sync {
    /// The rule code.
    fn code(&self) -> RuleCode;

    /// Check a single file and return diagnostics.
    fn check(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic>;

    /// Check a file pair (.fst and .fsti).
    fn check_pair(
        &self,
        _fst_file: &PathBuf,
        _fst_content: &str,
        _fsti_file: &PathBuf,
        _fsti_content: &str,
    ) -> Vec<Diagnostic> {
        // Default: no pair checking
        vec![]
    }

    /// Whether this rule requires pair checking.
    fn requires_pair(&self) -> bool {
        false
    }
}

/// Print all available rules in a formatted table.
pub fn print_rules() {
    println!("Available F* lint rules:\n");
    println!(
        "{:<8} {:<20} {:<8} {}",
        "Code", "Name", "Fixable", "Description"
    );
    println!("{}", "-".repeat(80));

    for code in RuleCode::all() {
        let fixable = if code.is_fixable() { "Yes" } else { "No" };
        // Truncate description to first sentence for table
        let desc = code.description();
        let short_desc = desc.split('.').next().unwrap_or(desc);

        println!(
            "{:<8} {:<20} {:<8} {}",
            code,
            code.name(),
            fixable,
            short_desc
        );
    }

    println!("\nUse --select to enable specific rules (e.g., --select FST001,FST002)");
    println!("Use --ignore to disable specific rules (e.g., --ignore FST003)");
}

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

    // =========================================================================
    // FixSafetyLevel Tests
    // =========================================================================

    #[test]
    fn test_fix_safety_level_ordering() {
        // Safe < Caution < Unsafe
        assert!(FixSafetyLevel::Safe < FixSafetyLevel::Caution);
        assert!(FixSafetyLevel::Caution < FixSafetyLevel::Unsafe);
        assert!(FixSafetyLevel::Safe < FixSafetyLevel::Unsafe);
    }

    #[test]
    fn test_fix_safety_level_display() {
        assert_eq!(format!("{}", FixSafetyLevel::Safe), "safe");
        assert_eq!(format!("{}", FixSafetyLevel::Caution), "caution");
        assert_eq!(format!("{}", FixSafetyLevel::Unsafe), "unsafe");
    }

    #[test]
    fn test_fix_safety_level_default() {
        assert_eq!(FixSafetyLevel::default(), FixSafetyLevel::Caution);
    }

    // =========================================================================
    // FixConfidence Tests
    // =========================================================================

    #[test]
    fn test_fix_confidence_as_f64() {
        assert_eq!(FixConfidence::Low.as_f64(), 0.25);
        assert_eq!(FixConfidence::Medium.as_f64(), 0.5);
        assert_eq!(FixConfidence::High.as_f64(), 1.0);
    }

    #[test]
    fn test_fix_confidence_from_f64() {
        assert_eq!(FixConfidence::from_f64(0.0), FixConfidence::Low);
        assert_eq!(FixConfidence::from_f64(0.3), FixConfidence::Low);
        assert_eq!(FixConfidence::from_f64(0.5), FixConfidence::Medium);
        assert_eq!(FixConfidence::from_f64(0.7), FixConfidence::Medium);
        assert_eq!(FixConfidence::from_f64(0.8), FixConfidence::High);
        assert_eq!(FixConfidence::from_f64(1.0), FixConfidence::High);
    }

    // =========================================================================
    // Fix Constructor Tests
    // =========================================================================

    #[test]
    fn test_fix_new_defaults() {
        let fix = Fix::new("test fix", vec![]);
        assert_eq!(fix.confidence, FixConfidence::Medium);
        assert!(fix.is_safe);
        assert!(fix.unsafe_reason.is_none());
        assert_eq!(fix.safety_level, FixSafetyLevel::Caution);
        assert!(fix.reversible);
        assert!(!fix.requires_review);
    }

    #[test]
    fn test_fix_safe() {
        let fix = Fix::safe("safe fix", vec![]);
        assert_eq!(fix.confidence, FixConfidence::High);
        assert!(fix.is_safe);
        assert!(fix.unsafe_reason.is_none());
        assert_eq!(fix.safety_level, FixSafetyLevel::Safe);
        assert!(fix.reversible);
        assert!(!fix.requires_review);
    }

    #[test]
    fn test_fix_caution() {
        let fix = Fix::caution("caution fix", vec![]);
        assert_eq!(fix.confidence, FixConfidence::Medium);
        assert!(fix.is_safe);
        assert!(fix.unsafe_reason.is_none());
        assert_eq!(fix.safety_level, FixSafetyLevel::Caution);
        assert!(fix.reversible);
        assert!(fix.requires_review);
    }

    #[test]
    fn test_fix_unsafe_fix() {
        let fix = Fix::unsafe_fix("unsafe fix", vec![], FixConfidence::Low, "reason");
        assert_eq!(fix.confidence, FixConfidence::Low);
        assert!(!fix.is_safe);
        assert_eq!(fix.unsafe_reason, Some("reason".to_string()));
        assert_eq!(fix.safety_level, FixSafetyLevel::Unsafe);
        assert!(!fix.reversible);
        assert!(fix.requires_review);
    }

    // =========================================================================
    // Fix Builder Methods Tests
    // =========================================================================

    #[test]
    fn test_fix_with_safety_level() {
        let fix = Fix::new("test", vec![])
            .with_safety_level(FixSafetyLevel::Safe);
        assert_eq!(fix.safety_level, FixSafetyLevel::Safe);
        assert!(fix.is_safe);  // is_safe should be updated to match

        let fix = Fix::new("test", vec![])
            .with_safety_level(FixSafetyLevel::Unsafe);
        assert_eq!(fix.safety_level, FixSafetyLevel::Unsafe);
        assert!(!fix.is_safe);  // is_safe should be updated to match
    }

    #[test]
    fn test_fix_with_reversible() {
        let fix = Fix::new("test", vec![]).with_reversible(false);
        assert!(!fix.reversible);

        let fix = Fix::new("test", vec![]).with_reversible(true);
        assert!(fix.reversible);
    }

    #[test]
    fn test_fix_with_requires_review() {
        let fix = Fix::new("test", vec![]).with_requires_review(true);
        assert!(fix.requires_review);

        let fix = Fix::new("test", vec![]).with_requires_review(false);
        assert!(!fix.requires_review);
    }

    #[test]
    fn test_fix_mark_unsafe() {
        let fix = Fix::safe("originally safe", vec![])
            .mark_unsafe("now unsafe");
        assert!(!fix.is_safe);
        assert_eq!(fix.unsafe_reason, Some("now unsafe".to_string()));
        assert_eq!(fix.safety_level, FixSafetyLevel::Unsafe);
        assert!(fix.requires_review);
    }

    // =========================================================================
    // Fix Application Tests
    // =========================================================================

    #[test]
    fn test_can_auto_apply() {
        // Only high-confidence safe fixes can auto-apply
        let fix = Fix::safe("safe", vec![]);
        assert!(fix.can_auto_apply());

        let fix = Fix::caution("caution", vec![]);
        assert!(!fix.can_auto_apply());

        let fix = Fix::unsafe_fix("unsafe", vec![], FixConfidence::High, "reason");
        assert!(!fix.can_auto_apply());

        let fix = Fix::new("medium", vec![]);  // Medium confidence
        assert!(!fix.can_auto_apply());
    }

    #[test]
    fn test_can_apply_without_force() {
        // Safe and Caution can be applied without force
        let fix = Fix::safe("safe", vec![]);
        assert!(fix.can_apply_without_force());

        let fix = Fix::caution("caution", vec![]);
        assert!(fix.can_apply_without_force());

        // Unsafe requires force
        let fix = Fix::unsafe_fix("unsafe", vec![], FixConfidence::Low, "reason");
        assert!(!fix.can_apply_without_force());
    }

    #[test]
    fn test_requires_force() {
        let fix = Fix::safe("safe", vec![]);
        assert!(!fix.requires_force());

        let fix = Fix::caution("caution", vec![]);
        assert!(!fix.requires_force());

        let fix = Fix::unsafe_fix("unsafe", vec![], FixConfidence::Low, "reason");
        assert!(fix.requires_force());
    }

    // =========================================================================
    // Chained Builder Pattern Tests
    // =========================================================================

    #[test]
    fn test_chained_builders() {
        let fix = Fix::new("test", vec![])
            .with_confidence(FixConfidence::High)
            .with_safety_level(FixSafetyLevel::Safe)
            .with_reversible(true)
            .with_requires_review(false);

        assert_eq!(fix.confidence, FixConfidence::High);
        assert_eq!(fix.safety_level, FixSafetyLevel::Safe);
        assert!(fix.reversible);
        assert!(!fix.requires_review);
    }
}