lang-parsing-substrate 0.17.3

Shared language-parsing substrate for knots, moldy, aurora-lint, and clew
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
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
//! Call-graph edge extraction.
//!
//! Ported from knots' `external_calls` metric (function/macro-name collection
//! plus the call-node-kind vocabulary in `handle_call_node` /
//! `collect_external_calls_recursive`), generalized to record every call
//! target rather than only the ones that fall outside the file's own
//! function/macro names. Unlike [`crate::imports`], this dispatch is *not*
//! keyed by language: the node kinds involved (`call_expression`, `call`,
//! `method_invocation`, ...) are shared across enough grammars that a single
//! generic walk covers all 16 languages without a per-language table.
//!
//! No cross-file resolution happens here — `is_external` only means "not one
//! of the names this file itself defines." Turning that into an actual
//! cross-file call graph (deciding which external callee belongs to which
//! other file) is a per-tool concern, same as `import_sources`.

use crate::query::{find_first_descendant, walk_preorder, Walk};
use std::collections::{HashMap, HashSet};
use tree_sitter::Node;

/// One call site: `caller` (a function/macro name defined in this file)
/// invoked `callee`. `is_external` is true when `callee` is not among the
/// function/macro names this file defines — i.e. it's presumably resolved
/// elsewhere (another file, a library, a language builtin).
///
/// Only named functions become callers; anonymous closures/lambdas are
/// skipped as call *sites* (matching knots' default, non-anonymous-counting
/// behavior), though calls made from inside them are still attributed to
/// their nearest enclosing named function, since the underlying traversal
/// does not stop at nested-function boundaries — the same behavior as the
/// existing `external_calls` metric it extends.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallEdge {
    /// Name of the calling function.
    pub caller: String,
    /// Name of the called function/macro.
    pub callee: String,
    /// Whether `callee` is not locally defined in the same file — see the
    /// struct-level docs for why this is per-file, not per-corpus.
    pub is_external: bool,
}

/// Builds call-graph edges for every named function/macro in `tree`.
///
/// Building a corpus-wide graph is left to the caller: concatenate
/// `call_edges` results across every file's tree. This function only sees
/// one file, so `is_external` can't distinguish "external to this file, but
/// defined in another file of the same project" from "genuinely external" —
/// that classification needs the whole corpus's local-name sets, which is
/// the caller's job.
pub fn call_edges(root: Node, source: &str) -> Vec<CallEdge> {
    let local_names = collect_local_names(root, source);
    let mut functions = Vec::new();
    collect_functions(root, source, &mut functions);

    let mut edges = Vec::new();
    for (node, caller) in functions {
        let mut callees = Vec::new();
        let mut aliases = HashMap::new();
        collect_fn_ptr_aliases(node, source, &mut aliases);
        // A syntax error anywhere in this function's subtree means its span
        // can't be trusted (see collect_call_names doc comment) — a brace
        // that opens and closes in different branches of the same repeated
        // #ifdef guard, for example, makes tree-sitter-c's grammar swallow
        // every subsequent sibling function as a nested descendant. In that
        // case, stop at nested function boundaries instead of attributing
        // a swallowed sibling's calls to this caller.
        collect_call_names(node, source, node.has_error(), &aliases, &mut callees);
        for callee in callees {
            let is_external = !local_names.contains(&callee);
            edges.push(CallEdge {
                caller: caller.clone(),
                callee,
                is_external,
            });
        }
    }
    edges
}

/// Collects every named function-like node in `root`'s subtree, in pre-order.
///
/// Iterative (explicit worklist), not recursive, for the reason
/// [`crate::query::find_descendants`] documents: this walk's depth is the
/// AST's own nesting depth, which is unbounded — a corrupted-`#ifdef` parse
/// reaches thousands of levels — and it runs on worker threads whose stacks
/// are far smaller than main's. [`walk_preorder`] keeps the pre-order the
/// recursion produced, with one cursor for the whole walk.
fn collect_functions<'a>(root: Node<'a>, source: &str, out: &mut Vec<(Node<'a>, String)>) {
    walk_preorder(root, |node| {
        if is_function_kind(node.kind()) && !is_macro_function_definition(node) {
            if let Some(name) = get_function_name(node, source) {
                out.push((node, name));
            }
        }
        Walk::Continue
    });
}

/// Returns `true` if `kind` is a function-like node this module treats as a
/// potential call-graph caller.
pub fn is_function_kind(kind: &str) -> bool {
    matches!(
        kind,
        "function_definition"
            | "function_item"
            | "function_declaration"
            | "function_expression"
            | "arrow_function"
            | "method_definition"
            | "generator_function_declaration"
            | "generator_function"
            | "subprogram_body"
            | "expression_function_declaration"
            | "task_body"
            | "method_declaration"
            | "func_literal"
            | "constructor_declaration"
            | "local_function_statement"
            | "init_declaration"
            // Fortran: function subprogram, subroutine subprogram, module procedure, main program
            | "function"
            | "subroutine"
            | "module_procedure"
            | "program"
    )
}

fn is_macro_function_definition(node: Node) -> bool {
    node.kind() == "function_definition"
        && node
            .child_by_field_name("declarator")
            .map(|d| d.kind() == "parenthesized_declarator")
            .unwrap_or(false)
}

/// Resolves the name of a function-like node, or `None` for genuinely
/// anonymous usage (callbacks, IIFEs, return values, etc.) that can't be
/// traced back to a binding.
pub fn get_function_name(node: Node, source: &str) -> Option<String> {
    match node.kind() {
        "function_item"
        | "method_definition"
        | "generator_function_declaration"
        | "generator_function"
        | "method_declaration"
        | "constructor_declaration"
        | "local_function_statement" => name_field(node, source),

        "function_declaration" => name_field(node, source).or_else(|| {
            let mut cursor = node.walk();
            let found = node
                .children(&mut cursor)
                .find(|c| c.kind() == "simple_identifier");
            found
                .and_then(|c| c.utf8_text(source.as_bytes()).ok())
                .map(|s| s.to_string())
        }),

        "function_definition" => name_field(node, source)
            .or_else(|| get_c_name(node, source))
            .or_else(|| get_lua_assignment_name(node, source)),

        "function_expression" => {
            name_field(node, source).or_else(|| get_name_from_assignment_context(node, source))
        }

        "arrow_function" => get_name_from_assignment_context(node, source),

        "init_declaration" => Some("init".to_string()),

        "func_literal" => None,

        "subprogram_body" | "expression_function_declaration" => {
            let mut cursor = node.walk();
            let spec = node.children(&mut cursor).find(|c| {
                matches!(
                    c.kind(),
                    "function_specification" | "procedure_specification"
                )
            })?;
            name_field(spec, source)
        }

        "task_body" => {
            let mut cursor = node.walk();
            let found = node
                .children(&mut cursor)
                .find(|c| c.kind() == "identifier");
            found
                .and_then(|c| c.utf8_text(source.as_bytes()).ok())
                .map(|s| s.to_string())
        }

        "function" => name_in_child(node, "function_statement", source),
        "subroutine" => name_in_child(node, "subroutine_statement", source),
        "module_procedure" => name_in_child(node, "module_procedure_statement", source),

        "program" => {
            let mut cursor = node.walk();
            let stmt = node
                .children(&mut cursor)
                .find(|c| c.kind() == "program_statement")?;
            let mut inner = stmt.walk();
            let first_named = stmt.named_children(&mut inner).next();
            first_named
                .and_then(|n| n.utf8_text(source.as_bytes()).ok())
                .map(|s| s.to_string())
                .or_else(|| Some("program".to_string()))
        }

        _ => get_c_name(node, source),
    }
}

fn name_field(node: Node, source: &str) -> Option<String> {
    node.child_by_field_name("name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string())
}

fn name_in_child(node: Node, child_kind: &str, source: &str) -> Option<String> {
    let mut cursor = node.walk();
    let child = node
        .children(&mut cursor)
        .find(|c| c.kind() == child_kind)?;
    name_field(child, source)
}

fn get_c_name(node: Node, source: &str) -> Option<String> {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "function_declarator" {
            return get_declarator_name(child, source);
        }
        if child.kind() == "pointer_declarator" {
            if let Some(name) = get_function_name_from_declarator(child, source) {
                return Some(name);
            }
        }
    }
    None
}

fn get_function_name_from_declarator(node: Node, source: &str) -> Option<String> {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "function_declarator" {
            return get_declarator_name(child, source);
        } else if child.kind() == "pointer_declarator" {
            if let Some(name) = get_function_name_from_declarator(child, source) {
                return Some(name);
            }
        }
    }
    None
}

fn get_declarator_name(node: Node, source: &str) -> Option<String> {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "identifier"
            | "qualified_identifier"
            | "destructor_name"
            | "operator_name"
            | "field_identifier" => {
                return Some(child.utf8_text(source.as_bytes()).ok()?.to_string());
            }
            "pointer_declarator" | "function_declarator" => {
                if let Some(name) = get_declarator_name(child, source) {
                    return Some(name);
                }
            }
            _ => {}
        }
    }
    None
}

/// Extract the name of a Lua anonymous function_definition from its
/// assignment context.
fn get_lua_assignment_name(node: Node, source: &str) -> Option<String> {
    let parent = node.parent()?;
    match parent.kind() {
        "field" => {
            let mut cur = parent.walk();
            let found = parent
                .named_children(&mut cur)
                .find(|c| c.kind() == "identifier");
            found
                .and_then(|n| n.utf8_text(source.as_bytes()).ok())
                .map(|s| s.to_string())
        }
        "expression_list" => {
            let idx = {
                let mut cur = parent.walk();
                let pos = parent
                    .named_children(&mut cur)
                    .position(|c| c.id() == node.id())
                    .unwrap_or(0);
                pos
            };
            let assign = parent.parent()?;
            if assign.kind() != "assignment_statement" {
                return None;
            }
            let mut cur = assign.walk();
            let found = assign
                .children(&mut cur)
                .find(|c| c.kind() == "variable_list");
            let var_list = found?;
            let mut cur2 = var_list.walk();
            let var = var_list.named_children(&mut cur2).nth(idx)?;
            if var.kind() != "identifier" {
                return None;
            }
            var.utf8_text(source.as_bytes()).ok().map(|s| s.to_string())
        }
        _ => None,
    }
}

/// Extract the name of an arrow_function or anonymous function_expression
/// from the surrounding assignment context. Returns None for truly
/// anonymous usage (callbacks, IIFEs, return values, etc.).
fn get_name_from_assignment_context(node: Node, source: &str) -> Option<String> {
    let parent = node.parent()?;
    match parent.kind() {
        // const foo = () => {}  or  const foo = function() {}
        "variable_declarator" => parent
            .child_by_field_name("name")
            .and_then(|n| n.utf8_text(source.as_bytes()).ok())
            .map(|s| s.to_string()),
        // { foo: () => {} }
        "pair" => parent
            .child_by_field_name("key")
            .and_then(|n| n.utf8_text(source.as_bytes()).ok())
            .map(|s| s.to_string()),
        // class { foo = () => {} }
        "public_field_definition" => parent
            .child_by_field_name("name")
            .and_then(|n| n.utf8_text(source.as_bytes()).ok())
            .map(|s| s.to_string()),
        _ => None,
    }
}

/// Collects all function and macro names defined in this translation unit.
/// Used to classify call sites as local vs. external.
pub fn collect_local_names(root: Node, source: &str) -> HashSet<String> {
    let mut names = HashSet::new();
    collect_local_names_into(root, source, &mut names);
    names
}

/// Iterative for the reason [`collect_functions`] documents.
fn collect_local_names_into(root: Node, source: &str, names: &mut HashSet<String>) {
    walk_preorder(root, |node| {
        if is_function_kind(node.kind()) {
            if let Some(name) = get_function_name(node, source) {
                names.insert(name);
            }
        } else if matches!(node.kind(), "preproc_def" | "preproc_function_def") {
            if let Some(name_node) = node.child_by_field_name("name") {
                if let Ok(name) = name_node.utf8_text(source.as_bytes()) {
                    names.insert(name.to_string());
                }
            }
        }
        Walk::Continue
    });
}

fn handle_call_node(
    node: Node,
    source: &str,
    aliases: &HashMap<String, String>,
    out: &mut Vec<String>,
) {
    let Some(func_node) = node.child_by_field_name("function") else {
        return;
    };
    match func_node.kind() {
        "identifier" => {
            if let Ok(name) = func_node.utf8_text(source.as_bytes()) {
                let resolved = aliases.get(name).map(String::as_str).unwrap_or(name);
                out.push(resolved.to_string());
            }
        }
        "scoped_identifier"
        | "attribute"
        | "member_expression"
        | "selector_expression"
        | "member_access_expression" => {
            if let Ok(name) = func_node.utf8_text(source.as_bytes()) {
                out.push(name.to_string());
            }
        }
        "field_expression" => {
            if let Some(field) = func_node.child_by_field_name("field") {
                if let Ok(method_name) = field.utf8_text(source.as_bytes()) {
                    out.push(method_name.to_string());
                }
            }
        }
        _ => {}
    }
}

/// Collects every call target name reachable from `root`, descending through
/// nested function bodies (a nested closure's calls are attributed to every
/// enclosing named function, not just its own) — matching the traversal the
/// `external_calls` metric already uses.
///
/// `stop_at_nested`: when true, does not descend into a nested function-like
/// node (see [`is_function_kind`]). Callers set this when `root.has_error()`
/// — a syntax error anywhere in the subtree means the span can't be trusted,
/// and for grammars where a function-like node can never legitimately nest
/// inside another of the same call-graph role (e.g. C's `function_definition`
/// — C has no nested functions), an apparent nesting is a sign the grammar
/// swallowed unrelated sibling code, not a real closure. Attributing that
/// sibling's calls to the outer, corrupted caller would be wrong, so the walk
/// stops at the boundary instead and lets the nested node be counted (in a
/// separate, correctly-scoped pass) under its own name.
///
/// Iterative for the reason [`collect_functions`] documents — and the more
/// pressing case of it, since the corrupted parses that set `stop_at_nested`
/// are exactly the deeply nested ones.
fn collect_call_names(
    root: Node,
    source: &str,
    stop_at_nested: bool,
    aliases: &HashMap<String, String>,
    out: &mut Vec<String>,
) {
    walk_preorder(root, |node| {
        // A pruned nested function is skipped whole: neither it nor its subtree is
        // visited, exactly as the old worklist never pushed it. The root itself is
        // always visited.
        let pruned = stop_at_nested
            && node != root
            && is_function_kind(node.kind())
            && !is_macro_function_definition(node)
            && !is_error_recovery_debris(node, source);
        if pruned {
            return Walk::SkipChildren;
        }
        if node.kind() == "call_expression"
            || node.kind() == "call"
            || node.kind() == "invocation_expression"
        {
            handle_call_node(node, source, aliases, out);
        }
        if node.kind() == "procedure_call_statement" || node.kind() == "function_call" {
            if let Some(name_node) = node.child_by_field_name("name") {
                if let Ok(name) = name_node.utf8_text(source.as_bytes()) {
                    out.push(name.to_string());
                }
            }
        }
        if node.kind() == "method_invocation" {
            if let Some(name_node) = node.child_by_field_name("name") {
                if let Ok(name) = name_node.utf8_text(source.as_bytes()) {
                    out.push(name.to_string());
                }
            }
        }
        if node.kind() == "call_expression" && node.child_by_field_name("function").is_none() {
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if !child.is_named() {
                    continue;
                }
                if matches!(
                    child.kind(),
                    "value_arguments" | "type_arguments" | "annotated_lambda" | "call_suffix"
                ) {
                    continue;
                }
                let text = child.utf8_text(source.as_bytes()).unwrap_or("").to_string();
                out.push(text);
                break;
            }
        }
        if node.kind() == "object_creation_expression" {
            if let Some(type_node) = node.child_by_field_name("type") {
                if let Ok(name) = type_node.utf8_text(source.as_bytes()) {
                    out.push(name.to_string());
                }
            }
        }
        Walk::Continue
    });
}

/// True when a function-like node's extracted name is actually a bare C/C++
/// keyword (`if`, `while`, ...). Under error recovery, tree-sitter-c can
/// mis-parse ordinary control flow as a nameless function_definition-shaped
/// node whose "name" resolves to the keyword itself — that node will never
/// get its own call-graph entry, so treating it as a real nested sibling and
/// stopping at its boundary would silently drop the real calls inside it.
/// Scoped to `function_definition` (C/C++/Lua's shared kind) since that's
/// the only kind this failure mode has been reproduced against; other
/// languages' function-like kinds are left as-is absent similar evidence.
fn is_error_recovery_debris(node: Node, source: &str) -> bool {
    node.kind() == "function_definition"
        && get_function_name(node, source).is_some_and(|name| is_c_keyword(&name))
}

fn is_c_keyword(name: &str) -> bool {
    matches!(
        name,
        "if" | "else"
            | "for"
            | "while"
            | "do"
            | "switch"
            | "case"
            | "default"
            | "return"
            | "break"
            | "continue"
            | "goto"
            | "sizeof"
            | "typedef"
            | "struct"
            | "union"
            | "enum"
    )
}

/// Populate `aliases` with function-pointer variable → target-function
/// mappings found inside `node`'s subtree. Matches both init declarators
/// (`void (*fp)(char *) = foo;`) and plain assignments to a name previously
/// declared as a function pointer (`fp = foo;`). Non-identifier initializers
/// and compound RHS expressions are ignored.
///
/// The node kinds matched here (`declaration`, `init_declarator`,
/// `function_declarator`, `pointer_declarator`) are specific to the C/C++
/// grammar family — this simply never matches in other languages' trees, so
/// no explicit language gate is needed (same principle as the rest of this
/// module's node-kind dispatch).
///
/// Iterative for the reason [`collect_functions`] documents. Pre-order is
/// what makes a later rebinding assignment overwrite an earlier one, and
/// [`walk_preorder`] preserves it.
fn collect_fn_ptr_aliases(root: Node, source: &str, aliases: &mut HashMap<String, String>) {
    walk_preorder(root, |node| {
        match node.kind() {
            "declaration" => {
                let mut cursor = node.walk();
                for child in node.children(&mut cursor) {
                    if child.kind() != "init_declarator" {
                        continue;
                    }
                    let Some(decl) = child.child_by_field_name("declarator") else {
                        continue;
                    };
                    if !declarator_is_function_pointer(decl) {
                        continue;
                    }
                    let Some(name) = extract_innermost_identifier(decl, source) else {
                        continue;
                    };
                    if let Some(value) = child.child_by_field_name("value") {
                        if let Some(target) = rhs_target_function_name(value, source) {
                            aliases.insert(name, target);
                        }
                    }
                }
            }
            "assignment_expression" => {
                // Rebind an existing function-pointer alias. Only applies when the
                // LHS is already known to be a function pointer.
                if let (Some(lhs), Some(rhs)) = (
                    node.child_by_field_name("left"),
                    node.child_by_field_name("right"),
                ) {
                    if lhs.kind() == "identifier" {
                        if let Ok(lhs_name) = lhs.utf8_text(source.as_bytes()) {
                            if aliases.contains_key(lhs_name) {
                                if let Some(target) = rhs_target_function_name(rhs, source) {
                                    aliases.insert(lhs_name.to_string(), target);
                                }
                            }
                        }
                    }
                }
            }
            _ => {}
        }
        Walk::Continue
    });
}

/// True when a declarator subtree shapes a function pointer: it contains
/// both a `function_declarator` (the callable signature) and a
/// `pointer_declarator` (the indirection). A bare `function_declarator`
/// indicates a function prototype, and a bare `pointer_declarator` is a
/// plain pointer.
fn declarator_is_function_pointer(node: Node) -> bool {
    find_first_descendant(node, |n| n.kind() == "function_declarator").is_some()
        && find_first_descendant(node, |n| n.kind() == "pointer_declarator").is_some()
}

/// Find the deepest identifier under a declarator chain (the name being
/// declared). For `(*fp)` this is `fp`.
fn extract_innermost_identifier(node: Node, source: &str) -> Option<String> {
    if node.kind() == "identifier" {
        return node.utf8_text(source.as_bytes()).ok().map(String::from);
    }
    if let Some(inner) = node.child_by_field_name("declarator") {
        if let Some(name) = extract_innermost_identifier(inner, source) {
            return Some(name);
        }
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(name) = extract_innermost_identifier(child, source) {
            return Some(name);
        }
    }
    None
}

/// Return the target-function identifier for a function-pointer RHS.
/// Accepts `foo` and `&foo`; anything else is None.
fn rhs_target_function_name(node: Node, source: &str) -> Option<String> {
    let mut n = node;
    // Unwrap parens/casts and leading `&`.
    loop {
        match n.kind() {
            "parenthesized_expression" => {
                if let Some(inner) = n.named_child(0) {
                    n = inner;
                    continue;
                }
                return None;
            }
            "cast_expression" => {
                if let Some(value) = n.child_by_field_name("value") {
                    n = value;
                    continue;
                }
                return None;
            }
            "pointer_expression" | "unary_expression" => {
                // `&foo` — unwrap to `foo`.
                if let Some(arg) = n.child_by_field_name("argument") {
                    n = arg;
                    continue;
                }
                return None;
            }
            _ => break,
        }
    }
    if n.kind() == "identifier" {
        n.utf8_text(source.as_bytes()).ok().map(String::from)
    } else {
        None
    }
}

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

    fn edges(key: &str, code: &str) -> Vec<CallEdge> {
        let language = language_for_key(key).unwrap_or_else(|| panic!("no grammar for {key}"));
        let mut parser = Parser::new();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();
        call_edges(tree.root_node(), code)
    }

    #[cfg(feature = "lang-rust")]
    #[test]
    fn rust_local_and_external_calls() {
        let code =
            "fn helper() {}\nfn main() { helper(); println!(\"hi\"); std::fs::read(\"x\"); }\n";
        let e = edges("rust", code);
        assert!(e.contains(&CallEdge {
            caller: "main".into(),
            callee: "helper".into(),
            is_external: false,
        }));
        assert!(e
            .iter()
            .any(|c| c.caller == "main" && c.callee == "std::fs::read" && c.is_external));
    }

    #[cfg(feature = "lang-python")]
    #[test]
    fn python_calls() {
        let code = "def helper():\n    pass\n\ndef main():\n    helper()\n    os.path.join('a')\n";
        let e = edges("python", code);
        assert!(e.contains(&CallEdge {
            caller: "main".into(),
            callee: "helper".into(),
            is_external: false,
        }));
        assert!(e
            .iter()
            .any(|c| c.caller == "main" && c.callee == "os.path.join" && c.is_external));
    }

    #[cfg(feature = "lang-go")]
    #[test]
    fn go_calls() {
        let code =
            "package main\nfunc helper() {}\nfunc main() {\n\thelper()\n\tfmt.Println(\"hi\")\n}\n";
        let e = edges("go", code);
        assert!(e.contains(&CallEdge {
            caller: "main".into(),
            callee: "helper".into(),
            is_external: false,
        }));
        assert!(e
            .iter()
            .any(|c| c.caller == "main" && c.callee == "fmt.Println" && c.is_external));
    }

    #[cfg(feature = "lang-java")]
    #[test]
    fn java_method_invocation() {
        let code = "class A {\n  void helper() {}\n  void main() {\n    helper();\n    System.out.println(\"hi\");\n  }\n}\n";
        let e = edges("java", code);
        assert!(e.contains(&CallEdge {
            caller: "main".into(),
            callee: "helper".into(),
            is_external: false,
        }));
        assert!(e
            .iter()
            .any(|c| c.caller == "main" && c.callee == "println" && c.is_external));
    }

    #[cfg(feature = "lang-c")]
    #[test]
    fn deeply_nested_input_does_not_overflow_the_stack() {
        // Regression: every walk in this module descends to the AST's own
        // nesting depth, and prescan runs them on rayon workers whose stacks
        // are far smaller than main's. A corrupted-#ifdef parse of raylib
        // reached thousands of levels while a sibling recursive walk in a
        // consumer overflowed on the same tree; the margin here was
        // accidental, not designed. 20k levels is well past what a recursive
        // walk of this shape survives.
        //
        // Exercises all four walks at once: call_edges runs collect_local_names,
        // collect_functions, collect_fn_ptr_aliases and collect_call_names over
        // the same deep tree.
        let depth = 20_000;
        let mut code = String::from("void helper(void) {}\nvoid f(int x) {\n");
        for _ in 0..depth {
            code.push_str("if (x) {\n");
        }
        code.push_str("helper();\n");
        for _ in 0..depth {
            code.push_str("}\n");
        }
        code.push_str("}\n");
        let e = edges("c", &code);
        assert!(e.contains(&CallEdge {
            caller: "f".into(),
            callee: "helper".into(),
            is_external: false,
        }));
    }

    #[cfg(feature = "lang-c")]
    #[test]
    fn c_calls() {
        let code =
            "int helper() { return 1; }\nint main() { helper(); printf(\"hi\"); return 0; }\n";
        let e = edges("c", code);
        assert!(e.contains(&CallEdge {
            caller: "main".into(),
            callee: "helper".into(),
            is_external: false,
        }));
        assert!(e
            .iter()
            .any(|c| c.caller == "main" && c.callee == "printf" && c.is_external));
    }

    #[cfg(feature = "lang-rust")]
    #[test]
    fn no_functions_yields_no_edges() {
        assert!(edges("rust", "const X: i32 = 1;\n").is_empty());
    }

    /// Regression for the sqlite3Init/sqlite3InitOne false MSC04-C
    /// indirect-recursion cycle in aurora-lint, reproduced with the
    /// real sqlite3/src/prepare.c source (trimmed to just the two functions
    /// involved): a brace that opens under `#ifndef SQLITE_OMIT_AUTHORIZATION`
    /// and closes under a second, identical `#ifndef SQLITE_OMIT_AUTHORIZATION`
    /// guard a few lines later can't be reconciled by tree-sitter-c without a
    /// real preprocessor. It emits a local error and `sqlite3InitOne`'s
    /// function_definition never closes normally, nesting `sqlite3Init` (and
    /// everything after it in the file) as a descendant. Without the
    /// has_error() guard, `sqlite3InitOne`'s callee set wrongly absorbs
    /// `sqlite3Init`'s calls too -- including a call back to `sqlite3InitOne`
    /// itself, producing a false self-recursion edge that doesn't exist in
    /// the source.
    #[test]
    #[cfg(feature = "lang-c")]
    fn c_ifdef_spanning_brace_does_not_leak_swallowed_sibling_calls() {
        let code = r#"int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
  int rc;
  int i;
#ifndef SQLITE_OMIT_DEPRECATED
  int size;
#endif
  Db *pDb;
  char const *azArg[6];
  int meta[5];
  InitData initData;
  const char *zSchemaTabName;
  int openedTransaction = 0;
  int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);

  assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
  assert( iDb>=0 && iDb<db->nDb );
  assert( db->aDb[iDb].pSchema );
  assert( sqlite3_mutex_held(db->mutex) );
  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );

  db->init.busy = 1;

  /* Construct the in-memory representation schema tables (sqlite_schema or
  ** sqlite_temp_schema) by invoking the parser directly.  The appropriate
  ** table name will be inserted automatically by the parser so we can just
  ** use the abbreviation "x" here.  The parser will also automatically tag
  ** the schema table as read-only. */
  azArg[0] = "table";
  azArg[1] = zSchemaTabName = SCHEMA_TABLE(iDb);
  azArg[2] = azArg[1];
  azArg[3] = "1";
  azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text,"
                            "rootpage int,sql text)";
  azArg[5] = 0;
  initData.db = db;
  initData.iDb = iDb;
  initData.rc = SQLITE_OK;
  initData.pzErrMsg = pzErrMsg;
  initData.mInitFlags = mFlags;
  initData.nInitRow = 0;
  initData.mxPage = 0;
  sqlite3InitCallback(&initData, 5, (char **)azArg, 0);
  db->mDbFlags &= mask;
  if( initData.rc ){
    rc = initData.rc;
    goto error_out;
  }

  /* Create a cursor to hold the database open
  */
  pDb = &db->aDb[iDb];
  if( pDb->pBt==0 ){
    assert( iDb==1 );
    DbSetProperty(db, 1, DB_SchemaLoaded);
    rc = SQLITE_OK;
    goto error_out;
  }

  /* If there is not already a read-only (or read-write) transaction opened
  ** on the b-tree database, open one now. If a transaction is opened, it
  ** will be closed before this function returns.  */
  sqlite3BtreeEnter(pDb->pBt);
  if( sqlite3BtreeTxnState(pDb->pBt)==SQLITE_TXN_NONE ){
    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
    if( rc!=SQLITE_OK ){
      sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
      goto initone_error_out;
    }
    openedTransaction = 1;
  }

  /* Get the database meta information.
  **
  ** Meta values are as follows:
  **    meta[0]   Schema cookie.  Changes with each schema change.
  **    meta[1]   File format of schema layer.
  **    meta[2]   Size of the page cache.
  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  **    meta[5]   User version
  **    meta[6]   Incremental vacuum mode
  **    meta[7]   unused
  **    meta[8]   unused
  **    meta[9]   unused
  **
  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  ** the possible values of meta[4].
  */
  for(i=0; i<ArraySize(meta); i++){
    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  }
  if( (db->flags & SQLITE_ResetDatabase)!=0 ){
    memset(meta, 0, sizeof(meta));
  }
  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];

  /* If opening a non-empty database, check the text encoding. For the
  ** main database, set sqlite3.enc to the encoding of the main database.
  ** For an attached db, it is an error if the encoding is not the same
  ** as sqlite3.enc.
  */
  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
    if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
      u8 encoding;
#ifndef SQLITE_OMIT_UTF16
      /* If opening the main database, set ENC(db). */
      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
      if( encoding==0 ) encoding = SQLITE_UTF8;
#else
      encoding = SQLITE_UTF8;
#endif
      sqlite3SetTextEncoding(db, encoding);
    }else{
      /* If opening an attached database, the encoding much match ENC(db) */
      if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){
        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
            " text encoding as main database");
        rc = SQLITE_ERROR;
        goto initone_error_out;
      }
    }
  }
  pDb->pSchema->enc = ENC(db);

  if( pDb->pSchema->cache_size==0 ){
#ifndef SQLITE_OMIT_DEPRECATED
    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
    pDb->pSchema->cache_size = size;
#else
    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
#endif
    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  }

  /*
  ** file_format==1    Version 3.0.0.
  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
  */
  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  if( pDb->pSchema->file_format==0 ){
    pDb->pSchema->file_format = 1;
  }
  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
    sqlite3SetString(pzErrMsg, db, "unsupported file format");
    rc = SQLITE_ERROR;
    goto initone_error_out;
  }

  /* Ticket #2804:  When we open a database in the newer file format,
  ** clear the legacy_file_format pragma flag so that a VACUUM will
  ** not downgrade the database and thus invalidate any descending
  ** indices that the user might have created.
  */
  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
    db->flags &= ~(u64)SQLITE_LegacyFileFmt;
  }

  /* Read the schema information out of the schema tables
  */
  assert( db->init.busy );
  initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
  {
    char *zSql;
    zSql = sqlite3MPrintf(db,
        "SELECT*FROM\"%w\".%s ORDER BY rowid",
        db->aDb[iDb].zDbSName, zSchemaTabName);
#ifndef SQLITE_OMIT_AUTHORIZATION
    {
      sqlite3_xauth xAuth;
      xAuth = db->xAuth;
      db->xAuth = 0;
#endif
      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
#ifndef SQLITE_OMIT_AUTHORIZATION
      db->xAuth = xAuth;
    }
#endif
    if( rc==SQLITE_OK ) rc = initData.rc;
    sqlite3DbFree(db, zSql);
#ifndef SQLITE_OMIT_ANALYZE
    if( rc==SQLITE_OK ){
      sqlite3AnalysisLoad(db, iDb);
    }
#endif
  }
  assert( pDb == &(db->aDb[iDb]) );
  if( db->mallocFailed ){
    rc = SQLITE_NOMEM_BKPT;
    sqlite3ResetAllSchemasOfConnection(db);
    pDb = &db->aDb[iDb];
  }else
  if( rc==SQLITE_OK || ((db->flags&SQLITE_NoSchemaError) && rc!=SQLITE_NOMEM)){
    /* Hack: If the SQLITE_NoSchemaError flag is set, then consider
    ** the schema loaded, even if errors (other than OOM) occurred. In
    ** this situation the current sqlite3_prepare() operation will fail,
    ** but the following one will attempt to compile the supplied statement
    ** against whatever subset of the schema was loaded before the error
    ** occurred.
    **
    ** The primary purpose of this is to allow access to the sqlite_schema
    ** table even when its contents have been corrupted.
    */
    DbSetProperty(db, iDb, DB_SchemaLoaded);
    rc = SQLITE_OK;
  }

  /* Jump here for an error that occurs after successfully allocating
  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  ** before that point, jump to error_out.
  */
initone_error_out:
  if( openedTransaction ){
    sqlite3BtreeCommit(pDb->pBt);
  }
  sqlite3BtreeLeave(pDb->pBt);

error_out:
  if( rc ){
    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
      sqlite3OomFault(db);
    }
    sqlite3ResetOneSchema(db, iDb);
  }
  db->init.busy = 0;
  return rc;
}

/*
** Initialize all database files - the main database file, the file
** used to store temporary tables, and any additional database files
** created using ATTACH statements.  Return a success code.  If an
** error occurs, write an error message into *pzErrMsg.
**
** After a database is initialized, the DB_SchemaLoaded bit is set
** bit is set in the flags field of the Db structure.
*/
int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  int i, rc;
  int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);

  assert( sqlite3_mutex_held(db->mutex) );
  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  assert( db->init.busy==0 );
  ENC(db) = SCHEMA_ENC(db);
  assert( db->nDb>0 );
  /* Do the main schema first */
  if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
    rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
    if( rc ) return rc;
  }
  /* All other schemas after the main schema. The "temp" schema must be last */
  for(i=db->nDb-1; i>0; i--){
    assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
    if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
      rc = sqlite3InitOne(db, i, pzErrMsg, 0);
      if( rc ) return rc;
    }
  }
  if( commit_internal ){
    sqlite3CommitInternalChanges(db);
  }
  return SQLITE_OK;
}

"#;
        let e = edges("c", code);
        // The real edge must still be found (via sqlite3Init's own, correctly
        // scoped span).
        assert!(e.contains(&CallEdge {
            caller: "sqlite3Init".into(),
            callee: "sqlite3InitOne".into(),
            is_external: false,
        }));
        // sqlite3InitOne must NOT be credited with calling itself -- that
        // edge only exists because the corrupted span swallowed sqlite3Init
        // (whose real body calls sqlite3InitOne) as a descendant. Crediting
        // it to sqlite3InitOne is exactly the false-recursion bug.
        assert!(!e
            .iter()
            .any(|c| c.caller == "sqlite3InitOne" && c.callee == "sqlite3InitOne"));
        // Likewise sqlite3CommitInternalChanges is only ever called from
        // sqlite3Init's real body, never sqlite3InitOne's.
        assert!(!e
            .iter()
            .any(|c| c.caller == "sqlite3InitOne" && c.callee == "sqlite3CommitInternalChanges"));
    }

    /// Regression for a second false-negative discovered while validating the
    /// has_error() fix above: sqlite3/src/vdbemem.c's
    /// valueFromExpr has an unrelated, separate parse error that makes
    /// tree-sitter-c mis-parse one of its `if` blocks as a
    /// function_definition-shaped node whose extracted "name" resolves to the
    /// keyword `if` itself. Without the is_error_recovery_debris() check, the
    /// naive stop-at-any-nested-function_definition guard treated that debris
    /// as a real swallowed sibling and stopped descending into it, silently
    /// dropping the real call to valueFromFunction that lives textually
    /// inside it.
    #[test]
    #[cfg(feature = "lang-c")]
    fn c_mis_parsed_if_does_not_lose_real_calls() {
        let code = r#"static int valueFromExpr(
  sqlite3 *db,                    /* The database connection */
  const Expr *pExpr,              /* The expression to evaluate */
  u8 enc,                         /* Encoding to use */
  u8 affinity,                    /* Affinity to use */
  sqlite3_value **ppVal,          /* Write the new value here */
  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
){
  int op;
  char *zVal = 0;
  sqlite3_value *pVal = 0;
  int negInt = 1;
  const char *zNeg = "";
  int rc = SQLITE_OK;

  assert( pExpr!=0 );
  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  if( op==TK_REGISTER ) op = pExpr->op2;

  /* Compressed expressions only appear when parsing the DEFAULT clause
  ** on a table column definition, and hence only when pCtx==0.  This
  ** check ensures that an EP_TokenOnly expression is never passed down
  ** into valueFromFunction(). */
  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );

  if( op==TK_CAST ){
    u8 aff;
    assert( !ExprHasProperty(pExpr, EP_IntValue) );
    aff = sqlite3AffinityType(pExpr->u.zToken,0);
    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
    testcase( rc!=SQLITE_OK );
    if( *ppVal ){
#ifdef SQLITE_ENABLE_STAT4
      rc = ExpandBlob(*ppVal);
#else
      /* zero-blobs only come from functions, not literal values.  And
      ** functions are only processed under STAT4 */
      assert( (ppVal[0][0].flags & MEM_Zero)==0 );
#endif
      sqlite3VdbeMemCast(*ppVal, aff, enc);
      sqlite3ValueApplyAffinity(*ppVal, affinity, enc);
    }
    return rc;
  }

  /* Handle negative integers in a single step.  This is needed in the
  ** case when the value is -9223372036854775808. Except - do not do this
  ** for hexadecimal literals.  */
  if( op==TK_UMINUS ){
    Expr *pLeft = pExpr->pLeft;
    if( (pLeft->op==TK_INTEGER || pLeft->op==TK_FLOAT) ){
      if( ExprHasProperty(pLeft, EP_IntValue)
       || pLeft->u.zToken[0]!='0' || (pLeft->u.zToken[1] & ~0x20)!='X'
      ){
        pExpr = pLeft;
        op = pExpr->op;
        negInt = -1;
        zNeg = "-";
      }
    }
  }

  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
    pVal = valueNew(db, pCtx);
    if( pVal==0 ) goto no_mem;
    if( ExprHasProperty(pExpr, EP_IntValue) ){
      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
    }else{
      i64 iVal;
      if( op==TK_INTEGER && 0==sqlite3DecOrHexToI64(pExpr->u.zToken, &iVal) ){
        sqlite3VdbeMemSetInt64(pVal, iVal*negInt);
      }else{
        zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
        if( zVal==0 ) goto no_mem;
        sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
      }
    }
    if( affinity==SQLITE_AFF_BLOB ){
      if( op==TK_FLOAT ){
        assert( pVal && pVal->z && pVal->flags==(MEM_Str|MEM_Term) );
        sqlite3AtoF(pVal->z, &pVal->u.r);
        pVal->flags = MEM_Real;
      }else if( op==TK_INTEGER ){
        /* This case is required by -9223372036854775808 and other strings
        ** that look like integers but cannot be handled by the
        ** sqlite3DecOrHexToI64() call above.  */
        sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
      }
    }else{
      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
    }
    assert( (pVal->flags & MEM_IntReal)==0 );
    if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
      testcase( pVal->flags & MEM_Int );
      testcase( pVal->flags & MEM_Real );
      pVal->flags &= ~MEM_Str;
    }
    if( enc!=SQLITE_UTF8 ){
      rc = sqlite3VdbeChangeEncoding(pVal, enc);
    }
  }else if( op==TK_UMINUS ) {
    /* This branch happens for multiple negative signs.  Ex: -(-5) */
    if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
     && pVal!=0
    ){
      sqlite3VdbeMemNumerify(pVal);
      if( pVal->flags & MEM_Real ){
        pVal->u.r = -pVal->u.r;
      }else if( pVal->u.i==SMALLEST_INT64 ){
#ifndef SQLITE_OMIT_FLOATING_POINT
        pVal->u.r = -(double)SMALLEST_INT64;
#else
        pVal->u.r = LARGEST_INT64;
#endif
        MemSetTypeFlag(pVal, MEM_Real);
      }else{
        pVal->u.i = -pVal->u.i;
      }
      sqlite3ValueApplyAffinity(pVal, affinity, enc);
    }
  }else if( op==TK_NULL ){
    pVal = valueNew(db, pCtx);
    if( pVal==0 ) goto no_mem;
    sqlite3VdbeMemSetNull(pVal);
  }
#ifndef SQLITE_OMIT_BLOB_LITERAL
  else if( op==TK_BLOB ){
    int nVal;
    assert( !ExprHasProperty(pExpr, EP_IntValue) );
    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
    assert( pExpr->u.zToken[1]=='\'' );
    pVal = valueNew(db, pCtx);
    if( !pVal ) goto no_mem;
    zVal = &pExpr->u.zToken[2];
    nVal = sqlite3Strlen30(zVal)-1;
    assert( zVal[nVal]=='\'' );
    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
                         0, SQLITE_DYNAMIC);
  }
#endif
#ifdef SQLITE_ENABLE_STAT4
  else if( op==TK_FUNCTION && pCtx!=0 ){
    rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  }
#endif
  else if( op==TK_TRUEFALSE ){
    assert( !ExprHasProperty(pExpr, EP_IntValue) );
    pVal = valueNew(db, pCtx);
    if( pVal ){
      pVal->flags = MEM_Int;
      pVal->u.i = pExpr->u.zToken[4]==0;
      sqlite3ValueApplyAffinity(pVal, affinity, enc);
    }
  }

  *ppVal = pVal;
  return rc;

no_mem:
#ifdef SQLITE_ENABLE_STAT4
  if( pCtx==0 || NEVER(pCtx->pParse->nErr==0) )
#endif
    sqlite3OomFault(db);
  sqlite3DbFree(db, zVal);
  assert( *ppVal==0 );
#ifdef SQLITE_ENABLE_STAT4
  if( pCtx==0 ) sqlite3ValueFree(pVal);
#else
  assert( pCtx==0 ); sqlite3ValueFree(pVal);
#endif
  return SQLITE_NOMEM_BKPT;
}

/*
"#;
        let e = edges("c", code);
        assert!(
            e.iter()
                .any(|c| c.caller == "valueFromExpr" && c.callee == "valueFromFunction"),
            "real call inside a mis-parsed if-block was dropped"
        );
    }

    #[test]
    #[cfg(feature = "lang-c")]
    fn c_resolves_fn_ptr_alias() {
        // Juliet variant 65a pattern: function pointer assigned to a sink
        // function, then invoked via the pointer. The call graph should
        // record the underlying function as a callee of `caller`, not `fp`.
        let code = "void target(char *d) {}\n\
                    void caller(void) {\n\
                        void (*fp)(char *) = target;\n\
                        char *data = 0;\n\
                        fp(data);\n\
                    }";
        let e = edges("c", code);
        assert!(
            e.iter()
                .any(|c| c.caller == "caller" && c.callee == "target"),
            "expected 'target' as a callee of 'caller', got {e:?}"
        );
        assert!(
            !e.iter().any(|c| c.callee == "fp"),
            "the raw pointer name 'fp' should never appear as a callee: {e:?}"
        );
    }

    #[test]
    #[cfg(feature = "lang-c")]
    fn c_resolves_fn_ptr_address_of() {
        // Initializer uses the address-of form `&target`, exercising the
        // unary-argument unwrap in rhs_target_function_name.
        let code = "void target(int x) {}\n\
                    void caller(void) {\n\
                        int (*fp)(int) = &target;\n\
                        fp(1);\n\
                    }";
        let e = edges("c", code);
        assert!(
            e.iter()
                .any(|c| c.caller == "caller" && c.callee == "target"),
            "expected 'target' as a callee of 'caller', got {e:?}"
        );
    }

    #[test]
    #[cfg(feature = "lang-c")]
    fn c_plain_pointer_not_aliased() {
        // A plain pointer assignment `int *p = &x;` is not a function
        // pointer -- make sure we don't pollute the call graph with `x`
        // as a callee just because p is later indirected somehow.
        let code = "void caller(void) {\n\
                        int x = 0;\n\
                        int *p = &x;\n\
                        *p = 1;\n\
                    }";
        let e = edges("c", code);
        assert!(
            !e.iter().any(|c| c.callee == "x"),
            "plain pointer decl should not produce a callee edge: {e:?}"
        );
    }
}