aurora-lint 0.5.2

aurora-lint - a fast CERT C static analyzer
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
/// Which storage object a call argument names, in the caller's frame
/// (task 936).
pub mod argument_objects;
/// Shared AST-based fixed-array-declaration size resolution (task 504).
pub mod array_size;
pub mod buffer_size;
pub mod cfg;
/// Optional `compile_commands.json` ingestion: feeds a build's include search
/// paths and `-D` macro state into the existing prescan/expansion pipeline.
pub mod compile_commands;
pub mod concurrency_roots;
pub mod const_eval;
/// Cross-file project context ([`context::ProjectContext`]) gathered by the
/// pre-scan phase and injected into rules that need whole-project data.
pub mod context;
/// Pre-parse repair for a preprocessor guard that falls between a control-flow
/// header (`if`/`while`/`for`) and the body it governs -- `tree-sitter-c`
/// synthesizes an empty consequence, which reads as an unbraced body.
pub mod control_header_preproc_guard;
pub mod dataflow;
/// Preprocessor-dead line ranges under the assumed platform profile, for
/// collectors that must keep one of several same-named conditional
/// definitions (task 1142).
pub mod dead_regions;
pub mod embedded_js_blank;
pub mod empty_macro_blank;
pub mod function_summary;
pub mod init_state;
/// Pre-parse repair for a label immediately followed by an `#ifdef`/`#if`
/// block -- `tree-sitter-c`'s `labeled_statement` can't parse that shape.
pub mod label_preproc_guard;
pub mod macro_expand;
pub mod macro_gaps;
pub mod macro_semantics;
/// Noreturn-function detection shared by CFG construction (task 648).
pub mod noreturn;
pub mod null_state;
pub mod paren_preproc_guard;
/// Points-to/alias analysis: resolving an lvalue expression to the set of
/// storage locations it may refer to.
pub mod points_to;
/// Which byte offsets a preprocessor conditional puts in mutually exclusive
/// arms, so a positional lookup does not answer with a record from a branch
/// this position cannot coexist with.
pub mod preproc_arms;
pub mod preproc_dangling_else;
pub mod preproc_split_chain;
/// The pre-scan phase: a first pass over the project (and sibling headers)
/// that builds the [`context::ProjectContext`] later rule passes consume.
pub mod prescan;
pub mod relevance;
/// Inline `AURORA-SUPPRESS` comment parsing and suppression-file matching.
pub mod suppression;
/// Recovering the compiler's *implicit* system header directories
/// (`cc -E -Wp,-v -`), which a `compile_commands.json` can never contain.
pub mod system_includes;
pub mod unknown_identifier_recovery;
pub mod value_range;
pub mod vra_access;

use super::files::ProjectSource;
use super::manifest::RuleManifest;
use super::parser::CParser;
use super::progress::ProgressReporter;
use super::rules::{RuleRegistry, RuleViolation};
use suppression::SuppressionManager;

use anyhow::Result;
use rayon::prelude::*;
use std::collections::HashMap;
use std::fs;
use std::sync::atomic::{AtomicUsize, Ordering};

/// A violation that was suppressed by an inline AURORA-SUPPRESS comment.
pub struct SuppressedViolation {
    /// The violation that would have fired without the suppression.
    pub violation: RuleViolation,
    /// The justification text from the suppression comment/file.
    pub justification: String,
}

/// Results from project analysis, containing both active and suppressed violations.
pub struct AnalysisResults {
    /// Violations that were not suppressed.
    pub violations: Vec<RuleViolation>,
    /// Violations suppressed by an inline comment or suppression file.
    pub suppressed: Vec<SuppressedViolation>,
    /// Where the macro-expansion engine was blind during this scan; built
    /// only when `report_macro_gaps` was requested (task 1180).
    pub macro_gaps: Option<macro_gaps::MacroGapReport>,
}

/// Run every enabled rule over `project_source`, returning active and
/// suppressed violations. `directories`/`include_paths`/`excludes` scope
/// which files are analyzed; `diff_only` limits analysis to changed files;
/// `save_prescan`/`load_prescan` cache the cross-file pre-scan phase across
/// runs; `jobs` bounds parallelism. `compile_db`, when supplied, contributes
/// the build's `-D` macro state to the cross-file context (its include paths
/// are expected to be already merged into `include_paths` by the caller).
/// `report_macro_gaps` adds a parse-only audit pass that fills
/// `AnalysisResults::macro_gaps`; it never changes a finding.
pub fn analyze_project(
    project_source: &ProjectSource,
    manifest: &RuleManifest,
    progress: Option<&dyn ProgressReporter>,
    directories: &[String],
    include_paths: &[String],
    excludes: &[String],
    diff_only: bool,
    suppress_file: Option<&str>,
    save_prescan: Option<&str>,
    load_prescan: Option<&str>,
    compile_db: Option<&compile_commands::CompileDb>,
    jobs: usize,
    report_macro_gaps: bool,
) -> Result<AnalysisResults> {
    let mut violations = Vec::new();
    let mut suppressed = Vec::new();
    let registry = RuleRegistry::new();

    // Pre-compute whether any enabled rule needs VRA (used by prescan + per-file analysis)
    let needs_vra = manifest
        .enabled_rules()
        .any(|(rule_id, _)| registry.get_rule(rule_id).is_some_and(|r| r.needs_vra()));

    // Load or compute cross-file context (prescan, includes, optional cache save)
    let context = load_project_context(
        project_source,
        progress,
        directories,
        include_paths,
        diff_only,
        save_prescan,
        load_prescan,
        compile_db,
        needs_vra,
    )?;

    if context.has_cross_file_data() {
        set_project_context_for_enabled(&registry, manifest, &context);
    }

    // The parse-repair pass consults the prescan's macro table to blank a
    // stranded declaration's *macro* rather than its real type or declarator
    // (task 1019). Built once and shared: parallel mode makes one parser per
    // file.
    let repair_macros = std::sync::Arc::new(
        unknown_identifier_recovery::RepairMacros::from_context(&context),
    );

    warn_unimplemented_rules(manifest, &registry);

    let c_files = collect_c_files(project_source, diff_only, excludes)?;
    let total_files = c_files.len();
    let mut suppression_manager = build_suppression_manager(suppress_file, project_source);

    // Independent of the rules: it reads the same files and context, so it
    // can run first and the findings loop below stays untouched.
    let macro_gaps = report_macro_gaps
        .then(|| macro_gaps::build_report(&c_files, &context, directories, include_paths));

    // Determine effective parallelism
    let effective_jobs = if jobs == 0 {
        std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1)
    } else {
        jobs
    };

    if effective_jobs > 1 && total_files > 1 {
        // Parallel analysis with rayon — per-file parser and rule registry
        // Worker threads get an explicit stack, not the 2 MiB a spawned
        // thread defaults to on Linux. Several analyses recurse with AST
        // nesting depth, and real C reaches thousands of levels, so a
        // parallel scan aborted the whole process on input a `-j 1` run --
        // which does this work on the 8 MiB main thread -- completed
        // (task 952, this repo).
        const WORKER_STACK_BYTES: usize = 16 * 1024 * 1024;
        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(effective_jobs)
            .stack_size(WORKER_STACK_BYTES)
            .build()?;
        let has_cross_file_data = context.has_cross_file_data();
        let file_counter = AtomicUsize::new(0);

        let results: Vec<_> = pool.install(|| {
            c_files
                .iter()
                .par_bridge()
                .map(|file_path| {
                    if let Some(reporter) = progress {
                        if reporter.is_cancelled() {
                            return (Vec::new(), Vec::new());
                        }
                    }

                    let mut parser = match CParser::new() {
                        Ok(p) => p,
                        Err(_) => return (Vec::new(), Vec::new()),
                    };
                    parser.set_repair_macros(std::sync::Arc::clone(&repair_macros));
                    let file_registry = RuleRegistry::new();
                    if has_cross_file_data {
                        set_project_context_for_enabled(&file_registry, manifest, &context);
                    }
                    let mut file_supp = suppression_manager.clone();

                    let result = analyze_one_file(
                        file_path,
                        &mut parser,
                        &file_registry,
                        manifest,
                        &context,
                        needs_vra,
                        &mut file_supp,
                        None,
                        0,
                        total_files,
                        false,
                    );

                    let completed = file_counter.fetch_add(1, Ordering::Relaxed) + 1;
                    if let Some(reporter) = progress {
                        reporter.report_file(completed, total_files, file_path, "");
                    }

                    result
                })
                .collect()
        });

        for (v, s) in results {
            violations.extend(v);
            suppressed.extend(s);
        }

        sort_for_deterministic_output(&mut violations, &mut suppressed);

        if let Some(reporter) = progress {
            reporter.report_complete(violations.len());
        }

        return Ok(AnalysisResults {
            violations,
            suppressed,
            macro_gaps,
        });
    }

    // Sequential analysis (single-threaded)
    // Fresh registry per file to prevent cross-file state leakage from RefCell fields
    let mut parser = CParser::new()?;
    parser.set_repair_macros(std::sync::Arc::clone(&repair_macros));
    let has_cross_file_data = context.has_cross_file_data();

    for (file_idx, file_path) in c_files.iter().enumerate() {
        // Check for cancellation before processing each file
        if let Some(reporter) = progress {
            if reporter.is_cancelled() {
                // Return partial results collected so far
                break;
            }
        }

        // Create fresh rule instances per file (matches parallel mode behavior)
        let file_registry = RuleRegistry::new();
        if has_cross_file_data {
            set_project_context_for_enabled(&file_registry, manifest, &context);
        }

        let (file_violations, file_suppressed) = analyze_one_file(
            file_path,
            &mut parser,
            &file_registry,
            manifest,
            &context,
            needs_vra,
            &mut suppression_manager,
            progress,
            file_idx,
            total_files,
            true,
        );
        violations.extend(file_violations);
        suppressed.extend(file_suppressed);
    }

    sort_for_deterministic_output(&mut violations, &mut suppressed);

    // Report completion
    if let Some(reporter) = progress {
        reporter.report_complete(violations.len());
    }

    Ok(AnalysisResults {
        violations,
        suppressed,
        macro_gaps,
    })
}

/// Load or compute the cross-file project context: prescan cache, directory
/// prescan or sibling-header scan, #include resolution, and optional cache save.
#[allow(clippy::too_many_arguments)]
fn load_project_context(
    project_source: &ProjectSource,
    progress: Option<&dyn ProgressReporter>,
    directories: &[String],
    include_paths: &[String],
    diff_only: bool,
    save_prescan: Option<&str>,
    load_prescan: Option<&str>,
    compile_db: Option<&compile_commands::CompileDb>,
    needs_vra: bool,
) -> Result<context::ProjectContext> {
    let mut context = if let Some(cache_path) = load_prescan {
        let path = std::path::Path::new(cache_path);
        if path.exists() {
            if let Some(reporter) = progress {
                reporter.report_prescan_start(0);
            }
            let ctx = context::ProjectContext::load_from_file(path)?;
            if let Some(reporter) = progress {
                reporter.report_prescan_complete(ctx.known_functions.len());
            }
            ctx
        } else {
            anyhow::bail!("Prescan cache file not found: {}", cache_path);
        }
    } else if directories.is_empty() {
        // No -d: the target is its own context. Prescan the scan set itself
        // (every C file in the target, not the --diff subset -- unmodified
        // files are exactly the context a diff needs) as if `-d <target>`
        // had been given, so a first-touch `aurora-lint foo.c` has seen the
        // definitions in the file it is about to analyse. Before this, a
        // single-file target got only its sibling headers' declarations and
        // a directory target nothing at all, producing findings that
        // vanished the moment the same directory was named with -d (task
        // 980). -d remains the way to add context from OUTSIDE the target.
        let mut files: Vec<std::path::PathBuf> = project_source
            .get_c_files()?
            .into_iter()
            .map(std::path::PathBuf::from)
            .collect();
        if let Some(dir) = project_source.prescan_dir() {
            files.extend(prescan::sibling_headers(&dir));
        }
        prescan::prescan_files(files, progress, needs_vra)?
    } else {
        prescan::prescan_directories(directories, progress, needs_vra)?
    };

    // Resolve #include directives against include search paths
    if !include_paths.is_empty() {
        let c_files = if diff_only {
            project_source.get_modified_c_files()?
        } else {
            project_source.get_c_files()?
        };
        // The project is the tree being scanned plus any -d directory: a
        // search root outside it cannot make an unresolvable include a
        // *project* header (task 690).
        let mut project_roots: Vec<String> = vec![project_source.get_root_path().to_string()];
        project_roots.extend(directories.iter().cloned());
        prescan::resolve_includes(
            &c_files,
            include_paths,
            &project_roots,
            &mut context,
            progress,
            needs_vra,
        )?;
    }

    // Documented preconditions override the call-site vote for parameter
    // null seeding; both the -d pre-scan and the -I header pass contribute.
    prescan::apply_documented_preconditions(&mut context);

    // Fold in the build's `-D` macro state last, so that any macro the real
    // source already defined wins over a command-line flag of the same name
    // (see `compile_commands`' gap-filling invariant). Runs before the cache
    // save so a saved prescan carries the same context a live run would build.
    if let Some(db) = compile_db {
        db.merge_defines_into(&mut context)?;
    }

    // Save prescan cache if requested (after prescan + include resolution)
    if let Some(cache_path) = save_prescan {
        context.save_to_file(std::path::Path::new(cache_path))?;
        eprintln!(
            "Saved prescan cache ({} functions, {} summaries) to: {}",
            context.known_functions.len(),
            context.function_summaries.len(),
            cache_path,
        );
    }

    Ok(context)
}

/// Hand the cross-file context to the rules this scan will actually run.
///
/// Every file gets a fresh registry (see the per-file loops above), and most
/// rules take the context by deep-copying the parts they read -- function
/// summaries, macro tables, an inverted call graph -- into their own cells.
/// Offering it to all ~300 registered rules made that copy the dominant cost
/// of a scan: on a Juliet CWE directory it outweighed parsing, CFG/VRA and
/// the enabled rules' own checks combined by an order of magnitude, and it
/// grew with every rule that learned to read a new context table. Only a
/// rule the manifest enables is ever asked to check a file, so only those
/// receive the context.
fn set_project_context_for_enabled(
    registry: &RuleRegistry,
    manifest: &RuleManifest,
    context: &context::ProjectContext,
) {
    for (rule_id, _) in manifest.enabled_rules() {
        if let Some(rule) = registry.get_rule(rule_id) {
            rule.set_project_context(context);
        }
    }
}

/// Warn about rules that are enabled in the manifest but have no implementation.
fn warn_unimplemented_rules(manifest: &RuleManifest, registry: &RuleRegistry) {
    let mut unimplemented_rules = Vec::new();
    for (rule_id, _) in manifest.enabled_rules() {
        if registry.get_rule(rule_id).is_none() {
            unimplemented_rules.push(rule_id.clone());
        }
    }

    if !unimplemented_rules.is_empty() {
        eprintln!("Warning: The following rules are enabled in manifest but not implemented:");
        for rule_id in &unimplemented_rules {
            eprintln!("  - {}", rule_id);
        }
        eprintln!("These rules will be skipped during analysis.\n");
    }
}

/// Collect the C files to analyze: gather (all or modified), drop ignored
/// matches (`toolchain.toml` `[ignore].paths` plus `--exclude`), then sort by
/// size descending for LPT scheduling.
fn collect_c_files(
    project_source: &ProjectSource,
    diff_only: bool,
    excludes: &[String],
) -> Result<Vec<String>> {
    let mut c_files = if diff_only {
        project_source.get_modified_c_files()?
    } else {
        project_source.get_c_files()?
    };

    // Drop files matching a project-wide `toolchain.toml` ignore or a
    // --exclude path glob (e.g. checked-in amalgamations or test harnesses).
    // Prescan/cross-file context is intentionally left intact so excluded
    // files still contribute callee definitions; only their own findings are
    // suppressed.
    let ignore = build_path_ignore(project_source, excludes)?;
    let root = project_source.get_root_path();
    let before = c_files.len();
    c_files.retain(|f| !ignore.is_ignored(std::path::Path::new(&relative_to_root(f, root))));
    let removed = before - c_files.len();
    if removed > 0 {
        eprintln!("Excluded {} file(s) matching ignore patterns", removed);
    }

    // LPT scheduling: sort files by size descending so largest files are dispatched first.
    // Combined with par_bridge() demand-driven dispatch, this implements Graham's LPT
    // algorithm (1969) for makespan minimization — (4/3 - 1/3m) approximation ratio.
    c_files
        .sort_by_cached_key(|f| std::cmp::Reverse(fs::metadata(f).map(|m| m.len()).unwrap_or(0)));

    Ok(c_files)
}

/// Builds the combined ignore matcher from `toolchain.toml`'s shared
/// `[ignore].paths` (discovered by walking up from the project root) and the
/// CLI's `--exclude` globs, so a project's file/directory ignores can be
/// expressed once instead of only via `--exclude` on every invocation.
fn build_path_ignore(
    project_source: &ProjectSource,
    excludes: &[String],
) -> Result<lang_parsing_substrate::PathIgnore> {
    let mut patterns: Vec<String> = Vec::new();
    let root = std::path::Path::new(project_source.get_root_path());
    if let Some(toolchain) = crate::toolchain::ToolchainConfig::discover(root)? {
        patterns.extend(toolchain.ignore.paths);
    }
    patterns.extend(excludes.iter().cloned());

    // Validate patterns individually so one bad `--exclude` glob doesn't
    // discard every other ignore pattern (toolchain.toml's included).
    let valid: Vec<String> = patterns
        .into_iter()
        .filter(|p| {
            let ok = lang_parsing_substrate::PathIgnore::new([p.as_str()]).is_ok();
            if !ok {
                eprintln!("Warning: invalid ignore glob '{}'", p);
            }
            ok
        })
        .collect();

    lang_parsing_substrate::PathIgnore::new(&valid)
        .map_err(|e| anyhow::anyhow!("Invalid ignore glob pattern: {e}"))
}

/// Strips `root` (and a leading path separator) from `path`, and normalizes
/// to `/` separators, so a pattern like `"vendor/**"` in `toolchain.toml`
/// matches regardless of whether the project was opened with an absolute or
/// relative path — glob patterns anchor to the start of the matched string.
fn relative_to_root(path: &str, root: &str) -> String {
    let normalized = path.replace('\\', "/");
    let root_normalized = root.replace('\\', "/");
    normalized
        .strip_prefix(&root_normalized)
        .map(|s| s.trim_start_matches('/').to_string())
        .unwrap_or(normalized)
}

/// Build a suppression manager, loading the TOML suppression file if provided
/// or auto-detected at `<root>/suppress.toml` — the shared, all-tools file
/// from `lang_parsing_substrate/docs/unified-config-spec.md` — falling back
/// to the legacy `<root>/.aurora-lint-suppress.toml` and `<root>/.sqc-suppress.toml`
/// names if `suppress.toml` isn't present (all are parsed with the same
/// `[[suppress]]` schema).
fn build_suppression_manager(
    suppress_file: Option<&str>,
    project_source: &ProjectSource,
) -> SuppressionManager {
    let mut suppression_manager = SuppressionManager::new();

    let toml_path = suppress_file.map(String::from).or_else(|| {
        let root = std::path::Path::new(project_source.get_root_path());
        [
            root.join("suppress.toml"),
            root.join(".aurora-lint-suppress.toml"),
            root.join(".sqc-suppress.toml"),
        ]
        .into_iter()
        .find(|p| p.exists())
        .and_then(|p| p.to_str().map(String::from))
    });
    if let Some(ref path) = toml_path {
        match suppression_manager.load_from_toml(path) {
            Ok(count) => {
                let wc = suppression_manager.wildcard_count();
                if wc > 0 {
                    eprintln!(
                        "Loaded {} suppressions ({} wildcard) from {}",
                        count, wc, path
                    );
                } else {
                    eprintln!("Loaded {} suppressions from {}", count, path);
                }
            }
            Err(e) => {
                eprintln!("Warning: {}", e);
            }
        }
    }

    suppression_manager
}

/// Total order on violations, so two runs of one binary over one tree
/// export byte-identical files. `(file, line, column, rule_id)` alone is
/// not total: a rule that reports two messages at one site, or emits the
/// same finding twice, leaves those records in whatever order the worker
/// threads finished, and a `cmp` of two exports fails on every pair of
/// runs even when nothing changed (task 932). Records equal on every field
/// here are indistinguishable in any export, so their relative order does
/// not matter.
fn violation_order(a: &RuleViolation, b: &RuleViolation) -> std::cmp::Ordering {
    a.file_path
        .cmp(&b.file_path)
        .then(a.line.cmp(&b.line))
        .then(a.column.cmp(&b.column))
        .then(a.rule_id.cmp(&b.rule_id))
        .then(a.message.cmp(&b.message))
        .then(a.suggestion.cmp(&b.suggestion))
        .then(a.requires_manual_review.cmp(&b.requires_manual_review))
}

/// Order both result vectors by [`violation_order`]. Called on the
/// sequential path as well as the parallel one, so `-j 1` and `-j N`
/// produce the same bytes, and on `suppressed` too, since SARIF exports
/// it alongside the active findings.
fn sort_for_deterministic_output(
    violations: &mut [RuleViolation],
    suppressed: &mut [SuppressedViolation],
) {
    violations.sort_by(violation_order);
    suppressed.sort_by(|a, b| {
        violation_order(&a.violation, &b.violation).then(a.justification.cmp(&b.justification))
    });
}

/// Parse and run all enabled rules over a single file, partitioning findings
/// into active and suppressed. Shared by the parallel and sequential drivers.
///
/// When `per_rule_progress` is set (sequential mode), cancellation is checked
/// and progress reported before each rule; parallel mode reports once per file
/// in the caller instead.
#[allow(clippy::too_many_arguments)]
fn analyze_one_file(
    file_path: &str,
    parser: &mut CParser,
    file_registry: &RuleRegistry,
    manifest: &RuleManifest,
    context: &context::ProjectContext,
    needs_vra: bool,
    suppression_manager: &mut SuppressionManager,
    progress: Option<&dyn ProgressReporter>,
    file_idx: usize,
    total_files: usize,
    per_rule_progress: bool,
) -> (Vec<RuleViolation>, Vec<SuppressedViolation>) {
    let mut file_violations = Vec::new();
    let mut file_suppressed = Vec::new();

    let parsed = match parser.parse_file(file_path) {
        Ok(parsed) => Some(parsed),
        Err(e) => {
            // A file the directory walk listed but the parser would not
            // take -- a binary blob with a C extension (task 1131), an
            // unreadable path. Say so once here, at the one place each
            // file is scanned; silently producing nothing for it is how a
            // whole file used to vanish from a run unnoticed.
            eprintln!("Warning: {}: {}", file_path, e.root_cause());
            None
        }
    };
    if let Some((tree, source)) = parsed {
        // A `.h` file is ambiguous between C and C++ by extension alone; a
        // header written entirely in C++ (a vendored C++ wrapper API
        // shipped alongside a C library, e.g. mosquitto's
        // libmosquittopp.h) parses under tree-sitter-c anyway, producing
        // ERROR-node garbage that several independent C-oriented rules
        // (DCL15-C, DCL19-C, DCL20-C, MSC13-C, WIN04-C, API02-C, EXP37-C)
        // have each misread as real C declarations (task 571). Detect and
        // skip such files entirely rather than analyzing nonsense --
        // tools_sqc is CERT-C only, so a file that can only be C++ is out
        // of scope, not a source of findings.
        if file_path.ends_with(".h") && lang_parsing_substrate::looks_like_cpp(source.as_bytes()) {
            return (file_violations, file_suppressed);
        }

        let root_node = tree.root_node();

        // CFGs for every function definition in this file, plus VRA if any
        // enabled rule needs it. The generated fixture tests build their state
        // through this same call (task 951, this repo).
        let analysis = build_file_analysis(&root_node, &source, context, needs_vra);

        // Extract suppressions from the current file
        suppression_manager.extract_from_source(file_path, &source);

        for (rule_id, rule_config) in manifest.enabled_rules() {
            // Sequential mode: check cancellation and report progress per rule
            if per_rule_progress {
                if let Some(reporter) = progress {
                    if reporter.is_cancelled() {
                        break;
                    }
                    reporter.report_file(file_idx + 1, total_files, file_path, rule_id);
                }
            }

            // Check if rule is implemented
            if let Some(rule) = file_registry.get_rule(rule_id) {
                // Skip rules that don't apply to this file type (e.g. header-only rules)
                if !rule.applies_to_file(file_path) {
                    continue;
                }
                // Provide CFGs for flow-sensitive rules (e.g. EXP34-C) and
                // VRA results for integer-range-sensitive ones.
                analysis.apply_to(rule);
                let mut rule_violations = rule.check(&root_node, &source);

                // Set file path and severity on all violations
                for v in &mut rule_violations {
                    v.file_path = file_path.to_string();
                    v.severity = rule_config
                        .severity
                        .clone()
                        .unwrap_or_else(|| rule.severity());
                }

                // Partition into active and suppressed violations
                for v in rule_violations {
                    if let Some(j) = suppression_manager
                        .should_suppress(file_path, rule_id, v.line, &source, &v.message)
                    {
                        file_suppressed.push(SuppressedViolation {
                            justification: j.to_string(),
                            violation: v,
                        });
                    } else {
                        file_violations.push(v);
                    }
                }
            }
        }
    }

    (file_violations, file_suppressed)
}

/// Print a suppression-comment snippet for `spec` (`FILE:LINE:RULE`), for a
/// user to paste inline rather than hand-writing the comment syntax.
pub fn handle_generate_suppression(spec: &str) -> Result<()> {
    // Parse the specification: FILE:LINE:RULE
    let parts: Vec<&str> = spec.splitn(3, ':').collect();
    if parts.len() != 3 {
        eprintln!("Error: Invalid format. Use FILE:LINE:RULE");
        eprintln!("Example: src/main.c:42:ARR30-C");
        return Ok(());
    }

    let file_path = parts[0];
    let rule_id = parts[2];

    let line: usize = match parts[1].parse() {
        Ok(n) if n > 0 => n,
        _ => {
            eprintln!("Error: Invalid line number");
            return Ok(());
        }
    };

    // Read the source file
    let source = match fs::read_to_string(file_path) {
        Ok(content) => content,
        Err(e) => {
            eprintln!("Error: Cannot read file '{}': {}", file_path, e);
            return Ok(());
        }
    };

    let lines: Vec<&str> = source.lines().collect();
    if line > lines.len() {
        eprintln!(
            "Error: Line {} exceeds file length ({} lines)",
            line,
            lines.len()
        );
        return Ok(());
    }

    // Get the code line, stripping any existing suppress comment (either
    // spelling) so the hash covers only the code portion.
    let raw_line = lines[line - 1];
    let code = [
        "// AURORA-SUPPRESS",
        "/* AURORA-SUPPRESS",
        "// SQC-SUPPRESS",
        "/* SQC-SUPPRESS",
    ]
    .iter()
    .filter_map(|opener| raw_line.find(opener))
    .min()
    .map_or(raw_line, |pos| &raw_line[..pos]);

    let hash = SuppressionManager::calculate_suppression_hash(rule_id, code);

    println!(
        "Generated suppression for {}:{}:{}",
        file_path, line, rule_id
    );
    println!();
    println!("Code:");
    println!("{:4}: {}", line, raw_line);
    println!();
    let filename = std::path::Path::new(file_path)
        .file_name()
        .and_then(|f| f.to_str())
        .unwrap_or(file_path);

    println!("Add on the line before (standalone comment):");
    println!(
        "// tools:suppress aurora-lint:{} HASH:{} JUSTIFICATION:\"TODO: Add justification\"",
        rule_id, hash
    );
    println!();
    println!("Native form (also accepted; standalone or inline):");
    println!(
        "// AURORA-SUPPRESS: {} HASH:{} JUSTIFICATION: \"TODO: Add justification\"",
        rule_id, hash
    );
    println!();
    println!("Or add to suppress.toml (for read-only codebases):");
    println!("[[suppress]]");
    println!("name = \"TODO-unique-name\"");
    println!("tool = \"aurora-lint\"");
    println!("file = \"{}\"", filename);
    println!("rule = \"{}\"", rule_id);
    println!("hash = \"{}\"", hash);
    println!("justification = \"TODO: Add justification\"");

    Ok(())
}

/// The per-file analysis state a scan hands to every rule: control-flow graphs
/// for each function definition, plus value ranges when some enabled rule asks
/// for them.
///
/// Both `analyze_one_file` and the fixture tests `build.rs` generates go
/// through [`build_file_analysis`] and [`FileAnalysis::apply_to`], so a rule
/// can never be exercised in tests under a context the shipped scan does not
/// build (task 951, this repo).
pub(crate) struct FileAnalysis {
    pub(crate) function_cfgs: HashMap<usize, cfg::FunctionCfg>,
    pub(crate) vra_results: HashMap<usize, value_range::RangeAnalysisResult>,
}

impl FileAnalysis {
    /// Hand this file's state to `rule` the way a scan does -- VRA only when
    /// there is any, matching the shipped gate.
    pub(crate) fn apply_to<R: crate::rules::CertRule + ?Sized>(&self, rule: &R) {
        rule.set_function_cfgs(&self.function_cfgs);
        if !self.vra_results.is_empty() {
            rule.set_vra_results(&self.vra_results);
        }
    }
}

/// Build the per-file analysis state for one already-parsed file.
pub(crate) fn build_file_analysis(
    root_node: &tree_sitter::Node,
    source: &str,
    context: &context::ProjectContext,
    needs_vra: bool,
) -> FileAnalysis {
    let mut function_cfgs: HashMap<usize, cfg::FunctionCfg> = HashMap::new();
    collect_function_cfgs(root_node, source, &mut function_cfgs);

    let vra_results = compute_vra_if_needed(
        needs_vra,
        &function_cfgs,
        root_node,
        source,
        &context.function_summaries,
        &context.macro_constants,
    );

    FileAnalysis {
        function_cfgs,
        vra_results,
    }
}

/// Compute VRA for all functions if any enabled rule needs it.
///
/// `pub(crate)` so the generated rule tests in
/// `src/rules/cert_c/integration/` can build the same VRA state the real
/// scan does -- a rule whose FP suppression depends on value ranges is
/// otherwise untestable from a `.c` fixture (task 674).
pub(crate) fn compute_vra_if_needed(
    needs_vra: bool,
    function_cfgs: &HashMap<usize, cfg::FunctionCfg>,
    root_node: &tree_sitter::Node,
    source: &str,
    prescan_summaries: &HashMap<String, function_summary::FunctionSummary>,
    project_macros: &const_eval::MacroConstantMap,
) -> HashMap<usize, value_range::RangeAnalysisResult> {
    if !needs_vra || function_cfgs.is_empty() {
        return HashMap::new();
    }

    // Only compute macros and same-file summaries when VRA is actually needed.
    // Project-wide macros (from prescan) are merged under the current file's
    // own `#define`s, which win on collision. Without the project half, a
    // guard written against a header-defined constant -- `if (irq <
    // NORMAL_IRQ_OFFSET) return;` where that macro lives in a driver header
    // -- refined nothing, so every variable derived from the guarded one
    // stayed at its full type range for the rest of the function (task 674).
    let macros = const_eval::merged_macro_constants(project_macros, root_node, source);
    let mut file_summaries = function_summary::compute_summaries(
        root_node,
        source,
        &macros,
        true,
        &[],
        &std::collections::HashMap::new(),
        &std::collections::HashMap::new(),
    );

    // Augment same-file summaries with caller constant arg propagation so that
    // VRA can narrow parameter ranges (e.g. goodG2B passes data=2 to goodG2BSink).
    {
        let mut callsite_int_args = std::collections::HashMap::new();
        prescan::collect_callsite_int_args_from_tree(root_node, source, &mut callsite_int_args);
        prescan::aggregate_callsite_int_args(
            &callsite_int_args,
            &mut file_summaries,
            &std::collections::HashSet::new(),
        );
    }

    // Merge prescan (cross-file) summaries with same-file summaries by reference.
    // Only clone+extend if both sides are non-empty; otherwise use whichever is available.
    let merged;
    let summaries: &HashMap<String, function_summary::FunctionSummary> =
        if prescan_summaries.is_empty() {
            &file_summaries
        } else if file_summaries.is_empty() {
            prescan_summaries
        } else {
            merged = {
                let mut m = prescan_summaries.clone();
                m.extend(file_summaries);
                m
            };
            &merged
        };

    let mut results = HashMap::new();
    for (&start_byte, func_cfg) in function_cfgs {
        if let Some(func_node) = find_function_at_byte(root_node, start_byte) {
            results.insert(
                start_byte,
                value_range::analyze_value_ranges(func_cfg, &func_node, source, &macros, summaries),
            );
        }
    }
    results
}

/// Find the function_definition node at a given start byte.
fn find_function_at_byte<'a>(
    node: &tree_sitter::Node<'a>,
    start_byte: usize,
) -> Option<tree_sitter::Node<'a>> {
    if node.kind() == "function_definition" && node.start_byte() == start_byte {
        return Some(*node);
    }
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            // Prune: only descend into children whose range contains start_byte.
            if child.start_byte() <= start_byte && child.end_byte() >= start_byte {
                if let Some(found) = find_function_at_byte(&child, start_byte) {
                    return Some(found);
                }
            }
        }
    }
    None
}

/// Collect CFGs for all function_definition nodes in the AST.
/// Keyed by the function's start byte offset.
/// Uses file-level constants for dead-branch pruning in conditions.
pub fn collect_function_cfgs(
    node: &tree_sitter::Node,
    source: &str,
    cfgs: &mut HashMap<usize, cfg::FunctionCfg>,
) {
    let constants = const_eval::collect_macro_constants(node, source);
    let noreturn_names = noreturn::collect_noreturn_function_names(node, source);
    collect_function_cfgs_with_constants(node, source, cfgs, &constants, &noreturn_names);
}

fn collect_function_cfgs_with_constants(
    node: &tree_sitter::Node,
    source: &str,
    cfgs: &mut HashMap<usize, cfg::FunctionCfg>,
    constants: &const_eval::MacroConstantMap,
    noreturn_names: &std::collections::HashSet<String>,
) {
    if node.kind() == "function_definition" {
        if let Some(function_cfg) = cfg::build_function_cfg_with_constants_and_noreturn(
            node,
            source,
            constants,
            noreturn_names,
        ) {
            cfgs.insert(node.start_byte(), function_cfg);
        }
    }
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            collect_function_cfgs_with_constants(&child, source, cfgs, constants, noreturn_names);
        }
    }
}

/// The trimmed source text of `line_number` in `file_path`, or a placeholder
/// string if the line is out of range.
pub fn get_code_snippet(file_path: &str, line_number: usize) -> Result<String> {
    let content = fs::read_to_string(file_path)?;
    let lines: Vec<&str> = content.lines().collect();

    if line_number > 0 && line_number <= lines.len() {
        let line = lines[line_number - 1].trim();
        Ok(line.to_string())
    } else {
        Ok("(line not found)".to_string())
    }
}

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

    fn parse_c(code: &str) -> (tree_sitter::Tree, String) {
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&crate::parser::c_language()).unwrap();
        let tree = parser.parse(code, None).unwrap();
        (tree, code.to_string())
    }

    // -- collect_c_files / build_path_ignore --

    #[test]
    fn collect_c_files_respects_toolchain_toml_ignore() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("toolchain.toml"),
            "[ignore]\npaths = [\"vendor/**\"]\n",
        )
        .unwrap();
        fs::create_dir_all(dir.path().join("vendor")).unwrap();
        fs::write(dir.path().join("vendor").join("lib.c"), "int x;\n").unwrap();
        fs::write(dir.path().join("main.c"), "int y;\n").unwrap();

        let project_source = ProjectSource::open(dir.path().to_str().unwrap()).unwrap();
        let c_files = collect_c_files(&project_source, false, &[]).unwrap();

        assert!(c_files.iter().any(|f| f.ends_with("main.c")));
        assert!(!c_files.iter().any(|f| f.contains("vendor")));
    }

    #[test]
    fn collect_c_files_merges_toolchain_and_cli_excludes() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("toolchain.toml"),
            "[ignore]\npaths = [\"vendor/**\"]\n",
        )
        .unwrap();
        fs::create_dir_all(dir.path().join("vendor")).unwrap();
        fs::write(dir.path().join("vendor").join("lib.c"), "int x;\n").unwrap();
        fs::write(dir.path().join("generated.c"), "int z;\n").unwrap();
        fs::write(dir.path().join("main.c"), "int y;\n").unwrap();

        let project_source = ProjectSource::open(dir.path().to_str().unwrap()).unwrap();
        let c_files =
            collect_c_files(&project_source, false, &["**/generated.c".to_string()]).unwrap();

        assert!(c_files.iter().any(|f| f.ends_with("main.c")));
        assert!(!c_files.iter().any(|f| f.contains("vendor")));
        assert!(!c_files.iter().any(|f| f.ends_with("generated.c")));
    }

    #[test]
    fn build_path_ignore_skips_invalid_pattern_but_keeps_valid_ones() {
        let dir = tempfile::tempdir().unwrap();
        let project_source = ProjectSource::open(dir.path().to_str().unwrap()).unwrap();
        let ignore =
            build_path_ignore(&project_source, &["[".to_string(), "vendor/**".to_string()])
                .unwrap();
        assert!(ignore.is_ignored(std::path::Path::new("vendor/lib.c")));
        assert!(!ignore.is_ignored(std::path::Path::new("src/main.c")));
    }

    // -- collect_function_cfgs --

    #[test]
    fn test_collect_function_cfgs_basic() {
        let code = "void foo(void) { int x = 1; } void bar(int n) { return; }";
        let (tree, source) = parse_c(code);
        let mut cfgs = HashMap::new();
        collect_function_cfgs(&tree.root_node(), &source, &mut cfgs);
        assert_eq!(cfgs.len(), 2);
    }

    #[test]
    fn test_collect_function_cfgs_empty_source() {
        let code = "int x = 42;"; // no functions
        let (tree, source) = parse_c(code);
        let mut cfgs = HashMap::new();
        collect_function_cfgs(&tree.root_node(), &source, &mut cfgs);
        assert!(cfgs.is_empty());
    }

    // -- find_function_at_byte --

    #[test]
    fn test_find_function_at_byte_found() {
        let code = "void foo(void) { }";
        let (tree, _source) = parse_c(code);
        let root = tree.root_node();
        let func = root.child(0).unwrap();
        let start = func.start_byte();
        let found = find_function_at_byte(&root, start);
        assert!(found.is_some());
        assert_eq!(found.unwrap().kind(), "function_definition");
    }

    #[test]
    fn test_find_function_at_byte_not_found() {
        let code = "void foo(void) { }";
        let (tree, _source) = parse_c(code);
        let found = find_function_at_byte(&tree.root_node(), 9999);
        assert!(found.is_none());
    }

    #[test]
    fn test_find_function_at_byte_multiple() {
        let code = "void a(void) {} void b(void) {}";
        let (tree, _source) = parse_c(code);
        let root = tree.root_node();
        // Find second function
        let second_func = root.child(1).unwrap();
        let start = second_func.start_byte();
        let found = find_function_at_byte(&root, start);
        assert!(found.is_some());
    }

    // -- get_code_snippet --

    #[test]
    fn test_get_code_snippet() {
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("test.c");
        std::fs::write(&file, "int x = 1;\nint y = 2;\nint z = 3;\n").unwrap();
        let path = file.to_string_lossy().to_string();

        assert_eq!(get_code_snippet(&path, 1).unwrap(), "int x = 1;");
        assert_eq!(get_code_snippet(&path, 2).unwrap(), "int y = 2;");
        assert_eq!(get_code_snippet(&path, 3).unwrap(), "int z = 3;");
        assert_eq!(get_code_snippet(&path, 99).unwrap(), "(line not found)");
    }

    #[test]
    fn test_get_code_snippet_trims_whitespace() {
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("test.c");
        std::fs::write(&file, "    int x = 1;\n").unwrap();
        let path = file.to_string_lossy().to_string();
        assert_eq!(get_code_snippet(&path, 1).unwrap(), "int x = 1;");
    }

    // -- compute_vra_if_needed --

    #[test]
    fn test_compute_vra_not_needed() {
        let cfgs = HashMap::new();
        let code = "void f(void) {}";
        let (tree, source) = parse_c(code);
        let summaries = HashMap::new();
        let results = compute_vra_if_needed(
            false,
            &cfgs,
            &tree.root_node(),
            &source,
            &summaries,
            &const_eval::MacroConstantMap::new(),
        );
        assert!(results.is_empty());
    }

    #[test]
    fn test_compute_vra_empty_cfgs() {
        let cfgs = HashMap::new();
        let code = "void f(void) {}";
        let (tree, source) = parse_c(code);
        let summaries = HashMap::new();
        let results = compute_vra_if_needed(
            true,
            &cfgs,
            &tree.root_node(),
            &source,
            &summaries,
            &const_eval::MacroConstantMap::new(),
        );
        assert!(results.is_empty());
    }

    // -- AnalysisResults / SuppressedViolation construction --

    #[test]
    fn test_analysis_results_struct() {
        let results = AnalysisResults {
            violations: vec![],
            suppressed: vec![],
            macro_gaps: None,
        };
        assert!(results.violations.is_empty());
        assert!(results.suppressed.is_empty());
    }
}