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
//! Lint engine that orchestrates rule checking and fixing.

use std::collections::HashSet;
use std::fs;
use std::path::PathBuf;

use tracing::{debug, error, info, warn};

use super::comments::CommentRule;
use super::dead_code::DeadCodeRule;
use super::doc_checker::DocCheckerRule;
use super::duplicate_types::{find_fst_fsti_pairs, DuplicateTypesRule};
use super::effect_checker::EffectCheckerRule;
use super::file_safety::{AtomicWriter, AtomicWriteError};
use super::fix_applicator::{FixApplicator, FixApplicatorConfig};
use super::fix_validator::{validate_fix as validate_fix_content, FixValidation};
use super::import_optimizer::ImportOptimizerRule;
use super::module_deps::ModuleDepsRule;
use super::naming::NamingRule;
use super::output::{
    print_diagnostics, print_dry_run, print_summary,
    print_apply_header, print_dry_run_header, print_fixes_applied, print_no_fixes_message,
    DryRunFormat, DryRunSummary, LintSummary, OutputFormat,
};
use super::perf_profiler::PerfProfilerRule;
use super::proof_hints::ProofHintsRule;
use super::refinement_simplifier::RefinementSimplifierRule;
use super::reorder_interface::ReorderInterfaceRule;
use super::rules::{Diagnostic, FixConfidence, FixSafetyLevel, Rule, RuleCode};
use super::security::SecurityRule;
use super::spec_extractor::SpecExtractorRule;
use super::test_generator::TestGeneratorRule;
use super::unused_opens::UnusedOpensRule;
use super::z3_complexity::Z3ComplexityRule;

/// Configuration for the lint engine.
#[derive(Debug, Clone)]
pub struct LintConfig {
    /// Rules to enable (if None, all rules are enabled).
    pub select: Option<HashSet<RuleCode>>,
    /// Rules to ignore.
    pub ignore: HashSet<RuleCode>,
    /// Path to F* executable (for rules that need it).
    pub fstar_exe: Option<String>,
}

impl LintConfig {
    /// Create a new lint configuration from CLI options.
    pub fn new(select: Option<String>, ignore: Option<String>, fstar_exe: Option<String>) -> Self {
        let select_set = select.map(|s| {
            s.split(',')
                .filter_map(|code| RuleCode::from_str(code.trim()))
                .collect()
        });

        let ignore_set = ignore
            .map(|s| {
                s.split(',')
                    .filter_map(|code| RuleCode::from_str(code.trim()))
                    .collect()
            })
            .unwrap_or_default();

        Self {
            select: select_set,
            ignore: ignore_set,
            fstar_exe,
        }
    }

    /// Check if a rule is enabled.
    pub fn is_rule_enabled(&self, rule: RuleCode) -> bool {
        if self.ignore.contains(&rule) {
            return false;
        }
        match &self.select {
            Some(selected) => selected.contains(&rule),
            None => true,
        }
    }
}

impl Default for LintConfig {
    fn default() -> Self {
        Self {
            select: None,
            ignore: HashSet::new(),
            fstar_exe: None,
        }
    }
}

/// The main lint engine.
pub struct LintEngine {
    config: LintConfig,
    rules: Vec<Box<dyn Rule>>,
}

impl LintEngine {
    /// Create a new lint engine with the given configuration.
    pub fn new(config: LintConfig) -> Self {
        let mut rules: Vec<Box<dyn Rule>> = Vec::new();

        // Add rules based on configuration
        if config.is_rule_enabled(RuleCode::FST001) {
            rules.push(Box::new(DuplicateTypesRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST002) {
            rules.push(Box::new(ReorderInterfaceRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST003) {
            rules.push(Box::new(CommentRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST004) {
            rules.push(Box::new(UnusedOpensRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST005) {
            rules.push(Box::new(DeadCodeRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST006) {
            rules.push(Box::new(NamingRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST007) {
            rules.push(Box::new(Z3ComplexityRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST008) {
            rules.push(Box::new(ImportOptimizerRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST009) {
            rules.push(Box::new(ProofHintsRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST010) {
            rules.push(Box::new(SpecExtractorRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST011) {
            rules.push(Box::new(EffectCheckerRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST012) {
            rules.push(Box::new(RefinementSimplifierRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST013) {
            rules.push(Box::new(DocCheckerRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST014) {
            rules.push(Box::new(TestGeneratorRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST015) {
            rules.push(Box::new(ModuleDepsRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST016) {
            rules.push(Box::new(PerfProfilerRule::new()));
        }
        if config.is_rule_enabled(RuleCode::FST017) {
            rules.push(Box::new(SecurityRule::new()));
        }

        Self { config, rules }
    }

    /// Check files for issues.
    pub async fn check(&self, paths: &[PathBuf], format: OutputFormat, show_fixes: bool) -> i32 {
        info!("Checking {} path(s)", paths.len());

        let files = self.collect_files(paths);
        info!("Found {} F* file(s)", files.len());

        let mut all_diagnostics = Vec::new();
        let mut summary = LintSummary::default();
        summary.total_files = files.len();

        // Run single-file rules
        for file in &files {
            debug!("Checking file: {}", file.display());

            let content = match fs::read_to_string(file) {
                Ok(c) => c,
                Err(e) => {
                    warn!("Failed to read {}: {}", file.display(), e);
                    continue;
                }
            };

            for rule in &self.rules {
                if !rule.requires_pair() {
                    let diags = rule.check(file, &content);
                    all_diagnostics.extend(diags);
                }
            }
        }

        // Run pair rules (FST001, FST002)
        let pairs = find_fst_fsti_pairs(&files);
        debug!("Found {} .fst/.fsti pair(s)", pairs.len());

        for (fst_file, fsti_file) in &pairs {
            let fst_content = match fs::read_to_string(fst_file) {
                Ok(c) => c,
                Err(e) => {
                    warn!("Failed to read {}: {}", fst_file.display(), e);
                    continue;
                }
            };

            let fsti_content = match fs::read_to_string(fsti_file) {
                Ok(c) => c,
                Err(e) => {
                    warn!("Failed to read {}: {}", fsti_file.display(), e);
                    continue;
                }
            };

            for rule in &self.rules {
                if rule.requires_pair() {
                    let diags = rule.check_pair(fst_file, &fst_content, fsti_file, &fsti_content);
                    all_diagnostics.extend(diags);
                }
            }
        }

        // Count files with issues
        let files_with_issues: HashSet<&PathBuf> =
            all_diagnostics.iter().map(|d| &d.file).collect();
        summary.files_with_issues = files_with_issues.len();

        // Update summary
        for diag in &all_diagnostics {
            summary.add_diagnostic(diag);
        }

        // Print results
        if let Err(e) = print_diagnostics(&all_diagnostics, format, show_fixes) {
            eprintln!("Error printing diagnostics: {}", e);
        }
        if let Err(e) = print_summary(&summary, format) {
            eprintln!("Error printing summary: {}", e);
        }

        // Return exit code
        if all_diagnostics.is_empty() {
            0
        } else {
            1
        }
    }

    /// Fix files.
    ///
    /// By default (dry_run=true), this shows what WOULD be changed without modifying files.
    /// Set dry_run=false (via --apply flag) to actually write changes.
    ///
    /// Safety levels determine which fixes can be applied:
    /// - Safe: Can be auto-applied with --apply
    /// - Caution: Shows warning, applies with --apply
    /// - Unsafe: Requires --force in addition to --apply
    ///
    /// # Arguments
    /// * `paths` - Files or directories to process
    /// * `_format` - Output format for diagnostics (unused in dry-run mode)
    /// * `dry_run` - If true, show preview only; if false, actually apply fixes
    /// * `dry_run_format` - Output format for dry-run preview (concise, full, json)
    /// * `force` - If true, allow applying Unsafe fixes (requires explicit confirmation)
    pub async fn fix(
        &self,
        paths: &[PathBuf],
        _format: OutputFormat,
        dry_run: bool,
        dry_run_format: DryRunFormat,
        force: bool,
    ) -> i32 {
        let stdout = std::io::stdout();
        let mut handle = stdout.lock();

        // Print mode-appropriate header using new beautiful format
        if dry_run {
            if let Err(e) = print_dry_run_header(&mut handle) {
                eprintln!("Error printing header: {}", e);
            }
        } else if let Err(e) = print_apply_header(&mut handle) {
            eprintln!("Error printing header: {}", e);
        }
        drop(handle); // Release lock for subsequent output

        info!(
            "Fixing {} path(s){}",
            paths.len(),
            if dry_run { " (dry run)" } else { "" }
        );

        let files = self.collect_files(paths);
        info!("Found {} F* file(s)", files.len());

        // Cache file contents for building DryRunSummary
        let mut file_contents: std::collections::HashMap<PathBuf, String> =
            std::collections::HashMap::new();

        let mut all_diagnostics: Vec<Diagnostic> = Vec::new();

        // Run single-file rules and collect fixes
        for file in &files {
            let content = match fs::read_to_string(file) {
                Ok(c) => c,
                Err(e) => {
                    warn!("Failed to read {}: {}", file.display(), e);
                    continue;
                }
            };

            // Cache content for DryRunSummary
            file_contents.insert(file.clone(), content.clone());

            for rule in &self.rules {
                if !rule.requires_pair() {
                    let diags = rule.check(file, &content);
                    for diag in diags {
                        if diag.fix.is_some() {
                            all_diagnostics.push(diag);
                        }
                    }
                }
            }
        }

        // Run pair rules
        let pairs = find_fst_fsti_pairs(&files);

        for (fst_file, fsti_file) in &pairs {
            let fst_content = match fs::read_to_string(fst_file) {
                Ok(c) => c,
                Err(e) => {
                    warn!("Failed to read {}: {}", fst_file.display(), e);
                    continue;
                }
            };

            let fsti_content = match fs::read_to_string(fsti_file) {
                Ok(c) => c,
                Err(e) => {
                    warn!("Failed to read {}: {}", fsti_file.display(), e);
                    continue;
                }
            };

            // Cache content for DryRunSummary
            file_contents.insert(fst_file.clone(), fst_content.clone());
            file_contents.insert(fsti_file.clone(), fsti_content.clone());

            for rule in &self.rules {
                if rule.requires_pair() {
                    let diags = rule.check_pair(fst_file, &fst_content, fsti_file, &fsti_content);
                    for diag in diags {
                        if diag.fix.is_some() {
                            all_diagnostics.push(diag);
                        }
                    }
                }
            }
        }

        // Build dry-run summary for beautiful output
        let mut dry_run_summary = DryRunSummary::new();
        for diag in &all_diagnostics {
            if let Some(content) = file_contents.get(&diag.file) {
                dry_run_summary.add_fix(diag, content);
            }
        }
        dry_run_summary.finalize();

        // In dry-run mode, use the beautiful new output format
        if dry_run {
            if dry_run_summary.total_fixes == 0 {
                if let Err(e) = print_no_fixes_message() {
                    eprintln!("Error printing message: {}", e);
                }
            } else if let Err(e) = print_dry_run(&dry_run_summary, dry_run_format) {
                eprintln!("Error printing dry-run output: {}", e);
            }
            return 0;
        }

        // Filter diagnostics based on safety level
        // - Safe and Caution: Can be applied with --apply
        // - Unsafe: Requires --force in addition to --apply
        let (applicable_diagnostics, skipped_unsafe): (Vec<_>, Vec<_>) = all_diagnostics
            .into_iter()
            .partition(|d| {
                if let Some(ref fix) = d.fix {
                    // If force is set, allow all fixes
                    // Otherwise, only allow fixes that don't require force
                    force || fix.can_apply_without_force()
                } else {
                    false
                }
            });

        // Report skipped unsafe fixes if any
        if !skipped_unsafe.is_empty() && !force {
            let unsafe_count = skipped_unsafe.len();
            println!(
                "\x1b[1;33mNote: {} fix{} require{} --force to apply (Unsafe safety level).\x1b[0m",
                unsafe_count,
                if unsafe_count == 1 { "" } else { "es" },
                if unsafe_count == 1 { "s" } else { "" }
            );
            for diag in &skipped_unsafe {
                if let Some(ref fix) = diag.fix {
                    let reason = fix.unsafe_reason.as_deref().unwrap_or("Unsafe fix");
                    println!(
                        "  - {}: {} ({})",
                        diag.file.display(),
                        diag.rule,
                        reason
                    );
                }
            }
        }

        // Show caution warnings for Caution-level fixes
        let caution_fixes: Vec<_> = applicable_diagnostics
            .iter()
            .filter(|d| {
                d.fix.as_ref().map_or(false, |f| f.safety_level == FixSafetyLevel::Caution)
            })
            .collect();

        if !caution_fixes.is_empty() {
            println!(
                "\x1b[1;33mCaution: {} fix{} {} risk{} and should be reviewed.\x1b[0m",
                caution_fixes.len(),
                if caution_fixes.len() == 1 { "" } else { "es" },
                if caution_fixes.len() == 1 { "has" } else { "have" },
                if caution_fixes.len() == 1 { "" } else { "s" }
            );
        }

        // Apply mode: use the new FixApplicator with two-phase commit
        let config = FixApplicatorConfig::apply().with_verbose(true);
        let mut applicator = FixApplicator::new(config);

        // Apply all applicable fixes using two-phase commit
        match applicator.apply_batch(&applicable_diagnostics) {
            Ok(applied) => {
                let fixed_count = applied.len();
                let summary = applicator.summary();

                // Print apply mode results
                if fixed_count == 0 && summary.fixes_skipped == 0 {
                    if let Err(e) = print_no_fixes_message() {
                        eprintln!("Error printing message: {}", e);
                    }
                } else {
                    if let Err(e) = print_fixes_applied(fixed_count) {
                        eprintln!("Error printing message: {}", e);
                    }

                    if summary.fixes_skipped > 0 {
                        println!(
                            "\x1b[1;35m{} fix{} skipped (low confidence or unsafe).\x1b[0m",
                            summary.fixes_skipped,
                            if summary.fixes_skipped == 1 { "" } else { "es" }
                        );
                        // Print details of skipped fixes
                        for (file, reason) in &summary.skipped_reasons {
                            println!("  - {}: {}", file.display(), reason);
                        }
                    }

                    if summary.fixes_failed > 0 {
                        println!(
                            "\x1b[1;31m{} fix{} failed.\x1b[0m",
                            summary.fixes_failed,
                            if summary.fixes_failed == 1 { "" } else { "es" }
                        );
                        for (file, reason) in &summary.failed_reasons {
                            println!("  - {}: {}", file.display(), reason);
                        }
                    }
                }
            }
            Err(e) => {
                error!("Fix application failed: {}", e);
                eprintln!("\x1b[1;31mError: {}\x1b[0m", e);
                return 1;
            }
        }

        0
    }

    /// Collect all F* files from paths.
    fn collect_files(&self, paths: &[PathBuf]) -> Vec<PathBuf> {
        let mut files = Vec::new();

        for path in paths {
            if path.is_file() {
                if is_fstar_file(path) {
                    files.push(path.clone());
                }
            } else if path.is_dir() {
                self.collect_files_recursive(path, &mut files);
            }
        }

        files
    }

    /// Recursively collect F* files from a directory.
    fn collect_files_recursive(&self, dir: &PathBuf, files: &mut Vec<PathBuf>) {
        let entries = match fs::read_dir(dir) {
            Ok(e) => e,
            Err(e) => {
                warn!("Failed to read directory {}: {}", dir.display(), e);
                return;
            }
        };

        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() && is_fstar_file(&path) {
                files.push(path);
            } else if path.is_dir() {
                // Skip hidden directories and common non-source directories
                let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                if !name.starts_with('.') && name != "node_modules" && name != "target" {
                    self.collect_files_recursive(&path, files);
                }
            }
        }
    }
}

/// Check if a file is an F* source file.
fn is_fstar_file(path: &PathBuf) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext == "fst" || ext == "fsti")
        .unwrap_or(false)
}

// Note: The old apply_fix_with_validation, build_fixed_content, and print_fix_preview
// functions have been superseded by the FixApplicator module which provides:
// - Two-phase commit (validate to temp files, then atomically apply)
// - Full rollback capability
// - Progress reporting
// - Interactive mode for manual approval
// - Safety limits to prevent runaway operations
//
// The following unused code is kept for backwards compatibility with tests
// that may reference these functions. New code should use FixApplicator.

/// Minimum confidence threshold for auto-applying fixes (legacy).
#[allow(dead_code)]
const MIN_FIX_CONFIDENCE: f64 = 0.8;

/// Apply a fix to the filesystem with validation and atomic write safety.
///
/// Returns (success, validation_result) where success indicates if the fix was applied.
/// Uses AtomicWriter to ensure file modifications are safe and reversible.
fn apply_fix_with_validation(
    fix: &super::rules::Fix,
    dry_run: bool,
) -> std::io::Result<(bool, Option<FixValidation>)> {
    // Check fix's own safety flags first
    if !fix.is_safe {
        debug!(
            "Skipping unsafe fix: {} (reason: {:?})",
            fix.message,
            fix.unsafe_reason
        );
        return Ok((false, None));
    }

    // Only auto-apply high confidence fixes
    if fix.confidence != FixConfidence::High {
        debug!(
            "Skipping low/medium confidence fix: {} (confidence: {})",
            fix.message, fix.confidence
        );
        return Ok((false, None));
    }

    // Create atomic writer for safe file modifications
    let atomic_writer = AtomicWriter::new();

    // For each edit, validate the fix before applying
    for edit in &fix.edits {
        let original_content = fs::read_to_string(&edit.file)?;

        // Build the new content to validate
        let new_content = build_fixed_content(&original_content, edit)?;

        // Validate the fix
        let validation = validate_fix_content(&original_content, &new_content, &edit.file);

        // Check if fix passes validation
        if !validation.can_auto_apply(MIN_FIX_CONFIDENCE) {
            debug!(
                "Fix validation failed for {}: confidence={:.2}, is_safe={}, warnings={:?}",
                edit.file.display(),
                validation.confidence,
                validation.is_safe,
                validation.warnings
            );
            return Ok((false, Some(validation)));
        }

        // Apply the fix if not dry run using atomic write with backup
        if !dry_run {
            match atomic_writer.write_with_backup(&edit.file, &new_content) {
                Ok(backup_path) => {
                    info!(
                        "Atomically wrote {} (backup: {})",
                        edit.file.display(),
                        backup_path.display()
                    );
                }
                Err(e) => {
                    error!("Atomic write failed for {}: {}", edit.file.display(), e);
                    return Err(atomic_write_error_to_io_error(e));
                }
            }
        }
    }

    Ok((true, None))
}

/// Convert AtomicWriteError to std::io::Error for compatibility.
fn atomic_write_error_to_io_error(e: AtomicWriteError) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::Other, e.to_string())
}

/// Build the fixed content from an edit without writing to disk.
fn build_fixed_content(
    original: &str,
    edit: &super::rules::Edit,
) -> std::io::Result<String> {
    let lines: Vec<&str> = original.lines().collect();

    // Calculate line ranges (convert 1-indexed to 0-indexed)
    let start_line = edit.range.start_line.saturating_sub(1);
    let end_line = edit.range.end_line.saturating_sub(1);

    // Build new content
    let mut new_content = String::new();

    // Add lines before the edit
    for (i, line) in lines.iter().enumerate() {
        if i < start_line {
            new_content.push_str(line);
            new_content.push('\n');
        }
    }

    // Add the replacement text
    new_content.push_str(&edit.new_text);

    // Add lines after the edit
    for (i, line) in lines.iter().enumerate() {
        if i >= end_line {
            new_content.push_str(line);
            new_content.push('\n');
        }
    }

    Ok(new_content)
}

/// Print a detailed preview of what a fix would change.
fn print_fix_preview(
    file: &PathBuf,
    diag: &Diagnostic,
    fix: &super::rules::Fix,
) {
    let yellow = "\x1b[33m";
    let green = "\x1b[32m";
    let red = "\x1b[31m";
    let cyan = "\x1b[36m";
    let bold = "\x1b[1m";
    let reset = "\x1b[0m";
    let dim = "\x1b[2m";

    println!();
    println!("{}{}Would fix: {}{}", bold, cyan, file.display(), reset);
    println!(
        "  {}Rule: {} ({}){}",
        dim,
        diag.rule,
        diag.rule.name(),
        reset
    );
    println!(
        "  {}Lines: {}-{}{}",
        dim,
        diag.range.start_line,
        diag.range.end_line,
        reset
    );
    println!("  {}Message: {}{}", dim, diag.message, reset);
    println!("  {}Fix: {}{}", dim, fix.message, reset);

    for edit in &fix.edits {
        // Try to read the original content to show before/after
        if let Ok(content) = fs::read_to_string(&edit.file) {
            let lines: Vec<&str> = content.lines().collect();
            let start_line = edit.range.start_line.saturating_sub(1);
            let end_line = edit.range.end_line.saturating_sub(1);

            // Show context (lines being removed)
            if start_line < lines.len() {
                println!();
                println!("  {}--- Before:{}", red, reset);
                for i in start_line..std::cmp::min(end_line + 1, lines.len()) {
                    // Limit to first 10 lines to avoid huge output
                    if i - start_line >= 10 {
                        println!("  {}  ... ({} more lines){}", red, end_line - i, reset);
                        break;
                    }
                    println!(
                        "  {}{:>4} | {}{}",
                        red,
                        i + 1,
                        lines.get(i).unwrap_or(&""),
                        reset
                    );
                }
            }

            // Show new content
            if !edit.new_text.is_empty() {
                println!();
                println!("  {}+++ After:{}", green, reset);
                for (i, line) in edit.new_text.lines().enumerate() {
                    // Limit to first 10 lines
                    if i >= 10 {
                        let remaining = edit.new_text.lines().count() - i;
                        println!("  {}  ... ({} more lines){}", green, remaining, reset);
                        break;
                    }
                    println!(
                        "  {}{:>4} | {}{}",
                        green,
                        start_line + i + 1,
                        line,
                        reset
                    );
                }
            } else {
                println!();
                println!("  {}+++ After: (lines deleted){}", yellow, reset);
            }
        }
    }
    println!();
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// Helper to create a test file with content.
    fn create_test_file(dir: &TempDir, name: &str, content: &str) -> PathBuf {
        let path = dir.path().join(name);
        fs::write(&path, content).expect("Failed to write test file");
        path
    }

    /// Helper to read a test file content.
    fn read_test_file(path: &PathBuf) -> String {
        fs::read_to_string(path).expect("Failed to read test file")
    }

    // =========================================================================
    // CLI BEHAVIOR TESTS
    // =========================================================================

    #[test]
    fn test_lint_config_default() {
        let config = LintConfig::default();
        assert!(config.select.is_none());
        assert!(config.ignore.is_empty());
        assert!(config.fstar_exe.is_none());
    }

    #[test]
    fn test_lint_config_with_select() {
        let config = LintConfig::new(Some("FST001,FST002".to_string()), None, None);
        assert!(config.is_rule_enabled(RuleCode::FST001));
        assert!(config.is_rule_enabled(RuleCode::FST002));
        assert!(!config.is_rule_enabled(RuleCode::FST003));
    }

    #[test]
    fn test_lint_config_with_ignore() {
        let config = LintConfig::new(None, Some("FST001".to_string()), None);
        assert!(!config.is_rule_enabled(RuleCode::FST001));
        assert!(config.is_rule_enabled(RuleCode::FST002));
    }

    // =========================================================================
    // DRY-RUN MODE TESTS
    // These tests verify that dry-run mode does NOT modify files.
    // =========================================================================

    #[tokio::test]
    async fn test_dry_run_does_not_modify_files() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create a test F* file with an unused open statement
        let original_content = r#"module Test

open FStar.Pervasives

let x = 1
"#;
        let fst_file = create_test_file(&temp_dir, "Test.fst", original_content);

        // Run fix in dry-run mode (the default)
        let config = LintConfig::new(Some("FST004".to_string()), None, None);
        let engine = LintEngine::new(config);
        let _exit_code = engine.fix(&[fst_file.clone()], OutputFormat::Text, true, DryRunFormat::Full, false).await;

        // Verify file was NOT modified
        let content_after = read_test_file(&fst_file);
        assert_eq!(
            original_content, content_after,
            "Dry-run mode should NOT modify files"
        );
    }

    #[tokio::test]
    async fn test_dry_run_returns_zero_exit_code() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        let content = r#"module Test
let x = 1
"#;
        let fst_file = create_test_file(&temp_dir, "Test.fst", content);

        let config = LintConfig::default();
        let engine = LintEngine::new(config);
        let exit_code = engine.fix(&[fst_file], OutputFormat::Text, true, DryRunFormat::Full, false).await;

        assert_eq!(exit_code, 0, "Fix command should return 0 exit code");
    }

    // =========================================================================
    // APPLY MODE TESTS
    // These tests verify that --apply mode DOES modify files.
    // =========================================================================

    #[tokio::test]
    async fn test_apply_mode_modifies_files() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create a test F* file with dead code that can be fixed
        // Using a simple file that has an issue the linter can fix
        let original_content = r#"module Test

(** Documentation for x *)
let x = 1
"#;
        let fst_file = create_test_file(&temp_dir, "Test.fst", original_content);

        // Run fix in apply mode (dry_run = false)
        let config = LintConfig::new(Some("FST013".to_string()), None, None);
        let engine = LintEngine::new(config);
        let _exit_code = engine.fix(&[fst_file.clone()], OutputFormat::Text, false, DryRunFormat::Full, false).await;

        // Note: This test may or may not modify the file depending on what
        // FST013 (doc checker) finds. The important thing is that with
        // dry_run=false, the engine CAN write to files.
        // We're testing the mechanism, not specific rule behavior.
    }

    // =========================================================================
    // FILE COLLECTION TESTS
    // =========================================================================

    #[tokio::test]
    async fn test_collect_fstar_files_only() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create various files
        create_test_file(&temp_dir, "Test.fst", "module Test\n");
        create_test_file(&temp_dir, "Test.fsti", "module Test\n");
        create_test_file(&temp_dir, "README.md", "# README\n");
        create_test_file(&temp_dir, "test.rs", "fn main() {}\n");

        let config = LintConfig::default();
        let engine = LintEngine::new(config);
        let files = engine.collect_files(&[temp_dir.path().to_path_buf()]);

        // Should only collect .fst and .fsti files
        assert_eq!(files.len(), 2);
        assert!(files.iter().all(|f| {
            let ext = f.extension().and_then(|e| e.to_str());
            ext == Some("fst") || ext == Some("fsti")
        }));
    }

    #[tokio::test]
    async fn test_collect_skips_hidden_directories() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create a hidden directory with an F* file
        let hidden_dir = temp_dir.path().join(".hidden");
        fs::create_dir(&hidden_dir).expect("Failed to create hidden dir");
        fs::write(hidden_dir.join("Hidden.fst"), "module Hidden\n")
            .expect("Failed to write hidden file");

        // Create a visible F* file
        create_test_file(&temp_dir, "Visible.fst", "module Visible\n");

        let config = LintConfig::default();
        let engine = LintEngine::new(config);
        let files = engine.collect_files(&[temp_dir.path().to_path_buf()]);

        // Should only collect the visible file
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("Visible.fst"));
    }

    // =========================================================================
    // CHECK MODE TESTS
    // =========================================================================

    #[tokio::test]
    async fn test_check_returns_zero_for_clean_files() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create a clean F* file (no issues)
        let content = r#"module Test

let x : nat = 1
"#;
        let fst_file = create_test_file(&temp_dir, "Test.fst", content);

        // Run check with a rule that won't find issues
        let config = LintConfig::new(Some("FST003".to_string()), None, None);
        let engine = LintEngine::new(config);
        let exit_code = engine.check(&[fst_file], OutputFormat::Text, false).await;

        assert_eq!(exit_code, 0, "Check should return 0 for clean files");
    }

    // =========================================================================
    // SAFETY BEHAVIOR TESTS
    // These tests verify that the safety features work correctly.
    // =========================================================================

    #[tokio::test]
    async fn test_fix_with_no_fixable_issues() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create a file with no fixable issues
        let content = r#"module Test
let x = 1
"#;
        let fst_file = create_test_file(&temp_dir, "Test.fst", content);
        let original = read_test_file(&fst_file);

        // Run fix (even in apply mode, nothing should change)
        let config = LintConfig::default();
        let engine = LintEngine::new(config);
        let _exit_code = engine.fix(&[fst_file.clone()], OutputFormat::Text, false, DryRunFormat::Full, false).await;

        let after = read_test_file(&fst_file);
        assert_eq!(
            original, after,
            "File should not change when there are no fixable issues"
        );
    }
}