sqc 0.4.84

Software Code Quality - CERT C compliance checker
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
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
use super::super::{CertRule, RuleViolation};
use crate::analyze::cfg::{self as cfg_mod, FunctionCfg};
use crate::analyze::context::ProjectContext;
use crate::analyze::function_summary::FunctionSummary;
use crate::analyze::null_state::{self, NullAnalysisResult, NullState, StateMap};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils;
use lang_parsing_substrate::query;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use tree_sitter::Node;

pub struct Exp34C {
    function_summaries: RefCell<HashMap<String, FunctionSummary>>,
    function_cfgs: RefCell<HashMap<usize, FunctionCfg>>,
    /// Null states for file-scope (static/global) pointer variables,
    /// computed once per file by scanning all declarations and assignments.
    file_global_states: RefCell<StateMap>,
    /// Cross-file global pointer null states from prescan.
    /// Used to resolve `extern` pointer globals defined in other translation units.
    prescan_global_var_states: RefCell<HashMap<String, NullState>>,
}

impl Exp34C {
    pub fn new() -> Self {
        Self {
            function_summaries: RefCell::new(HashMap::new()),
            function_cfgs: RefCell::new(HashMap::new()),
            file_global_states: RefCell::new(StateMap::new()),
            prescan_global_var_states: RefCell::new(HashMap::new()),
        }
    }
}

impl CertRule for Exp34C {
    fn rule_id(&self) -> &'static str {
        "EXP34-C"
    }

    fn description(&self) -> &'static str {
        "Do not dereference null pointers"
    }

    fn severity(&self) -> Severity {
        Severity::High
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Rule
    }

    fn cert_id(&self) -> &'static str {
        "EXP34-C"
    }

    fn set_project_context(&self, context: &ProjectContext) {
        *self.function_summaries.borrow_mut() = context.function_summaries.clone();
        *self.prescan_global_var_states.borrow_mut() = context.global_var_null_states.clone();
    }

    fn set_function_cfgs(&self, cfgs: &HashMap<usize, FunctionCfg>) {
        *self.function_cfgs.borrow_mut() = cfgs.clone();
    }

    fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
        let mut violations = Vec::new();
        let summaries = self.function_summaries.borrow();
        let cfgs = self.function_cfgs.borrow();

        for n in
            query::find_descendants_of_kinds(*node, &["translation_unit", "function_definition"])
        {
            let node = &n;
            // At the top level (translation_unit), collect file-scope global null states
            if node.kind() == "translation_unit" {
                let mut globals =
                    null_state::collect_file_scope_null_states(node, source, &summaries);

                // Merge prescan cross-file states for extern pointer declarations.
                // For variables declared `extern` in this file, the file-scope analysis
                // has no assignments to track — inject prescan-derived states.
                let prescan_states = self.prescan_global_var_states.borrow();
                if !prescan_states.is_empty() {
                    merge_extern_global_states(node, source, &prescan_states, &mut globals);
                }

                *self.file_global_states.borrow_mut() = globals;
            }

            if node.kind() == "function_definition" {
                if let Some(body) = node.child_by_field_name("body") {
                    // Get pre-built CFG or build one on the fly
                    let inline_cfg;
                    let cfg = if let Some(c) = cfgs.get(&node.start_byte()) {
                        c
                    } else if let Some(c) = cfg_mod::build_function_cfg(node, source) {
                        inline_cfg = c;
                        &inline_cfg
                    } else {
                        // Skip: no CFG available for this function
                        continue;
                    };

                    // Extract function name for call-site param seeding
                    let func_name = node
                        .child_by_field_name("declarator")
                        .and_then(|d| extract_function_name(&d, source));

                    // Run CFG-based null-state dataflow, seeded with global states
                    let global_states = self.file_global_states.borrow();
                    let analysis = null_state::analyze_null_states_with_globals(
                        cfg,
                        node,
                        source,
                        &summaries,
                        &global_states,
                        func_name.as_deref(),
                    );

                    // Walk AST for dereferences and check each against the dataflow result
                    let mut reported_vars: HashSet<String> = HashSet::new();
                    check_dereferences_cfg(
                        &body,
                        source,
                        &analysis,
                        cfg,
                        &body,
                        &summaries,
                        &mut violations,
                        &mut reported_vars,
                    );
                }
            }
        }

        violations
    }
}

// ---------------------------------------------------------------------------
// Dereference walker (AST-based, queries CFG analysis for safety)
// ---------------------------------------------------------------------------

fn check_dereferences_cfg(
    node: &Node,
    source: &str,
    analysis: &NullAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    summaries: &HashMap<String, FunctionSummary>,
    violations: &mut Vec<RuleViolation>,
    reported_vars: &mut HashSet<String>,
) {
    for n in query::find_descendants_of_kinds(
        *node,
        &[
            "pointer_expression",
            "subscript_expression",
            "field_expression",
            "call_expression",
        ],
    ) {
        let node = &n;
        match node.kind() {
            "pointer_expression" => check_pointer_deref_cfg(
                node,
                source,
                analysis,
                cfg,
                body,
                summaries,
                violations,
                reported_vars,
            ),
            "subscript_expression" => check_subscript_deref_cfg(
                node,
                source,
                analysis,
                cfg,
                body,
                summaries,
                violations,
                reported_vars,
            ),
            "field_expression" => check_field_deref_cfg(
                node,
                source,
                analysis,
                cfg,
                body,
                summaries,
                violations,
                reported_vars,
            ),
            "call_expression" => check_call_expression_cfg(
                node,
                source,
                analysis,
                cfg,
                body,
                summaries,
                violations,
                reported_vars,
            ),
            _ => {}
        }
    }
}

/// `pointer_expression` case: `*ptr` where tree-sitter uses the same node
/// kind for both dereference and address-of, so only the `*` operator is a
/// candidate null-deref.
fn check_pointer_deref_cfg(
    node: &Node,
    source: &str,
    analysis: &NullAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    summaries: &HashMap<String, FunctionSummary>,
    violations: &mut Vec<RuleViolation>,
    reported_vars: &mut HashSet<String>,
) {
    let is_deref = node
        .child_by_field_name("operator")
        .map(|op| ast_utils::get_node_text_owned(&op, source) == "*")
        .unwrap_or(false);
    if !is_deref {
        return;
    }
    let Some(argument) = node.child_by_field_name("argument") else {
        return;
    };
    let mut deref_text = ast_utils::get_node_text_owned(&argument, source);

    // Strip parentheses
    if argument.kind() == "parenthesized_expression" {
        if let Some(inner) = argument.child(1) {
            deref_text = ast_utils::get_node_text_owned(&inner, source);
        }
    }

    if !matches!(
        argument.kind(),
        "identifier" | "field_expression" | "parenthesized_expression"
    ) {
        return;
    }
    if reported_vars.contains(&deref_text)
        || !is_unsafe_at(&deref_text, node, source, analysis, cfg, body, summaries)
    {
        return;
    }
    reported_vars.insert(deref_text.clone());
    let start_point = node.start_position();
    violations.push(RuleViolation {
        rule_id: "EXP34-C".to_string(),
        severity: Severity::High,
        message: format!(
            "Potential null pointer dereference of variable '{}'",
            deref_text
        ),
        file_path: String::new(),
        line: start_point.row + 1,
        column: start_point.column + 1,
        suggestion: Some(format!(
            "Check if '{}' is not NULL before dereferencing",
            deref_text
        )),
        ..Default::default()
    });
}

/// `subscript_expression` case: `arr[i]` where `arr` is a bare identifier.
fn check_subscript_deref_cfg(
    node: &Node,
    source: &str,
    analysis: &NullAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    summaries: &HashMap<String, FunctionSummary>,
    violations: &mut Vec<RuleViolation>,
    reported_vars: &mut HashSet<String>,
) {
    let Some(array) = node.child(0) else { return };
    if array.kind() != "identifier" {
        return;
    }
    let var_name = ast_utils::get_node_text_owned(&array, source);
    if reported_vars.contains(&var_name)
        || !is_unsafe_at(&var_name, node, source, analysis, cfg, body, summaries)
    {
        return;
    }
    reported_vars.insert(var_name.clone());
    let start_point = node.start_position();
    violations.push(RuleViolation {
        rule_id: "EXP34-C".to_string(),
        severity: Severity::High,
        message: format!(
            "Potential null pointer dereference in array access of variable '{}'",
            var_name
        ),
        file_path: String::new(),
        line: start_point.row + 1,
        column: start_point.column + 1,
        suggestion: Some(format!(
            "Check if '{}' is not NULL before array access",
            var_name
        )),
        ..Default::default()
    });
}

/// `field_expression` case: `s->field` / `s.field` where `s` is a bare identifier.
fn check_field_deref_cfg(
    node: &Node,
    source: &str,
    analysis: &NullAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    summaries: &HashMap<String, FunctionSummary>,
    violations: &mut Vec<RuleViolation>,
    reported_vars: &mut HashSet<String>,
) {
    let Some(argument) = node.child_by_field_name("argument") else {
        return;
    };
    if argument.kind() != "identifier" {
        return;
    }
    let var_name = ast_utils::get_node_text_owned(&argument, source);
    if reported_vars.contains(&var_name)
        || !is_unsafe_at(&var_name, node, source, analysis, cfg, body, summaries)
    {
        return;
    }
    reported_vars.insert(var_name.clone());
    let start_point = node.start_position();
    violations.push(RuleViolation {
        rule_id: "EXP34-C".to_string(),
        severity: Severity::High,
        message: format!(
            "Potential null pointer dereference in member access of variable '{}'",
            var_name
        ),
        file_path: String::new(),
        line: start_point.row + 1,
        column: start_point.column + 1,
        suggestion: Some(format!(
            "Check if '{}' is not NULL before member access",
            var_name
        )),
        ..Default::default()
    });
}

/// `call_expression` case: function-pointer-null calls, deref-function
/// argument checks, and call-site null-argument propagation to callees.
fn check_call_expression_cfg(
    node: &Node,
    source: &str,
    analysis: &NullAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    summaries: &HashMap<String, FunctionSummary>,
    violations: &mut Vec<RuleViolation>,
    reported_vars: &mut HashSet<String>,
) {
    let Some(function) = node.child_by_field_name("function") else {
        return;
    };

    // Function pointer call
    if function.kind() == "identifier" {
        let func_name = ast_utils::get_node_text_owned(&function, source);
        if !reported_vars.contains(&func_name)
            && is_unsafe_at(&func_name, node, source, analysis, cfg, body, summaries)
        {
            reported_vars.insert(func_name.clone());
            let start_point = function.start_position();
            violations.push(RuleViolation {
                rule_id: "EXP34-C".to_string(),
                severity: Severity::High,
                message: format!("Calling potentially null function pointer '{}'", func_name),
                file_path: String::new(),
                line: start_point.row + 1,
                column: start_point.column + 1,
                suggestion: Some(format!(
                    "Check if '{}' is not NULL before calling",
                    func_name
                )),
                ..Default::default()
            });
        }
    }

    let func_name = ast_utils::get_node_text_owned(&function, source);

    // Check deref-function arguments. Skip when the callee is known to
    // accept NULL (free/fclose no-op on NULL per C standard).
    if is_deref_function(&func_name) && !is_null_safe_function(&func_name) {
        if let Some(args) = node.child_by_field_name("arguments") {
            check_function_arguments_cfg(
                &args,
                source,
                analysis,
                cfg,
                body,
                summaries,
                violations,
                reported_vars,
            );
        }
    }

    // Call-site null propagation: flag DefinitelyNull args to callees that
    // don't null-check them. Only when callee has a summary (guards against
    // flagging unknown library functions).
    if !is_deref_function(&func_name)
        && !is_null_safe_function(&func_name)
        && summaries.contains_key(&func_name)
    {
        if let Some(args_node) = node.child_by_field_name("arguments") {
            check_callsite_null_args(
                &func_name, &args_node, source, analysis, cfg, body, summaries, violations,
            );
        }
    }
}

fn check_function_arguments_cfg(
    args: &Node,
    source: &str,
    analysis: &NullAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    summaries: &HashMap<String, FunctionSummary>,
    violations: &mut Vec<RuleViolation>,
    reported_vars: &mut HashSet<String>,
) {
    for i in 0..args.child_count() {
        if let Some(arg) = args.child(i) {
            if arg.kind() == "identifier" {
                let var_name = ast_utils::get_node_text_owned(&arg, source);
                if !reported_vars.contains(&var_name)
                    && is_unsafe_at(&var_name, &arg, source, analysis, cfg, body, summaries)
                {
                    reported_vars.insert(var_name.clone());
                    let start_point = arg.start_position();
                    violations.push(RuleViolation {
                        rule_id: "EXP34-C".to_string(),
                        severity: Severity::High,
                        message: format!(
                            "Passing potentially null pointer '{}' to function",
                            var_name
                        ),
                        file_path: String::new(),
                        line: start_point.row + 1,
                        column: start_point.column + 1,
                        suggestion: Some(format!(
                            "Check if '{}' is not NULL before passing to function",
                            var_name
                        )),
                        ..Default::default()
                    });
                }
            }
        }
    }
}

/// Call-site null propagation: flag passing a DefinitelyNull pointer to a
/// function that doesn't null-check that parameter. This catches the source
/// side of cross-file null dereferences (Juliet variants 51-68).
fn check_callsite_null_args(
    callee_name: &str,
    args: &Node,
    source: &str,
    analysis: &NullAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    summaries: &HashMap<String, FunctionSummary>,
    violations: &mut Vec<RuleViolation>,
) {
    let callee_summary = summaries.get(callee_name);

    let mut param_idx: usize = 0;
    for i in 0..args.child_count() {
        if let Some(arg) = args.child(i) {
            // Skip commas and other non-argument tokens
            if arg.kind() == "," || arg.kind() == "(" || arg.kind() == ")" {
                continue;
            }

            if arg.kind() == "identifier" {
                let var_name = ast_utils::get_node_text_owned(&arg, source);
                let state = null_state::get_var_state_at(
                    analysis,
                    cfg,
                    body,
                    source,
                    &var_name,
                    arg.start_byte(),
                    summaries,
                );

                // Only flag DefinitelyNull — PossiblyNull is too noisy for call sites
                if state == null_state::NullState::DefinitelyNull {
                    // If no summary, assume callee handles null (conservative for unknowns)
                    let callee_checks_null = callee_summary
                        .map(|s| s.checks_null_params.contains(&param_idx))
                        .unwrap_or(true);

                    // Same rc<->out-parameter success correlation as is_unsafe_at:
                    // a pointer set through `&p` by a call whose status is stored
                    // in `rc`, then passed under an `rc == SQLITE_OK` guard, is
                    // non-null at the call. This interprocedural arg check does
                    // not route through is_unsafe_at, so apply the guard here too.
                    if !callee_checks_null && !is_guarded_by_rc_success(&var_name, &arg, source) {
                        let start_point = arg.start_position();
                        violations.push(RuleViolation {
                            rule_id: "EXP34-C".to_string(),
                            severity: Severity::High,
                            message: format!(
                                "Passing null pointer '{}' to '{}' which does not check for NULL",
                                var_name, callee_name
                            ),
                            file_path: String::new(),
                            line: start_point.row + 1,
                            column: start_point.column + 1,
                            suggestion: Some(format!(
                                "Check if '{}' is not NULL before passing to '{}'",
                                var_name, callee_name
                            )),
                            ..Default::default()
                        });
                    }
                }
            }

            param_idx += 1;
        }
    }
}

/// Functions that safely handle NULL arguments (no dereference concern).
///
/// Includes:
/// - C standard: `free(NULL)` (C11 7.22.3.3) and `realloc(NULL, n)` (C11 7.22.3.5)
///   are defined as no-op / equivalent-to-malloc.
/// - Juliet test harness print helpers (null-tolerant stubs).
fn is_null_safe_function(name: &str) -> bool {
    matches!(
        name,
        "free"
            | "realloc"
            | "printLine"
            | "printWLine"
            | "printIntLine"
            | "printLongLine"
            | "printLongLongLine"
            | "printStructLine"
            | "printHexCharLine"
            | "printUnsignedLine"
            | "printFloatLine"
            | "printDoubleLine"
            | "printSizeTLine"
            | "printHexUnsignedCharLine"
    )
}

// ---------------------------------------------------------------------------
// Safety determination: CFG dataflow + AST expression guards
// ---------------------------------------------------------------------------

/// Check if dereferencing `var_name` at `deref_node` is unsafe.
/// Uses CFG dataflow as the primary check, with AST-based expression guards
/// for patterns that live within a single expression (&&, ternary).
fn is_unsafe_at(
    var_name: &str,
    deref_node: &Node,
    source: &str,
    analysis: &NullAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    summaries: &HashMap<String, FunctionSummary>,
) -> bool {
    let deref_byte = deref_node.start_byte();

    // A dereference inside `sizeof(...)` is never evaluated (unevaluated operand),
    // and one inside an `assert(...)` argument is a debug-only precondition check —
    // neither is a runtime null dereference. Suppress before consulting dataflow.
    if is_in_unevaluated_or_assert_context(deref_node, source) {
        return false;
    }

    // Primary check: CFG-based null state dataflow
    if !null_state::is_null_deref_at(analysis, cfg, body, source, var_name, deref_byte, summaries) {
        return false; // CFG says safe
    }

    // The CFG says potentially unsafe. But check AST-level expression guards
    // that the CFG cannot model (because they're within a single expression,
    // not separate CFG blocks).

    // Check && short-circuit: (ptr != NULL) && (ptr->field)
    // Check ternary: (ptr != NULL) ? *ptr : 0
    // Check if-statement scope (redundant with CFG for most cases, but catches
    // edge cases where CFG block boundaries don't align perfectly)
    if is_in_expression_guard(var_name, deref_node, source) {
        return false;
    }

    // rc<->out-parameter success correlation (the sqlite idiom):
    //   sqlite3_stmt *p = 0;
    //   rc = sqlite3_prepare(db, sql, -1, &p, 0);   // p set iff rc == SQLITE_OK
    //   if (rc == SQLITE_OK) { ... use p ... }       // or: while (rc==SQLITE_OK && step(p))
    // The pointer is assigned only through an out-parameter (&p) of a call whose
    // status is stored in `rc`, and the deref is dominated by an `rc == SQLITE_OK`
    // (== 0 / !rc) success guard. The null-state dataflow cannot correlate the
    // status code with the pointer, so it reports a spurious may-be-null. This is
    // distinct from the unguarded-malloc null-deref pattern (which has no status
    // guard and no out-parameter), so recall for that FN is unaffected.
    if is_guarded_by_rc_success(var_name, deref_node, source) {
        return false;
    }

    // Caller-contract / precondition idiom (the sqlite internal-helper pattern):
    //   pReg = &aMem[pC->seekResult];
    //   assert( pReg->flags & MEM_Blob );   // documented invariant
    //   ... use pReg ...                    // non-null by that invariant
    // A pointer established non-null by a dominating `assert(...)` — either an
    // explicit `assert(p)` / `assert(p != 0)` test or an unconditional
    // dereference of `p` inside the assert — is guaranteed non-null by the
    // documented invariant, so a later dereference is not a bug. This is
    // distinct from the unguarded-malloc null-deref FN, which has *no* such
    // precondition assert (the whole point of that pattern is the missing
    // check), so recall for that FN is unaffected. Guarded against the pointer
    // being reassigned between the assert and the dereference.
    if is_guarded_by_precondition_assert(var_name, deref_node, source) {
        return false;
    }

    // A dereference of an iterator macro's loop variable inside the macro body
    // (e.g. `el->field` within `DL_FOREACH(head, el) { ... }`) is guarded
    // non-null by the macro's expanded loop condition, which the parser cannot
    // see. See crate::analyze::macro_semantics (Phase 1 of
    // docs/design/macro-expansion.md).
    if crate::analyze::macro_semantics::is_in_iterator_macro_body(deref_node, source, var_name) {
        return false;
    }

    true
}

/// Check if a dereference is guarded by expression-level null checks
/// that the CFG cannot model (&&, ternary) or by pragmatic null-check
/// patterns (if (ptr == NULL) { /* handle error */ } — no explicit return).
fn is_in_expression_guard(var_name: &str, node: &Node, source: &str) -> bool {
    let mut current = node.parent();

    while let Some(parent) = current {
        // Short-circuit guards:
        // && : (ptr != NULL) && (ptr->field) — right side safe when left confirms non-null
        // || : (ptr == NULL) || (ptr[0] == ...) — right side safe when left is null-check
        //      (right only evaluates when left is false, i.e. ptr is NOT null)
        if parent.kind() == "binary_expression" {
            if let Some(operator) = parent.child_by_field_name("operator") {
                let op = ast_utils::get_node_text_owned(&operator, source);
                if op == "&&" || op == "||" {
                    if let (Some(left), Some(right)) = (
                        parent.child_by_field_name("left"),
                        parent.child_by_field_name("right"),
                    ) {
                        // For &&: right executes when left is TRUE  → check left confirms non-null (negated=false)
                        // For ||: right executes when left is FALSE → check left negated confirms non-null (negated=true)
                        let negated = op == "||";
                        if node_is_within(&right, node)
                            && analyze_condition_for_safety(&left, var_name, source, negated)
                        {
                            return true;
                        }
                    }
                }
            }
        }

        // Ternary: (ptr != NULL) ? *ptr : default
        if parent.kind() == "conditional_expression" {
            if let Some(condition) = parent.child_by_field_name("condition") {
                if let Some(checked_var) = get_null_check_var(&condition, source) {
                    if checked_var == var_name {
                        let is_safe_in_consequence =
                            analyze_condition_for_safety(&condition, var_name, source, false);

                        if let Some(consequence) = parent.child_by_field_name("consequence") {
                            if node_is_within(&consequence, node) {
                                return is_safe_in_consequence;
                            }
                        }
                        if let Some(alternative) = parent.child_by_field_name("alternative") {
                            if node_is_within(&alternative, node) {
                                return !is_safe_in_consequence;
                            }
                        }
                    }
                }
            }
        }

        current = parent.parent();
    }

    // AST-level null guard: dereference inside if(var != NULL) { ... }
    // This handles cases where the CFG treats the enclosing context as a single
    // opaque block (e.g., inside switch_statement case bodies), so CFG-based
    // edge refinement cannot see the null guard.
    if is_inside_ast_null_guard(var_name, node, source) {
        return true;
    }

    // Pragmatic dominance check: if there's an if-statement earlier in the same
    // function that checks (var == NULL) and the dereference is AFTER that
    // if-statement, treat it as safe. This matches the common pattern:
    //   if (ptr == NULL) { /* Handle error */ }
    //   use(ptr);  // programmer assumes error was handled
    if is_dominated_by_null_check(var_name, node, source) {
        return true;
    }

    false
}

/// True when the node is in an unevaluated `sizeof(...)` operand or syntactically
/// inside an `assert(...)` argument. `sizeof` never evaluates its operand, and an
/// `assert(p->x)` is itself the precondition check (and is compiled out under
/// NDEBUG) — flagging a dereference in either context is a false positive.
fn is_in_unevaluated_or_assert_context(node: &Node, source: &str) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "sizeof_expression" => return true,
            "call_expression"
                if parent
                    .child_by_field_name("function")
                    .map(|f| ast_utils::get_node_text_owned(&f, source) == "assert")
                    .unwrap_or(false) =>
            {
                return true;
            }
            "function_definition" => break,
            _ => {}
        }
        current = parent.parent();
    }
    false
}

/// Check if a dereference is inside the true branch of an `if(var != NULL)` statement.
/// Walks AST ancestors to find an enclosing if-statement that null-checks the variable.
fn is_inside_ast_null_guard(var_name: &str, node: &Node, source: &str) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        if parent.kind() == "function_definition" {
            break;
        }
        if parent.kind() == "if_statement" {
            if let Some(condition) = parent.child_by_field_name("condition") {
                if let Some(checked_var) = get_null_check_var(&condition, source) {
                    if checked_var == var_name {
                        // Check if we're in the consequence (true branch)
                        if let Some(consequence) = parent.child_by_field_name("consequence") {
                            if node_is_within(&consequence, node) {
                                // var != NULL → true branch means var is non-null → safe
                                if analyze_condition_for_safety(&condition, var_name, source, false)
                                {
                                    return true;
                                }
                            }
                        }
                        // Check if we're in the alternative (else branch)
                        if let Some(alternative) = parent.child_by_field_name("alternative") {
                            if node_is_within(&alternative, node) {
                                // var == NULL → true branch means null, else branch means non-null → safe
                                if !analyze_condition_for_safety(
                                    &condition, var_name, source, false,
                                ) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
        current = parent.parent();
    }
    false
}

/// Walk up the AST to find the enclosing function body, then search for
/// if-statements that check `var_name == NULL` and occur before the
/// dereference (byte-position dominance).
fn is_dominated_by_null_check(var_name: &str, node: &Node, source: &str) -> bool {
    let deref_byte = node.start_byte();

    // Find the enclosing compound_statement (function body)
    let mut current = node.parent();
    let mut func_body = None;
    while let Some(parent) = current {
        if parent.kind() == "function_definition" {
            func_body = parent.child_by_field_name("body");
            break;
        }
        current = parent.parent();
    }

    let body = match func_body {
        Some(b) => b,
        None => return false,
    };

    // Search for if-statements that null-check this variable
    has_dominating_null_check(&body, var_name, deref_byte, source)
}

fn has_dominating_null_check(node: &Node, var_name: &str, deref_byte: usize, source: &str) -> bool {
    if node.kind() == "if_statement" {
        // Must be BEFORE the dereference
        if node.end_byte() <= deref_byte {
            if let Some(condition) = node.child_by_field_name("condition") {
                if let Some(checked_var) = get_null_check_var(&condition, source) {
                    if checked_var == var_name {
                        // Check that the condition checks FOR null (== NULL, !ptr)
                        if !analyze_condition_for_safety(&condition, var_name, source, false) {
                            return true;
                        }
                    }
                }
            }
        }
    }

    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            // Don't search past the dereference point
            if child.start_byte() > deref_byte {
                break;
            }
            if has_dominating_null_check(&child, var_name, deref_byte, source) {
                return true;
            }
        }
    }

    false
}

// ---------------------------------------------------------------------------
// rc<->out-parameter success correlation
// ---------------------------------------------------------------------------

/// True when `var_name` is dereferenced under a status-code success guard
/// (`rc == SQLITE_OK` / `rc == 0` / `!rc`) and was itself assigned only through
/// an out-parameter (`&var_name`) of a call whose status was stored in that same
/// guard variable. See the call site in `is_unsafe_at` for the full idiom.
fn is_guarded_by_rc_success(var_name: &str, node: &Node, source: &str) -> bool {
    let deref_byte = node.start_byte();

    // Walk ancestors to find a success guard that dominates the dereference,
    // capturing the status variable it tests.
    let mut current = node.parent();
    while let Some(parent) = current {
        if parent.kind() == "function_definition" {
            break;
        }

        let guard_var = match parent.kind() {
            // while/if/for condition guards the body: cond holds inside it.
            "if_statement" | "while_statement" | "do_statement" => parent
                .child_by_field_name("condition")
                .and_then(|c| rc_success_guard_var(&c, source)),
            // `rc == SQLITE_OK && <expr deref'ing var>`: the deref is in the
            // right operand, the guard is the (whole) left operand.
            "binary_expression" => {
                let op = parent
                    .child_by_field_name("operator")
                    .map(|o| ast_utils::get_node_text_owned(&o, source));
                if op.as_deref() == Some("&&") {
                    parent
                        .child_by_field_name("left")
                        .filter(|left| !node_is_within(left, node))
                        .and_then(|left| rc_success_guard_var(&left, source))
                } else {
                    None
                }
            }
            _ => None,
        };

        if let Some(rc) = guard_var {
            if var_assigned_via_rc_outparam(var_name, &rc, node, deref_byte, source) {
                return true;
            }
        }

        current = parent.parent();
    }

    false
}

/// If `cond` is (or contains, across `&&` conjuncts) a status-code success
/// test, return the status variable name. Recognises `X == SQLITE_OK`,
/// `SQLITE_OK == X`, `X == 0`, `0 == X`, and `!X`.
fn rc_success_guard_var(cond: &Node, source: &str) -> Option<String> {
    match cond.kind() {
        "parenthesized_expression" => cond
            .child(1)
            .and_then(|inner| rc_success_guard_var(&inner, source)),
        "binary_expression" => {
            let op = cond
                .child_by_field_name("operator")
                .map(|o| ast_utils::get_node_text_owned(&o, source))?;
            let left = cond.child_by_field_name("left")?;
            let right = cond.child_by_field_name("right")?;
            if op == "&&" {
                // Any conjunct may carry the success test.
                return rc_success_guard_var(&left, source)
                    .or_else(|| rc_success_guard_var(&right, source));
            }
            if op == "==" {
                return success_equality_var(&left, &right, source);
            }
            None
        }
        _ => None,
    }
}

/// For an `==` comparison, return the identifier operand when the other operand
/// is the unambiguous success constant `SQLITE_OK`.
///
/// Deliberately excludes bare `0` / `!x`: `rc == 0` means success for a *status
/// code*, but `p == 0` means *failure* for a pointer-returning call
/// (`p = f(&out); if (p==0) use(out);` uses `out` on the failure path — a real
/// bug, not a guarded use). `SQLITE_OK` only appears in status-code context, so
/// it carries the success polarity unambiguously.
fn success_equality_var(a: &Node, b: &Node, source: &str) -> Option<String> {
    let is_success_const = |n: &Node| {
        let t = ast_utils::get_node_text_owned(n, source);
        t == "SQLITE_OK"
    };
    if a.kind() == "identifier" && is_success_const(b) {
        return Some(ast_utils::get_node_text_owned(a, source));
    }
    if b.kind() == "identifier" && is_success_const(a) {
        return Some(ast_utils::get_node_text_owned(b, source));
    }
    None
}

/// True when, before `deref_byte` in the enclosing function, `var_name` is
/// taken by address (`&var_name`) inside a call expression whose result is
/// assigned (or initialised) into the status variable `rc`. Handles both
/// `rc = call(&var)` and `int rc = call(&var)`.
fn var_assigned_via_rc_outparam(
    var_name: &str,
    rc: &str,
    node: &Node,
    deref_byte: usize,
    source: &str,
) -> bool {
    // Find the enclosing function body.
    let mut current = node.parent();
    let mut func_body = None;
    while let Some(parent) = current {
        if parent.kind() == "function_definition" {
            func_body = parent.child_by_field_name("body");
            break;
        }
        current = parent.parent();
    }
    match func_body {
        Some(body) => find_rc_outparam_assignment(&body, var_name, rc, deref_byte, source),
        None => false,
    }
}

fn find_rc_outparam_assignment(
    node: &Node,
    var_name: &str,
    rc: &str,
    deref_byte: usize,
    source: &str,
) -> bool {
    // Out-parameter assignment must occur before the dereference.
    if node.start_byte() < deref_byte {
        // `rc = call(..., &var_name, ...)`
        if node.kind() == "assignment_expression" {
            if let (Some(left), Some(right)) = (
                node.child_by_field_name("left"),
                node.child_by_field_name("right"),
            ) {
                if left.kind() == "identifier"
                    && ast_utils::get_node_text_owned(&left, source) == rc
                    && call_takes_address_of(&right, var_name, source)
                {
                    return true;
                }
            }
        }
        // `int rc = call(..., &var_name, ...)`
        if node.kind() == "init_declarator" {
            if let (Some(decl), Some(value)) = (
                node.child_by_field_name("declarator"),
                node.child_by_field_name("value"),
            ) {
                if ast_utils::get_node_text_owned(&decl, source) == rc
                    && call_takes_address_of(&value, var_name, source)
                {
                    return true;
                }
            }
        }
    }

    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            if child.start_byte() >= deref_byte {
                break;
            }
            if find_rc_outparam_assignment(&child, var_name, rc, deref_byte, source) {
                return true;
            }
        }
    }
    false
}

/// True when `expr` is a call expression that passes `&var_name` as an argument.
fn call_takes_address_of(expr: &Node, var_name: &str, source: &str) -> bool {
    let call = match expr.kind() {
        "call_expression" => *expr,
        // Unwrap a cast like `(int)call(...)`.
        _ => {
            let mut found = None;
            for i in 0..expr.child_count() {
                if let Some(c) = expr.child(i) {
                    if c.kind() == "call_expression" {
                        found = Some(c);
                        break;
                    }
                }
            }
            match found {
                Some(c) => c,
                None => return false,
            }
        }
    };
    let args = match call.child_by_field_name("arguments") {
        Some(a) => a,
        None => return false,
    };
    let target = format!("&{}", var_name);
    for i in 0..args.child_count() {
        if let Some(arg) = args.child(i) {
            if arg.kind() == "pointer_expression" {
                // Normalise whitespace: `& p` and `&p` both match.
                let t: String = ast_utils::get_node_text_owned(&arg, source)
                    .split_whitespace()
                    .collect();
                if t == target {
                    return true;
                }
            }
        }
    }
    false
}

// ---------------------------------------------------------------------------
// Condition analysis helpers (used for expression-level guards)
// ---------------------------------------------------------------------------

fn get_null_check_var(condition: &Node, source: &str) -> Option<String> {
    match condition.kind() {
        "parenthesized_expression" => condition
            .child(1)
            .and_then(|c| get_null_check_var(&c, source)),
        "binary_expression" => {
            if let (Some(left), Some(right)) = (
                condition.child_by_field_name("left"),
                condition.child_by_field_name("right"),
            ) {
                let lt = ast_utils::get_node_text_owned(&left, source);
                let rt = ast_utils::get_node_text_owned(&right, source);
                if is_null_value(&rt) && left.kind() == "identifier" {
                    return Some(lt);
                }
                if is_null_value(&lt) && right.kind() == "identifier" {
                    return Some(rt);
                }
                if let Some(operator) = condition.child_by_field_name("operator") {
                    let op = ast_utils::get_node_text_owned(&operator, source);
                    if op == "||" || op == "&&" {
                        if let Some(var) = get_null_check_var(&left, source) {
                            return Some(var);
                        }
                        return get_null_check_var(&right, source);
                    }
                }
            }
            None
        }
        "unary_expression" => {
            if let Some(operand) = condition.child_by_field_name("argument") {
                if operand.kind() == "identifier" {
                    return Some(ast_utils::get_node_text_owned(&operand, source));
                }
            }
            None
        }
        "identifier" => Some(ast_utils::get_node_text_owned(condition, source)),
        _ => None,
    }
}

fn analyze_condition_for_safety(node: &Node, var_name: &str, source: &str, negated: bool) -> bool {
    match node.kind() {
        "parenthesized_expression" => {
            if let Some(child) = node.child(1) {
                return analyze_condition_for_safety(&child, var_name, source, negated);
            }
        }
        "unary_expression" => {
            if let Some(operator) = node.child(0) {
                if ast_utils::get_node_text_owned(&operator, source) == "!" {
                    if let Some(argument) = node.child_by_field_name("argument") {
                        return analyze_condition_for_safety(&argument, var_name, source, !negated);
                    }
                }
            }
        }
        "binary_expression" => {
            if let Some(operator) = node.child_by_field_name("operator") {
                let op = ast_utils::get_node_text_owned(&operator, source);
                match op.as_str() {
                    "==" if is_null_comparison(node, var_name, source) => {
                        return negated;
                    }
                    "!=" if is_null_comparison(node, var_name, source) => {
                        return !negated;
                    }
                    "&&" => {
                        if let (Some(left), Some(right)) = (
                            node.child_by_field_name("left"),
                            node.child_by_field_name("right"),
                        ) {
                            let l = analyze_condition_for_safety(&left, var_name, source, negated);
                            let r = analyze_condition_for_safety(&right, var_name, source, negated);
                            return l || r;
                        }
                    }
                    "||" => {
                        if let (Some(left), Some(right)) = (
                            node.child_by_field_name("left"),
                            node.child_by_field_name("right"),
                        ) {
                            let l = analyze_condition_for_safety(&left, var_name, source, negated);
                            let r = analyze_condition_for_safety(&right, var_name, source, negated);
                            return l && r;
                        }
                    }
                    _ => {}
                }
            }
        }
        "identifier" => {
            let text = ast_utils::get_node_text_owned(node, source);
            if text == var_name {
                return !negated;
            }
        }
        _ => {}
    }
    false
}

fn is_null_comparison(binary_expr: &Node, var_name: &str, source: &str) -> bool {
    if let (Some(left), Some(right)) = (
        binary_expr.child_by_field_name("left"),
        binary_expr.child_by_field_name("right"),
    ) {
        let lt = ast_utils::get_node_text_owned(&left, source);
        let rt = ast_utils::get_node_text_owned(&right, source);
        (lt == var_name && is_null_value(&rt)) || (rt == var_name && is_null_value(&lt))
    } else {
        false
    }
}

fn node_is_within(parent_node: &Node, child_node: &Node) -> bool {
    parent_node.start_byte() <= child_node.start_byte()
        && parent_node.end_byte() >= child_node.end_byte()
}

// ---------------------------------------------------------------------------
// Caller-contract / precondition-assert suppression (task 207, EXP34 bucket 2)
// ---------------------------------------------------------------------------

/// True when a dominating `assert(...)` (or `ALWAYS(...)`) establishes `var_name`
/// non-null before the dereference, and `var_name` is not reassigned in between.
/// Models the sqlite documented-invariant idiom — see the call site in
/// `is_unsafe_at`.
fn is_guarded_by_precondition_assert(var_name: &str, deref_node: &Node, source: &str) -> bool {
    let base = base_identifier(var_name);
    if base.is_empty() {
        return false;
    }
    let deref_byte = deref_node.start_byte();

    // Find the enclosing function body (for the reassignment check).
    let mut current = deref_node.parent();
    let mut func_body = None;
    while let Some(parent) = current {
        if parent.kind() == "function_definition" {
            func_body = parent.child_by_field_name("body");
            break;
        }
        current = parent.parent();
    }
    let func_body = match func_body {
        Some(b) => b,
        None => return false,
    };

    // Walk the block nesting from the dereference up to the function body. At each
    // enclosing compound statement, scan the statements that lexically precede our
    // path for an `assert`/`ALWAYS` that establishes `base` non-null. Straight-line
    // statements before the dereference in an ancestor block dominate it.
    let mut child = *deref_node;
    let mut current = deref_node.parent();
    while let Some(parent) = current {
        if parent.kind() == "compound_statement" {
            let mut cursor = parent.walk();
            for stmt in parent.children(&mut cursor) {
                if stmt.start_byte() >= child.start_byte() {
                    break;
                }
                if let Some(cond) = assert_condition(&stmt, source) {
                    if assert_establishes_nonnull(&cond, base, source)
                        && !reassigned_between(
                            &func_body,
                            base,
                            stmt.end_byte(),
                            deref_byte,
                            source,
                        )
                    {
                        return true;
                    }
                }
            }
        }
        if parent.kind() == "function_definition" {
            break;
        }
        child = parent;
        current = parent.parent();
    }
    false
}

/// True when `base` is assigned (`base = ...` or `Type *base = ...`) at a byte
/// position in `(after, before)`. A reassignment between the precondition assert
/// and the dereference invalidates the assert's non-null guarantee.
fn reassigned_between(node: &Node, base: &str, after: usize, before: usize, source: &str) -> bool {
    let pos = node.start_byte();
    if pos >= before {
        return false; // subtree is entirely past the dereference
    }
    if pos > after {
        match node.kind() {
            "assignment_expression" => {
                if let Some(left) = node.child_by_field_name("left") {
                    if left.kind() == "identifier"
                        && ast_utils::get_node_text_owned(&left, source) == base
                    {
                        return true;
                    }
                }
            }
            "init_declarator" => {
                if let Some(decl) = node.child_by_field_name("declarator") {
                    if decl.kind() == "identifier"
                        && ast_utils::get_node_text_owned(&decl, source) == base
                    {
                        return true;
                    }
                }
            }
            _ => {}
        }
    }
    for i in 0..node.child_count() {
        if let Some(c) = node.child(i) {
            if reassigned_between(&c, base, after, before, source) {
                return true;
            }
        }
    }
    false
}

/// Leading C identifier of an expression text (`p->x` → `p`, `p[i]` → `p`).
fn base_identifier(text: &str) -> &str {
    let bytes = text.as_bytes();
    let mut end = 0;
    while end < bytes.len() {
        let c = bytes[end];
        if c == b'_' || c.is_ascii_alphanumeric() {
            end += 1;
        } else {
            break;
        }
    }
    &text[..end]
}

/// If `stmt` is an expression statement whose expression is an `assert(...)` or
/// `ALWAYS(...)` call, return the (single) condition argument node.
fn assert_condition<'a>(stmt: &Node<'a>, source: &str) -> Option<Node<'a>> {
    let expr = if stmt.kind() == "expression_statement" {
        stmt.child(0)?
    } else {
        return None;
    };
    if expr.kind() != "call_expression" {
        return None;
    }
    let func = expr.child_by_field_name("function")?;
    let name = ast_utils::get_node_text_owned(&func, source);
    if name != "assert" && name != "ALWAYS" {
        return None;
    }
    let args = expr.child_by_field_name("arguments")?;
    for i in 0..args.child_count() {
        let arg = args.child(i)?;
        if !matches!(arg.kind(), "(" | ")" | ",") {
            return Some(arg);
        }
    }
    None
}

/// True when an assert condition guarantees `base` is non-null when it holds:
/// either an explicit truthiness/`!= NULL` test, or an *unconditional*
/// dereference of `base` (no `||` / ternary that could short-circuit it).
fn assert_establishes_nonnull(cond: &Node, base: &str, source: &str) -> bool {
    if analyze_condition_for_safety(cond, base, source, false) {
        return true;
    }
    let text = ast_utils::get_node_text_owned(cond, source);
    if text.contains("||") || text.contains('?') {
        return false;
    }
    cond_dereferences_var(cond, base, source)
}

/// True when `base` is dereferenced (`base->`, `base[i]`, `*base`) anywhere in
/// the expression subtree.
fn cond_dereferences_var(node: &Node, base: &str, source: &str) -> bool {
    let matches_base = |n: &Node| {
        n.kind() == "identifier" && { ast_utils::get_node_text_owned(n, source) == base }
    };
    query::find_first_descendant(*node, |n| match n.kind() {
        "field_expression" => n
            .child_by_field_name("argument")
            .map(|arg| matches_base(&arg))
            .unwrap_or(false),
        "subscript_expression" => n.child(0).map(|arr| matches_base(&arr)).unwrap_or(false),
        "pointer_expression" => {
            let is_deref = n
                .child_by_field_name("operator")
                .map(|op| ast_utils::get_node_text_owned(&op, source) == "*")
                .unwrap_or(false);
            is_deref
                && n.child_by_field_name("argument")
                    .map(|arg| matches_base(&arg))
                    .unwrap_or(false)
        }
        _ => false,
    })
    .is_some()
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

fn is_null_value(text: &str) -> bool {
    null_state::is_null_value(text)
}

/// Merge prescan cross-file global null states into the file-scope state map
/// for any `extern` pointer declarations found in this translation unit.
///
/// Scans top-level declarations for `extern TYPE *name;` and, if the variable
/// is still Unknown in `file_globals`, inserts the prescan-derived state.
fn merge_extern_global_states(
    root: &Node,
    source: &str,
    prescan_states: &HashMap<String, NullState>,
    file_globals: &mut StateMap,
) {
    merge_extern_in_node(root, source, prescan_states, file_globals);

    fn merge_extern_in_node(
        node: &Node,
        source: &str,
        prescan_states: &HashMap<String, NullState>,
        file_globals: &mut StateMap,
    ) {
        for i in 0..node.child_count() {
            let child = match node.child(i) {
                Some(c) => c,
                None => continue,
            };
            match child.kind() {
                "declaration" => {
                    let mut has_extern = false;
                    for j in 0..child.child_count() {
                        if let Some(tc) = child.child(j) {
                            if tc.kind() == "storage_class_specifier" {
                                if tc.utf8_text(source.as_bytes()).unwrap_or("") == "extern" {
                                    has_extern = true;
                                }
                            }
                        }
                    }
                    if !has_extern {
                        continue;
                    }
                    // Find pointer declarators in this extern declaration
                    for j in 0..child.child_count() {
                        if let Some(decl) = child.child(j) {
                            let name = match decl.kind() {
                                "pointer_declarator" => extract_id_from_decl(&decl, source),
                                "init_declarator" => {
                                    // Check child for pointer_declarator
                                    if has_pointer_child(&decl) {
                                        extract_id_from_decl(&decl, source)
                                    } else {
                                        continue;
                                    }
                                }
                                _ => continue,
                            };
                            if name.is_empty() {
                                continue;
                            }
                            // Only inject if not already resolved by file-scope analysis
                            let current = file_globals
                                .get(&name)
                                .copied()
                                .unwrap_or(NullState::Unknown);
                            if current == NullState::Unknown {
                                if let Some(&prescan_state) = prescan_states.get(&name) {
                                    file_globals.insert(name, prescan_state);
                                }
                            }
                        }
                    }
                }
                k if k.starts_with("preproc_") => {
                    merge_extern_in_node(&child, source, prescan_states, file_globals);
                }
                _ => {}
            }
        }
    }

    fn extract_id_from_decl(node: &Node, source: &str) -> String {
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                match child.kind() {
                    "identifier" => {
                        return child.utf8_text(source.as_bytes()).unwrap_or("").to_string();
                    }
                    "pointer_declarator" | "init_declarator" => {
                        let result = extract_id_from_decl(&child, source);
                        if !result.is_empty() {
                            return result;
                        }
                    }
                    _ => {}
                }
            }
        }
        String::new()
    }

    fn has_pointer_child(node: &Node) -> bool {
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "pointer_declarator" {
                    return true;
                }
            }
        }
        false
    }
}

/// Extract the function name from a declarator node (handles pointer_declarator wrapping).
fn extract_function_name(declarator: &Node, source: &str) -> Option<String> {
    match declarator.kind() {
        "identifier" => {
            let name = ast_utils::get_node_text_owned(declarator, source);
            if name.is_empty() {
                None
            } else {
                Some(name)
            }
        }
        "function_declarator" | "pointer_declarator" => declarator
            .child_by_field_name("declarator")
            .and_then(|d| extract_function_name(&d, source)),
        _ => {
            for i in 0..declarator.child_count() {
                if let Some(child) = declarator.child(i) {
                    if child.kind() == "identifier" {
                        let name = ast_utils::get_node_text_owned(&child, source);
                        if !name.is_empty() {
                            return Some(name);
                        }
                    }
                }
            }
            None
        }
    }
}

fn is_deref_function(func_name: &str) -> bool {
    matches!(
        func_name,
        "strlen"
            | "strcpy"
            | "strcat"
            | "strcmp"
            | "strchr"
            | "strstr"
            | "sprintf"
            | "fprintf"
            | "printf"
            | "scanf"
            | "fscanf"
            | "fread"
            | "fwrite"
            | "fgets"
            | "fputs"
            | "fputc"
            | "fgetc"
            | "memcpy"
            | "memmove"
            | "memset"
            | "memcmp"
            | "free"
            | "fclose"
    )
}