relay-knowledge 1.1.16

Graph-database-based knowledge graph project.
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
use crate::domain::{CodeParseStatus, CodeRepositoryRegistration};

use super::*;

#[test]
fn c_macro_recovery_keeps_pascal_callback_and_skips_registration_macros() {
    let snapshot = parse_source_snapshot(
        "src/callbacks.c",
        br#"
DECLARE_CALLBACK(HandlerFn, Context *);
DECLARE_CALLBACK(PlainHandlerFn, Context);
REGISTER_HANDLER(rk_registered_handler);
"#,
    );

    assert!(
        snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "function" && symbol.name == "HandlerFn"),
        "PascalCase callback names should remain callable symbols: {:?}",
        snapshot.symbols
    );
    assert!(
        snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "function" && symbol.name == "PlainHandlerFn"),
        "plain context callback arguments should not replace the callback symbol: {:?}",
        snapshot.symbols
    );
    assert!(
        !snapshot.symbols.iter().any(|symbol| {
            symbol.kind == "function"
                && matches!(symbol.name.as_str(), "Context" | "rk_registered_handler")
        }),
        "type arguments and registration macros should not become function definitions: {:?}",
        snapshot.symbols
    );
}

#[test]
fn c_family_recoverable_line_accepts_declspec_prefix_payloads() {
    assert!(recoverable_c_family_error_line(
        "__declspec(dllexport) class ExportedWidget {"
    ));
    assert!(recoverable_c_family_error_line(
        "__attribute__((visibility(\"default\"))) class ExportedWidget {"
    ));
    assert!(!recoverable_c_family_error_line(
        "HTTP_MODULE class ExportedWidget {"
    ));
    assert!(!recoverable_c_family_error_line(
        "struct __kernel_timespec {"
    ));
}

#[test]
fn c_family_recoverable_line_accepts_external_typedef_shapes() {
    assert!(recoverable_c_family_error_line(
        "static ngx_int_t ngx_http_demo_init(ngx_pool_t *pool)"
    ));
    assert!(recoverable_c_family_error_line(
        "ngx_module_t ngx_http_demo_module = {"
    ));
    assert!(!recoverable_c_family_error_line("ngx_pool_t *pool;"));
    assert!(!recoverable_c_family_error_line(
        "return ngx_int_t handler(req)"
    ));
    assert!(!recoverable_c_family_error_line("ngx_int_t broken_call("));
    assert!(!recoverable_c_family_error_line(
        "ngx_int_t handler(req) + expr"
    ));
    assert!(!recoverable_c_family_error_line(
        "ngx_int_t broken_value = ;"
    ));
}

#[test]
fn c_external_header_macro_file_keeps_structured_facts() {
    let snapshot = parse_source_snapshot(
        "src/ngx_http_demo_module.c",
        br#"
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>

#define KONG_ACCESS_PHASE(name) static ngx_int_t name(ngx_http_request_t *request)

static ngx_int_t
ngx_http_demo_init(ngx_pool_t *pool)
{
    return ngx_array_init(pool);
}

KONG_ACCESS_PHASE(ngx_http_demo_access)
{
    return ngx_http_demo_init(request->pool);
}

static ngx_command_t ngx_http_demo_commands[] = {
    { ngx_string("demo"), NGX_HTTP_LOC_CONF, ngx_conf_set_str_slot, 0, 0, NULL },
    ngx_null_command
};

static ngx_http_module_t ngx_http_demo_module_ctx = {
    NULL,
    ngx_http_demo_init,
    NULL,
    NULL
};

ngx_module_t ngx_http_demo_module = {
    NGX_MODULE_V1,
    &ngx_http_demo_module_ctx,
    ngx_http_demo_commands,
    NGX_HTTP_MODULE,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NGX_MODULE_V1_PADDING
};
"#,
    );

    assert_eq!(
        snapshot.files[0].parse_status,
        CodeParseStatus::Parsed,
        "external typedef and macro recovery should avoid file degradation: {:?}",
        snapshot.diagnostics
    );
    assert!(snapshot.files[0].degraded_reason.is_none());
    for name in [
        "ngx_http_demo_init",
        "ngx_http_demo_access",
        "ngx_http_demo_commands",
        "ngx_http_demo_module_ctx",
        "ngx_http_demo_module",
    ] {
        assert!(
            snapshot.symbols.iter().any(|symbol| symbol.name == name),
            "{name} should be extracted as structured code graph evidence: {:?}",
            snapshot.symbols
        );
    }
    assert!(
        snapshot.calls.iter().any(|call| {
            call.caller_name.as_deref() == Some("ngx_http_demo_access")
                && call.callee_name == "ngx_http_demo_init"
        }),
        "macro-with-body definitions should own calls in their body: {:?}",
        snapshot.calls
    );
    assert!(
        snapshot.imports.iter().any(|import| {
            import.module.contains("ngx_http.h") && import.resolution_state == "unresolved"
        }),
        "external headers should remain unresolved import metadata: {:?}",
        snapshot.imports
    );
}

#[test]
fn c_gcc_attribute_inline_functions_recover_as_parsed() {
    let snapshot = parse_source_snapshot(
        "external_deps/sdk/policy_match.c",
        br#"
#include "securec.h"

#define WILD_MULTI_CHAR '*'

typedef struct PdpString {
    const char *data;
} PdpString;

typedef struct PdpStack PdpStack;

typedef struct PdpPolicyEntry {
    const char *name;
    int (*match)(PdpStack *stack, PdpString *pattern);
} PdpPolicyEntry;

static attribute((always_inline)) int pdp_wildcard_step(PdpString *pattern, int index)
{
    return pattern->data[index] == WILD_MULTI_CHAR;
}

static __attribute__((always_inline)) int pdp_secure_copy(PdpString *target, const PdpString *source)
{
    return memcpy_s((void *)target->data, 16, source->data, 16);
}

__always_inline int pdp_policy_regex_match(PdpStack *stack, PdpString *pattern)
{
    (void)stack;
    return pdp_wildcard_step(pattern, 0) || pdp_secure_copy(pattern, pattern);
}

static PdpPolicyEntry pdp_policy_entries[] = {
    { "wildcard", pdp_policy_regex_match },
};
"#,
    );

    assert_eq!(
        snapshot.files[0].parse_status,
        CodeParseStatus::Parsed,
        "GCC compiler extension recovery should keep structured files non-degraded: {:?}",
        snapshot.diagnostics
    );
    assert!(snapshot.files[0].degraded_reason.is_none());
    for name in [
        "pdp_wildcard_step",
        "pdp_secure_copy",
        "pdp_policy_regex_match",
        "pdp_policy_entries",
    ] {
        assert!(
            snapshot.symbols.iter().any(|symbol| symbol.name == name),
            "{name} should be extracted as structured evidence: {:?}",
            snapshot.symbols
        );
    }
    assert!(
        snapshot.calls.iter().any(|call| {
            call.caller_name.as_deref() == Some("pdp_policy_regex_match")
                && call.callee_name == "pdp_wildcard_step"
        }),
        "GCC-decorated function bodies should keep call ownership: {:?}",
        snapshot.calls
    );
    assert!(
        snapshot.imports.iter().any(|import| {
            import.module.contains("securec.h") && import.resolution_state == "unresolved"
        }),
        "missing SDK headers should stay unresolved import metadata: {:?}",
        snapshot.imports
    );
}

#[test]
fn c_gcc_attribute_broken_assignment_stays_partial() {
    let snapshot = parse_source_snapshot(
        "external_deps/sdk/broken_policy.c",
        br#"
#include "securec.h"

int valid_policy_symbol(void)
{
    return 1;
}

attribute((always_inline)) int broken_policy_value = ;
"#,
    );

    assert_eq!(
        snapshot.files[0].parse_status,
        CodeParseStatus::Partial,
        "broken assignments must not be hidden by compiler-extension recovery"
    );
    assert!(
        snapshot
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.message.contains("error nodes"))
    );
}

#[test]
fn c_gcc_recovery_handles_postfix_attribute_and_pascal_return_prefix() {
    let snapshot = parse_source_snapshot(
        "external_deps/sdk/postfix_policy.c",
        br#"
typedef struct PdpStack PdpStack;

typedef struct PdpPolicyEntry {
    int value;
} PdpPolicyEntry;

int pdp_postfix_policy(void) attribute((always_inline))
{
    return 1;
}

PdpPolicyEntry PdpPolicy(PdpStack *stack)
{
    (void)stack;
    return (PdpPolicyEntry){ 7 };
}
"#,
    );

    assert_eq!(
        snapshot.files[0].parse_status,
        CodeParseStatus::Parsed,
        "postfix attributes and PascalCase return prefixes should recover without degradation: {:?}",
        snapshot.diagnostics
    );
    for name in ["pdp_postfix_policy", "PdpPolicy"] {
        assert!(
            snapshot
                .symbols
                .iter()
                .any(|symbol| symbol.kind == "function" && symbol.name == name),
            "{name} should be recovered from the real declarator slot: {:?}",
            snapshot.symbols
        );
    }
}

#[test]
fn c_gcc_recovery_handles_literals_tag_returns_and_tail_validation() {
    let literal_snapshot = parse_source_snapshot(
        "external_deps/sdk/literal_policy.c",
        br#"
struct PdpPolicyToken {
    int value;
};

attribute((always_inline)) int pdp_literal_policy(int ch)
{
    const char *marker = "[";
    return ch == '(' || marker[0] == '[';
}

__always_inline struct PdpPolicyToken *make_pdp_policy_token(void)
{
    return 0;
}
"#,
    );

    assert_eq!(
        literal_snapshot.files[0].parse_status,
        CodeParseStatus::Parsed,
        "valid literals and C tag return types should not block GCC recovery: {:?}",
        literal_snapshot.diagnostics
    );
    for name in ["pdp_literal_policy", "make_pdp_policy_token"] {
        assert!(
            literal_snapshot
                .symbols
                .iter()
                .any(|symbol| symbol.kind == "function" && symbol.name == name),
            "{name} should be recovered from GCC-decorated C code: {:?}",
            literal_snapshot.symbols
        );
    }

    let malformed_tail = parse_source_snapshot(
        "external_deps/sdk/malformed_postfix_policy.c",
        br#"
int pdp_bad_tail(void) attribute((always_inline)) garbage
@
{
    return 1;
}
"#,
    );

    assert_eq!(
        malformed_tail.files[0].parse_status,
        CodeParseStatus::Partial,
        "malformed postfix attribute tails must not be accepted as recoverable"
    );
    assert!(
        !c_family_typedef_like_function_signature(
            "int pdp_bad_tail(void) attribute((always_inline)) garbage"
        ),
        "postfix attribute tail validation must consume the full suffix"
    );
}

#[test]
fn c_gcc_recovery_rejects_malformed_function_body_lines() {
    let snapshot = parse_source_snapshot(
        "external_deps/sdk/broken_body_policy.c",
        br#"
attribute((always_inline)) int pdp_broken_body_policy(void)
{
    int missing_semicolon
    return 1;
}
"#,
    );

    assert_eq!(
        snapshot.files[0].parse_status,
        CodeParseStatus::Partial,
        "malformed function bodies must not be hidden by GCC recovery"
    );
    assert!(
        snapshot
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.message.contains("error nodes"))
    );
}

#[test]
fn cpp_gcc_inline_extension_functions_recover_as_parsed() {
    let snapshot = parse_source_snapshot(
        "external_deps/sdk/PolicyStrRegexMatch.cpp",
        br#"
#include <string>

template <typename T>
class PdpStack {
 public:
    int Size() const;
};

class PdpString {};

namespace ns {
class PdpScopedStack {
 public:
    int Size() const;
};
}

__always_inline int PolicyStrRegexMatch(PdpStack<PdpString> *stack)
{
    return stack->Size();
}

__always_inline int ns::QualifiedPolicyStrRegexMatch(ns::PdpScopedStack *stack)
{
    return stack->Size();
}

__always_inline std::string BuildPolicyName()
{
    return std::string();
}
"#,
    );

    assert_eq!(
        snapshot.files[0].parse_status,
        CodeParseStatus::Parsed,
        "C++ GCC inline extensions should not force file degradation: {:?}",
        snapshot.diagnostics
    );
    for name in [
        "PolicyStrRegexMatch",
        "QualifiedPolicyStrRegexMatch",
        "BuildPolicyName",
    ] {
        assert!(
            snapshot.symbols.iter().any(|symbol| {
                matches!(symbol.kind.as_str(), "function" | "method") && symbol.name == name
            }),
            "{name} should be recovered from GCC-decorated C++ code: {:?}",
            snapshot.symbols
        );
    }
    assert!(
        !snapshot.symbols.iter().any(|symbol| {
            symbol.kind == "function"
                && symbol.name == "ns"
                && symbol.signature.contains("QualifiedPolicyStrRegexMatch")
        }),
        "qualified declarators must not recover the namespace qualifier as a function: {:?}",
        snapshot.symbols
    );
}

#[test]
fn c_macro_body_recovery_requires_definition_style_macro_name() {
    let snapshot = parse_source_snapshot(
        "src/generic_block_macro.c",
        br#"
#define MODULE_ACCESS_PHASE(name) name

static ngx_int_t
ngx_http_demo_init(ngx_pool_t *pool)
{
    return ngx_array_init(pool);
}

MODULE_ACCESS_PHASE(ngx_http_demo_access)
{
    ngx_http_demo_init(0);
}
"#,
    );

    assert!(
        !snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "function" && symbol.name == "ngx_http_demo_access"),
        "generic block macros should not become function definitions: {:?}",
        snapshot.symbols
    );
    assert!(
        !snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "function" && symbol.name == "MODULE_ACCESS_PHASE"),
        "generic block macro names should not fall back to function definitions: {:?}",
        snapshot.symbols
    );
    assert!(
        !snapshot.calls.iter().any(|call| {
            call.caller_name.as_deref() == Some("ngx_http_demo_access")
                && call.callee_name == "ngx_http_demo_init"
        }),
        "generic block macros should not own call graph edges: {:?}",
        snapshot.calls
    );
}

#[test]
fn c_macro_body_recovery_reads_continued_function_macro_definition() {
    let snapshot = parse_source_snapshot(
        "src/continued_macro_module.c",
        br#"
#define KONG_ACCESS_PHASE(name) \
    static ngx_int_t name(ngx_http_request_t *request)

static ngx_int_t
ngx_http_demo_init(ngx_pool_t *pool)
{
    return ngx_array_init(pool);
}

KONG_ACCESS_PHASE(ngx_http_demo_access)
{
    return ngx_http_demo_init(request->pool);
}
"#,
    );

    assert!(
        snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "function" && symbol.name == "ngx_http_demo_access"),
        "continued function macro definitions should recover the handler symbol: {:?}",
        snapshot.symbols
    );
    assert!(
        snapshot.calls.iter().any(|call| {
            call.caller_name.as_deref() == Some("ngx_http_demo_access")
                && call.callee_name == "ngx_http_demo_init"
        }),
        "continued function macro definitions should own calls in the body: {:?}",
        snapshot.calls
    );
}

#[test]
fn c_macro_body_recovery_reads_spaced_define_directive() {
    let snapshot = parse_source_snapshot(
        "src/spaced_define_macro_module.c",
        br#"
# define KONG_ACCESS_PHASE(name) static ngx_int_t name(ngx_http_request_t *request)

static ngx_int_t
ngx_http_demo_init(ngx_pool_t *pool)
{
    return ngx_array_init(pool);
}

KONG_ACCESS_PHASE(ngx_http_demo_access)
{
    return ngx_http_demo_init(request->pool);
}
"#,
    );

    assert!(
        snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "function" && symbol.name == "ngx_http_demo_access"),
        "spaced define directives should recover the handler symbol: {:?}",
        snapshot.symbols
    );
    assert!(
        snapshot.calls.iter().any(|call| {
            call.caller_name.as_deref() == Some("ngx_http_demo_access")
                && call.callee_name == "ngx_http_demo_init"
        }),
        "spaced define directives should own calls in the body: {:?}",
        snapshot.calls
    );
}

#[test]
fn c_macro_body_recovery_ignores_undef_and_inactive_macro_definitions() {
    let snapshot = parse_source_snapshot(
        "src/inactive_macro_module.c",
        br#"
#define KONG_ACCESS_PHASE(name) static ngx_int_t name(ngx_http_request_t *request)
#undef KONG_ACCESS_PHASE

#if 0
#define HIDDEN_PHASE(name) static ngx_int_t name(ngx_http_request_t *request)
#endif

#ifdef NEVER_DEFINED
#define CONDITIONAL_PHASE(name) static ngx_int_t name(ngx_http_request_t *request)
#endif

#define FEATURE_FLAG 0
#if FEATURE_FLAG
#define NUMERIC_FALSE_PHASE(name) static ngx_int_t name(ngx_http_request_t *request)
#endif

#define ENABLE_A 1
#if defined(ENABLE_A) && defined(ENABLE_B)
#define COMPOUND_DEFINED_PHASE(name) static ngx_int_t name(ngx_http_request_t *request)
#endif

static ngx_int_t
ngx_http_demo_init(ngx_pool_t *pool)
{
    return ngx_array_init(pool);
}

KONG_ACCESS_PHASE(ngx_http_after_undef)
{
    return ngx_http_demo_init(request->pool);
}

HIDDEN_PHASE(ngx_http_inactive_if)
{
    return ngx_http_demo_init(request->pool);
}

CONDITIONAL_PHASE(ngx_http_inactive_ifdef)
{
    return ngx_http_demo_init(request->pool);
}

NUMERIC_FALSE_PHASE(ngx_http_numeric_false)
{
    return ngx_http_demo_init(request->pool);
}

COMPOUND_DEFINED_PHASE(ngx_http_compound_defined_false)
{
    return ngx_http_demo_init(request->pool);
}
"#,
    );

    for name in [
        "ngx_http_after_undef",
        "ngx_http_inactive_if",
        "ngx_http_inactive_ifdef",
        "ngx_http_numeric_false",
        "ngx_http_compound_defined_false",
    ] {
        assert!(
            !snapshot
                .symbols
                .iter()
                .any(|symbol| symbol.kind == "function" && symbol.name == name),
            "inactive or undefined macros should not recover handler symbols: {:?}",
            snapshot.symbols
        );
        assert!(
            !snapshot
                .calls
                .iter()
                .any(|call| call.caller_name.as_deref() == Some(name)),
            "inactive or undefined macros should not own call graph edges: {:?}",
            snapshot.calls
        );
    }
}

#[test]
fn c_macro_body_recovery_reads_comparison_and_continued_if_conditions() {
    let snapshot = parse_source_snapshot(
        "src/conditional_macro_module.c",
        br#"
#define FEATURE_FLAG 1
#define EXTRA_FLAG 1
#define VERSION 3

#if FEATURE_FLAG == 1 && VERSION >= 2
#define COMPARISON_PHASE(name) static ngx_int_t name(ngx_http_request_t *request)
#endif

#if FEATURE_FLAG \
    && EXTRA_FLAG
#define CONTINUED_IF_PHASE(name) static ngx_int_t name(ngx_http_request_t *request)
#endif

static ngx_int_t
ngx_http_demo_init(ngx_pool_t *pool)
{
    return ngx_array_init(pool);
}

COMPARISON_PHASE(ngx_http_comparison_access)
{
    return ngx_http_demo_init(request->pool);
}

CONTINUED_IF_PHASE(ngx_http_continued_if_access)
{
    return ngx_http_demo_init(request->pool);
}
"#,
    );

    for name in ["ngx_http_comparison_access", "ngx_http_continued_if_access"] {
        assert!(
            snapshot
                .symbols
                .iter()
                .any(|symbol| symbol.kind == "function" && symbol.name == name),
            "active conditional macros should recover handler symbols: {:?}",
            snapshot.symbols
        );
        assert!(
            snapshot.calls.iter().any(|call| {
                call.caller_name.as_deref() == Some(name)
                    && call.callee_name == "ngx_http_demo_init"
            }),
            "active conditional macros should own call graph edges: {:?}",
            snapshot.calls
        );
    }
}

#[test]
fn c_macro_body_recovery_falls_back_after_unavailable_macro_history() {
    let snapshot = parse_source_snapshot(
        "src/uppercase_function_after_undef.c",
        br#"
#define KONG_ACCESS_PHASE(name) static ngx_int_t name(ngx_http_request_t *request)
#undef KONG_ACCESS_PHASE

KONG_ACCESS_PHASE(request)
{
    return request != 0;
}
"#,
    );

    assert!(
        snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "function" && symbol.name == "KONG_ACCESS_PHASE"),
        "unavailable macro history should still allow real declarator fallback: {:?}",
        snapshot.symbols
    );
    assert!(
        !snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "function" && symbol.name == "request"),
        "fallback should not turn the K&R parameter into a function symbol: {:?}",
        snapshot.symbols
    );
}

#[test]
fn cpp_manual_recovery_keeps_elaborated_return_type_functions() {
    let snapshot = parse_source_snapshot(
        "src/factory.cpp",
        br#"
class FactoryResult {};

class FactoryResult make_factory_result()
{
    return FactoryResult();
}
"#,
    );

    assert!(
        snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "function" && symbol.name == "make_factory_result"),
        "elaborated return types should not hide function definitions: {:?}",
        snapshot.symbols
    );
}

#[test]
fn cpp_manual_recovery_keeps_prefixed_elaborated_return_type_functions() {
    let snapshot = parse_source_snapshot(
        "src/prefixed_factory.cpp",
        br#"
#define RK_API __attribute__((visibility("default")))

class FactoryResult {};

RK_API class FactoryResult make_factory_result()
{
    return FactoryResult();
}
"#,
    );

    assert!(
        snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "function" && symbol.name == "make_factory_result"),
        "visibility prefixes should not route elaborated-return functions into type recovery: {:?}",
        snapshot.symbols
    );
    assert_eq!(
        snapshot
            .symbols
            .iter()
            .filter(|symbol| symbol.kind == "class" && symbol.name == "FactoryResult")
            .count(),
        1,
        "the return type should not be emitted again as the prefixed function definition"
    );
}

#[test]
fn cpp_decorated_type_recovery_rejects_broken_member_bodies() {
    let snapshot = parse_source_snapshot(
        "include/broken_exported.hpp",
        br#"
__declspec(dllexport) class BrokenWidget {
 public:
    void Run(;
};
"#,
    );

    assert_eq!(
        snapshot.files[0].parse_status,
        CodeParseStatus::Partial,
        "broken member syntax should keep diagnostics visible: symbols={:?}; diagnostics={:?}",
        snapshot.symbols,
        snapshot.diagnostics
    );
    assert!(
        snapshot
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.message.contains("error nodes")),
        "unrecoverable decorated type bodies should report parser diagnostics"
    );
}

#[test]
fn cpp_declspec_prefix_type_recovery_accepts_payload_tokens() {
    let snapshot = parse_source_snapshot(
        "include/exported.hpp",
        br#"
__declspec(dllexport) class ExportedWidget {
 public:
    void Run();
};
"#,
    );

    assert_eq!(
        snapshot.files[0].parse_status,
        CodeParseStatus::Parsed,
        "symbols={:?}; diagnostics={:?}",
        snapshot.symbols,
        snapshot.diagnostics
    );
    assert!(
        snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "class" && symbol.name == "ExportedWidget"),
        "__declspec payload tokens should not block type recovery: {:?}",
        snapshot.symbols
    );
}

#[test]
fn cpp_attribute_prefix_type_recovery_accepts_payload_tokens() {
    let snapshot = parse_source_snapshot(
        "include/attribute_exported.hpp",
        br#"
__attribute__((visibility("default"))) class AttributeWidget final {
 public:
    void Run();
};
"#,
    );

    assert_eq!(
        snapshot.files[0].parse_status,
        CodeParseStatus::Parsed,
        "symbols={:?}; diagnostics={:?}",
        snapshot.symbols,
        snapshot.diagnostics
    );
    assert!(
        snapshot
            .symbols
            .iter()
            .any(|symbol| symbol.kind == "class" && symbol.name == "AttributeWidget"),
        "__attribute__ payload tokens should not block type recovery: {:?}",
        snapshot.symbols
    );
}

#[test]
fn cpp_manual_recovery_uses_terminal_qualified_type_name() {
    let content = "class A::B { int value; };";
    let language = detect_language("src/qualified.cpp").expect("C++ should be configured");
    let parsed = parse_tree(language, content).expect("C++ should parse");
    let class_node = first_node_of_kind(parsed.root_node(), "class_specifier")
        .expect("qualified class definition should be present");

    let manual = manual_definitions(content, language.id, class_node);

    assert!(
        manual
            .iter()
            .any(|(name, kind, _)| name == "B" && *kind == "class"),
        "qualified type recovery should use the terminal declared name: {:?}",
        manual
    );
    assert!(
        !manual
            .iter()
            .any(|(name, kind, _)| name == "A" && *kind == "class"),
        "qualified type recovery should not stop at the qualifier namespace/type"
    );
}

#[test]
fn cpp_manual_recovery_keeps_type_name_before_inheritance() {
    let content = "class HTTP_MODULE : public BaseModule { int value; };";
    let language = detect_language("src/inherited.cpp").expect("C++ should be configured");
    let parsed = parse_tree(language, content).expect("C++ should parse");
    let class_node = first_node_of_kind(parsed.root_node(), "class_specifier")
        .expect("inherited class definition should be present");

    let manual = manual_definitions(content, language.id, class_node);

    assert!(
        manual
            .iter()
            .any(|(name, kind, _)| name == "HTTP_MODULE" && *kind == "class"),
        "inheritance should not make a later base type replace the class name: {:?}",
        manual
    );
    assert!(
        !manual
            .iter()
            .any(|(name, kind, _)| name == "BaseModule" && *kind == "class"),
        "base classes should not become recovered class definitions"
    );
}

fn parse_source_snapshot(path: &str, source: &[u8]) -> crate::domain::CodeIndexSnapshot {
    let registration =
        CodeRepositoryRegistration::new("repo", "alias", "/tmp/repo", Vec::new(), Vec::new())
            .expect("registration should validate");
    let mut build = SnapshotBuild::new(
        &registration,
        "commit".to_owned(),
        "tree".to_owned(),
        true,
        1,
        0,
    );

    parse_indexed_file(&mut build, path, source).expect("file should parse");

    build.finish()
}

fn first_node_of_kind<'tree>(
    root: tree_sitter::Node<'tree>,
    kind: &str,
) -> Option<tree_sitter::Node<'tree>> {
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if node.kind() == kind {
            return Some(node);
        }
        push_children_reverse(node, &mut stack);
    }

    None
}