aurora-lint 0.4.336

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
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
// Common AST utilities for CERT C rules
// This module provides reusable functions for navigating and extracting information from the C AST

use lang_parsing_substrate::query;
use tree_sitter::Node;

// ============================================================================
// Node Text Extraction
// ============================================================================

/// Extract the text content of a node from the source code
pub fn get_node_text<'a>(node: &Node, source: &'a str) -> &'a str {
    query::node_text(*node, source.as_bytes())
}

/// Heuristic: does this call's name look like a custom deallocator
/// (destroy_*, free_*, delete_*, cleanup_*, release_*, close_*, or the
/// matching suffix forms)? Shared between MEM31-C's own custom-deallocator
/// handling and the prescan field-frees collector (`frees_param_fields`),
/// so a macro-wrapped free like `#define mosquitto_FREE(A) free(A)` is
/// recognized consistently in both places (task 2: MEM31-C ownership model —
/// aurora-lint has no preprocessor, so such wrapper calls are otherwise invisible).
pub fn is_deallocation_call_name(func_name: &str) -> bool {
    if crate::analyze::macro_semantics::is_container_unlink_macro(func_name) {
        return false;
    }
    let lower_name = func_name.to_lowercase();
    lower_name.starts_with("destroy_")
        || lower_name.starts_with("free_")
        || lower_name.starts_with("delete_")
        || lower_name.starts_with("cleanup_")
        || lower_name.starts_with("release_")
        || lower_name.starts_with("close_")
        || lower_name.ends_with("_destroy")
        || lower_name.ends_with("_free")
        || lower_name.ends_with("_delete")
        || lower_name.ends_with("_cleanup")
        || lower_name.ends_with("_release")
        || lower_name.ends_with("_close")
}

/// Extract the text content of a node as an owned String
pub fn get_node_text_owned(node: &Node, source: &str) -> String {
    query::node_text(*node, source.as_bytes()).to_string()
}

/// Extract a node's text with comment, string-literal, and char-literal spans
/// blanked out (replaced with spaces, preserving byte offsets/length).
///
/// For rules whose heuristics are too intricate to safely re-derive as pure
/// AST structural checks, this lets an existing text-substring heuristic run
/// against sanitized text instead — so a `.contains("UINT_MAX")` or similar
/// pattern can no longer be spoofed by a comment or string literal elsewhere
/// in the scanned span (a real false-negative risk: silent suppression of a
/// genuine violation, which is the worse failure direction for a security tool).
pub fn get_sanitized_node_text(node: &Node, source: &str) -> String {
    let start = node.start_byte();
    let end = node.end_byte();
    let mut bytes = source.as_bytes()[start..end].to_vec();
    for lit in
        query::find_descendants_of_kinds(*node, &["comment", "string_literal", "char_literal"])
    {
        let lit_start = lit.start_byte().max(start);
        let lit_end = lit.end_byte().min(end);
        if lit_start < lit_end {
            // Blank every byte except embedded newlines, so a multi-line
            // comment/string doesn't collapse onto one line — callers that
            // scan sanitized text line-by-line (`.lines()`) rely on the
            // original line structure being preserved.
            for b in &mut bytes[(lit_start - start)..(lit_end - start)] {
                if *b != b'\n' {
                    *b = b' ';
                }
            }
        }
    }
    String::from_utf8_lossy(&bytes).into_owned()
}

// ============================================================================
// AST Navigation
// ============================================================================

/// Find the containing function definition for a given node
/// Returns the function_definition node that contains the given node
pub fn find_containing_function<'a>(node: &Node<'a>) -> Option<Node<'a>> {
    if node.kind() == "function_definition" {
        return Some(*node);
    }
    query::nearest_ancestor_of_kind(*node, "function_definition")
}

/// Every descendant of `root` matching one of `kinds` that lies **outside**
/// any function definition, found by pruning at `function_definition` on the
/// way down.
///
/// Use this instead of collecting all descendants and rejecting the ones
/// [`find_containing_function`] answers for. `Node::parent()` is not a
/// pointer hop: tree-sitter recovers a parent by descending from the tree
/// root, so it costs O(depth). An ancestor query per candidate therefore
/// costs O(depth²), and running one over a whole file whose node count grows
/// with its nesting depth makes the pass cubic — 800 nested `if`s took
/// CON40-C 23 s before this replaced two such filters (task 952, this repo).
/// Pruning is O(n) and needs no ancestor query at all.
pub fn file_scope_descendants_of_kinds<'a>(root: Node<'a>, kinds: &[&str]) -> Vec<Node<'a>> {
    let mut out = Vec::new();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if node.kind() == "function_definition" {
            continue;
        }
        if kinds.contains(&node.kind()) {
            out.push(node);
        }
        let mut cursor = node.walk();
        let children: Vec<Node<'a>> = node.children(&mut cursor).collect();
        stack.extend(children.into_iter().rev());
    }
    out
}

/// Walk up from `ident_node` through enclosing scopes — `compound_statement`
/// blocks and `for_statement` init clauses — to find the nearest
/// `declaration` that binds `name`, preferring the latest (highest byte
/// offset) such declaration before `ident_node`'s own position within each
/// scope. Correctly disambiguates shadowed re-declarations of the same name
/// in sibling or nested blocks — unlike a whole-function text/regex scan,
/// which cannot tell two different declarations of the same identifier
/// apart.
///
/// `for (int i = 0; i < n; i++) { ... }` declares `i` as a direct child of
/// the `for_statement` itself, not of any `compound_statement` — its scope
/// is the whole for-statement (condition, update, and body). A search that
/// only scanned `compound_statement` children would never find it, making
/// every read of a for-loop variable (in the condition, the update, or the
/// body) fail to resolve back to its own declaration.
///
/// A scope's own declaration search is preprocessor-transparent: `#ifdef
/// X ... #endif` is textual inclusion, not a new C scope, so `int color;`
/// written inside one has the same enclosing-block scope as if it were
/// written directly — a read anywhere else in that same block (inside a
/// different `#ifdef`/`#else` branch, or after the `#endif` entirely) must
/// still resolve back to it. Scanning only literal `declaration`-kind
/// direct children would miss any declaration nested one or more
/// `preproc_if`/`preproc_ifdef`/`preproc_elif`/`preproc_else` levels down.
///
/// Stops at the function body (does not resolve to a parameter — callers
/// needing that should also check `is_function_parameter` separately).
pub fn find_enclosing_declaration_for_identifier<'a>(
    ident_node: &Node<'a>,
    name: &str,
    source: &str,
) -> Option<Node<'a>> {
    let mut scopes = Vec::new();
    let mut search_from = *ident_node;
    while let Some(scope) = query::find_ancestor(search_from, |n| is_declaration_scope(&n)) {
        scopes.push(scope);
        search_from = scope;
    }
    find_declaration_in_scope_chain(&scopes, ident_node.start_byte(), name, source)
}

/// True if `node` opens one of the scopes
/// [`find_enclosing_declaration_for_identifier`] searches.
pub fn is_declaration_scope(node: &Node) -> bool {
    matches!(node.kind(), "compound_statement" | "for_statement")
}

/// The body of [`find_enclosing_declaration_for_identifier`], over a scope
/// chain the caller already has: `scopes` innermost-first, `ident_start` the
/// identifier's start byte.
///
/// A caller already descending the tree can keep that chain on a stack for
/// free. Rediscovering it per identifier cannot: `Node::parent()` recovers a
/// parent by descending from the tree root, so it costs O(depth), one
/// resolution costs O(depth²), and resolving every read in a file whose node
/// count grows with its nesting depth is cubic -- 2,000 nested `if`s took
/// MSC13-C 93 s (task 952, this repo).
pub fn find_declaration_in_scope_chain<'a>(
    scopes: &[Node<'a>],
    ident_start: usize,
    name: &str,
    source: &str,
) -> Option<Node<'a>> {
    for scope in scopes {
        let mut declarations = Vec::new();
        collect_declarations_transparent_to_preproc(scope, &mut declarations);
        let best = declarations
            .into_iter()
            .filter(|child| {
                child.start_byte() < ident_start && declaration_binds_name(child, name, source)
            })
            .max_by_key(|child| child.start_byte());
        if best.is_some() {
            return best;
        }
    }
    None
}

/// Collect every `declaration` directly inside `scope`, transparently
/// descending into any nested `#if`/`#ifdef`/`#elif`/`#else` branch (any
/// depth) — see [`find_enclosing_declaration_for_identifier`] for why —
/// and into `case`/`default` labels, which are not scopes either.
///
/// A `case` label with no braces around its body does not open a block:
/// `switch (x) { case 1: int y = f(); g(y); }` declares `y` in the
/// switch's own compound_statement, exactly as if the label were not
/// there. tree-sitter-c nests those statements under a `case_statement`
/// node all the same, so scanning only the compound_statement's literal
/// children finds no declaration and every read of `y` fails to resolve
/// back to it. A `case` whose body IS braced is a different matter: the
/// `compound_statement` under the label is a real scope and is left to
/// the caller's outward walk, which is why the recursion below descends
/// through `case_statement` but never through a block.
fn collect_declarations_transparent_to_preproc<'a>(scope: &Node<'a>, out: &mut Vec<Node<'a>>) {
    let condition_id = scope.child_by_field_name("condition").map(|n| n.id());
    let name_id = scope.child_by_field_name("name").map(|n| n.id());
    for i in 0..scope.child_count() {
        let Some(child) = scope.child(i) else {
            continue;
        };
        if Some(child.id()) == condition_id || Some(child.id()) == name_id {
            continue;
        }
        match child.kind() {
            "declaration" => out.push(child),
            "preproc_if" | "preproc_ifdef" | "preproc_elif" | "preproc_else" | "case_statement" => {
                collect_declarations_transparent_to_preproc(&child, out);
            }
            _ => {}
        }
    }
}

/// True if a `declaration` node binds `name` via a direct declarator (`T
/// name;`) or an `init_declarator` (`T name = value;`), including
/// comma-separated multi-declarator declarations.
fn declaration_binds_name(decl_node: &Node, name: &str, source: &str) -> bool {
    for i in 0..decl_node.child_count() {
        let Some(child) = decl_node.child(i) else {
            continue;
        };
        let declarator = match child.kind() {
            "init_declarator" => child.child_by_field_name("declarator").unwrap_or(child),
            "identifier" | "pointer_declarator" | "array_declarator" | "function_declarator" => {
                child
            }
            _ => continue,
        };
        if get_identifier_from_declarator(&declarator, source) == name {
            return true;
        }
    }
    false
}

/// Fallback for file-scope (global) declarations, which
/// `find_enclosing_declaration_for_identifier` intentionally does not
/// resolve to (it only walks enclosing `compound_statement` blocks).
/// Restricted to direct children of the translation unit so it can't cross
/// into an unrelated function body.
///
/// This generalizes a scan that MSC05-C, MSC15-C, and CON34-C each
/// hand-rolled independently (task 387 item #3) as a type- or
/// qualifier-filtered variant of the same walk.
pub fn find_global_declaration_for_identifier<'a>(
    ident_node: &Node<'a>,
    name: &str,
    source: &str,
) -> Option<Node<'a>> {
    let mut top = *ident_node;
    while let Some(p) = top.parent() {
        top = p;
    }
    (0..top.child_count())
        .filter_map(|i| top.child(i))
        .find(|decl| decl.kind() == "declaration" && declaration_binds_name(decl, name, source))
}

/// Where an identifier use resolves to its binding declaration/parameter.
pub enum IdentifierBinding<'a> {
    /// Bound by a local (block-scope) declaration.
    Local(Node<'a>),
    /// Bound by a function parameter; carries the parameter's type text
    /// since a parameter has no `declaration` node of its own to point at.
    Parameter(String),
    /// Bound by a file-scope (translation-unit level) declaration.
    Global(Node<'a>),
}

/// Resolve `ident_node` (an occurrence of `name`) to wherever it's bound:
/// the nearest enclosing local declaration, else the containing function's
/// parameter list, else a file-scope global declaration. Chains
/// [`find_enclosing_declaration_for_identifier`], [`get_function_parameters`],
/// and [`find_global_declaration_for_identifier`] in that order so callers
/// don't each hand-roll the same 3-way fallback (task 387 item #3 -- MSC05-C,
/// MSC15-C, FIO34-C, ENV34-C, INT34-C, and CON34-C all did this
/// independently).
pub fn resolve_identifier_binding<'a>(
    ident_node: &Node<'a>,
    name: &str,
    source: &str,
) -> Option<IdentifierBinding<'a>> {
    if let Some(decl) = find_enclosing_declaration_for_identifier(ident_node, name, source) {
        return Some(IdentifierBinding::Local(decl));
    }
    if let Some(func) = find_containing_function(ident_node) {
        if let Some(params) = get_function_parameters(&func, source) {
            if let Some((_, ptype)) = params.iter().find(|(n, _)| n == name) {
                return Some(IdentifierBinding::Parameter(ptype.clone()));
            }
        }
    }
    find_global_declaration_for_identifier(ident_node, name, source).map(IdentifierBinding::Global)
}

/// Extract the type text (tokens before the declarator) of a `declaration`
/// node, e.g. `time_t x;` -> `"time_t"`, `static unsigned int x;` ->
/// `"static unsigned int"`. Public because this exact scan was independently
/// hand-rolled in ARR39-C, MSC15-C, and FIO34-C (task 387/584) before being
/// consolidated here.
pub fn declaration_type_text(decl: &Node, source: &str) -> String {
    (0..decl.child_count())
        .filter_map(|i| decl.child(i))
        .take_while(|c| {
            !matches!(
                c.kind(),
                "identifier" | "init_declarator" | "pointer_declarator" | "array_declarator"
            )
        })
        .map(|c| get_node_text(&c, source))
        .collect::<Vec<_>>()
        .join(" ")
}

/// True if a `declaration` node carries the given `type_qualifier` (e.g.
/// `"const"`, `"volatile"`) as a direct child. Only looks at the
/// declaration's own qualifiers, not a specific declarator's — matches the
/// pattern already used by callers checking e.g. `const char *ptr;`.
pub fn declaration_has_qualifier(decl: &Node, qualifier: &str, source: &str) -> bool {
    (0..decl.child_count()).any(|i| {
        decl.child(i)
            .is_some_and(|c| c.kind() == "type_qualifier" && get_node_text(&c, source) == qualifier)
    })
}

/// True if a `declaration` node carries the given `storage_class_specifier`
/// (e.g. `"static"`, `"extern"`) as a direct child.
pub fn declaration_has_storage_class(decl: &Node, storage_class: &str, source: &str) -> bool {
    (0..decl.child_count()).any(|i| {
        decl.child(i).is_some_and(|c| {
            c.kind() == "storage_class_specifier" && get_node_text(&c, source) == storage_class
        })
    })
}

/// True if `node` is a `*p`-style dereference. `*p` and `&p` both parse as
/// `pointer_expression` in this grammar, disambiguated only by the
/// `operator` field's text -- conflating them is a real FP source (task
/// 391's MEM33-C fix, MEM30-C's `scope_derefs_var`), so this is the shared
/// primitive rather than each rule re-deriving the field check.
pub fn is_dereference_expression(node: &Node, source: &str) -> bool {
    node.kind() == "pointer_expression"
        && node
            .child_by_field_name("operator")
            .is_some_and(|o| get_node_text(&o, source) == "*")
}

/// True if `node` is a `&p`-style address-of expression. See
/// [`is_dereference_expression`].
#[allow(dead_code)]
pub fn is_address_of_expression(node: &Node, source: &str) -> bool {
    node.kind() == "pointer_expression"
        && node
            .child_by_field_name("operator")
            .is_some_and(|o| get_node_text(&o, source) == "&")
}

/// Convenience wrapper over [`resolve_identifier_binding`] for callers that
/// only need the resolved type text, not the binding site itself.
pub fn resolve_identifier_type(ident_node: &Node, name: &str, source: &str) -> Option<String> {
    match resolve_identifier_binding(ident_node, name, source)? {
        IdentifierBinding::Local(decl) | IdentifierBinding::Global(decl) => {
            Some(declaration_type_text(&decl, source))
        }
        IdentifierBinding::Parameter(ptype) => Some(ptype),
    }
}

/// Check if a node is inside a loop (for, while, or do-while)
///
/// No function-boundary short-circuit: `function_definition`s never nest in
/// C, so walking past one to check outer scopes can't happen in practice —
/// same result as the boundary-stopping version, one predicate instead of two.
pub fn is_inside_loop(node: &Node) -> bool {
    query::find_ancestor(*node, |n| {
        matches!(
            n.kind(),
            "for_statement" | "while_statement" | "do_statement"
        )
    })
    .is_some()
}

/// Check if a node is inside a conditional statement (if, else if, switch)
#[allow(dead_code)]
pub fn is_inside_conditional(node: &Node) -> bool {
    query::find_ancestor(*node, |n| {
        matches!(n.kind(), "if_statement" | "switch_statement")
    })
    .is_some()
}

// ============================================================================
// Identifier Extraction from Declarators
// ============================================================================

/// Extract identifier name from a declarator node
/// Handles simple identifiers, pointer declarators, and array declarators
///
/// Examples:
/// - int x           -> "x"
/// - int *ptr        -> "ptr"
/// - int arr[10]     -> "arr"
/// - int **ptr       -> "ptr"
/// - int (*fn)(int)  -> "fn"
pub fn get_identifier_from_declarator(declarator: &Node, source: &str) -> String {
    match declarator.kind() {
        "identifier" => get_node_text_owned(declarator, source),
        "pointer_declarator"
        | "array_declarator"
        | "function_declarator"
        | "parenthesized_declarator" => {
            // Recursively search for the identifier
            for i in 0..declarator.child_count() {
                if let Some(child) = declarator.child(i) {
                    if child.kind() == "identifier" {
                        return get_node_text_owned(&child, source);
                    }
                    let nested = get_identifier_from_declarator(&child, source);
                    if !nested.is_empty() {
                        return nested;
                    }
                }
            }
            String::new() // Return empty string for consistency with original implementations
        }
        _ => String::new(), // Return empty string for consistency with original implementations
    }
}

/// Find identifier in a declarator node, returns Option instead of "unknown" string.
///
/// Delegates to [`get_identifier_from_declarator`], which (unlike this
/// function's original implementation) checks the declarator's own node kind
/// before scanning its children — needed for a bare, unwrapped declarator
/// (`int j = 0;`) where the declarator field IS the identifier directly.
/// The old children-only scan returned `None` for that shape, which caused a
/// live regression in CON34-C's OpenMP shared-variable detection (task 385).
pub fn find_identifier_in_declarator(declarator: &Node, source: &str) -> Option<String> {
    let name = get_identifier_from_declarator(declarator, source);
    if name.is_empty() {
        None
    } else {
        Some(name)
    }
}

// ============================================================================
// Function Parameter Extraction
// ============================================================================

/// Extract function parameters as (name, full_type) tuples
/// Returns None if the function has no parameters or parameter list not found
pub fn get_function_parameters(
    function_node: &Node,
    source: &str,
) -> Option<Vec<(String, String)>> {
    let declarator = find_function_declarator(function_node)?;
    extract_parameters(&declarator, source)
}

/// Find the `function_declarator` in a function's declarator subtree. For a
/// function returning a non-pointer type it is a direct child of the
/// `function_definition`; for a pointer-returning function (`char *
/// name(...)`) it is nested one level deeper inside a `pointer_declarator`,
/// which the previous direct-children-only scan missed entirely.
fn find_function_declarator<'a>(function_node: &Node<'a>) -> Option<Node<'a>> {
    for i in 0..function_node.child_count() {
        let child = function_node.child(i)?;
        match child.kind() {
            "function_declarator" => return Some(child),
            "pointer_declarator" => {
                if let Some(found) = find_function_declarator(&child) {
                    return Some(found);
                }
            }
            _ => {}
        }
    }
    None
}

/// Extract parameters from a function declarator node
fn extract_parameters(declarator_node: &Node, source: &str) -> Option<Vec<(String, String)>> {
    let mut parameters = Vec::new();

    // Find parameter_list node
    for i in 0..declarator_node.child_count() {
        if let Some(child) = declarator_node.child(i) {
            if child.kind() == "parameter_list" {
                // Extract each parameter
                for j in 0..child.child_count() {
                    if let Some(param) = child.child(j) {
                        if param.kind() == "parameter_declaration" {
                            if let Some((name, param_type)) = extract_parameter_info(&param, source)
                            {
                                parameters.push((name, param_type));
                            }
                        }
                    }
                }
            }
        }
    }

    if parameters.is_empty() {
        None
    } else {
        Some(parameters)
    }
}

/// Extract parameter information (name and type) from a parameter declaration
fn extract_parameter_info(param_node: &Node, source: &str) -> Option<(String, String)> {
    let param_text = get_node_text(param_node, source);

    // Look for declarator pattern
    for i in 0..param_node.child_count() {
        if let Some(child) = param_node.child(i) {
            if matches!(
                child.kind(),
                "array_declarator" | "pointer_declarator" | "function_declarator"
            ) {
                // Found array, pointer, or function pointer parameter
                if let Some(identifier) = find_identifier_in_declarator(&child, source) {
                    return Some((identifier, param_text.to_string()));
                }
            } else if child.kind() == "identifier" {
                // Simple parameter
                let name = get_node_text(&child, source);
                return Some((name.to_string(), param_text.to_string()));
            }
        }
    }

    None
}

/// Check if a variable name appears in the function's parameter list
pub fn is_function_parameter(function_node: &Node, var_name: &str, source: &str) -> bool {
    // Find parameter list in function
    for i in 0..function_node.child_count() {
        if let Some(child) = function_node.child(i) {
            if child.kind() == "function_declarator" {
                for j in 0..child.child_count() {
                    if let Some(param_list) = child.child(j) {
                        if param_list.kind() == "parameter_list" {
                            let param_text = get_node_text(&param_list, source);
                            // Check for word boundaries to avoid substring matches
                            let words: Vec<&str> = param_text
                                .split(|c: char| !c.is_alphanumeric() && c != '_')
                                .collect();
                            if words.contains(&var_name) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
    }
    false
}

// ============================================================================
// Type Checking Utilities
// ============================================================================

/// Check if a parameter type string indicates an array parameter
pub fn is_array_parameter_type(param_type: &str) -> bool {
    param_type.contains('[') || (param_type.contains('*') && !param_type.contains("const char *"))
}

/// Check if a type string represents a pointer type
pub fn is_pointer_type(type_str: &str) -> bool {
    type_str.contains('*')
}

/// Check if a type string represents a generic (non-pointer-storage) integer
/// type: `int`/`unsigned`/`long`/`short`/`char`/`size_t`/`ptrdiff_t`, but NOT
/// `uintptr_t`/`intptr_t` (those are pointer-storage-safe integer types, a
/// distinct concept from "is this an integer at all").
pub fn is_integer_type(type_str: &str) -> bool {
    const INTEGER_TYPES: &[&str] = &[
        "int",
        "unsigned",
        "long",
        "short",
        "char",
        "size_t",
        "ptrdiff_t",
    ];
    INTEGER_TYPES.iter().any(|&t| {
        type_str.contains(t) && !type_str.contains("uintptr_t") && !type_str.contains("intptr_t")
    })
}

/// Check if a type string represents a signed integer type
#[allow(dead_code)]
pub fn is_signed_type(type_str: &str) -> bool {
    matches!(
        type_str.trim(),
        "int"
            | "short"
            | "long"
            | "char"
            | "signed"
            | "signed int"
            | "signed short"
            | "signed long"
            | "long long"
            | "signed long long"
            | "signed char"
            | "int8_t"
            | "int16_t"
            | "int32_t"
            | "int64_t"
            | "ptrdiff_t"
            | "ssize_t"
    )
}

/// Check if a type string represents an unsigned integer type
#[allow(dead_code)]
pub fn is_unsigned_type(type_str: &str) -> bool {
    type_str.contains("unsigned")
        || matches!(
            type_str.trim(),
            "size_t" | "uint8_t" | "uint16_t" | "uint32_t" | "uint64_t" | "uintptr_t" | "uintmax_t"
        )
}

// ============================================================================
// Operator Extraction
// ============================================================================

/// Extract the operator from a binary expression node
pub fn get_binary_operator<'a>(node: &Node, source: &'a str) -> Option<&'a str> {
    // The operator is usually a child of the binary expression
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            let kind = child.kind();
            // Check if this is an operator token
            if matches!(
                kind,
                "+" | "-"
                    | "*"
                    | "/"
                    | "%"
                    | "=="
                    | "!="
                    | "<"
                    | ">"
                    | "<="
                    | ">="
                    | "&&"
                    | "||"
                    | "&"
                    | "|"
                    | "^"
                    | "<<"
                    | ">>"
                    | "="
                    | "+="
                    | "-="
                    | "*="
                    | "/="
                    | "%="
                    | "&="
                    | "|="
                    | "^="
                    | "<<="
                    | ">>="
            ) {
                return Some(get_node_text(&child, source));
            }
        }
    }
    None
}

// ============================================================================
// Array Size Extraction
// ============================================================================

/// Find array size from declaration in preceding text
/// Looks for patterns like: type array_name[size]
/// Returns the size if found and it's a constant
#[allow(dead_code)]
pub fn find_array_size(array_name: &str, preceding_text: &str) -> Option<usize> {
    // Look for array declaration pattern: array_name[number]
    let pattern = format!("{}[", array_name);

    if let Some(pos) = preceding_text.rfind(&pattern) {
        // Extract the size between [ and ]
        let after_bracket = &preceding_text[pos + pattern.len()..];
        if let Some(close_bracket) = after_bracket.find(']') {
            let size_str = after_bracket[..close_bracket].trim();

            // Try to parse as a number
            if let Ok(size) = size_str.parse::<usize>() {
                return Some(size);
            }

            // Try to handle simple arithmetic expressions like 2*3 or 10+5
            if size_str.contains('*') {
                let parts: Vec<&str> = size_str.split('*').collect();
                if parts.len() == 2 {
                    if let (Ok(a), Ok(b)) = (
                        parts[0].trim().parse::<usize>(),
                        parts[1].trim().parse::<usize>(),
                    ) {
                        return Some(a * b);
                    }
                }
            }
        }
    }

    None
}

/// Get the size of a C type in bytes
/// This is a best-effort approximation for common types
#[allow(dead_code)]
pub fn get_type_size(type_name: &str) -> usize {
    match type_name.trim() {
        "char" | "signed char" | "unsigned char" | "int8_t" | "uint8_t" => 1,
        "short" | "signed short" | "unsigned short" | "int16_t" | "uint16_t" => 2,
        "int" | "signed int" | "unsigned int" | "int32_t" | "uint32_t" | "float" => 4,
        "long" | "signed long" | "unsigned long" | "long long" | "signed long long"
        | "unsigned long long" | "int64_t" | "uint64_t" | "double" | "size_t" | "ptrdiff_t" => 8,
        "long double" => 16,
        t if t.ends_with('*') => 8, // Pointer size on 64-bit
        _ => 4,                     // Default to int size
    }
}

// ============================================================================
// Context Analysis
// ============================================================================

/// Check if a subscript expression is on the left side of an assignment (write context)
/// Handles nested subscripts like matrix[i][j] = value
pub fn is_write_context(node: &Node) -> bool {
    let mut current = *node;

    // Walk up the tree while we're in subscript expressions
    loop {
        if let Some(parent) = current.parent() {
            if parent.kind() == "assignment_expression" {
                // Check if current node (or its ancestor subscript) is the left side
                if let Some(left) = parent.child_by_field_name("left") {
                    return left.id() == current.id();
                }
                return false;
            } else if parent.kind() == "subscript_expression" {
                // Keep walking up through nested subscripts
                current = parent;
            } else {
                // Hit a different node type, not a write context
                return false;
            }
        } else {
            // No parent, not a write context
            return false;
        }
    }
}

/// The identifier sitting in the "type" position of a cast that
/// `tree-sitter-c` mis-parsed as something else, or `None` when `node` is not
/// one of those shapes.
///
/// Whether `(N)&x` is a cast or a bitwise AND depends on whether `N` names a
/// type -- the C grammar cannot decide it without a typedef table, and
/// `tree-sitter-c` does not consult one here. Measured, for
/// `typedef word_t seL4_Word;` declared in the same file:
///
/// ```text
///   (seL4_Word)x     cast_expression                      <- the only one that works
///   (seL4_Word)&x    binary_expression   left: (T)  op &
///   (seL4_Word)*p    binary_expression   left: (T)  op *
///   (seL4_Word)-y    binary_expression   left: (T)  op -
///   (seL4_Word)+y    binary_expression   left: (T)  op +
///   (seL4_Word)(x)   call_expression     function: (T)
/// ```
///
/// The parse is IDENTICAL with the typedef absent, so this is not a matter of
/// the typedef being out of scope in a per-file parse -- there is no scanner
/// state to pre-seed, and no amount of cross-file typedef knowledge reaches
/// it. Recognising the shape after the fact is the only available fix
/// (task 675).
///
/// Deliberately PURELY STRUCTURAL: it returns the name whatever it is, and the
/// caller must confirm the name is a typedef before treating the node as a
/// cast. `(mask) & flags` has exactly this shape and is a real bitwise AND
/// when `mask` is a variable, so the type knowledge -- which is per-rule and
/// sometimes cross-file -- has to stay with the caller.
pub fn misparsed_cast_type_name<'a>(node: &Node, source: &'a str) -> Option<&'a str> {
    let candidate = match node.kind() {
        // `(T)&x` and friends: the "type" lands in the left operand.
        "binary_expression" => {
            let op = node.child_by_field_name("operator")?;
            if !matches!(get_node_text(&op, source), "&" | "*" | "-" | "+") {
                return None;
            }
            node.child_by_field_name("left")?
        }
        // `(T)(x)`: the "type" lands in the callee position.
        "call_expression" => node.child_by_field_name("function")?,
        _ => return None,
    };

    if candidate.kind() != "parenthesized_expression" {
        return None;
    }
    // Exactly one named child, and it is a bare identifier -- `(a + b) & c`
    // and `(s->mask) & c` are ordinary expressions, not mis-parsed casts.
    if candidate.named_child_count() != 1 {
        return None;
    }
    let inner = candidate.named_child(0)?;
    if inner.kind() != "identifier" {
        return None;
    }
    Some(get_node_text(&inner, source))
}

/// Check if a node is part of a sizeof expression
#[allow(dead_code)]
pub fn is_in_sizeof(node: &Node) -> bool {
    query::nearest_ancestor_of_kind(*node, "sizeof_expression").is_some()
}

// ============================================================================
// Control Flow Navigation Utilities
// ============================================================================

/// Find the containing for loop statement for a given node
///
/// # Arguments
/// * `node` - The starting node to search from
///
/// # Returns
/// The for_statement node that contains the given node, or None if not found
///
/// # Examples
/// ```no_run
/// use aurora_lint::utility::cert_c::ast_utils::find_containing_for_loop;
/// use tree_sitter::Node;
/// // When checking a subscript inside a for loop:
/// // let subscript_node: Node = /* get from parsed AST */;
/// // if let Some(for_loop) = find_containing_for_loop(&subscript_node) {
/// //     // Analyze loop bounds
/// // }
/// ```
pub fn find_containing_for_loop<'a>(node: &Node<'a>) -> Option<Node<'a>> {
    query::nearest_ancestor_of_kind(*node, "for_statement")
}

/// Find the containing if statement for a given node
///
/// # Arguments
/// * `node` - The starting node to search from
///
/// # Returns
/// The if_statement node that contains the given node, or None if not found
///
/// # Examples
/// ```no_run
/// use aurora_lint::utility::cert_c::ast_utils::find_containing_if_statement;
/// use tree_sitter::Node;
/// // When checking if array access is within a bounds check:
/// // let subscript_node: Node = /* get from parsed AST */;
/// // if let Some(if_stmt) = find_containing_if_statement(&subscript_node) {
/// //     // Check if condition validates bounds
/// // }
/// ```
pub fn find_containing_if_statement<'a>(node: &Node<'a>) -> Option<Node<'a>> {
    query::nearest_ancestor_of_kind(*node, "if_statement")
}

// ============================================================================
// Struct Type Resolution
// ============================================================================

/// Extract the struct name from a C type string.
///
/// Handles patterns like:
/// - `"struct MyStruct *"` → `Some("MyStruct")`
/// - `"struct MyStruct"` → `Some("MyStruct")`
/// - `"MyStruct *"` → `Some("MyStruct")`
/// - `"MyStruct"` → `Some("MyStruct")`
/// - `"int"` → `None` (primitive type, not a struct)
///
/// For typedef'd structs (e.g., `typedef struct Foo { ... } Foo;`), the
/// type_map entry may be just `"Foo *"` without the `struct` keyword.
pub fn extract_struct_name_from_type(type_str: &str) -> Option<&str> {
    let trimmed = type_str.trim();

    // Strip pointer/const/volatile qualifiers from both ends
    let mut base = trimmed
        .trim_end_matches('*')
        .trim_end()
        .trim_end_matches("const")
        .trim_end_matches("volatile")
        .trim();
    loop {
        let next = base
            .strip_prefix("const ")
            .or_else(|| base.strip_prefix("volatile "))
            .unwrap_or(base)
            .trim();
        if next == base {
            break;
        }
        base = next;
    }

    // Skip obvious primitives
    if matches!(
        base,
        "int"
            | "unsigned int"
            | "signed int"
            | "short"
            | "unsigned short"
            | "long"
            | "unsigned long"
            | "long long"
            | "unsigned long long"
            | "char"
            | "unsigned char"
            | "signed char"
            | "float"
            | "double"
            | "void"
            | "_Bool"
    ) {
        return None;
    }
    // Skip stdint types
    if base.ends_with("_t")
        && (base.starts_with("int") || base.starts_with("uint") || base.starts_with("size"))
    {
        return None;
    }

    // "struct MyStruct" → "MyStruct"
    if let Some(name) = base.strip_prefix("struct ") {
        let name = name.trim();
        if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
            return Some(name);
        }
        return None;
    }

    // Bare identifier (typedef'd name) — must look like an identifier, not a primitive
    if !base.is_empty()
        && base
            .chars()
            .next()
            .is_some_and(|c| c.is_alphabetic() || c == '_')
        && base.chars().all(|c| c.is_alphanumeric() || c == '_')
    {
        return Some(base);
    }

    None
}

/// Resolve the type of a `field_expression` node using the variable type map
/// and struct field type database.
///
/// Given `s->count` where `s` is declared as `struct MyStruct *s`:
/// 1. Extracts field name "count" from the field_expression
/// 2. Looks up base variable "s" → "struct MyStruct *" in type_map
/// 3. Extracts struct name "MyStruct"
/// 4. Looks up "MyStruct"."count" → "int" in struct_field_types
pub fn resolve_field_expression_type(
    node: &Node,
    source: &str,
    type_map: &std::collections::HashMap<String, String>,
    struct_field_types: &std::collections::HashMap<
        String,
        std::collections::HashMap<String, String>,
    >,
) -> Option<String> {
    let field_node = node.child_by_field_name("field")?;
    let field_name = field_node.utf8_text(source.as_bytes()).ok()?;
    let argument = node.child_by_field_name("argument")?;

    // Resolve the struct type of the argument. Supports chained access
    // (`a.b.c`, `a->b.c`) by recursing through nested field_expressions.
    let base_type = match argument.kind() {
        "identifier" => {
            let base_name = argument.utf8_text(source.as_bytes()).ok()?;
            type_map.get(base_name)?.clone()
        }
        "field_expression" => {
            resolve_field_expression_type(&argument, source, type_map, struct_field_types)?
        }
        "pointer_expression" => {
            // `*p.field` — dereference one pointer level from `p`'s type.
            let inner = argument.child_by_field_name("argument")?;
            let inner_name = inner.utf8_text(source.as_bytes()).ok()?;
            let t = type_map.get(inner_name)?;
            t.strip_suffix(" *")
                .or_else(|| t.strip_suffix('*'))
                .map(|s| s.trim().to_string())?
        }
        _ => return None,
    };

    let struct_name = extract_struct_name_from_type(&base_type)?;

    struct_field_types
        .get(struct_name)
        .and_then(|fields| fields.get(field_name))
        .cloned()
}

/// Result of inspecting a `struct_specifier` for packed-ness.
pub enum PackedSignal {
    /// Not packed (or no signal found).
    No,
    /// Directly `__attribute__((packed))` on the specifier — resolved
    /// without needing any other file's context.
    Direct,
    /// A trailing bare identifier between the closing brace and the
    /// terminating `;`/field name (e.g. `struct foo { ... } STRUCT_PACKED;`)
    /// that *might* be a packed-attribute macro — its `#define` may live in
    /// a different file (a header this one doesn't textually include in
    /// aurora-lint's no-preprocessor model), so the caller must resolve the name
    /// against a project-wide macro-name set.
    MacroCandidate(String),
}

/// Inspect `struct_specifier` (a struct *definition*, with a body) for a
/// packed-attribute signal. Some C parsers have no preprocessor, so a
/// trailing macro token like hostap's `STRUCT_PACKED` gets parsed as if it
/// were a declarator/field name rather than an attribute — the caller
/// resolves that candidate name against `#define`s collected project-wide
/// (see `macro_expands_to_packed`), which keeps this codebase-independent
/// rather than a hardcoded name heuristic.
pub fn struct_specifier_packed_signal(s: &Node, source: &str) -> PackedSignal {
    for attr in query::find_descendants_of_kind(*s, "attribute_specifier") {
        if get_node_text(&attr, source).contains("packed") {
            return PackedSignal::Direct;
        }
    }
    let Some(parent) = s.parent() else {
        return PackedSignal::No;
    };
    if !matches!(
        parent.kind(),
        "declaration" | "field_declaration" | "type_definition"
    ) {
        return PackedSignal::No;
    }
    let parent_text = get_node_text(&parent, source);
    let struct_text = get_node_text(s, source);
    let Some(tail) = parent_text.strip_prefix(struct_text) else {
        return PackedSignal::No;
    };
    let Ok(ident_re) = regex::Regex::new(r"[A-Za-z_][A-Za-z0-9_]*") else {
        return PackedSignal::No;
    };
    match ident_re.find(tail) {
        Some(m) => PackedSignal::MacroCandidate(m.as_str().to_string()),
        None => PackedSignal::No,
    }
}

/// True if `struct_specifier` is packed, resolving any trailing-macro
/// candidate against `#define`s in this SAME `source` text only. Used by
/// the single-file/intra-file prescan path (test fixtures); the cross-file
/// prescan path resolves `MacroCandidate`s against a project-wide macro-name
/// set instead (see `analyze::prescan::collect_packed_structs`).
pub fn struct_specifier_is_packed(s: &Node, source: &str) -> bool {
    match struct_specifier_packed_signal(s, source) {
        PackedSignal::Direct => true,
        PackedSignal::MacroCandidate(name) => macro_expands_to_packed(&name, source),
        PackedSignal::No => false,
    }
}

/// True if `#define name ...` appears in `source` and its replacement text
/// contains "packed" (e.g. `#define STRUCT_PACKED __attribute__
/// ((packed))`).
pub fn macro_expands_to_packed(name: &str, source: &str) -> bool {
    let Ok(re) = regex::Regex::new(&format!(
        r"(?m)^\s*#\s*define\s+{}\b.*$",
        regex::escape(name)
    )) else {
        return false;
    };
    re.find(source)
        .map(|m| m.as_str().contains("packed"))
        .unwrap_or(false)
}

/// Collect every `#define NAME ...` object-macro name in `source` whose
/// replacement text contains "packed" (e.g. hostap's `#define STRUCT_PACKED
/// __attribute__ ((packed))`). Plain regex over raw text, not AST-based —
/// deliberately independent of any single file's struct definitions so it
/// can be merged project-wide and used to resolve `PackedSignal::MacroCandidate`s
/// found in *other* files.
pub fn collect_packed_macro_names(source: &str, out: &mut std::collections::HashSet<String>) {
    let Ok(re) = regex::Regex::new(r"(?m)^\s*#\s*define\s+([A-Za-z_][A-Za-z0-9_]*)\b.*$") else {
        return;
    };
    for cap in re.captures_iter(source) {
        let line = cap.get(0).map(|m| m.as_str()).unwrap_or("");
        if line.contains("packed") {
            if let Some(name) = cap.get(1) {
                out.insert(name.as_str().to_string());
            }
        }
    }
}

/// True if `#define name ...` appears anywhere in `source`, regardless of
/// what it expands to. Used to recognize a trailing bare identifier right
/// after a struct/union/enum body (e.g. `struct foo { ... } SOME_MACRO;`) as
/// an attribute-position macro invocation rather than a genuine object
/// declaration: aurora-lint has no preprocessor, so such a macro is parsed as if it
/// were the declared object's name, but a real C identifier can never
/// collide with an in-scope `#define` name (the preprocessor would have
/// substituted it first) — so if the name is a known macro, this can't be a
/// real declaration (DCL40-C task 432).
pub fn is_defined_macro_name(name: &str, source: &str) -> bool {
    let Ok(re) = regex::Regex::new(&format!(r"(?m)^\s*#\s*define\s+{}\b", regex::escape(name)))
    else {
        return false;
    };
    re.is_match(source)
}

/// True if `name` looks like a preprocessor macro constant *by naming
/// convention alone*: ALL_CAPS letters, digits and underscores only, and not
/// starting with a digit (so a bare numeric literal is never mistaken for a
/// macro name). Empty input is never a macro name.
///
/// This never consults an actual `#define` — prefer
/// `is_defined_macro_name` (or `ProjectContext`'s project-wide macro-name
/// set) whenever the definition is reachable, and prefer
/// `analyze::macro_expand` whenever the macro's *value* matters. This is the
/// last-resort guess for "is this identifier a compile-time constant?" when
/// no definition is in scope — e.g. distinguishing `int a[SIZE]` (not a VLA)
/// from `int a[n]` (a VLA).
///
/// Single source of truth for a heuristic that was independently
/// reimplemented in five rules with slightly different edge cases
/// (task 603): MEM05-C, ARR32-C, MEM33-C, DCL03-C, EXP08-C.
///
/// # Examples
/// ```
/// use aurora_lint::utility::cert_c::ast_utils::is_likely_macro_constant;
/// assert!(is_likely_macro_constant("MAX_SIZE"));
/// assert!(is_likely_macro_constant("_BUF_LEN2"));
/// assert!(!is_likely_macro_constant("bufLen"));
/// assert!(!is_likely_macro_constant("10"));
/// assert!(!is_likely_macro_constant(""));
/// ```
pub fn is_likely_macro_constant(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_uppercase() || c == '_' || c.is_ascii_digit())
        && name
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_uppercase() || c == '_')
}

/// Collect every `#define NAME ...` object-macro name in `source`,
/// regardless of what it expands to. Plain regex over raw text, not
/// AST-based — deliberately independent of any single file's declarations
/// so it can be merged project-wide and used to resolve a trailing bare
/// identifier found in *other* files against the macro's actual `#define`
/// (which commonly lives in a different header, e.g. hostap's
/// `STRUCT_PACKED` in `utils/common.h` vs. structs in
/// `common/ieee802_11_defs.h`). Generalizes `collect_packed_macro_names` to
/// any macro name, not just packed-attribute ones — see `is_defined_macro_name`.
pub fn collect_defined_macro_names(source: &str, out: &mut std::collections::HashSet<String>) {
    let Ok(re) = regex::Regex::new(r"(?m)^\s*#\s*define\s+([A-Za-z_][A-Za-z0-9_]*)\b") else {
        return;
    };
    for cap in re.captures_iter(source) {
        if let Some(name) = cap.get(1) {
            out.insert(name.as_str().to_string());
        }
    }
}

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

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

    #[test]
    fn test_get_node_text() {
        let (tree, source) = parse_c_code("int x = 5;");
        let root = tree.root_node();
        let text = get_node_text(&root, &source);
        assert_eq!(text, "int x = 5;");
    }

    #[test]
    fn test_find_containing_function() {
        let (tree, _source) = parse_c_code("void foo() { int x = 5; }");
        let root = tree.root_node();

        // Find the declaration node (int x = 5)
        let func_def = root.child(0).unwrap();
        assert_eq!(func_def.kind(), "function_definition");

        // Find a node inside the function
        let compound_stmt = func_def.child_by_field_name("body").unwrap();
        let decl = compound_stmt.child(1).unwrap(); // Skip opening brace

        let containing_func = find_containing_function(&decl);
        assert!(containing_func.is_some());
        assert_eq!(containing_func.unwrap().kind(), "function_definition");
    }

    #[test]
    fn test_find_array_size() {
        let text = "int main() { int arr[10]; }";
        let size = find_array_size("arr", text);
        assert_eq!(size, Some(10));
    }

    #[test]
    fn test_is_signed_type() {
        assert!(is_signed_type("int"));
        assert!(is_signed_type("signed int"));
        assert!(is_signed_type("int32_t"));
        assert!(!is_signed_type("unsigned int"));
        assert!(!is_signed_type("size_t"));
    }

    #[test]
    fn test_is_unsigned_type() {
        assert!(is_unsigned_type("unsigned int"));
        assert!(is_unsigned_type("size_t"));
        assert!(is_unsigned_type("uint32_t"));
        assert!(!is_unsigned_type("int"));
        assert!(!is_unsigned_type("signed int"));
    }

    #[test]
    fn test_get_type_size() {
        assert_eq!(get_type_size("char"), 1);
        assert_eq!(get_type_size("short"), 2);
        assert_eq!(get_type_size("int"), 4);
        assert_eq!(get_type_size("long"), 8);
        assert_eq!(get_type_size("int *"), 8);
    }

    /// `find_enclosing_declaration_for_identifier` must resolve a
    /// `for (int i = ...; ...) { ... }` loop variable's declaration for
    /// every occurrence within the for-statement (condition, update, and
    /// body) -- not just ones inside a nested `compound_statement`. The
    /// declaration is a direct child of `for_statement`, one level away
    /// from any `compound_statement`, which an earlier version of this
    /// function never looked at (task 386 regression, fixed alongside).
    #[test]
    fn test_find_enclosing_declaration_for_identifier_for_loop_var() {
        let (tree, source) =
            parse_c_code("void f(void) { for (int i = 0; i < 10; i++) { use(i); } }");
        let root = tree.root_node();
        let idents = query::find_descendants_of_kind(root, "identifier");
        let occurrences: Vec<_> = idents
            .iter()
            .filter(|n| get_node_text(n, &source) == "i")
            .collect();
        // declarator, condition, update, and the body's use(i) -- 4 total.
        assert_eq!(occurrences.len(), 4);
        let decl_node = occurrences[0];
        for occurrence in &occurrences[1..] {
            let resolved = find_enclosing_declaration_for_identifier(occurrence, "i", &source);
            assert!(
                resolved.is_some(),
                "expected occurrence at byte {} to resolve to the for-loop's own declaration",
                occurrence.start_byte()
            );
            let resolved = resolved.unwrap();
            assert!(resolved.start_byte() <= decl_node.start_byte());
            assert_eq!(resolved.kind(), "declaration");
        }
    }

    /// A shadowing re-declaration inside the loop body must still win over
    /// the for-loop's own declaration -- the widened for_statement search
    /// must not short-circuit the existing nearest-scope-wins behavior.
    #[test]
    fn test_find_enclosing_declaration_for_identifier_shadow_in_loop_body() {
        let (tree, source) =
            parse_c_code("void f(void) { for (int i = 0; i < 10; i++) { int i = 5; use(i); } }");
        let root = tree.root_node();
        let idents = query::find_descendants_of_kind(root, "identifier");
        let use_i = idents
            .iter()
            .rev()
            .find(|n| get_node_text(n, &source) == "i")
            .unwrap();
        let resolved = find_enclosing_declaration_for_identifier(use_i, "i", &source).unwrap();
        let inner_decl_text = get_node_text(&resolved, &source);
        assert!(
            inner_decl_text.contains("= 5"),
            "expected the inner shadowing declaration, got: {inner_decl_text}"
        );
    }

    /// A declaration written inside a `#ifdef`/`#endif` block has the same
    /// enclosing scope as one written directly -- textual inclusion, not a
    /// new C scope. A read anywhere else in that enclosing block (inside
    /// the same `#ifdef` branch, or after the `#endif` entirely) must still
    /// resolve back to it, not fail to resolve just because the
    /// declaration is nested one level inside a `preproc_ifdef` rather than
    /// being a direct child of the enclosing `compound_statement`.
    #[test]
    fn test_find_enclosing_declaration_for_identifier_inside_ifdef() {
        let (tree, source) = parse_c_code(
            "int f(int x) { \
             #ifdef NEED_AP_MLME\n\
             int color = x;\n\
             #endif\n\
             return color; }",
        );
        let root = tree.root_node();
        let idents = query::find_descendants_of_kind(root, "identifier");
        let use_color = idents
            .iter()
            .rev()
            .find(|n| get_node_text(n, &source) == "color")
            .unwrap();
        let resolved = find_enclosing_declaration_for_identifier(use_color, "color", &source);
        assert!(
            resolved.is_some(),
            "expected the ifdef-nested declaration to resolve"
        );
        assert_eq!(resolved.unwrap().kind(), "declaration");
    }
}