sqc 0.4.13

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
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
//! Null-state forward dataflow analysis using the CFG.
//!
//! Computes the null/non-null state of pointer variables at every point in a
//! function. Used by EXP34-C to detect null pointer dereferences with proper
//! flow sensitivity through branches, loops, and early returns.

use super::cfg::{BasicBlock, BlockId, CfgEdge, FunctionCfg};
use super::dataflow::find_node_at_range;
use crate::analyze::function_summary::FunctionSummary;
use std::collections::{HashMap, HashSet, VecDeque};
use tree_sitter::Node;

// ---------------------------------------------------------------------------
// Null lattice
// ---------------------------------------------------------------------------

/// Null state for a single pointer variable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum NullState {
    /// No information (bottom of lattice).
    Unknown,
    /// Definitely assigned NULL / 0 / nullptr.
    DefinitelyNull,
    /// May or may not be null (merged paths, malloc return, etc.).
    PossiblyNull,
    /// Known non-null (checked, assigned &var, assigned non-null literal, etc.).
    NotNull,
}

impl NullState {
    /// Lattice join: merge two states from converging paths.
    pub fn join(self, other: NullState) -> NullState {
        use NullState::*;
        if self == other {
            return self;
        }
        match (self, other) {
            (Unknown, x) | (x, Unknown) => x,
            _ => PossiblyNull,
        }
    }

    /// Returns true if dereference at this state is potentially unsafe.
    pub fn is_unsafe(self) -> bool {
        matches!(self, NullState::DefinitelyNull | NullState::PossiblyNull)
    }
}

/// State map: variable name -> NullState.
pub type StateMap = HashMap<String, NullState>;

/// Join two state maps (union of keys, lattice join per key).
fn join_states(a: &StateMap, b: &StateMap) -> StateMap {
    let mut result = a.clone();
    for (var, &state_b) in b {
        let entry = result.entry(var.clone()).or_insert(NullState::Unknown);
        *entry = entry.join(state_b);
    }
    result
}

// ---------------------------------------------------------------------------
// Analysis result
// ---------------------------------------------------------------------------

/// Result of null-state analysis for one function.
pub struct NullAnalysisResult {
    /// Entry state for each block (after joining predecessors + edge refinement).
    pub block_entry_states: HashMap<BlockId, StateMap>,
    /// Exit state for each block (after simulating block statements).
    #[allow(dead_code)]
    pub block_exit_states: HashMap<BlockId, StateMap>,
    /// Set of variables declared as pointer types.
    pub declared_pointers: HashSet<String>,
}

// ---------------------------------------------------------------------------
// Edge refinement (condition parsing)
// ---------------------------------------------------------------------------

/// Information extracted from a condition for edge refinement.
struct ConditionInfo {
    /// Variable being checked.
    var_name: String,
    /// State on the true-branch edge.
    true_state: NullState,
    /// State on the false-branch edge.
    false_state: NullState,
}

/// Parse a condition AST node and collect ALL null-check conditions.
/// For compound `||` conditions like `ptr == NULL || q == NULL`, returns info
/// for every null-checked variable (not just the first one).
fn parse_all_null_conditions(node: &Node, source: &str) -> Vec<ConditionInfo> {
    match node.kind() {
        "parenthesized_expression" => {
            // Unwrap parens: child(0)='(', child(1)=expr, child(2)=')'
            node.child(1)
                .map(|inner| parse_all_null_conditions(&inner, source))
                .unwrap_or_default()
        }
        "binary_expression" => {
            let Some(left) = node.child_by_field_name("left") else {
                return Vec::new();
            };
            let Some(operator) = node.child_by_field_name("operator") else {
                return Vec::new();
            };
            let Some(right) = node.child_by_field_name("right") else {
                return Vec::new();
            };
            let op = get_text(&operator, source);

            match op.as_str() {
                "==" => {
                    // ptr == NULL  => true: DefinitelyNull, false: NotNull
                    // NULL == ptr  => same
                    if let Some(var) = extract_null_check_var(&left, &right, source) {
                        return vec![ConditionInfo {
                            var_name: var,
                            true_state: NullState::DefinitelyNull,
                            false_state: NullState::NotNull,
                        }];
                    }
                    Vec::new()
                }
                "!=" => {
                    // ptr != NULL  => true: NotNull, false: DefinitelyNull
                    if let Some(var) = extract_null_check_var(&left, &right, source) {
                        return vec![ConditionInfo {
                            var_name: var,
                            true_state: NullState::NotNull,
                            false_state: NullState::DefinitelyNull,
                        }];
                    }
                    Vec::new()
                }
                "||" => {
                    // Collect all null checks from both sides.
                    // On the FALSE branch, ALL conditions are false → all vars NotNull.
                    // On the TRUE branch, at least one is true → conservative (don't refine).
                    let mut all = parse_all_null_conditions(&left, source);
                    all.extend(parse_all_null_conditions(&right, source));
                    all
                }
                "&&" => {
                    // Collect all null checks from both sides.
                    // On the TRUE branch, ALL conditions are true → all vars have true_state.
                    let mut all = parse_all_null_conditions(&left, source);
                    all.extend(parse_all_null_conditions(&right, source));
                    all
                }
                _ => Vec::new(),
            }
        }
        "unary_expression" => {
            // !ptr => true: DefinitelyNull, false: NotNull
            let Some(operator) = node.child(0) else {
                return Vec::new();
            };
            if get_text(&operator, source) == "!" {
                let Some(arg) = node.child_by_field_name("argument") else {
                    return Vec::new();
                };
                if arg.kind() == "identifier" {
                    return vec![ConditionInfo {
                        var_name: get_text(&arg, source),
                        true_state: NullState::DefinitelyNull,
                        false_state: NullState::NotNull,
                    }];
                }
            }
            Vec::new()
        }
        "identifier" => {
            // if (ptr) => true: NotNull, false: DefinitelyNull
            vec![ConditionInfo {
                var_name: get_text(node, source),
                true_state: NullState::NotNull,
                false_state: NullState::DefinitelyNull,
            }]
        }
        _ => Vec::new(),
    }
}

/// Given left and right operands of == or !=, extract the variable name
/// if one side is NULL and the other is an identifier.
fn extract_null_check_var(left: &Node, right: &Node, source: &str) -> Option<String> {
    let lt = get_text(left, source);
    let rt = get_text(right, source);
    if is_null_value(&rt) && left.kind() == "identifier" {
        Some(lt)
    } else if is_null_value(&lt) && right.kind() == "identifier" {
        Some(rt)
    } else {
        None
    }
}

// ---------------------------------------------------------------------------
// Transfer function (per-block simulation)
// ---------------------------------------------------------------------------

/// Simulate a single block's statements on the given entry state,
/// returning the exit state.
fn apply_transfer(
    block: &BasicBlock,
    entry: &StateMap,
    body_node: &Node,
    source: &str,
    declared_pointers: &mut HashSet<String>,
    summaries: &HashMap<String, FunctionSummary>,
) -> StateMap {
    let mut state = entry.clone();
    for &(start, end) in &block.statements {
        if let Some(stmt_node) = find_node_at_range(body_node, start, end) {
            process_statement_for_null_state(
                &stmt_node,
                source,
                &mut state,
                declared_pointers,
                summaries,
            );
        }
    }
    state
}

/// Process a single statement/expression, updating null state.
fn process_statement_for_null_state(
    node: &Node,
    source: &str,
    state: &mut StateMap,
    declared_pointers: &mut HashSet<String>,
    summaries: &HashMap<String, FunctionSummary>,
) {
    match node.kind() {
        "declaration" => {
            process_declaration_null(node, source, state, declared_pointers, summaries);
        }
        "expression_statement" => {
            // Handle assert(var) before other expression processing
            process_assert_for_null_state(node, source, state);
            if let Some(expr) = node.child(0) {
                process_expression_null(&expr, source, state, declared_pointers, summaries);
            }
        }
        "assignment_expression" => {
            process_expression_null(node, source, state, declared_pointers, summaries);
        }
        // Switch statements are opaque in the CFG — walk the body to find
        // declarations and assignments inside case/default blocks.
        "switch_statement" => {
            if let Some(body) = node.child_by_field_name("body") {
                walk_switch_body_for_null_state(&body, source, state, declared_pointers, summaries);
            }
        }
        // Condition expressions (parenthesized_expression at top level of if/while)
        // are added as statements in the condition block. We don't mutate null state
        // from conditions — that's handled by edge refinement.
        _ => {
            // Recognize assert(var) / assert(var != NULL) as making var NotNull
            process_assert_for_null_state(node, source, state);
            // Recurse into compound expressions to find nested assignments
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "assignment_expression" {
                        process_expression_null(
                            &child,
                            source,
                            state,
                            declared_pointers,
                            summaries,
                        );
                    }
                }
            }
        }
    }
}

/// Recursively walk the body of a switch_statement (compound_statement containing
/// case_statement / default nodes) and process all declarations and assignments
/// for null-state tracking.  The switch is opaque in the CFG, so we process
/// all reachable statements sequentially as an approximation.
fn walk_switch_body_for_null_state(
    node: &Node,
    source: &str,
    state: &mut StateMap,
    declared_pointers: &mut HashSet<String>,
    summaries: &HashMap<String, FunctionSummary>,
) {
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            match child.kind() {
                "case_statement" | "compound_statement" => {
                    // Recurse into case/default bodies and compound blocks
                    walk_switch_body_for_null_state(
                        &child,
                        source,
                        state,
                        declared_pointers,
                        summaries,
                    );
                }
                "declaration" | "expression_statement" | "assignment_expression" => {
                    process_statement_for_null_state(
                        &child,
                        source,
                        state,
                        declared_pointers,
                        summaries,
                    );
                }
                _ => {}
            }
        }
    }
}

fn process_declaration_null(
    node: &Node,
    source: &str,
    state: &mut StateMap,
    declared_pointers: &mut HashSet<String>,
    summaries: &HashMap<String, FunctionSummary>,
) {
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            if child.kind() == "init_declarator" {
                if let Some(declarator) = child.child_by_field_name("declarator") {
                    let var_name = get_identifier_from_declarator(&declarator, source);
                    if var_name.is_empty() {
                        continue;
                    }
                    let is_ptr = is_pointer_declarator(&declarator) && !contains_array(&declarator);

                    if is_ptr {
                        declared_pointers.insert(var_name.clone());
                    }

                    if let Some(value) = child.child_by_field_name("value") {
                        if is_ptr {
                            let rval = classify_rvalue_null(&value, source, summaries);
                            // Propagate from another variable: Node *current = head;
                            if rval == NullState::NotNull && value.kind() == "identifier" {
                                let src_name = get_text(&value, source);
                                if let Some(&src_state) = state.get(&src_name) {
                                    state.insert(var_name, src_state);
                                    continue;
                                }
                            }
                            // Propagate from field access: ptr = other->next
                            if rval == NullState::NotNull && value.kind() == "field_expression" {
                                if let Some(arg) = value.child_by_field_name("argument") {
                                    let base = get_text(&arg, source);
                                    // Check dotted key first (struct field null propagation)
                                    if let Some(field_node) = value.child_by_field_name("field") {
                                        let field_name = get_text(&field_node, source);
                                        let dotted = format!("{}.{}", base, field_name);
                                        if let Some(&field_state) = state.get(&dotted) {
                                            state.insert(var_name, field_state);
                                            continue;
                                        }
                                    }
                                    if let Some(&base_state) = state.get(&base) {
                                        if base_state.is_unsafe() {
                                            state.insert(var_name, NullState::PossiblyNull);
                                            continue;
                                        }
                                    }
                                }
                            }
                            // Propagate from array subscript: data = arr[idx]
                            // Variant 66: array element null propagation (uses "arr.idx" dotted key)
                            if rval == NullState::NotNull && value.kind() == "subscript_expression"
                            {
                                if let (Some(arg), Some(idx)) = (
                                    value.child_by_field_name("argument"),
                                    value.child_by_field_name("index"),
                                ) {
                                    let base = get_text(&arg, source);
                                    let index = get_text(&idx, source);
                                    let dotted = format!("{}.{}", base, index);
                                    if let Some(&elem_state) = state.get(&dotted) {
                                        state.insert(var_name, elem_state);
                                        continue;
                                    }
                                }
                            }
                            // Propagate from pointer dereference: data = *dataPtr
                            // or data = (*dataPtr) (parenthesized form in variant 64)
                            // Variant 63/64: pointer-to-pointer null propagation
                            if rval == NullState::NotNull {
                                if let Some(deref_state) =
                                    extract_deref_pointee_state(&value, source, state)
                                {
                                    state.insert(var_name, deref_state);
                                    continue;
                                }
                            }
                            // Propagate pointee state through cast: dataPtr = (T*)voidPtr
                            // Variant 64: void pointer cast preserves pointee null state
                            if value.kind() == "cast_expression" {
                                if let Some(inner) = value.child_by_field_name("value") {
                                    let inner = unwrap_parens(&inner);
                                    if inner.kind() == "identifier" {
                                        let inner_name = get_text(&inner, source);
                                        let src_key = format!("*{}", inner_name);
                                        if let Some(&s) = state.get(&src_key) {
                                            let dst_key = format!("*{}", var_name);
                                            state.insert(dst_key, s);
                                        }
                                    }
                                }
                            }
                            state.insert(var_name, rval);
                        }
                    } else if is_ptr {
                        // Uninitialized pointer
                        state.insert(var_name, NullState::PossiblyNull);
                    }
                }
            } else if child.kind() == "pointer_declarator" || child.kind() == "identifier" {
                // Bare uninitialized pointer: "int *ptr;"
                let var_name = get_identifier_from_declarator(&child, source);
                if !var_name.is_empty() && is_pointer_declarator(&child) && !contains_array(&child)
                {
                    declared_pointers.insert(var_name.clone());
                    state.insert(var_name, NullState::PossiblyNull);
                }
            }
        }
    }
}

fn process_expression_null(
    node: &Node,
    source: &str,
    state: &mut StateMap,
    declared_pointers: &HashSet<String>,
    summaries: &HashMap<String, FunctionSummary>,
) {
    if node.kind() == "assignment_expression" {
        if let (Some(left), Some(right)) = (
            node.child_by_field_name("left"),
            node.child_by_field_name("right"),
        ) {
            let left_name = get_text(&left, source);
            let left_is_ptr = left.kind() != "identifier" || declared_pointers.contains(&left_name);

            if !left_is_ptr {
                return;
            }

            let new_state = classify_rvalue_null(&right, source, summaries);
            // Propagation from another variable
            if new_state == NullState::NotNull && right.kind() == "identifier" {
                let right_name = get_text(&right, source);
                if let Some(&rhs_state) = state.get(&right_name) {
                    state.insert(left_name, rhs_state);
                    return;
                }
            }
            if new_state == NullState::NotNull && right.kind() == "field_expression" {
                // ptr = other->next: propagate other's state
                if let Some(arg) = right.child_by_field_name("argument") {
                    let base = get_text(&arg, source);
                    // Check dotted key first (struct field null propagation)
                    if let Some(field_node) = right.child_by_field_name("field") {
                        let field_name = get_text(&field_node, source);
                        let dotted = format!("{}.{}", base, field_name);
                        if let Some(&field_state) = state.get(&dotted) {
                            state.insert(left_name, field_state);
                            return;
                        }
                    }
                    if let Some(&base_state) = state.get(&base) {
                        if base_state.is_unsafe() {
                            state.insert(left_name, NullState::PossiblyNull);
                            return;
                        }
                    }
                }
            }
            // Propagate from array subscript: data = arr[idx] (variant 66)
            if new_state == NullState::NotNull && right.kind() == "subscript_expression" {
                if let (Some(arg), Some(idx)) = (
                    right.child_by_field_name("argument"),
                    right.child_by_field_name("index"),
                ) {
                    let base = get_text(&arg, source);
                    let index = get_text(&idx, source);
                    let dotted = format!("{}.{}", base, index);
                    if let Some(&elem_state) = state.get(&dotted) {
                        state.insert(left_name, elem_state);
                        return;
                    }
                }
            }
            // Propagate from pointer dereference: data = *dataPtr or (*dataPtr)
            // Variant 63/64: pointer-to-pointer null propagation
            if new_state == NullState::NotNull {
                if let Some(deref_state) = extract_deref_pointee_state(&right, source, state) {
                    state.insert(left_name, deref_state);
                    return;
                }
            }
            // Propagate pointee state through cast: dataPtr = (T*)voidPtr (variant 64)
            if right.kind() == "cast_expression" {
                if let Some(inner) = right.child_by_field_name("value") {
                    let inner = unwrap_parens(&inner);
                    if inner.kind() == "identifier" {
                        let inner_name = get_text(&inner, source);
                        let src_key = format!("*{}", inner_name);
                        if let Some(&s) = state.get(&src_key) {
                            let dst_key = format!("*{}", left_name);
                            state.insert(dst_key, s);
                        }
                    }
                }
            }
            // Non-nullable function call clears null taint
            if right.kind() == "call_expression" && new_state == NullState::NotNull {
                state.insert(left_name, NullState::NotNull);
                return;
            }
            state.insert(left_name, new_state);
        }
    }
}

/// Recognize assert(var) or assert(var != NULL) and set var to NotNull.
fn process_assert_for_null_state(node: &Node, source: &str, state: &mut StateMap) {
    // Look for expression_statement -> call_expression -> assert
    let call_node = if node.kind() == "expression_statement" {
        node.child(0)
    } else if node.kind() == "call_expression" {
        Some(*node)
    } else {
        None
    };

    if let Some(call) = call_node {
        if call.kind() != "call_expression" {
            return;
        }
        if let Some(function) = call.child_by_field_name("function") {
            let func_name = get_text(&function, source);
            if func_name != "assert" {
                return;
            }
            if let Some(args) = call.child_by_field_name("arguments") {
                for i in 0..args.child_count() {
                    if let Some(arg) = args.child(i) {
                        if arg.kind() == "(" || arg.kind() == ")" || arg.kind() == "," {
                            continue;
                        }
                        // assert(var) — var is non-null after this
                        if arg.kind() == "identifier" {
                            let name = get_text(&arg, source);
                            state.insert(name, NullState::NotNull);
                            return;
                        }
                        // assert(var != NULL) or assert(NULL != var)
                        if arg.kind() == "binary_expression" {
                            if let (Some(left), Some(right)) = (
                                arg.child_by_field_name("left"),
                                arg.child_by_field_name("right"),
                            ) {
                                let lt = get_text(&left, source);
                                let rt = get_text(&right, source);
                                if is_null_value(rt.trim()) && left.kind() == "identifier" {
                                    state.insert(lt, NullState::NotNull);
                                } else if is_null_value(lt.trim()) && right.kind() == "identifier" {
                                    state.insert(rt, NullState::NotNull);
                                }
                            }
                            return;
                        }
                    }
                }
            }
        }
    }
}

/// Unwrap parenthesized_expression nodes to get the inner expression.
fn unwrap_parens<'a>(node: &'a Node<'a>) -> Node<'a> {
    let mut n = *node;
    while n.kind() == "parenthesized_expression" {
        if let Some(inner) = n.child(1) {
            n = inner;
        } else {
            break;
        }
    }
    n
}

/// Extract pointee null state from a dereference expression (*ptr or (*ptr)).
/// Returns Some(state) if the dereference target has a "*name" key in state.
fn extract_deref_pointee_state(node: &Node, source: &str, state: &StateMap) -> Option<NullState> {
    let inner = unwrap_parens(node);
    if inner.kind() == "pointer_expression" {
        if let Some(op) = inner.child_by_field_name("operator") {
            if get_text(&op, source) == "*" {
                if let Some(arg) = inner.child_by_field_name("argument") {
                    let arg_name = get_text(&arg, source);
                    let deref_key = format!("*{}", arg_name);
                    if let Some(&deref_state) = state.get(&deref_key) {
                        return Some(deref_state);
                    }
                }
            }
        }
    }
    None
}

/// Classify the null state resulting from an rvalue expression.
fn classify_rvalue_null(
    node: &Node,
    source: &str,
    summaries: &HashMap<String, FunctionSummary>,
) -> NullState {
    let text = get_text(node, source);
    let trimmed = text.trim();

    // NULL/0/nullptr
    if is_null_value(trimmed) {
        return NullState::DefinitelyNull;
    }

    // Cast to NULL: (type*)NULL
    if node.kind() == "cast_expression" {
        if let Some(value) = node.child_by_field_name("value") {
            let vt = get_text(&value, source);
            if is_null_value(vt.trim()) {
                return NullState::DefinitelyNull;
            }
        }
    }

    // Nullable function call
    if node.kind() == "call_expression" {
        if let Some(function) = node.child_by_field_name("function") {
            let func_name = get_text(&function, source);
            if is_nullable_function(&func_name, summaries) {
                return NullState::PossiblyNull;
            }
        }
    }

    // Cast wrapping a nullable call
    if node.kind() == "cast_expression" {
        if let Some(value) = node.child_by_field_name("value") {
            if value.kind() == "call_expression" {
                if let Some(function) = value.child_by_field_name("function") {
                    let func_name = get_text(&function, source);
                    if is_nullable_function(&func_name, summaries) {
                        return NullState::PossiblyNull;
                    }
                }
            }
        }
    }

    // Address-of is always non-null
    if node.kind() == "pointer_expression" {
        if let Some(op) = node.child_by_field_name("operator") {
            if get_text(&op, source) == "&" {
                return NullState::NotNull;
            }
        }
    }

    // String literal is always non-null
    if node.kind() == "string_literal" {
        return NullState::NotNull;
    }

    NullState::NotNull
}

// ---------------------------------------------------------------------------
// File-scope global null-state pre-pass
// ---------------------------------------------------------------------------

/// Collect null states for file-scope (static or global) pointer variables.
///
/// Scans all file-scope pointer variable declarations, then walks all function
/// bodies to find assignments to those variables. Returns a map from variable
/// name to its joined null state across all assignment sites.
///
/// Used by EXP34-C to detect patterns like Juliet variant 45:
/// ```c
/// static char *globalData;
/// void bad() { globalData = NULL; badSink(); }
/// void badSink() { char *data = globalData; data[0]; }
/// ```
pub fn collect_file_scope_null_states(
    root: &Node,
    source: &str,
    summaries: &HashMap<String, FunctionSummary>,
) -> StateMap {
    let mut global_vars: HashSet<String> = HashSet::new();
    let mut result: StateMap = StateMap::new();

    // Pass 1: Identify file-scope pointer variable declarations.
    // Walk top-level nodes (and preproc blocks) for declarations.
    collect_file_scope_pointer_decls(root, source, &mut global_vars, &mut result, summaries);

    if global_vars.is_empty() {
        return result;
    }

    // Pass 2: Walk all function bodies for assignments to these globals.
    collect_global_assignments(root, source, &global_vars, &mut result, summaries);

    result
}

/// Identify file-scope pointer declarations and their initializer states.
fn collect_file_scope_pointer_decls(
    node: &Node,
    source: &str,
    global_vars: &mut HashSet<String>,
    result: &mut StateMap,
    summaries: &HashMap<String, FunctionSummary>,
) {
    for i in 0..node.child_count() {
        let child = match node.child(i) {
            Some(c) => c,
            None => continue,
        };

        match child.kind() {
            "declaration" => {
                // Check if any declarator is a pointer type
                for j in 0..child.child_count() {
                    if let Some(declarator) = child.child(j) {
                        if declarator.kind() == "init_declarator" {
                            if let Some(decl) = declarator.child_by_field_name("declarator") {
                                if is_pointer_declarator(&decl) && !contains_array(&decl) {
                                    let name = get_identifier_from_declarator(&decl, source);
                                    if !name.is_empty() {
                                        global_vars.insert(name.clone());

                                        // Classify the initializer if present
                                        if let Some(value) = declarator.child_by_field_name("value")
                                        {
                                            let state =
                                                classify_rvalue_null(&value, source, summaries);
                                            result.insert(name, state);
                                        }
                                        // No initializer: C default for file-scope is zero/NULL
                                        // but we'll be conservative and leave as Unknown to
                                        // let assignments determine the state
                                    }
                                }
                            }
                        } else if is_pointer_declarator(&declarator) && !contains_array(&declarator)
                        {
                            // Direct declarator without init (e.g., `static char *p;`)
                            let name = get_identifier_from_declarator(&declarator, source);
                            if !name.is_empty()
                                && declarator.kind() != "storage_class_specifier"
                                && declarator.kind() != "type_qualifier"
                                && declarator.kind() != "primitive_type"
                                && declarator.kind() != "type_identifier"
                            {
                                global_vars.insert(name);
                                // File-scope without initializer: technically zero-initialized
                                // but leave as Unknown to let assignments drive the state
                            }
                        }
                    }
                }
            }
            // Recurse into preprocessor blocks to find declarations
            k if k.starts_with("preproc_") => {
                collect_file_scope_pointer_decls(&child, source, global_vars, result, summaries);
            }
            _ => {}
        }
    }
}

/// Walk all function bodies looking for assignments to file-scope globals.
fn collect_global_assignments(
    node: &Node,
    source: &str,
    global_vars: &HashSet<String>,
    result: &mut StateMap,
    summaries: &HashMap<String, FunctionSummary>,
) {
    for i in 0..node.child_count() {
        let child = match node.child(i) {
            Some(c) => c,
            None => continue,
        };

        match child.kind() {
            "function_definition" => {
                if let Some(body) = child.child_by_field_name("body") {
                    scan_body_for_global_assignments(&body, source, global_vars, result, summaries);
                }
            }
            k if k.starts_with("preproc_") => {
                collect_global_assignments(&child, source, global_vars, result, summaries);
            }
            _ => {}
        }
    }
}

/// Recursively scan a function body for assignments to global variables.
fn scan_body_for_global_assignments(
    node: &Node,
    source: &str,
    global_vars: &HashSet<String>,
    result: &mut StateMap,
    summaries: &HashMap<String, FunctionSummary>,
) {
    if node.kind() == "assignment_expression" {
        if let Some(left) = node.child_by_field_name("left") {
            let var_name = get_text(&left, source);
            if global_vars.contains(&var_name) {
                if let Some(right) = node.child_by_field_name("right") {
                    let rhs_text = get_text(&right, source);
                    // If RHS is itself a variable, check if it's a known global
                    // or classify the rvalue directly
                    let new_state =
                        if right.kind() == "identifier" && global_vars.contains(&rhs_text) {
                            result.get(&rhs_text).copied().unwrap_or(NullState::Unknown)
                        } else if right.kind() == "identifier" {
                            // RHS is a local variable — we can't know its value
                            // from the pre-pass. Check if it's a null literal.
                            if is_null_value(&rhs_text) {
                                NullState::DefinitelyNull
                            } else {
                                // Could be anything — look at what we can infer.
                                // In Juliet variant 45, the pattern is:
                                //   data = NULL; globalVar = data;
                                // We need to check if this local was just assigned NULL.
                                // Since we can't track locals in the pre-pass, check
                                // the preceding statement for a null assignment to this var.
                                check_preceding_null_assign(node, &rhs_text, source)
                            }
                        } else {
                            classify_rvalue_null(&right, source, summaries)
                        };

                    // Join with existing state
                    let existing = result.get(&var_name).copied().unwrap_or(NullState::Unknown);
                    result.insert(var_name, existing.join(new_state));
                }
            }
        }
    }

    // Recurse into children
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            scan_body_for_global_assignments(&child, source, global_vars, result, summaries);
        }
    }
}

/// Check if the preceding statement in the same compound_statement assigns
/// NULL to the given variable. Handles the common Juliet pattern:
///   data = NULL;
///   globalVar = data;
fn check_preceding_null_assign(assignment_node: &Node, var_name: &str, source: &str) -> NullState {
    // Walk up to find the containing expression_statement, then check the previous sibling
    let expr_stmt = if assignment_node.parent().map(|p| p.kind()) == Some("expression_statement") {
        assignment_node.parent().unwrap()
    } else {
        return NullState::Unknown;
    };

    if let Some(prev) = expr_stmt.prev_sibling() {
        if prev.kind() == "expression_statement" {
            if let Some(expr) = prev.child(0) {
                if expr.kind() == "assignment_expression" {
                    if let Some(left) = expr.child_by_field_name("left") {
                        if get_text(&left, source) == var_name {
                            if let Some(right) = expr.child_by_field_name("right") {
                                let rhs = get_text(&right, source);
                                if is_null_value(rhs.trim()) {
                                    return NullState::DefinitelyNull;
                                }
                                // Non-null assignment (e.g., data = "Good")
                                return classify_rvalue_null(&right, source, &HashMap::new());
                            }
                        }
                    }
                }
            }
        }
        // Check for declaration: `char *data = NULL;` or `char *data;`
        if prev.kind() == "declaration" {
            for i in 0..prev.child_count() {
                if let Some(child) = prev.child(i) {
                    if child.kind() == "init_declarator" {
                        if let Some(decl) = child.child_by_field_name("declarator") {
                            let name = get_identifier_from_declarator(&decl, source);
                            if name == var_name {
                                if let Some(value) = child.child_by_field_name("value") {
                                    let vtext = get_text(&value, source);
                                    if is_null_value(vtext.trim()) {
                                        return NullState::DefinitelyNull;
                                    }
                                    return classify_rvalue_null(&value, source, &HashMap::new());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    NullState::Unknown
}

// ---------------------------------------------------------------------------
// Forward dataflow (worklist algorithm)
// ---------------------------------------------------------------------------

/// Run null-state forward dataflow on a function CFG.
///
/// `func_node` is the `function_definition` AST node (for param extraction).
/// `source` is the full source text.
/// `summaries` are inter-procedural function summaries.
#[allow(dead_code)]
pub fn analyze_null_states(
    cfg: &FunctionCfg,
    func_node: &Node,
    source: &str,
    summaries: &HashMap<String, FunctionSummary>,
) -> NullAnalysisResult {
    analyze_null_states_with_globals(cfg, func_node, source, summaries, &StateMap::new(), None)
}

/// Like `analyze_null_states` but seeds the initial state with file-scope
/// global variable null states collected by `collect_file_scope_null_states`.
///
/// If `func_name` is provided, uses call-site-derived parameter null states
/// from `summaries[func_name].callsite_param_null_states` to seed parameters
/// instead of blanket PossiblyNull.
pub fn analyze_null_states_with_globals(
    cfg: &FunctionCfg,
    func_node: &Node,
    source: &str,
    summaries: &HashMap<String, FunctionSummary>,
    global_states: &StateMap,
    func_name: Option<&str>,
) -> NullAnalysisResult {
    let body = match func_node.child_by_field_name("body") {
        Some(b) => b,
        None => {
            return NullAnalysisResult {
                block_entry_states: HashMap::new(),
                block_exit_states: HashMap::new(),
                declared_pointers: HashSet::new(),
            }
        }
    };

    let mut declared_pointers = HashSet::new();

    // Initialize entry state: pointer params -> NotNull (or callsite-derived), globals -> precomputed
    let mut initial_state = StateMap::new();

    // Seed with global variable states
    for (name, &state) in global_states {
        initial_state.insert(name.clone(), state);
        declared_pointers.insert(name.clone());
    }

    // Look up call-site-derived param states if func_name is available
    let func_summary = func_name.and_then(|name| summaries.get(name));
    let callsite_states = func_summary.map(|s| &s.callsite_param_null_states);

    if let Some(declarator) = func_node.child_by_field_name("declarator") {
        collect_param_pointer_state(
            &declarator,
            source,
            &mut initial_state,
            &mut declared_pointers,
            callsite_states,
        );

        // Seed struct field null states: "paramName.fieldName" → NullState
        // Enables variant 67 detection (struct field null propagation across functions)
        if let Some(summary) = func_summary {
            if !summary.callsite_param_field_null_states.is_empty() {
                let param_names =
                    crate::analyze::function_summary::collect_param_names(func_node, source);
                for (param_idx, field_states) in &summary.callsite_param_field_null_states {
                    if let Some(param_name) = param_names.get(*param_idx) {
                        if !param_name.is_empty() {
                            for (field_name, &state) in field_states {
                                let key = format!("{}.{}", param_name, field_name);
                                initial_state.insert(key, state);
                            }
                        }
                    }
                }
            }
        }

        // Seed pointer-to-pointer pointee null states: "*paramName" → NullState
        // Enables variant 63 detection (pointer-to-pointer null propagation)
        // When caller passes &data where data=NULL, sink receives **param and
        // *param yields the NULL pointer.
        if let Some(summary) = func_summary {
            if !summary.callsite_param_pointee_null_states.is_empty() {
                let param_names =
                    crate::analyze::function_summary::collect_param_names(func_node, source);
                for (param_idx, &state) in &summary.callsite_param_pointee_null_states {
                    if let Some(param_name) = param_names.get(*param_idx) {
                        if !param_name.is_empty() {
                            let key = format!("*{}", param_name);
                            initial_state.insert(key, state);
                        }
                    }
                }
            }
        }
    }

    let mut entry_states: HashMap<BlockId, StateMap> = HashMap::new();
    let mut exit_states: HashMap<BlockId, StateMap> = HashMap::new();

    // Initialize all blocks
    for block in &cfg.blocks {
        entry_states.insert(block.id, StateMap::new());
        exit_states.insert(block.id, StateMap::new());
    }

    // Entry block gets initial state
    entry_states.insert(cfg.entry, initial_state.clone());
    let entry_exit = apply_transfer(
        &cfg.blocks[cfg.entry],
        &initial_state,
        &body,
        source,
        &mut declared_pointers,
        summaries,
    );
    exit_states.insert(cfg.entry, entry_exit);

    // Worklist — companion set for O(1) membership test instead of O(N) VecDeque::contains.
    let mut worklist: VecDeque<BlockId> = VecDeque::new();
    let mut in_worklist: HashSet<BlockId> = HashSet::new();
    for (succ, _) in cfg.successors(cfg.entry) {
        worklist.push_back(succ);
        in_worklist.insert(succ);
    }

    let mut iterations = 0;
    const MAX_ITERATIONS: usize = 500;

    while let Some(block_id) = worklist.pop_front() {
        in_worklist.remove(&block_id);
        iterations += 1;
        if iterations > MAX_ITERATIONS * cfg.blocks.len() {
            break;
        }

        // Join predecessor exit states with edge refinement
        let preds = cfg.predecessors(block_id);
        let mut new_entry = StateMap::new();
        let mut first = true;

        for (pred_id, edge_kind) in &preds {
            let pred_exit = exit_states.get(pred_id).cloned().unwrap_or_default();

            // Apply edge refinement from condition
            let refined =
                apply_edge_refinement(&pred_exit, *pred_id, edge_kind, cfg, &body, source);

            if first {
                new_entry = refined;
                first = false;
            } else {
                new_entry = join_states(&new_entry, &refined);
            }
        }

        if first {
            // No predecessors (unreachable block)
            continue;
        }

        // Compute exit state
        let block = &cfg.blocks[block_id];
        let new_exit = apply_transfer(
            block,
            &new_entry,
            &body,
            source,
            &mut declared_pointers,
            summaries,
        );

        // Check convergence
        let old_exit = exit_states.get(&block_id);
        if old_exit.is_none_or(|old| *old != new_exit) {
            entry_states.insert(block_id, new_entry);
            exit_states.insert(block_id, new_exit);

            // Add successors to worklist
            for (succ, _) in cfg.successors(block_id) {
                if in_worklist.insert(succ) {
                    worklist.push_back(succ);
                }
            }
        } else {
            entry_states.insert(block_id, new_entry);
        }
    }

    NullAnalysisResult {
        block_entry_states: entry_states,
        block_exit_states: exit_states,
        declared_pointers,
    }
}

/// Apply edge refinement: given a predecessor's exit state and the edge type,
/// refine the state based on the predecessor's condition.
fn apply_edge_refinement(
    pred_exit: &StateMap,
    pred_id: BlockId,
    edge_kind: &CfgEdge,
    cfg: &FunctionCfg,
    body: &Node,
    source: &str,
) -> StateMap {
    let mut state = pred_exit.clone();

    // Only refine on TrueBranch/FalseBranch edges
    let is_true = matches!(edge_kind, CfgEdge::TrueBranch);
    let is_false = matches!(edge_kind, CfgEdge::FalseBranch);
    if !is_true && !is_false {
        return state;
    }

    // Get the condition range from the predecessor block
    let pred_block = match cfg.get_block(pred_id) {
        Some(b) => b,
        None => return state,
    };
    let (cond_start, cond_end) = match pred_block.condition_range {
        Some(r) => r,
        None => return state,
    };

    // Find the condition AST node
    let cond_node = match find_node_at_range(body, cond_start, cond_end) {
        Some(n) => n,
        None => return state,
    };

    // Parse condition for null-check info (all vars in compound conditions)
    for info in parse_all_null_conditions(&cond_node, source) {
        let refined_state = if is_true {
            info.true_state
        } else {
            info.false_state
        };
        // Only refine if the variable is tracked
        if state.contains_key(&info.var_name) {
            state.insert(info.var_name, refined_state);
        }
    }

    state
}

// ---------------------------------------------------------------------------
// Dereference query
// ---------------------------------------------------------------------------

/// Check if dereferencing `var_name` at byte offset `deref_byte` is potentially unsafe.
///
/// Finds the block containing `deref_byte`, simulates from block entry up to
/// that point, and returns true if the variable is in an unsafe null state.
pub fn is_null_deref_at(
    result: &NullAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    source: &str,
    var_name: &str,
    deref_byte: usize,
    summaries: &HashMap<String, FunctionSummary>,
) -> bool {
    // Find which block contains this dereference
    let block = match find_block_containing(cfg, deref_byte) {
        Some(b) => b,
        None => return false, // Can't determine — be conservative
    };

    // Get entry state for this block
    let entry = match result.block_entry_states.get(&block.id) {
        Some(s) => s,
        None => return false,
    };

    // Simulate forward from entry through statements up to the dereference
    let mut state = entry.clone();
    let mut declared_pointers = result.declared_pointers.clone();

    for &(start, end) in &block.statements {
        // Stop before processing statements that come after the dereference
        if start >= deref_byte {
            break;
        }
        if let Some(stmt_node) = find_node_at_range(body, start, end) {
            process_statement_for_null_state(
                &stmt_node,
                source,
                &mut state,
                &mut declared_pointers,
                summaries,
            );
        }
    }

    // Check variable's state at dereference point
    match state.get(var_name) {
        Some(ns) => ns.is_unsafe(),
        None => false, // Unknown variable — not tracked as pointer
    }
}

/// Query the null state of a variable at a given byte offset.
///
/// Returns the concrete NullState (not just unsafe/safe). Used by call-site
/// null propagation to distinguish DefinitelyNull from PossiblyNull.
pub fn get_var_state_at(
    result: &NullAnalysisResult,
    cfg: &FunctionCfg,
    body: &Node,
    source: &str,
    var_name: &str,
    byte_offset: usize,
    summaries: &HashMap<String, FunctionSummary>,
) -> NullState {
    let block = match find_block_containing(cfg, byte_offset) {
        Some(b) => b,
        None => return NullState::Unknown,
    };

    let entry = match result.block_entry_states.get(&block.id) {
        Some(s) => s,
        None => return NullState::Unknown,
    };

    let mut state = entry.clone();
    let mut declared_pointers = result.declared_pointers.clone();

    for &(start, end) in &block.statements {
        if start >= byte_offset {
            break;
        }
        if let Some(stmt_node) = find_node_at_range(body, start, end) {
            process_statement_for_null_state(
                &stmt_node,
                source,
                &mut state,
                &mut declared_pointers,
                summaries,
            );
        }
    }

    state.get(var_name).copied().unwrap_or(NullState::Unknown)
}

/// Find the basic block whose byte range contains the given offset.
fn find_block_containing(cfg: &FunctionCfg, byte_offset: usize) -> Option<&BasicBlock> {
    // First try statement-level containment (more precise)
    for block in &cfg.blocks {
        for &(start, end) in &block.statements {
            if byte_offset >= start && byte_offset < end {
                return Some(block);
            }
        }
    }
    // Fallback to block byte range
    cfg.blocks.iter().find(|block| {
        block.byte_range.0 > 0
            && byte_offset >= block.byte_range.0
            && byte_offset < block.byte_range.1
    })
}

// ---------------------------------------------------------------------------
// Parameter collection
// ---------------------------------------------------------------------------

fn collect_param_pointer_state(
    declarator: &Node,
    source: &str,
    state: &mut StateMap,
    declared_pointers: &mut HashSet<String>,
    callsite_states: Option<&HashMap<usize, NullState>>,
) {
    if declarator.kind() == "function_declarator" {
        if let Some(params) = declarator.child_by_field_name("parameters") {
            let mut param_idx: usize = 0;
            for i in 0..params.child_count() {
                if let Some(param) = params.child(i) {
                    if param.kind() == "parameter_declaration" {
                        let param_text = get_text(&param, source);
                        if let Some(param_decl) = param.child_by_field_name("declarator") {
                            let name = get_identifier_from_declarator(&param_decl, source);
                            if !name.is_empty()
                                && (is_pointer_declarator(&param_decl)
                                    || param_text.contains('*')
                                    || param_text.starts_with("FILE")
                                    || name.contains("callback"))
                            {
                                declared_pointers.insert(name.clone());
                                // Use call-site-derived state if available,
                                // falling back to PossiblyNull (default)
                                let seed_state = if let Some(cs) = callsite_states {
                                    // Have inter-procedural call-site data.
                                    // If prescan resolved a concrete state, use it.
                                    // If Unknown or missing, treat as NotNull — same
                                    // as no-callsite-data ("callers are responsible").
                                    cs.get(&param_idx)
                                        .copied()
                                        .map(|s| match s {
                                            NullState::Unknown => NullState::NotNull,
                                            other => other,
                                        })
                                        .unwrap_or(NullState::NotNull)
                                } else {
                                    // No call-site data — assume params are non-null
                                    // (callers are responsible for null checks)
                                    NullState::NotNull
                                };
                                state.insert(name, seed_state);
                            }
                        }
                        param_idx += 1;
                    }
                }
            }
        }
    } else {
        for i in 0..declarator.child_count() {
            if let Some(child) = declarator.child(i) {
                collect_param_pointer_state(
                    &child,
                    source,
                    state,
                    declared_pointers,
                    callsite_states,
                );
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Helper functions (shared with EXP34-C)
// ---------------------------------------------------------------------------

fn get_text(node: &Node, source: &str) -> String {
    source[node.start_byte()..node.end_byte()].to_string()
}

pub fn is_null_value(text: &str) -> bool {
    let t = text.trim();
    t == "NULL" || t == "0" || t == "nullptr"
}

pub fn is_nullable_function(func_name: &str, summaries: &HashMap<String, FunctionSummary>) -> bool {
    if let Some(summary) = summaries.get(func_name) {
        if summary.can_return_null {
            return true;
        }
    }
    matches!(
        func_name,
        "malloc"
            | "calloc"
            | "realloc"
            | "strstr"
            | "strchr"
            | "strrchr"
            | "fopen"
            | "fdopen"
            | "freopen"
            | "tmpfile"
            | "popen"
            | "getenv"
            | "setlocale"
            | "strtok"
            | "bsearch"
            | "fgets"
            | "gets"
            | "strdup"
            | "strndup"
            | "strpbrk"
            | "memchr"
            | "localtime"
            | "gmtime"
            | "asctime"
            | "ctime"
            | "create_int"
    )
}

#[allow(dead_code)]
pub fn is_cast_to_null(node: &Node, source: &str) -> bool {
    if node.kind() == "cast_expression" {
        if let Some(value) = node.child_by_field_name("value") {
            let vt = get_text(&value, source);
            return is_null_value(vt.trim());
        }
    }
    false
}

pub fn is_pointer_declarator(declarator: &Node) -> bool {
    match declarator.kind() {
        "pointer_declarator" => true,
        "array_declarator" => true,
        _ => {
            for i in 0..declarator.child_count() {
                if let Some(child) = declarator.child(i) {
                    if is_pointer_declarator(&child) {
                        return true;
                    }
                }
            }
            false
        }
    }
}

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

fn get_identifier_from_declarator(declarator: &Node, source: &str) -> String {
    match declarator.kind() {
        "identifier" => get_text(declarator, source),
        "pointer_declarator" | "array_declarator" => {
            if let Some(inner) = declarator.child_by_field_name("declarator") {
                get_identifier_from_declarator(&inner, source)
            } else {
                String::new()
            }
        }
        _ => {
            for i in 0..declarator.child_count() {
                if let Some(child) = declarator.child(i) {
                    if child.kind() == "identifier" {
                        return get_text(&child, source);
                    }
                }
            }
            String::new()
        }
    }
}

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

    fn analyze(code: &str) -> (FunctionCfg, NullAnalysisResult, tree_sitter::Tree, String) {
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&tree_sitter_c::language()).unwrap();
        let tree = parser.parse(code, None).unwrap();
        let root = tree.root_node();
        let func = (0..root.child_count())
            .filter_map(|i| root.child(i))
            .find(|c| c.kind() == "function_definition")
            .unwrap();
        let cfg = build_function_cfg(&func, code).unwrap();
        let summaries = HashMap::new();
        let result = analyze_null_states(&cfg, &func, code, &summaries);
        (cfg, result, tree, code.to_string())
    }

    #[test]
    fn test_null_assigned_then_deref() {
        let code = r#"
void foo() {
    int *p = NULL;
    *p = 42;
}
"#;
        let (cfg, result, tree, source) = analyze(code);
        let root = tree.root_node();
        let func = root.child(0).unwrap();
        let body = func.child_by_field_name("body").unwrap();
        // Find dereference byte — "*p = 42"
        let deref_pos = source.find("*p = 42").unwrap();
        let summaries = HashMap::new();
        assert!(is_null_deref_at(
            &result, &cfg, &body, &source, "p", deref_pos, &summaries
        ));
    }

    #[test]
    fn test_null_check_before_deref() {
        let code = r#"
void foo() {
    int *p = NULL;
    if (p != NULL) {
        *p = 42;
    }
}
"#;
        let (cfg, result, tree, source) = analyze(code);
        let root = tree.root_node();
        let func = root.child(0).unwrap();
        let body = func.child_by_field_name("body").unwrap();
        let deref_pos = source.find("*p = 42").unwrap();
        let summaries = HashMap::new();
        assert!(!is_null_deref_at(
            &result, &cfg, &body, &source, "p", deref_pos, &summaries
        ));
    }

    #[test]
    fn test_early_return_after_null_check() {
        let code = r#"
int foo(int *p) {
    if (p == NULL) {
        return -1;
    }
    *p = 42;
    return 0;
}
"#;
        let (cfg, result, tree, source) = analyze(code);
        let root = tree.root_node();
        let func = root.child(0).unwrap();
        let body = func.child_by_field_name("body").unwrap();
        let deref_pos = source.find("*p = 42").unwrap();
        let summaries = HashMap::new();
        assert!(!is_null_deref_at(
            &result, &cfg, &body, &source, "p", deref_pos, &summaries
        ));
    }

    #[test]
    fn test_deref_inside_null_branch() {
        let code = r#"
void foo(int *p) {
    if (p == NULL) {
        *p = 42;
    }
}
"#;
        let (cfg, result, tree, source) = analyze(code);
        let root = tree.root_node();
        let func = root.child(0).unwrap();
        let body = func.child_by_field_name("body").unwrap();
        let deref_pos = source.find("*p = 42").unwrap();
        let summaries = HashMap::new();
        assert!(is_null_deref_at(
            &result, &cfg, &body, &source, "p", deref_pos, &summaries
        ));
    }

    #[test]
    fn test_malloc_with_check() {
        let code = r#"
void foo() {
    int *p = malloc(sizeof(int));
    if (p == NULL) {
        return;
    }
    *p = 42;
}
"#;
        let (cfg, result, tree, source) = analyze(code);
        let root = tree.root_node();
        let func = root.child(0).unwrap();
        let body = func.child_by_field_name("body").unwrap();
        let deref_pos = source.find("*p = 42").unwrap();
        let summaries = HashMap::new();
        assert!(!is_null_deref_at(
            &result, &cfg, &body, &source, "p", deref_pos, &summaries
        ));
    }

    #[test]
    fn test_malloc_without_check() {
        let code = r#"
void foo() {
    int *p = malloc(sizeof(int));
    *p = 42;
}
"#;
        let (cfg, result, tree, source) = analyze(code);
        let root = tree.root_node();
        let func = root.child(0).unwrap();
        let body = func.child_by_field_name("body").unwrap();
        let deref_pos = source.find("*p = 42").unwrap();
        let summaries = HashMap::new();
        assert!(is_null_deref_at(
            &result, &cfg, &body, &source, "p", deref_pos, &summaries
        ));
    }

    #[test]
    fn test_while_loop_guard() {
        let code = r#"
void foo(int *p) {
    while (p != NULL) {
        *p = 42;
        p = NULL;
    }
}
"#;
        let (cfg, result, tree, source) = analyze(code);
        let root = tree.root_node();
        let func = root.child(0).unwrap();
        let body = func.child_by_field_name("body").unwrap();
        let deref_pos = source.find("*p = 42").unwrap();
        let summaries = HashMap::new();
        assert!(!is_null_deref_at(
            &result, &cfg, &body, &source, "p", deref_pos, &summaries
        ));
    }

    #[test]
    fn test_global_prepass_null_static() {
        // Variant 45 pattern: static global assigned NULL, read in sink function
        let code = r#"
static int *globalData;

void source() {
    int *data;
    data = NULL;
    globalData = data;
}

void sink() {
    int *data = globalData;
    *data = 42;
}
"#;
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&tree_sitter_c::language()).unwrap();
        let tree = parser.parse(code, None).unwrap();
        let root = tree.root_node();
        let summaries = HashMap::new();

        let globals = collect_file_scope_null_states(&root, code, &summaries);
        assert_eq!(globals.get("globalData"), Some(&NullState::DefinitelyNull));

        // Now analyze sink() with global states
        let sink_func = (0..root.child_count())
            .filter_map(|i| root.child(i))
            .find(|c| {
                c.kind() == "function_definition"
                    && code[c.start_byte()..c.end_byte()].contains("sink")
            })
            .unwrap();
        let cfg = build_function_cfg(&sink_func, code).unwrap();
        let result =
            analyze_null_states_with_globals(&cfg, &sink_func, code, &summaries, &globals, None);
        let body = sink_func.child_by_field_name("body").unwrap();
        let deref_pos = code.find("*data = 42").unwrap();
        assert!(is_null_deref_at(
            &result, &cfg, &body, code, "data", deref_pos, &summaries
        ));
    }

    #[test]
    fn test_global_prepass_nonnull_static() {
        // Good variant: static global assigned non-null, should NOT flag
        let code = r#"
static char *globalData;

void source() {
    char *data;
    data = "Good";
    globalData = data;
}

void sink() {
    char *data = globalData;
    data[0];
}
"#;
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&tree_sitter_c::language()).unwrap();
        let tree = parser.parse(code, None).unwrap();
        let root = tree.root_node();
        let summaries = HashMap::new();

        let globals = collect_file_scope_null_states(&root, code, &summaries);
        assert_eq!(globals.get("globalData"), Some(&NullState::NotNull));
    }
}