bonsai-ninja-lang-java 0.3.1

Java language adapter.
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
use bonsai_conformance::run_language_suite;
use std::sync::Arc;

#[test]
fn conformance_traced() {
    let adapter: Arc<dyn bonsai_lang_api::LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    run_language_suite!(
        adapter,
        trace_from = "main",
        [("A.java", "class A { public static void main(String[] s) {} }")]
    );
}

#[test]
fn ternary_call_argument_retains_the_dynamic_branch_as_compiler_flow() {
    let workspace = bonsai_testkit::workspace_with(
        vec![Arc::new(bonsai_lang_java::JavaAdapter::new())],
        &[(
            "Ternary.java",
            r#"
class Ternary {
  String escape(String q) {
    String safe = HtmlUtils.htmlEscape(q == null ? "" : q);
    String body = "<p>" + safe + "</p>";
    return ResponseEntity.ok(body);
  }
}
"#,
        )],
    );
    let file = workspace.db().vfs().all_files()[0];
    let index = workspace.db().decl_index(file).expect("Java compiler index");
    let escape = index
        .defs
        .iter()
        .find(|decl| decl.name == "escape")
        .expect("escape declaration");
    let (call_span, argument) = escape
        .flow_events
        .iter()
        .find_map(|event| match event {
            bonsai_lang_api::FlowEvent::Call { name, span, args, .. } if name == "HtmlUtils.htmlEscape" => {
                args.first().map(|argument| (*span, argument))
            }
            _ => None,
        })
        .expect("HtmlUtils call argument");
    assert!(
        argument.source_names.iter().any(|source| source == "q"),
        "the dynamic ternary branch must reach the call argument: {argument:#?}"
    );
    let value = bonsai_lang_api::call_argument_value_fact(&index.call_argument_values, call_span, 0)
        .expect("exact call-argument value fact");
    assert!(
        value.value_flow.source_names.iter().any(|source| source == "q")
            || value.value_flow.place.as_deref() == Some("q"),
        "the parsed ternary value must retain its dynamic branch: {value:#?}"
    );
    let body_assignment = escape
        .flow_events
        .iter()
        .find_map(|event| match event {
            bonsai_lang_api::FlowEvent::Assign {
                target, source_names, ..
            } if target == "body" => Some(source_names),
            _ => None,
        })
        .expect("body assignment");
    assert!(
        body_assignment.iter().any(|source| source == "safe"),
        "string composition must retain the sanitized binding: {body_assignment:#?}"
    );
    let response_argument = escape
        .flow_events
        .iter()
        .find_map(|event| match event {
            bonsai_lang_api::FlowEvent::Call { name, args, .. } if name == "ResponseEntity.ok" => {
                args.first()
            }
            _ => None,
        })
        .expect("ResponseEntity.ok argument");
    assert!(
        response_argument
            .source_names
            .iter()
            .any(|source| source == "body")
            || response_argument.place.as_deref() == Some("body"),
        "the response call must read the composed body: {response_argument:#?}"
    );
}

#[test]
fn inline_callbacks_expose_only_complete_exact_scalar_returns() {
    use bonsai_lang_api::StaticScalarValue;

    let workspace = bonsai_testkit::workspace_with(
        vec![Arc::new(bonsai_lang_java::JavaAdapter::new())],
        &[(
            "Callbacks.java",
            r#"
interface Check { boolean test(boolean value); }
class Consumer { static void use(Check check) {} }
class App {
  static boolean named(boolean value) { return true; }
  void configure() {
    Consumer.use(value -> true);
    Consumer.use(value -> false);
    Consumer.use(value -> { return true; });
    Consumer.use(value -> { if (value) return true; return false; });
    Consumer.use(value -> value ? true : false);
    Consumer.use(App::named);
  }
}
"#,
        )],
    );
    let file = workspace.db().vfs().all_files()[0];
    let source = workspace.db().vfs().snapshot(file).expect("fixture source");
    let index = workspace.db().decl_index(file).expect("Java compiler index");
    let callback_return = |needle: &str| {
        index
            .call_argument_values
            .iter()
            .find(|fact| {
                &source.text[fact.argument_span.start as usize..fact.argument_span.end as usize] == needle
            })
            .map(|fact| fact.inline_callback_static_return.clone())
    };

    assert_eq!(
        callback_return("value -> true"),
        Some(Some(StaticScalarValue::Boolean(true)))
    );
    assert_eq!(
        callback_return("value -> false"),
        Some(Some(StaticScalarValue::Boolean(false)))
    );
    assert_eq!(
        callback_return("value -> { return true; }"),
        Some(Some(StaticScalarValue::Boolean(true)))
    );
    assert_eq!(
        callback_return("value -> { if (value) return true; return false; }"),
        Some(None)
    );
    assert_eq!(callback_return("value -> value ? true : false"), Some(None));
    assert_eq!(
        callback_return("App::named"),
        Some(None),
        "method references require a separate exact summary"
    );
}

#[test]
fn annotated_parameter_fact_does_not_confuse_an_identifier_with_the_annotation() {
    let adapter: Arc<dyn bonsai_lang_api::LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let workspace = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Controller.java",
            r#"
import org.springframework.web.bind.annotation.RequestParam;
class Controller {
  void annotated(@RequestParam("q") String value) {}
  void ordinary(String RequestParam) {}
}
"#,
        )],
    );
    let global = workspace.db().global_index();
    let annotated = global
        .all_files()
        .flat_map(|file| global.decls_in(file))
        .find(|decl| decl.name == "annotated")
        .expect("annotated method");
    assert_eq!(annotated.params, ["value"]);
    assert_eq!(annotated.param_annotations, [vec!["RequestParam".to_string()]]);

    let ordinary = global
        .all_files()
        .flat_map(|file| global.decls_in(file))
        .find(|decl| decl.name == "ordinary")
        .expect("ordinary method");
    assert_eq!(ordinary.params, ["RequestParam"]);
    assert_eq!(ordinary.param_annotations, [Vec::<String>::new()]);
}

#[test]
fn instanceof_pattern_binds_the_declared_name_not_the_type() {
    use bonsai_lang_api::FlowEvent;

    let adapter: Arc<dyn bonsai_lang_api::LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "A.java",
            "class A { void main(Object subject) { if (subject instanceof String value) sink(value); } void sink(String value) {} }",
        )],
    );
    let global = ws.db().global_index();
    let main = global
        .all_files()
        .flat_map(|file| global.decls_in(file))
        .find(|decl| decl.name == "main")
        .expect("main declaration");
    let mut facts = Vec::new();
    collect_assignments(&main.flow_events, &mut facts);
    assert!(
        facts
            .iter()
            .any(|(target, source)| target == "value" && source.as_deref() == Some("subject")),
        "missing value <- subject: {facts:#?}"
    );
    assert!(facts.iter().all(|(target, _)| target != "String"));

    fn collect_assignments(events: &[FlowEvent], out: &mut Vec<(String, Option<String>)>) {
        for event in events {
            match event {
                FlowEvent::Assign {
                    target, source_name, ..
                } => out.push((target.clone(), source_name.clone())),
                FlowEvent::Branch {
                    then_events,
                    else_events,
                    ..
                } => {
                    collect_assignments(then_events, out);
                    collect_assignments(else_events, out);
                }
                _ => {}
            }
        }
    }
}

#[test]
fn fully_qualified_type_use_is_local_package_evidence() {
    use bonsai_lang_api::{ImportScope, LanguageAdapter};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Directory.java",
            r#"
class Directory {
  void find(String query) throws Exception {
    javax.naming.directory.InitialDirContext ctx =
        new javax.naming.directory.InitialDirContext();
    ctx.search(query, query, null);
  }
}
"#,
        )],
    );
    let file = ws.db().vfs().all_files()[0];
    let imports = ws.db().import_index(file).expect("Java package facts");
    assert!(imports.imports.iter().any(|import| {
        import.module == "javax.naming.directory.InitialDirContext"
            && import.alias.as_deref() == Some("InitialDirContext")
            && import.scope == ImportScope::Local
    }));
    assert!(
        imports
            .imports
            .iter()
            .all(|import| import.module != "javax.naming.directory"),
        "the adapter must emit the exact syntax qualifier, not invent a package prefix"
    );
}

#[test]
fn url_rebuild_assignment_lowers_exact_call_composition() {
    use bonsai_lang_api::{LanguageAdapter, StringCompositionPart};
    use std::sync::Arc;

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "UrlProbe.java",
            r#"
class UrlProbe {
  String rebuild(java.net.URI uri) {
    String safe = "https://" + uri.getHost()
        + (uri.getPath() == null ? "/" : uri.getPath());
    return safe;
  }
}
"#,
        )],
    );
    let file = *ws.db().vfs().all_files().first().expect("fixture file");
    let index = ws.db().decl_index(file).expect("Java declaration index");
    let [fact] = index.string_compositions.as_slice() else {
        panic!("expected one composition: {:#?}", index.string_compositions);
    };
    assert_eq!(fact.target.as_deref(), Some("safe"));
    assert!(matches!(
        fact.parts.as_slice(),
        [
            StringCompositionPart::Literal { value },
            StringCompositionPart::Call { .. },
            StringCompositionPart::CallOrLiteral { fallback, .. }
        ] if value == "https://" && fallback == "/"
    ));
}

#[test]
fn constructor_assignments_inside_try_bind_each_call_result_to_the_declared_local() {
    use bonsai_lang_api::{AssignValueKind, FlowEvent, LanguageAdapter};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Pipeline.java",
            r#"
class App { record Envelope(String cmd) {} }
class Pipeline {
  App.Envelope run(String routed) {
    App.Envelope valid;
    try {
      valid = new App.Envelope(routed);
    } catch (RuntimeException error) {
      valid = new App.Envelope(routed);
    }
    return valid;
  }
}
"#,
        )],
    );
    let file = *ws.db().vfs().all_files().first().expect("fixture file");
    let index = ws.db().decl_index(file).expect("Java declaration index");
    let run = index
        .defs
        .iter()
        .find(|decl| decl.name == "run")
        .expect("run declaration");
    fn collect<'a>(
        events: &'a [FlowEvent],
        out: &mut Vec<(&'a Option<String>, &'a Vec<String>, &'a Option<AssignValueKind>)>,
    ) {
        for event in events {
            match event {
                FlowEvent::Assign {
                    target,
                    source_call,
                    source_call_args,
                    value_kind,
                    ..
                } if target == "valid" => out.push((source_call, source_call_args, value_kind)),
                FlowEvent::Branch {
                    then_events,
                    else_events,
                    ..
                } => {
                    collect(then_events, out);
                    collect(else_events, out);
                }
                FlowEvent::Loop { body, .. }
                | FlowEvent::Defer { body, .. }
                | FlowEvent::Using { body, .. } => collect(body, out),
                FlowEvent::Try {
                    body,
                    catch_events,
                    finally_events,
                    ..
                } => {
                    collect(body, out);
                    collect(catch_events, out);
                    collect(finally_events, out);
                }
                _ => {}
            }
        }
    }
    let mut assignments = Vec::new();
    collect(&run.flow_events, &mut assignments);

    assert_eq!(assignments.len(), 2, "{:#?}", run.flow_events);
    assert!(
        assignments.iter().all(|(source_call, args, value_kind)| {
            source_call.as_deref() == Some("App.Envelope")
                && args.as_slice() == ["routed".to_string()]
                && value_kind == &&Some(AssignValueKind::CallResult)
        }),
        "{:#?}",
        run.flow_events
    );
}

#[test]
fn instance_field_call_receiver_is_qualified_without_overriding_a_shadowing_local() {
    use bonsai_lang_api::{FlowEvent, LanguageAdapter};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Storage.java",
            r#"
record Envelope(String cmd) {}
class Storage {
  private final Envelope data;
  Storage(Envelope data) { this.data = data; }
  String fromField() { return data.cmd(); }
  String fromLocal(Envelope data) { return data.cmd(); }
}
"#,
        )],
    );
    let file = ws.db().vfs().all_files()[0];
    let index = ws.db().decl_index(file).expect("Java declaration index");

    let constructor = index
        .defs
        .iter()
        .find(|decl| decl.name == "Storage" && decl.kind == bonsai_lang_api::DeclKind::Constructor)
        .expect("Storage constructor");
    assert_eq!(constructor.params, ["data"]);
    assert!(
        constructor
            .receiver_field_writes
            .iter()
            .any(|write| { write.target == "this.data" && write.source_param_indices == [0] }),
        "constructor assignment must be lowered as exact receiver state: {constructor:#?}"
    );
    assert_eq!(
        constructor.receiver_field_writes.len(),
        1,
        "local or type-qualified writes must not become receiver state: {constructor:#?}"
    );
    assert!(
        constructor
            .flow_events
            .iter()
            .all(|event| !matches!(event, FlowEvent::Return { .. })),
        "a Java constructor cannot return a value: {:#?}",
        constructor.flow_events
    );

    let receiver_for = |decl_name: &str| {
        let decl = index
            .defs
            .iter()
            .find(|decl| decl.name == decl_name)
            .unwrap_or_else(|| panic!("{decl_name} declaration"));
        decl.flow_events.iter().find_map(|event| match event {
            FlowEvent::Call {
                span, name, receiver, ..
            } if bonsai_common::short_qualified_tail(name) == "cmd" => {
                Some((*span, name.clone(), receiver.clone()))
            }
            _ => None,
        })
    };

    let (field_span, field_call, field_receiver) = receiver_for("fromField").expect("field call");
    assert_eq!(field_call, "this.data.cmd");
    assert_eq!(field_receiver.as_deref(), Some("this.data"));
    assert_eq!(
        index
            .call_receivers
            .iter()
            .find(|fact| fact.call_span == field_span)
            .and_then(|fact| fact.value_flow.place.as_deref()),
        Some("this.data")
    );

    let (local_span, local_call, local_receiver) = receiver_for("fromLocal").expect("local call");
    assert_eq!(local_call, "data.cmd");
    assert_eq!(local_receiver.as_deref(), Some("data"));
    assert_eq!(
        index
            .call_receivers
            .iter()
            .find(|fact| fact.call_span == local_span)
            .and_then(|fact| fact.value_flow.place.as_deref()),
        Some("data")
    );
}

#[test]
fn constructor_local_receiver_shadows_an_instance_field() {
    use bonsai_lang_api::{FlowEvent, LanguageAdapter};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "SearchPage.java",
            r#"
class Label { void setEscapeModelStrings(boolean enabled) {} }
class SearchPage {
  private Label results;
  SearchPage() {
    Label results = new Label();
    results.setEscapeModelStrings(false);
  }
  void configureField() { results.setEscapeModelStrings(true); }
}
"#,
        )],
    );
    let file = ws.db().vfs().all_files()[0];
    let index = ws.db().decl_index(file).expect("Java declaration index");

    let receiver_for = |decl_name: &str| {
        index
            .defs
            .iter()
            .find(|decl| decl.name == decl_name)
            .unwrap_or_else(|| panic!("{decl_name} declaration"))
            .flow_events
            .iter()
            .find_map(|event| match event {
                FlowEvent::Call { name, receiver, .. }
                    if bonsai_common::short_qualified_tail(name) == "setEscapeModelStrings" =>
                {
                    Some((name.clone(), receiver.clone()))
                }
                _ => None,
            })
    };

    let (constructor_call, constructor_receiver) = receiver_for("SearchPage").expect("constructor call");
    assert_eq!(constructor_call, "results.setEscapeModelStrings");
    assert_eq!(constructor_receiver.as_deref(), Some("results"));

    let (field_call, field_receiver) = receiver_for("configureField").expect("field call");
    assert_eq!(field_call, "this.results.setEscapeModelStrings");
    assert_eq!(field_receiver.as_deref(), Some("this.results"));
}

#[test]
fn chained_call_argument_preserves_nested_receiver_call_inputs() {
    use bonsai_lang_api::{FlowEvent, LanguageAdapter};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Audit.java",
            r#"
class Pattern {
  Matcher matcher(String value) { return new Matcher(); }
}
class Matcher { String replaceAll(String replacement) { return replacement; } }
class MDC { static void put(String key, String value) {} }
class Audit {
  private static final Pattern CONTROL = new Pattern();
  void event(String rid) {
    MDC.put("rid", CONTROL.matcher(rid).replaceAll("_"));
  }
}
"#,
        )],
    );
    let file = ws.db().vfs().all_files()[0];
    let index = ws.db().decl_index(file).expect("Java declaration index");
    let event = index
        .defs
        .iter()
        .find(|decl| decl.name == "event")
        .expect("event declaration");
    let value = event.flow_events.iter().find_map(|event| match event {
        FlowEvent::Call { name, args, .. } if name == "MDC.put" => args.get(1),
        _ => None,
    });
    let value = value.expect("MDC value argument");
    assert!(
        value.source_names.iter().any(|source| source == "rid"),
        "nested receiver-call input must reach the outer argument: {value:#?}"
    );
}

#[test]
fn url_guard_syntax_emits_typed_conditions_and_static_scalars() {
    use bonsai_lang_api::{ConditionExpressionFact, LanguageAdapter, StaticScalarValue};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "UrlGuard.java",
            r#"
import java.net.*;
import java.util.*;
class UrlGuard {
  private static final Set<String> ALLOWED_HOSTS = Set.of("api.example.com", "partner.example.com");
  void fetch(String raw) throws Exception {
    URL parsed = new URL(raw);
    if (!"https".equalsIgnoreCase(parsed.getProtocol())) throw new SecurityException();
    if (!ALLOWED_HOSTS.contains(parsed.getHost())) throw new SecurityException();
    InetAddress addr = InetAddress.getByName(parsed.getHost());
    if (addr.isLoopbackAddress() || addr.isSiteLocalAddress()) throw new SecurityException();
    HttpURLConnection conn = (HttpURLConnection) parsed.openConnection();
    conn.setInstanceFollowRedirects(false);
  }
  void authenticate(Object email, Object password) {
    if (!(email instanceof String) || !(password instanceof String)) {
      throw new IllegalArgumentException();
    }
  }
}
"#,
        )],
    );
    let file = *ws.db().vfs().all_files().first().expect("fixture file");
    let index = ws.db().decl_index(file).expect("Java declaration index");

    assert!(index
        .branch_conditions
        .iter()
        .any(|fact| matches!(&fact.expression, Some(ConditionExpressionFact::Not { .. }))));
    assert!(index.branch_conditions.iter().any(|fact| matches!(
        &fact.expression,
        Some(ConditionExpressionFact::Any { operands, .. }) if operands.len() == 2
    )));
    assert!(index.branch_conditions.iter().any(|fact| matches!(
        &fact.expression,
        Some(ConditionExpressionFact::Any { operands, .. })
            if operands.iter().all(|operand| matches!(
                operand,
                ConditionExpressionFact::Not { operand, .. }
                    if matches!(
                        operand.as_ref(),
                        ConditionExpressionFact::TypeTest { type_name, .. }
                            if type_name == "String"
                    )
            ))
    )));
    assert!(index
        .call_receivers
        .iter()
        .any(|fact| { fact.static_value == Some(StaticScalarValue::String("https".to_string())) }));
    assert!(index
        .call_argument_values
        .iter()
        .any(|fact| { fact.static_value == Some(StaticScalarValue::Boolean(false)) }));
    let allowlist = index
        .assignment_values
        .iter()
        .find(|fact| fact.target.as_deref() == Some("ALLOWED_HOSTS"))
        .expect("static Set.of assignment");
    assert_eq!(allowlist.exact_static_call_args.as_ref().map(Vec::len), Some(2));
}

#[test]
fn finite_map_selection_requires_java_util_map_final_binding_and_literal_default() {
    use bonsai_lang_api::LanguageAdapter;

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Selections.java",
            r#"
import java.util.Map;
class Selections {
  private static final Map<String, String> SORTABLE =
      Map.of("id", "id", "email", "email");
  private static Map<String, String> MUTABLE =
      Map.of("id", "id");

  String safe(String key) {
    String column = SORTABLE.getOrDefault(key, "id");
    return column;
  }
  String dynamicDefault(String key, String fallback) {
    String dynamic = SORTABLE.getOrDefault(key, fallback);
    return dynamic;
  }
  String shadowed(Map<String, String> SORTABLE, String key) {
    String shadow = SORTABLE.getOrDefault(key, "id");
    return shadow;
  }
  String lambdaShadow(String key) {
    java.util.function.Function<Map<String, String>, String> select =
        SORTABLE -> SORTABLE.getOrDefault(key, "id");
    return select.apply(SORTABLE);
  }
  String inferredLambdaShadow(String key) {
    java.util.function.BiFunction<Map<String, String>, String, String> select =
        (SORTABLE, fallback) -> SORTABLE.getOrDefault(key, fallback);
    return select.apply(SORTABLE, "id");
  }
  String catchShadow(String key) {
    try {
      throw new RuntimeException();
    } catch (RuntimeException SORTABLE) {
      String caught = SORTABLE.getOrDefault(key, "id");
      return caught;
    }
  }
  String enhancedForShadow(String key, Iterable<Map<String, String>> values) {
    for (Map<String, String> SORTABLE : values) {
      String looped = SORTABLE.getOrDefault(key, "id");
      return looped;
    }
    return "id";
  }
  String nonFinal(String key) {
    String mutable = MUTABLE.getOrDefault(key, "id");
    return mutable;
  }
}
"#,
        )],
    );
    let file = *ws.db().vfs().all_files().first().expect("fixture file");
    let index = ws.db().decl_index(file).expect("Java declaration index");

    assert_eq!(
        index
            .finite_literal_selections
            .iter()
            .filter_map(|fact| fact.target.as_deref())
            .collect::<Vec<_>>(),
        ["column"]
    );
}

#[test]
fn finite_map_selection_rejects_a_shadowing_java_value() {
    use bonsai_lang_api::LanguageAdapter;

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Shadow.java",
            r#"
import java.util.Map;
class Shadow {
  static final FakeMap Map = new FakeMap();
  static final java.util.Map<String, String> LOOKUP = Map.of("id", "id");
  String unsafe(String key) {
    String selected = LOOKUP.getOrDefault(key, "id");
    return selected;
  }
}
class FakeMap {
  java.util.Map<String, String> of(String key, String value) {
    return java.util.Map.of(key, key);
  }
}
"#,
        )],
    );
    let file = *ws.db().vfs().all_files().first().expect("fixture file");
    let index = ws.db().decl_index(file).expect("Java declaration index");
    assert!(index.finite_literal_selections.is_empty());
}

#[test]
fn inherited_bare_member_call_has_explicit_receiver_fact() {
    use bonsai_lang_api::{CallKind, FlowEvent, LanguageAdapter};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Storage.java",
            r#"
class Base { String cmd() { return ""; } }
class Repository extends Base {
  String run() { return cmd(); }
}
"#,
        )],
    );
    for file in ws.db().vfs().all_files() {
        let _ = ws.db().decl_index(file);
    }
    let global = ws.db().global_index();
    let run = global
        .all_files()
        .flat_map(|file| global.decls_in(file))
        .find(|decl| decl.name == "run")
        .expect("run declaration");

    assert!(
        run.flow_events.iter().any(|event| matches!(
            event,
            FlowEvent::Call {
                name,
                receiver: Some(receiver),
                call_kind: CallKind::Method,
                ..
            } if name == "this.cmd" && receiver == "this"
        )),
        "{:#?}",
        run.flow_events
    );
}

#[test]
fn explicit_super_invocation_remains_constructor_syntax() {
    use bonsai_lang_api::{CallKind, FlowEvent, LanguageAdapter};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Storage.java",
            r#"
class Base { Base(String data) {} }
class Derived extends Base {
  Derived(String data) { super(data); }
}
"#,
        )],
    );
    for file in ws.db().vfs().all_files() {
        let _ = ws.db().decl_index(file);
    }
    let global = ws.db().global_index();
    let derived = global
        .all_files()
        .flat_map(|file| global.decls_in(file))
        .find(|decl| decl.name == "Derived" && decl.kind == bonsai_lang_api::DeclKind::Constructor)
        .expect("derived constructor");

    assert!(
        derived.flow_events.iter().any(|event| matches!(
            event,
            FlowEvent::Call {
                name,
                receiver: Some(receiver),
                call_kind: CallKind::Constructor,
                ..
            } if name == "Base" && receiver == "super"
        )),
        "{:#?}",
        derived.flow_events
    );
}

#[test]
fn generic_receiver_carries_tree_sitter_upper_bound() {
    use bonsai_lang_api::{FlowEvent, LanguageAdapter};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Box.java",
            r#"
class Payload { String cmd() { return ""; } }
class Box<T extends Payload> {
  T data;
  String read() { return data.cmd(); }
}
"#,
        )],
    );
    for file in ws.db().vfs().all_files() {
        let _ = ws.db().decl_index(file);
    }
    let global = ws.db().global_index();
    let read = global
        .all_files()
        .flat_map(|file| global.decls_in(file))
        .find(|decl| decl.name == "read")
        .expect("read method");

    assert!(
        read.flow_events.iter().any(|event| matches!(
            event,
            FlowEvent::Call {
                receiver: Some(receiver),
                receiver_types,
                ..
            } if receiver == "this.data" && receiver_types.iter().any(|ty| ty == "Payload")
        )),
        "{:#?}",
        read.flow_events
    );
}

#[test]
fn replacement_helpers_emit_exact_escape_and_constraint_summaries() {
    use bonsai_lang_api::{CharacterConstraintDomain, LanguageAdapter};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Escapes.java",
            r#"
class Text {
  String replace(String pattern, String replacement) { return replacement; }
}
class Escapes {
  static String html(String value) {
    return value.replace("&", "&amp;").replace("<", "&lt;");
  }
  static String header(String value) {
    return value.replaceAll("[\\r\\n]", "_");
  }
  static String incomplete(String value) {
    return value.replaceAll("[\\r\\n]", value);
  }
  static String collision(Text value) {
    return value.replace("<", "&lt;");
  }
}
"#,
        )],
    );
    let file = ws.db().vfs().all_files()[0];
    let index = ws.db().decl_index(file).expect("Java declaration index");
    assert_eq!(
        index.character_substitutions.len(),
        0,
        "runtime calls must remain provider-bound constraints: {:#?}",
        index.character_substitutions
    );
    assert!(index.character_constraints.iter().any(|fact| matches!(
        &fact.domain,
        CharacterConstraintDomain::ProviderBound {
            factory_call,
            operation_call,
            domain,
        } if factory_call.is_empty()
            && operation_call == "String.replace#single-character-string|String.replace#single-character-string"
            && matches!(domain.as_ref(), CharacterConstraintDomain::SubstitutesExact { mappings }
                if mappings.iter().any(|mapping| mapping.key == "&" && mapping.value == "&amp;")
                    && mappings.iter().any(|mapping| mapping.key == "<" && mapping.value == "&lt;"))
    )),
    "typed direct operations retain exact provider and mapping identity: {:#?}",
        index.character_constraints
    );
    assert!(index.character_constraints.iter().any(|fact| matches!(
        &fact.domain,
        CharacterConstraintDomain::ProviderBound {
            operation_call,
            domain,
            ..
        } if operation_call == "String.replaceAll#regex-character-class"
            && matches!(domain.as_ref(), CharacterConstraintDomain::ExcludesExact { characters }
                if characters.contains(&"\r".to_string()) && characters.contains(&"\n".to_string()))
    )));
    assert!(
        index.character_constraints.iter().any(|fact| matches!(
            &fact.domain,
            CharacterConstraintDomain::ProviderBound { operation_call, .. }
                if operation_call == "workspace.Text.replace#single-character-string"
        )),
        "same-spelled local operations retain a non-runtime provider identity"
    );
    assert_eq!(
        index
            .character_constraints
            .iter()
            .filter(|fact| fact.function_span
                == index
                    .defs
                    .iter()
                    .find(|decl| decl.name == "incomplete")
                    .unwrap()
                    .span)
            .count(),
        0,
        "a dynamic replacement cannot produce an exact transform summary: {:#?}",
        index.character_constraints
    );
}

#[test]
fn switch_character_transform_requires_total_identity_default() {
    use bonsai_lang_api::LanguageAdapter;

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Escaper.java",
            r#"
class Escaper {
  static String safe(String value) {
    StringBuilder out = new StringBuilder(value.length());
    for (char c : value.toCharArray()) {
      switch (c) {
        case '*': out.append("\\2a"); break;
        case '(': out.append("\\28"); break;
        default: out.append(c);
      }
    }
    return out.toString();
  }
  static String partial(String value) {
    StringBuilder out = new StringBuilder(value.length());
    for (char c : value.toCharArray()) {
      switch (c) {
        case '*': out.append("\\2a"); break;
        default: out.append("x");
      }
    }
    return out.toString();
  }
}
"#,
        )],
    );
    let file = ws.db().vfs().all_files()[0];
    let index = ws.db().decl_index(file).expect("Java declaration index");
    assert_eq!(
        index
            .character_substitutions
            .iter()
            .filter(|fact| !fact.exact_mappings.is_empty())
            .count(),
        1,
        "partial switch must not produce a transform summary: {:#?}",
        index.character_substitutions
    );
    assert!(index.character_substitutions[0]
        .exact_mappings
        .iter()
        .any(|entry| entry.key == "*" && entry.value == "\\2a"));
}

#[test]
fn array_call_arguments_preserve_exact_positional_scalar_facts() {
    use bonsai_lang_api::{LanguageAdapter, StaticScalarValue};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Command.java",
            r#"
class Command {
  void run(String host) throws Exception {
    Runtime.getRuntime().exec(new String[] { "sh", "-c", "ping " + host });
  }
}
"#,
        )],
    );
    let file = ws.db().vfs().all_files()[0];
    let index = ws.db().decl_index(file).expect("Java declaration index");
    let sequence = index
        .call_argument_values
        .iter()
        .find_map(|fact| fact.exact_static_sequence_values.as_ref())
        .expect("exact Java array initializer");
    assert_eq!(
        sequence,
        &vec![
            Some(StaticScalarValue::String("sh".to_string())),
            Some(StaticScalarValue::String("-c".to_string())),
            None,
        ]
    );
}

#[test]
fn nested_inline_callbacks_preserve_exact_parameter_bindings() {
    use bonsai_lang_api::LanguageAdapter;

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Callbacks.java",
            r#"
class Callbacks {
  void configure(Server server) {
    server.requestHandler(request -> {
      request.bodyHandler(buffer -> consume(buffer));
    });
  }
  void consume(Object value) {}
}
"#,
        )],
    );
    let file = ws.db().vfs().all_files()[0];
    let index = ws.db().decl_index(file).expect("Java declaration index");
    let body_callback = index
        .call_argument_values
        .iter()
        .find(|fact| fact.inline_callback_params == ["buffer"])
        .expect("nested body callback argument fact");
    assert_eq!(body_callback.argument_index, 0);
    assert!(body_callback.inline_callback_span.is_some());
}

#[test]
fn compiled_pattern_constraints_resolve_the_exact_immutable_binding() {
    use bonsai_lang_api::{CharacterConstraintDomain, LanguageAdapter};

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Patterns.java",
            r#"
import java.util.regex.Pattern;
class LocalPattern {
  static LocalPattern compile(String value) { return new LocalPattern(); }
  LocalMatcher matcher(String value) { return new LocalMatcher(); }
}
class LocalMatcher { String replaceAll(String value) { return ""; } }
class Patterns {
  private static final Pattern CONTROL = Pattern.compile("\\p{Cntrl}");
  private static final LocalPattern LOCAL = LocalPattern.compile("\\p{Cntrl}");
  static String safe(String value) {
    return CONTROL.matcher(value).replaceAll("_");
  }
  static String collision(String value) {
    return LOCAL.matcher(value).replaceAll("_");
  }
  static String shadowed(String value) {
    final Pattern CONTROL = Pattern.compile(".*");
    return CONTROL.matcher(value).replaceAll("_");
  }
}
"#,
        )],
    );
    let file = ws.db().vfs().all_files()[0];
    let index = ws.db().decl_index(file).expect("Java declaration index");
    let safe = index
        .defs
        .iter()
        .find(|decl| decl.name == "safe")
        .expect("safe method");
    let collision = index
        .defs
        .iter()
        .find(|decl| decl.name == "collision")
        .expect("collision method");
    let safe_fact = index
        .character_constraints
        .iter()
        .find(|fact| fact.function_span == safe.span)
        .expect("import-bound compiled pattern constraint");
    assert!(matches!(
        &safe_fact.domain,
        CharacterConstraintDomain::ProviderBound {
            factory_call,
            operation_call,
            domain,
        } if factory_call == "java.util.regex.Pattern.compile"
            && operation_call == "matcher|replaceAll"
            && matches!(domain.as_ref(), CharacterConstraintDomain::ExcludesExact { characters }
                if characters.contains(&"\r".to_string()) && characters.contains(&"\n".to_string()))
    ));
    let collision_fact = index
        .character_constraints
        .iter()
        .find(|fact| fact.function_span == collision.span)
        .expect("local provider remains a distinct candidate");
    assert!(matches!(
        &collision_fact.domain,
        CharacterConstraintDomain::ProviderBound { factory_call, .. }
            if factory_call == "workspace.LocalPattern.compile"
    ));
    let shadowed = index
        .defs
        .iter()
        .find(|decl| decl.name == "shadowed")
        .expect("shadowed method");
    assert!(
        index
            .character_constraints
            .iter()
            .all(|fact| fact.function_span != shadowed.span),
        "a shadowing binding with a dynamic pattern must not inherit the field proof: {:#?}",
        index.character_constraints
    );
}

#[test]
fn final_field_assignment_carries_exact_immutable_owner() {
    use bonsai_lang_api::LanguageAdapter;

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    let ws = bonsai_testkit::workspace_with(
        vec![adapter],
        &[(
            "Config.java",
            r#"
class Client {}
class Config {
  private final Client stable = new Client();
  private Client mutable = new Client();
}
"#,
        )],
    );
    let file = ws.db().vfs().all_files()[0];
    let index = ws.db().decl_index(file).expect("Java declaration index");
    let owner = index
        .defs
        .iter()
        .find(|decl| decl.name == "Config")
        .expect("Config class")
        .symbol;
    let stable = index
        .assignment_values
        .iter()
        .find(|fact| fact.target.as_deref() == Some("this.stable"))
        .expect("stable field assignment");
    let mutable = index
        .assignment_values
        .iter()
        .find(|fact| fact.target.as_deref() == Some("this.mutable"))
        .expect("mutable field assignment");
    assert!(stable.target_is_immutable);
    assert_eq!(stable.target_owner, Some(owner));
    assert!(!mutable.target_is_immutable);
    assert_eq!(mutable.target_owner, None);
}

#[test]
fn guarded_value_helper_preserves_predicate_polarity_without_api_meaning() {
    use bonsai_lang_api::LanguageAdapter;

    let adapter: Arc<dyn LanguageAdapter> = Arc::new(bonsai_lang_java::JavaAdapter::new());
    for (condition, fallback, expected) in [
        (
            r#"target == null || !target.startsWith("/") || target.startsWith("//")"#,
            r#"return "/";"#,
            true,
        ),
        (
            r#"target == null || !target.startsWith("/")"#,
            r#"return "/";"#,
            true,
        ),
        (
            r#"target == null || !target.startsWith("/") || target.startsWith("//")"#,
            "return target;",
            false,
        ),
        (
            r#"!target.startsWith("/") || target.startsWith("//")"#,
            r#"if (target.isEmpty()) return "/";"#,
            false,
        ),
        (
            r#"!target.startsWith("/") || target.startsWith("//")"#,
            r#"java.util.function.Supplier<String> fallback = () -> { return "/"; };"#,
            false,
        ),
        (
            r#"!target.startsWith("/") || target.startsWith("//")"#,
            r#"{ /* exact nested block */ return "/"; }"#,
            true,
        ),
    ] {
        let source = format!(
            "class Redirect {{ static String sameSite(String target) {{ if ({condition}) {{ {fallback} }} return target; }} }}"
        );
        let ws = bonsai_testkit::workspace_with(vec![Arc::clone(&adapter)], &[("Redirect.java", &source)]);
        let file = ws.db().vfs().all_files()[0];
        let index = ws.db().decl_index(file).expect("Java declaration index");
        assert_eq!(
            !index.guarded_value_constraints.is_empty(),
            expected,
            "{condition}: {:#?}",
            index.guarded_value_constraints
        );
    }

    let source = r#"
class Selection {
    static String select(String target) {
        if (!target.isAccepted("local") || target.isRejected("remote")) return "fallback";
        return target;
    }
}
"#;
    let ws = bonsai_testkit::workspace_with(
        vec![Arc::new(bonsai_lang_java::JavaAdapter::new())],
        &[("Selection.java", source)],
    );
    let file = ws.db().vfs().all_files()[0];
    let index = ws.db().decl_index(file).expect("Java declaration index");
    let [fact] = index.guarded_value_constraints.as_slice() else {
        panic!(
            "generic Java predicate calls must lower: {:#?}",
            index.guarded_value_constraints
        );
    };
    assert!(fact.accepted_prefixes.is_empty());
    assert!(fact.rejected_prefixes.is_empty());
    assert!(fact.predicate_calls.iter().any(|call| call.required_result));
    assert!(fact.predicate_calls.iter().any(|call| !call.required_result));
}