summaryrefslogtreecommitdiff
path: root/compiler/InterpreterLoopsMatchCtxs.ml
blob: 74f9ba2c7e8b68e5e861d4a1500efa7b9191348c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
(** This module implements support to match contexts for loops.

    The matching functions are used for instance to compute joins, or
    to check if two contexts are equivalent (modulo conversion).
 *)

open Types
open Values
open Contexts
open TypesUtils
open ValuesUtils
open Cps
open InterpreterUtils
open InterpreterBorrows
open InterpreterLoopsCore
module S = SynthesizeSymbolic

(** The local logger *)
let log = Logging.loops_match_ctxs_log

let compute_abs_borrows_loans_maps (no_duplicates : bool)
    (explore : abs -> bool) (env : env) : abs_borrows_loans_maps =
  let abs_ids = ref [] in
  let abs_to_borrows = ref AbstractionId.Map.empty in
  let abs_to_loans = ref AbstractionId.Map.empty in
  let abs_to_borrows_loans = ref AbstractionId.Map.empty in
  let borrow_to_abs = ref BorrowId.Map.empty in
  let loan_to_abs = ref BorrowId.Map.empty in
  let borrow_loan_to_abs = ref BorrowId.Map.empty in

  let module R (Id0 : Identifiers.Id) (Id1 : Identifiers.Id) = struct
    (*
       [check_singleton_sets]: check that the mapping maps to a singletong.
       [check_not_already_registered]: check if the mapping was not already registered.
    *)
    let register_mapping (check_singleton_sets : bool)
        (check_not_already_registered : bool) (map : Id1.Set.t Id0.Map.t ref)
        (id0 : Id0.id) (id1 : Id1.id) : unit =
      (* Sanity check *)
      (if check_singleton_sets || check_not_already_registered then
         match Id0.Map.find_opt id0 !map with
         | None -> ()
         | Some set ->
             assert (
               (not check_not_already_registered) || not (Id1.Set.mem id1 set)));
      (* Update the mapping *)
      map :=
        Id0.Map.update id0
          (fun ids ->
            match ids with
            | None -> Some (Id1.Set.singleton id1)
            | Some ids ->
                (* Sanity check *)
                assert (not check_singleton_sets);
                assert (
                  (not check_not_already_registered)
                  || not (Id1.Set.mem id1 ids));
                (* Update *)
                Some (Id1.Set.add id1 ids))
          !map
  end in
  let module RAbsBorrow = R (AbstractionId) (BorrowId) in
  let module RBorrowAbs = R (BorrowId) (AbstractionId) in
  let register_borrow_id abs_id bid =
    RAbsBorrow.register_mapping false no_duplicates abs_to_borrows abs_id bid;
    RAbsBorrow.register_mapping false false abs_to_borrows_loans abs_id bid;
    RBorrowAbs.register_mapping no_duplicates no_duplicates borrow_to_abs bid
      abs_id;
    RBorrowAbs.register_mapping false false borrow_loan_to_abs bid abs_id
  in

  let register_loan_id abs_id bid =
    RAbsBorrow.register_mapping false no_duplicates abs_to_loans abs_id bid;
    RAbsBorrow.register_mapping false false abs_to_borrows_loans abs_id bid;
    RBorrowAbs.register_mapping no_duplicates no_duplicates loan_to_abs bid
      abs_id;
    RBorrowAbs.register_mapping false false borrow_loan_to_abs bid abs_id
  in

  let explore_abs =
    object (self : 'self)
      inherit [_] iter_typed_avalue as super

      (** Make sure we don't register the ignored ids *)
      method! visit_aloan_content abs_id lc =
        match lc with
        | AMutLoan _ | ASharedLoan _ ->
            (* Process those normally *)
            super#visit_aloan_content abs_id lc
        | AIgnoredMutLoan (_, child)
        | AEndedIgnoredMutLoan { child; given_back = _; given_back_meta = _ }
        | AIgnoredSharedLoan child ->
            (* Ignore the id of the loan, if there is *)
            self#visit_typed_avalue abs_id child
        | AEndedMutLoan _ | AEndedSharedLoan _ -> raise (Failure "Unreachable")

      (** Make sure we don't register the ignored ids *)
      method! visit_aborrow_content abs_id bc =
        match bc with
        | AMutBorrow _ | ASharedBorrow _ | AProjSharedBorrow _ ->
            (* Process those normally *)
            super#visit_aborrow_content abs_id bc
        | AIgnoredMutBorrow (_, child)
        | AEndedIgnoredMutBorrow { child; given_back = _; given_back_meta = _ }
          ->
            (* Ignore the id of the borrow, if there is *)
            self#visit_typed_avalue abs_id child
        | AEndedMutBorrow _ | AEndedSharedBorrow ->
            raise (Failure "Unreachable")

      method! visit_borrow_id abs_id bid = register_borrow_id abs_id bid
      method! visit_loan_id abs_id lid = register_loan_id abs_id lid
    end
  in

  env_iter_abs
    (fun abs ->
      let abs_id = abs.abs_id in
      if explore abs then (
        abs_to_borrows :=
          AbstractionId.Map.add abs_id BorrowId.Set.empty !abs_to_borrows;
        abs_to_loans :=
          AbstractionId.Map.add abs_id BorrowId.Set.empty !abs_to_loans;
        abs_ids := abs.abs_id :: !abs_ids;
        List.iter (explore_abs#visit_typed_avalue abs.abs_id) abs.avalues)
      else ())
    env;

  (* Rem.: there is no need to reverse the abs ids, because we explored the environment
     starting with the freshest values and abstractions *)
  {
    abs_ids = !abs_ids;
    abs_to_borrows = !abs_to_borrows;
    abs_to_loans = !abs_to_loans;
    abs_to_borrows_loans = !abs_to_borrows_loans;
    borrow_to_abs = !borrow_to_abs;
    loan_to_abs = !loan_to_abs;
    borrow_loan_to_abs = !borrow_loan_to_abs;
  }

(** Match two types during a join.

    TODO: probably don't need to take [match_regions] as input anymore.
 *)
let rec match_types (match_distinct_types : ty -> ty -> ty)
    (match_regions : region -> region -> region) (ty0 : ty) (ty1 : ty) : ty =
  let match_rec = match_types match_distinct_types match_regions in
  match (ty0, ty1) with
  | TAdt (id0, generics0), TAdt (id1, generics1) ->
      assert (id0 = id1);
      assert (generics0.const_generics = generics1.const_generics);
      assert (generics0.trait_refs = generics1.trait_refs);
      let id = id0 in
      let const_generics = generics1.const_generics in
      let trait_refs = generics1.trait_refs in
      let regions =
        List.map
          (fun (id0, id1) -> match_regions id0 id1)
          (List.combine generics0.regions generics1.regions)
      in
      let types =
        List.map
          (fun (ty0, ty1) -> match_rec ty0 ty1)
          (List.combine generics0.types generics1.types)
      in
      let generics = { regions; types; const_generics; trait_refs } in
      TAdt (id, generics)
  | TVar vid0, TVar vid1 ->
      assert (vid0 = vid1);
      let vid = vid0 in
      TVar vid
  | TLiteral lty0, TLiteral lty1 ->
      assert (lty0 = lty1);
      ty0
  | TNever, TNever -> ty0
  | TRef (r0, ty0, k0), TRef (r1, ty1, k1) ->
      let r = match_regions r0 r1 in
      let ty = match_rec ty0 ty1 in
      assert (k0 = k1);
      let k = k0 in
      TRef (r, ty, k)
  | _ -> match_distinct_types ty0 ty1

module MakeMatcher (M : PrimMatcher) : Matcher = struct
  let rec match_typed_values (ctx : eval_ctx) (v0 : typed_value)
      (v1 : typed_value) : typed_value =
    let match_rec = match_typed_values ctx in
    let ty = M.match_etys v0.ty v1.ty in
    match (v0.value, v1.value) with
    | VLiteral lv0, VLiteral lv1 ->
        if lv0 = lv1 then v1 else M.match_distinct_literals ty lv0 lv1
    | VAdt av0, VAdt av1 ->
        if av0.variant_id = av1.variant_id then
          let fields = List.combine av0.field_values av1.field_values in
          let field_values =
            List.map (fun (f0, f1) -> match_rec f0 f1) fields
          in
          let value : value =
            VAdt { variant_id = av0.variant_id; field_values }
          in
          { value; ty = v1.ty }
        else (
          (* For now, we don't merge ADTs which contain borrows *)
          assert (not (value_has_borrows ctx v0.value));
          assert (not (value_has_borrows ctx v1.value));
          (* Merge *)
          M.match_distinct_adts ty av0 av1)
    | VBottom, VBottom -> v0
    | VBorrow bc0, VBorrow bc1 ->
        let bc =
          match (bc0, bc1) with
          | VSharedBorrow bid0, VSharedBorrow bid1 ->
              let bid = M.match_shared_borrows match_rec ty bid0 bid1 in
              VSharedBorrow bid
          | VMutBorrow (bid0, bv0), VMutBorrow (bid1, bv1) ->
              let bv = match_rec bv0 bv1 in
              assert (not (value_has_borrows ctx bv.value));
              let bid, bv = M.match_mut_borrows ty bid0 bv0 bid1 bv1 bv in
              VMutBorrow (bid, bv)
          | VReservedMutBorrow _, _
          | _, VReservedMutBorrow _
          | VSharedBorrow _, VMutBorrow _
          | VMutBorrow _, VSharedBorrow _ ->
              (* If we get here, either there is a typing inconsistency, or we are
                 trying to match a reserved borrow, which shouldn't happen because
                 reserved borrow should be eliminated very quickly - they are introduced
                 just before function calls which activate them *)
              raise (Failure "Unexpected")
        in
        { value = VBorrow bc; ty }
    | VLoan lc0, VLoan lc1 ->
        (* TODO: maybe we should enforce that the ids are always exactly the same -
           without matching *)
        let lc =
          match (lc0, lc1) with
          | VSharedLoan (ids0, sv0), VSharedLoan (ids1, sv1) ->
              let sv = match_rec sv0 sv1 in
              assert (not (value_has_borrows ctx sv.value));
              let ids, sv = M.match_shared_loans ty ids0 ids1 sv in
              VSharedLoan (ids, sv)
          | VMutLoan id0, VMutLoan id1 ->
              let id = M.match_mut_loans ty id0 id1 in
              VMutLoan id
          | VSharedLoan _, VMutLoan _ | VMutLoan _, VSharedLoan _ ->
              raise (Failure "Unreachable")
        in
        { value = VLoan lc; ty = v1.ty }
    | VSymbolic sv0, VSymbolic sv1 ->
        (* For now, we force all the symbolic values containing borrows to
           be eagerly expanded, and we don't support nested borrows *)
        assert (not (value_has_borrows ctx v0.value));
        assert (not (value_has_borrows ctx v1.value));
        (* Match *)
        let sv = M.match_symbolic_values sv0 sv1 in
        { v1 with value = VSymbolic sv }
    | VLoan lc, _ -> (
        match lc with
        | VSharedLoan (ids, _) -> raise (ValueMatchFailure (LoansInLeft ids))
        | VMutLoan id -> raise (ValueMatchFailure (LoanInLeft id)))
    | _, VLoan lc -> (
        match lc with
        | VSharedLoan (ids, _) -> raise (ValueMatchFailure (LoansInRight ids))
        | VMutLoan id -> raise (ValueMatchFailure (LoanInRight id)))
    | VSymbolic sv, _ -> M.match_symbolic_with_other true sv v1
    | _, VSymbolic sv -> M.match_symbolic_with_other false sv v0
    | VBottom, _ -> M.match_bottom_with_other true v1
    | _, VBottom -> M.match_bottom_with_other false v0
    | _ ->
        log#ldebug
          (lazy
            ("Unexpected match case:\n- value0: "
            ^ typed_value_to_string ctx v0
            ^ "\n- value1: "
            ^ typed_value_to_string ctx v1));
        raise (Failure "Unexpected match case")

  and match_typed_avalues (ctx : eval_ctx) (v0 : typed_avalue)
      (v1 : typed_avalue) : typed_avalue =
    log#ldebug
      (lazy
        ("match_typed_avalues:\n- value0: "
        ^ typed_avalue_to_string ctx v0
        ^ "\n- value1: "
        ^ typed_avalue_to_string ctx v1));

    let match_rec = match_typed_values ctx in
    let match_arec = match_typed_avalues ctx in
    let ty = M.match_rtys v0.ty v1.ty in
    match (v0.value, v1.value) with
    | AAdt av0, AAdt av1 ->
        if av0.variant_id = av1.variant_id then
          let fields = List.combine av0.field_values av1.field_values in
          let field_values =
            List.map (fun (f0, f1) -> match_arec f0 f1) fields
          in
          let value : avalue =
            AAdt { variant_id = av0.variant_id; field_values }
          in
          { value; ty }
        else (* Merge *)
          M.match_distinct_aadts v0.ty av0 v1.ty av1 ty
    | ABottom, ABottom -> mk_abottom ty
    | AIgnored, AIgnored -> mk_aignored ty
    | ABorrow bc0, ABorrow bc1 -> (
        log#ldebug (lazy "match_typed_avalues: borrows");
        match (bc0, bc1) with
        | ASharedBorrow bid0, ASharedBorrow bid1 ->
            log#ldebug (lazy "match_typed_avalues: shared borrows");
            M.match_ashared_borrows v0.ty bid0 v1.ty bid1 ty
        | AMutBorrow (bid0, av0), AMutBorrow (bid1, av1) ->
            log#ldebug (lazy "match_typed_avalues: mut borrows");
            log#ldebug
              (lazy
                "match_typed_avalues: mut borrows: matching children values");
            let av = match_arec av0 av1 in
            log#ldebug
              (lazy "match_typed_avalues: mut borrows: matched children values");
            M.match_amut_borrows v0.ty bid0 av0 v1.ty bid1 av1 ty av
        | AIgnoredMutBorrow _, AIgnoredMutBorrow _ ->
            (* The abstractions are destructured: we shouldn't get there *)
            raise (Failure "Unexpected")
        | AProjSharedBorrow asb0, AProjSharedBorrow asb1 -> (
            match (asb0, asb1) with
            | [], [] ->
                (* This case actually stands for ignored shared borrows, when
                   there are no nested borrows *)
                v0
            | _ ->
                (* We should get there only if there are nested borrows *)
                raise (Failure "Unexpected"))
        | _ ->
            (* TODO: getting there is not necessarily inconsistent (it may
               just be because the environments don't match) so we may want
               to call a specific function (which could raise the proper
               exception).
               Rem.: we shouldn't get to the ended borrow cases, because
               an abstraction should never contain ended borrows unless
               we are *currently* ending it, in which case we need
               to completely end it before continuing.
            *)
            raise (Failure "Unexpected"))
    | ALoan lc0, ALoan lc1 -> (
        log#ldebug (lazy "match_typed_avalues: loans");
        (* TODO: maybe we should enforce that the ids are always exactly the same -
           without matching *)
        match (lc0, lc1) with
        | ASharedLoan (ids0, sv0, av0), ASharedLoan (ids1, sv1, av1) ->
            log#ldebug (lazy "match_typed_avalues: shared loans");
            let sv = match_rec sv0 sv1 in
            let av = match_arec av0 av1 in
            assert (not (value_has_borrows ctx sv.value));
            M.match_ashared_loans v0.ty ids0 sv0 av0 v1.ty ids1 sv1 av1 ty sv av
        | AMutLoan (id0, av0), AMutLoan (id1, av1) ->
            log#ldebug (lazy "match_typed_avalues: mut loans");
            log#ldebug
              (lazy "match_typed_avalues: mut loans: matching children values");
            let av = match_arec av0 av1 in
            log#ldebug
              (lazy "match_typed_avalues: mut loans: matched children values");
            M.match_amut_loans v0.ty id0 av0 v1.ty id1 av1 ty av
        | AIgnoredMutLoan _, AIgnoredMutLoan _
        | AIgnoredSharedLoan _, AIgnoredSharedLoan _ ->
            (* Those should have been filtered when destructuring the abstractions -
               they are necessary only when there are nested borrows *)
            raise (Failure "Unreachable")
        | _ -> raise (Failure "Unreachable"))
    | ASymbolic _, ASymbolic _ ->
        (* For now, we force all the symbolic values containing borrows to
           be eagerly expanded, and we don't support nested borrows *)
        raise (Failure "Unreachable")
    | _ -> M.match_avalues v0 v1
end

module MakeJoinMatcher (S : MatchJoinState) : PrimMatcher = struct
  (** Small utility *)
  let push_abs (abs : abs) : unit = S.nabs := abs :: !S.nabs

  let push_absl (absl : abs list) : unit = List.iter push_abs absl

  let match_etys ty0 ty1 =
    assert (ty0 = ty1);
    ty0

  let match_rtys ty0 ty1 =
    (* The types must be equal - in effect, this forbids to match symbolic
       values containing borrows *)
    assert (ty0 = ty1);
    ty0

  let match_distinct_literals (ty : ety) (_ : literal) (_ : literal) :
      typed_value =
    mk_fresh_symbolic_typed_value_from_no_regions_ty LoopJoin ty

  let match_distinct_adts (ty : ety) (adt0 : adt_value) (adt1 : adt_value) :
      typed_value =
    (* Check that the ADTs don't contain borrows - this is redundant with checks
       performed by the caller, but we prefer to be safe with regards to future
       updates
    *)
    let check_no_borrows (v : typed_value) =
      assert (not (value_has_borrows S.ctx v.value))
    in
    List.iter check_no_borrows adt0.field_values;
    List.iter check_no_borrows adt1.field_values;

    (* Check if there are loans: we request to end them *)
    let check_loans (left : bool) (fields : typed_value list) : unit =
      match InterpreterBorrowsCore.get_first_loan_in_values fields with
      | Some (VSharedLoan (ids, _)) ->
          if left then raise (ValueMatchFailure (LoansInLeft ids))
          else raise (ValueMatchFailure (LoansInRight ids))
      | Some (VMutLoan id) ->
          if left then raise (ValueMatchFailure (LoanInLeft id))
          else raise (ValueMatchFailure (LoanInRight id))
      | None -> ()
    in
    check_loans true adt0.field_values;
    check_loans false adt1.field_values;

    (* No borrows, no loans: we can introduce a symbolic value *)
    mk_fresh_symbolic_typed_value_from_no_regions_ty LoopJoin ty

  let match_shared_borrows _ (ty : ety) (bid0 : borrow_id) (bid1 : borrow_id) :
      borrow_id =
    if bid0 = bid1 then bid0
    else
      (* We replace bid0 and bid1 with a fresh borrow id, and introduce
         an abstraction which links all of them:
         {[
           { SB bid0, SB bid1, SL {bid2} }
         ]}
      *)
      let rid = fresh_region_id () in
      let bid2 = fresh_borrow_id () in

      (* Generate a fresh symbolic value for the shared value *)
      let _, bv_ty, kind = ty_as_ref ty in
      let sv =
        mk_fresh_symbolic_typed_value_from_no_regions_ty LoopJoin bv_ty
      in

      let borrow_ty = mk_ref_ty (RVar rid) bv_ty kind in

      (* Generate the avalues for the abstraction *)
      let mk_aborrow (bid : borrow_id) : typed_avalue =
        let value = ABorrow (ASharedBorrow bid) in
        { value; ty = borrow_ty }
      in
      let borrows = [ mk_aborrow bid0; mk_aborrow bid1 ] in

      let loan =
        ASharedLoan (BorrowId.Set.singleton bid2, sv, mk_aignored bv_ty)
      in
      (* Note that an aloan has a borrow type *)
      let loan : typed_avalue = { value = ALoan loan; ty = borrow_ty } in

      let avalues = List.append borrows [ loan ] in

      (* Generate the abstraction *)
      let abs =
        {
          abs_id = fresh_abstraction_id ();
          kind = Loop (S.loop_id, None, LoopSynthInput);
          can_end = true;
          parents = AbstractionId.Set.empty;
          original_parents = [];
          regions = RegionId.Set.singleton rid;
          ancestors_regions = RegionId.Set.empty;
          avalues;
        }
      in
      push_abs abs;

      (* Return the new borrow *)
      bid2

  let match_mut_borrows (ty : ety) (bid0 : borrow_id) (bv0 : typed_value)
      (bid1 : borrow_id) (bv1 : typed_value) (bv : typed_value) :
      borrow_id * typed_value =
    if bid0 = bid1 then (
      (* If the merged value is not the same as the original value, we introduce
         an abstraction:

         {[
           { MB bid0, ML nbid }  // where nbid fresh
         ]}

         and we use bid' for the borrow id that we return.

         We do this because we want to make sure that, whenever a mutably
         borrowed value is modified in a loop iteration, then there is
         a fresh abstraction between this borrowed value and the fixed
         abstractions.

         Example:
         ========
         {[
           fn clear(v: &mut Vec<u32>) {
               let mut i = 0;
               while i < v.len() {
                   v[i] = 0;
                   i += 1;
               }
           }
         ]}

         When entering the loop, we have the following environment:
         {[
           abs'0 { ML l0 } // input abstraction
           v -> MB l0 s0
           i -> 0
         ]}

         At every iteration, we update the symbolic value of the vector [v]
         (i.e., [s0]).

         For now, because the translation of the loop is responsible of the
         execution of the end of the function (up to the [return]), we want
         the loop to reborrow the vector [v]: this way, the forward loop
         function returns nothing (it returns what [clear] returns, that is
         to say [unit]) while the backward loop function gives back a new value
         for [v] (i.e., a new symbolic value which will replace [s0]).

         In the future, we will also compute joins at the *loop exits*: when we
         do so, we won't introduce reborrows like above: the forward loop function
         will update [v], while the backward loop function will return nothing.
      *)
      assert (not (value_has_borrows S.ctx bv.value));

      if bv0 = bv1 then (
        assert (bv0 = bv);
        (bid0, bv))
      else
        let rid = fresh_region_id () in
        let nbid = fresh_borrow_id () in

        let kind = RMut in
        let bv_ty = bv.ty in
        assert (ty_no_regions bv_ty);
        let borrow_ty = mk_ref_ty (RVar rid) bv_ty kind in

        let borrow_av =
          let ty = borrow_ty in
          let value = ABorrow (AMutBorrow (bid0, mk_aignored bv_ty)) in
          mk_typed_avalue ty value
        in

        let loan_av =
          let ty = borrow_ty in
          let value = ALoan (AMutLoan (nbid, mk_aignored bv_ty)) in
          mk_typed_avalue ty value
        in

        let avalues = [ borrow_av; loan_av ] in

        (* Generate the abstraction *)
        let abs =
          {
            abs_id = fresh_abstraction_id ();
            kind = Loop (S.loop_id, None, LoopSynthInput);
            can_end = true;
            parents = AbstractionId.Set.empty;
            original_parents = [];
            regions = RegionId.Set.singleton rid;
            ancestors_regions = RegionId.Set.empty;
            avalues;
          }
        in
        push_abs abs;

        (* Return the new borrow *)
        (nbid, bv))
    else
      (* We replace bid0 and bid1 with a fresh borrow id, and introduce
         an abstraction which links all of them:
         {[
           { MB bid0, MB bid1, ML bid2 }
         ]}
      *)
      let rid = fresh_region_id () in
      let bid2 = fresh_borrow_id () in

      (* Generate a fresh symbolic value for the borrowed value *)
      let _, bv_ty, kind = ty_as_ref ty in
      let sv =
        mk_fresh_symbolic_typed_value_from_no_regions_ty LoopJoin bv_ty
      in

      let borrow_ty = mk_ref_ty (RVar rid) bv_ty kind in

      (* Generate the avalues for the abstraction *)
      let mk_aborrow (bid : borrow_id) (bv : typed_value) : typed_avalue =
        let bv_ty = bv.ty in
        assert (ty_no_regions bv_ty);
        let value = ABorrow (AMutBorrow (bid, mk_aignored bv_ty)) in
        { value; ty = borrow_ty }
      in
      let borrows = [ mk_aborrow bid0 bv0; mk_aborrow bid1 bv1 ] in

      let loan = AMutLoan (bid2, mk_aignored bv_ty) in
      (* Note that an aloan has a borrow type *)
      let loan : typed_avalue = { value = ALoan loan; ty = borrow_ty } in

      let avalues = List.append borrows [ loan ] in

      (* Generate the abstraction *)
      let abs =
        {
          abs_id = fresh_abstraction_id ();
          kind = Loop (S.loop_id, None, LoopSynthInput);
          can_end = true;
          parents = AbstractionId.Set.empty;
          original_parents = [];
          regions = RegionId.Set.singleton rid;
          ancestors_regions = RegionId.Set.empty;
          avalues;
        }
      in
      push_abs abs;

      (* Return the new borrow *)
      (bid2, sv)

  let match_shared_loans (_ : ety) (ids0 : loan_id_set) (ids1 : loan_id_set)
      (sv : typed_value) : loan_id_set * typed_value =
    (* Check if the ids are the same - Rem.: we forbid the sets of loans
       to be different. However, if we dive inside data-structures (by
       using a shared borrow) the shared values might themselves contain
       shared loans, which need to be matched. For this reason, we destructure
       the shared values (see {!destructure_abs}).
    *)
    let extra_ids_left = BorrowId.Set.diff ids0 ids1 in
    let extra_ids_right = BorrowId.Set.diff ids1 ids0 in
    if not (BorrowId.Set.is_empty extra_ids_left) then
      raise (ValueMatchFailure (LoansInLeft extra_ids_left));
    if not (BorrowId.Set.is_empty extra_ids_right) then
      raise (ValueMatchFailure (LoansInRight extra_ids_right));

    (* This should always be true if we get here *)
    assert (ids0 = ids1);
    let ids = ids0 in

    (* Return *)
    (ids, sv)

  let match_mut_loans (_ : ety) (id0 : loan_id) (id1 : loan_id) : loan_id =
    if id0 = id1 then id0
    else
      (* We forbid this case for now: if we get there, we force to end
         both borrows *)
      raise (ValueMatchFailure (LoanInLeft id0))

  let match_symbolic_values (sv0 : symbolic_value) (sv1 : symbolic_value) :
      symbolic_value =
    let id0 = sv0.sv_id in
    let id1 = sv1.sv_id in
    if id0 = id1 then (
      (* Sanity check *)
      assert (sv0 = sv1);
      (* Return *)
      sv0)
    else (
      (* The caller should have checked that the symbolic values don't contain
         borrows *)
      assert (not (ty_has_borrows S.ctx.type_context.type_infos sv0.sv_ty));
      (* We simply introduce a fresh symbolic value *)
      mk_fresh_symbolic_value LoopJoin sv0.sv_ty)

  let match_symbolic_with_other (left : bool) (sv : symbolic_value)
      (v : typed_value) : typed_value =
    (* Check that:
       - there are no borrows in the symbolic value
       - there are no borrows in the "regular" value
       If there are loans in the regular value, raise an exception.
    *)
    assert (not (ty_has_borrows S.ctx.type_context.type_infos sv.sv_ty));
    assert (not (value_has_borrows S.ctx v.value));
    let value_is_left = not left in
    (match InterpreterBorrowsCore.get_first_loan_in_value v with
    | None -> ()
    | Some (VSharedLoan (ids, _)) ->
        if value_is_left then raise (ValueMatchFailure (LoansInLeft ids))
        else raise (ValueMatchFailure (LoansInRight ids))
    | Some (VMutLoan id) ->
        if value_is_left then raise (ValueMatchFailure (LoanInLeft id))
        else raise (ValueMatchFailure (LoanInRight id)));
    (* Return a fresh symbolic value *)
    mk_fresh_symbolic_typed_value LoopJoin sv.sv_ty

  let match_bottom_with_other (left : bool) (v : typed_value) : typed_value =
    (* If there are outer loans in the non-bottom value, raise an exception.
       Otherwise, convert it to an abstraction and return [Bottom].
    *)
    let with_borrows = false in
    let value_is_left = not left in
    match
      InterpreterBorrowsCore.get_first_outer_loan_or_borrow_in_value
        with_borrows v
    with
    | Some (BorrowContent _) -> raise (Failure "Unreachable")
    | Some (LoanContent lc) -> (
        match lc with
        | VSharedLoan (ids, _) ->
            if value_is_left then raise (ValueMatchFailure (LoansInLeft ids))
            else raise (ValueMatchFailure (LoansInRight ids))
        | VMutLoan id ->
            if value_is_left then raise (ValueMatchFailure (LoanInLeft id))
            else raise (ValueMatchFailure (LoanInRight id)))
    | None ->
        (* Convert the value to an abstraction *)
        let abs_kind : abs_kind = Loop (S.loop_id, None, LoopSynthInput) in
        let can_end = true in
        let destructure_shared_values = true in
        let absl =
          convert_value_to_abstractions abs_kind can_end
            destructure_shared_values S.ctx v
        in
        push_absl absl;
        (* Return [Bottom] *)
        mk_bottom v.ty

  (* As explained in comments: we don't use the join matcher to join avalues,
     only concrete values *)

  let match_distinct_aadts _ _ _ _ _ = raise (Failure "Unreachable")
  let match_ashared_borrows _ _ _ _ = raise (Failure "Unreachable")
  let match_amut_borrows _ _ _ _ _ _ _ _ = raise (Failure "Unreachable")
  let match_ashared_loans _ _ _ _ _ _ _ _ _ _ _ = raise (Failure "Unreachable")
  let match_amut_loans _ _ _ _ _ _ _ _ = raise (Failure "Unreachable")
  let match_avalues _ _ = raise (Failure "Unreachable")
end

module MakeCheckEquivMatcher (S : MatchCheckEquivState) : CheckEquivMatcher =
struct
  module MkGetSetM (Id : Identifiers.Id) = struct
    module Inj = Id.InjSubst

    let add (msg : string) (m : Inj.t ref) (k0 : Id.id) (k1 : Id.id) =
      (* Check if k0 is already registered as a key *)
      match Inj.find_opt k0 !m with
      | None ->
          (* Not registered: check if k1 is in the set of values,
             otherwise add the binding *)
          if Inj.Set.mem k1 (Inj.elements !m) then
            raise
              (Distinct
                 (msg ^ "adding [k0=" ^ Id.to_string k0 ^ " -> k1="
                ^ Id.to_string k1 ^ " ]: k1 already in the set of elements"))
          else (
            m := Inj.add k0 k1 !m;
            k1)
      | Some k1' ->
          (* It is: check that the bindings are consistent *)
          if k1 <> k1' then raise (Distinct (msg ^ "already a binding for k0"))
          else k1

    let match_e (msg : string) (m : Inj.t ref) (k0 : Id.id) (k1 : Id.id) : Id.id
        =
      (* TODO: merge the add and merge functions *)
      add msg m k0 k1

    let match_el (msg : string) (m : Inj.t ref) (kl0 : Id.id list)
        (kl1 : Id.id list) : Id.id list =
      List.map (fun (k0, k1) -> match_e msg m k0 k1) (List.combine kl0 kl1)

    (** Figuring out mappings between sets of ids is hard in all generality...
        We use the fact that the fresh ids should have been generated
        the same way (i.e., in the same order) and match the ids two by
        two in increasing order.
     *)
    let match_es (msg : string) (m : Inj.t ref) (ks0 : Id.Set.t)
        (ks1 : Id.Set.t) : Id.Set.t =
      Id.Set.of_list
        (match_el msg m (Id.Set.elements ks0) (Id.Set.elements ks1))
  end

  module GetSetRid = MkGetSetM (RegionId)

  let match_rid = GetSetRid.match_e "match_rid: " S.rid_map
  let match_rids = GetSetRid.match_es "match_rids: " S.rid_map

  module GetSetBid = MkGetSetM (BorrowId)

  let match_blid msg = GetSetBid.match_e msg S.blid_map
  let match_blidl msg = GetSetBid.match_el msg S.blid_map
  let match_blids msg = GetSetBid.match_es msg S.blid_map

  let match_borrow_id =
    if S.check_equiv then match_blid "match_borrow_id: "
    else GetSetBid.match_e "match_borrow_id: " S.borrow_id_map

  let match_borrow_idl =
    if S.check_equiv then match_blidl "match_borrow_idl: "
    else GetSetBid.match_el "match_borrow_idl: " S.borrow_id_map

  let match_borrow_ids =
    if S.check_equiv then match_blids "match_borrow_ids: "
    else GetSetBid.match_es "match_borrow_ids: " S.borrow_id_map

  let match_loan_id =
    if S.check_equiv then match_blid "match_loan_id: "
    else GetSetBid.match_e "match_loan_id: " S.loan_id_map

  let match_loan_idl =
    if S.check_equiv then match_blidl "match_loan_idl: "
    else GetSetBid.match_el "match_loan_idl: " S.loan_id_map

  let match_loan_ids =
    if S.check_equiv then match_blids "match_loan_ids: "
    else GetSetBid.match_es "match_loan_ids: " S.loan_id_map

  module GetSetSid = MkGetSetM (SymbolicValueId)
  module GetSetAid = MkGetSetM (AbstractionId)

  let match_aid = GetSetAid.match_e "match_aid: " S.aid_map
  let match_aidl = GetSetAid.match_el "match_aidl: " S.aid_map
  let match_aids = GetSetAid.match_es "match_aids: " S.aid_map

  (** *)
  let match_etys ty0 ty1 =
    if ty0 <> ty1 then raise (Distinct "match_etys") else ty0

  let match_rtys ty0 ty1 =
    let match_distinct_types _ _ = raise (Distinct "match_rtys") in
    let match_regions r0 r1 =
      match (r0, r1) with
      | RStatic, RStatic -> r1
      | RVar rid0, RVar rid1 ->
          let rid = match_rid rid0 rid1 in
          RVar rid
      | _ -> raise (Distinct "match_rtys")
    in
    match_types match_distinct_types match_regions ty0 ty1

  let match_distinct_literals (ty : ety) (_ : literal) (_ : literal) :
      typed_value =
    mk_fresh_symbolic_typed_value_from_no_regions_ty LoopJoin ty

  let match_distinct_adts (_ty : ety) (_adt0 : adt_value) (_adt1 : adt_value) :
      typed_value =
    raise (Distinct "match_distinct_adts")

  let match_shared_borrows
      (match_typed_values : typed_value -> typed_value -> typed_value)
      (_ty : ety) (bid0 : borrow_id) (bid1 : borrow_id) : borrow_id =
    log#ldebug
      (lazy
        ("MakeCheckEquivMatcher: match_shared_borrows: " ^ "bid0: "
       ^ BorrowId.to_string bid0 ^ ", bid1: " ^ BorrowId.to_string bid1));

    let bid = match_borrow_id bid0 bid1 in
    (* If we don't check for equivalence (i.e., we apply a fixed-point),
       we lookup the shared values and match them.
    *)
    let _ =
      if S.check_equiv then ()
      else
        let v0 = S.lookup_shared_value_in_ctx0 bid0 in
        let v1 = S.lookup_shared_value_in_ctx1 bid1 in
        log#ldebug
          (lazy
            ("MakeCheckEquivMatcher: match_shared_borrows: looked up values:"
           ^ "sv0: "
            ^ typed_value_to_string S.ctx v0
            ^ ", sv1: "
            ^ typed_value_to_string S.ctx v1));

        let _ = match_typed_values v0 v1 in
        ()
    in
    bid

  let match_mut_borrows (_ty : ety) (bid0 : borrow_id) (_bv0 : typed_value)
      (bid1 : borrow_id) (_bv1 : typed_value) (bv : typed_value) :
      borrow_id * typed_value =
    let bid = match_borrow_id bid0 bid1 in
    (bid, bv)

  let match_shared_loans (_ : ety) (ids0 : loan_id_set) (ids1 : loan_id_set)
      (sv : typed_value) : loan_id_set * typed_value =
    let ids = match_loan_ids ids0 ids1 in
    (ids, sv)

  let match_mut_loans (_ : ety) (bid0 : loan_id) (bid1 : loan_id) : loan_id =
    match_loan_id bid0 bid1

  let match_symbolic_values (sv0 : symbolic_value) (sv1 : symbolic_value) :
      symbolic_value =
    let id0 = sv0.sv_id in
    let id1 = sv1.sv_id in

    log#ldebug
      (lazy
        ("MakeCheckEquivMatcher: match_symbolic_values: " ^ "sv0: "
        ^ SymbolicValueId.to_string id0
        ^ ", sv1: "
        ^ SymbolicValueId.to_string id1));

    (* If we don't check for equivalence, we also update the map from sids
       to values *)
    if S.check_equiv then
      (* Create the joined symbolic value *)
      let sv_id =
        GetSetSid.match_e "match_symbolic_values: ids: " S.sid_map id0 id1
      in
      let sv_ty = match_rtys sv0.sv_ty sv1.sv_ty in
      let sv_kind =
        if sv0.sv_kind = sv1.sv_kind then sv0.sv_kind
        else raise (Distinct "match_symbolic_values: sv_kind")
      in
      let sv = { sv_id; sv_ty; sv_kind } in
      sv
    else (
      (* Check: fixed values are fixed *)
      assert (id0 = id1 || not (SymbolicValueId.InjSubst.mem id0 !S.sid_map));

      (* Update the symbolic value mapping *)
      let sv1 = mk_typed_value_from_symbolic_value sv1 in

      (* Update the symbolic value mapping *)
      S.sid_to_value_map :=
        SymbolicValueId.Map.add_strict id0 sv1 !S.sid_to_value_map;

      (* Return - the returned value is not used: we can return  whatever
         we want *)
      sv0)

  let match_symbolic_with_other (left : bool) (sv : symbolic_value)
      (v : typed_value) : typed_value =
    if S.check_equiv then raise (Distinct "match_symbolic_with_other")
    else (
      assert left;
      let id = sv.sv_id in
      (* Check: fixed values are fixed *)
      assert (not (SymbolicValueId.InjSubst.mem id !S.sid_map));
      (* Update the binding for the target symbolic value *)
      S.sid_to_value_map :=
        SymbolicValueId.Map.add_strict id v !S.sid_to_value_map;
      (* Return - the returned value is not used, so we can return whatever we want *)
      v)

  let match_bottom_with_other (left : bool) (v : typed_value) : typed_value =
    (* It can happen that some variables get initialized in some branches
       and not in some others, which causes problems when matching. *)
    (* TODO: the returned value is not used, while it should: in generality it
       should be ok to match a fixed-point with the environment we get at
       a continue, where the fixed point contains some bottom values. *)
    if left && not (value_has_loans_or_borrows S.ctx v.value) then
      mk_bottom v.ty
    else raise (Distinct "match_bottom_with_other")

  let match_distinct_aadts _ _ _ _ _ = raise (Distinct "match_distinct_adts")

  let match_ashared_borrows _ty0 bid0 _ty1 bid1 ty =
    let bid = match_borrow_id bid0 bid1 in
    let value = ABorrow (ASharedBorrow bid) in
    { value; ty }

  let match_amut_borrows _ty0 bid0 _av0 _ty1 bid1 _av1 ty av =
    let bid = match_borrow_id bid0 bid1 in
    let value = ABorrow (AMutBorrow (bid, av)) in
    { value; ty }

  let match_ashared_loans _ty0 ids0 _v0 _av0 _ty1 ids1 _v1 _av1 ty v av =
    let bids = match_loan_ids ids0 ids1 in
    let value = ALoan (ASharedLoan (bids, v, av)) in
    { value; ty }

  let match_amut_loans _ty0 id0 _av0 _ty1 id1 _av1 ty av =
    log#ldebug
      (lazy
        ("MakeCheckEquivMatcher:match_amut_loans:" ^ "\n- id0: "
       ^ BorrowId.to_string id0 ^ "\n- id1: " ^ BorrowId.to_string id1
       ^ "\n- ty: " ^ ty_to_string S.ctx ty ^ "\n- av: "
        ^ typed_avalue_to_string S.ctx av));

    let id = match_loan_id id0 id1 in
    let value = ALoan (AMutLoan (id, av)) in
    { value; ty }

  let match_avalues v0 v1 =
    log#ldebug
      (lazy
        ("avalues don't match:\n- v0: "
        ^ typed_avalue_to_string S.ctx v0
        ^ "\n- v1: "
        ^ typed_avalue_to_string S.ctx v1));
    raise (Distinct "match_avalues")
end

let match_ctxs (check_equiv : bool) (fixed_ids : ids_sets)
    (lookup_shared_value_in_ctx0 : BorrowId.id -> typed_value)
    (lookup_shared_value_in_ctx1 : BorrowId.id -> typed_value) (ctx0 : eval_ctx)
    (ctx1 : eval_ctx) : ids_maps option =
  log#ldebug
    (lazy
      ("match_ctxs:\n\n- fixed_ids:\n" ^ show_ids_sets fixed_ids
     ^ "\n\n- ctx0:\n"
      ^ eval_ctx_to_string_no_filter ctx0
      ^ "\n\n- ctx1:\n"
      ^ eval_ctx_to_string_no_filter ctx1
      ^ "\n\n"));

  (* Initialize the maps and instantiate the matcher *)
  let module IdMap (Id : Identifiers.Id) = struct
    let mk_map_ref (ids : Id.Set.t) : Id.InjSubst.t ref =
      ref
        (Id.InjSubst.of_list (List.map (fun x -> (x, x)) (Id.Set.elements ids)))
  end in
  let rid_map =
    let module IdMap = IdMap (RegionId) in
    IdMap.mk_map_ref fixed_ids.rids
  in
  let blid_map =
    let module IdMap = IdMap (BorrowId) in
    IdMap.mk_map_ref fixed_ids.blids
  in
  let borrow_id_map =
    let module IdMap = IdMap (BorrowId) in
    IdMap.mk_map_ref fixed_ids.borrow_ids
  in
  let loan_id_map =
    let module IdMap = IdMap (BorrowId) in
    IdMap.mk_map_ref fixed_ids.loan_ids
  in
  let aid_map =
    let module IdMap = IdMap (AbstractionId) in
    IdMap.mk_map_ref fixed_ids.aids
  in
  let sid_map =
    let module IdMap = IdMap (SymbolicValueId) in
    IdMap.mk_map_ref fixed_ids.sids
  in
  (* In case we don't try to check equivalence but want to compute a mapping
     from a source context to a target context, we use a map from symbolic
     value ids to values (rather than to ids).
  *)
  let sid_to_value_map : typed_value SymbolicValueId.Map.t ref =
    ref SymbolicValueId.Map.empty
  in

  let module S : MatchCheckEquivState = struct
    let check_equiv = check_equiv
    let ctx = ctx0
    let rid_map = rid_map
    let blid_map = blid_map
    let borrow_id_map = borrow_id_map
    let loan_id_map = loan_id_map
    let sid_map = sid_map
    let sid_to_value_map = sid_to_value_map
    let aid_map = aid_map
    let lookup_shared_value_in_ctx0 = lookup_shared_value_in_ctx0
    let lookup_shared_value_in_ctx1 = lookup_shared_value_in_ctx1
  end in
  let module CEM = MakeCheckEquivMatcher (S) in
  let module M = MakeMatcher (CEM) in
  (* Match the environments - we assume that they have the same structure
     (and fail if they don't) *)

  (* Small utility: check that ids are fixed/mapped to themselves *)
  let ids_are_fixed (ids : ids_sets) : bool =
    let { aids; blids = _; borrow_ids; loan_ids; dids; rids; sids } = ids in
    AbstractionId.Set.subset aids fixed_ids.aids
    && BorrowId.Set.subset borrow_ids fixed_ids.borrow_ids
    && BorrowId.Set.subset loan_ids fixed_ids.loan_ids
    && DummyVarId.Set.subset dids fixed_ids.dids
    && RegionId.Set.subset rids fixed_ids.rids
    && SymbolicValueId.Set.subset sids fixed_ids.sids
  in

  (* We need to pick a context for some functions like [match_typed_values]:
     the context is only used to lookup module data, so we can pick whichever
     we want.
     TODO: this is not very clean. Maybe we should just carry the relevant data
     (i.e.e, not the whole context) around.
  *)
  let ctx = ctx0 in

  (* Rem.: this function raises exceptions of type [Distinct] *)
  let match_abstractions (abs0 : abs) (abs1 : abs) : unit =
    let {
      abs_id = abs_id0;
      kind = kind0;
      can_end = can_end0;
      parents = parents0;
      original_parents = original_parents0;
      regions = regions0;
      ancestors_regions = ancestors_regions0;
      avalues = avalues0;
    } =
      abs0
    in

    let {
      abs_id = abs_id1;
      kind = kind1;
      can_end = can_end1;
      parents = parents1;
      original_parents = original_parents1;
      regions = regions1;
      ancestors_regions = ancestors_regions1;
      avalues = avalues1;
    } =
      abs1
    in

    let _ = CEM.match_aid abs_id0 abs_id1 in
    if kind0 <> kind1 || can_end0 <> can_end1 then
      raise (Distinct "match_abstractions: kind or can_end");
    let _ = CEM.match_aids parents0 parents1 in
    let _ = CEM.match_aidl original_parents0 original_parents1 in
    let _ = CEM.match_rids regions0 regions1 in
    let _ = CEM.match_rids ancestors_regions0 ancestors_regions1 in

    log#ldebug (lazy "match_abstractions: matching values");
    let _ =
      List.map
        (fun (v0, v1) -> M.match_typed_avalues ctx v0 v1)
        (List.combine avalues0 avalues1)
    in
    log#ldebug (lazy "match_abstractions: values matched OK");
    ()
  in

  (* Rem.: this function raises exceptions of type [Distinct] *)
  let rec match_envs (env0 : env) (env1 : env) : unit =
    log#ldebug
      (lazy
        ("match_ctxs: match_envs:\n\n- fixed_ids:\n" ^ show_ids_sets fixed_ids
       ^ "\n\n- rid_map: "
        ^ RegionId.InjSubst.show_t !rid_map
        ^ "\n- blid_map: "
        ^ BorrowId.InjSubst.show_t !blid_map
        ^ "\n- sid_map: "
        ^ SymbolicValueId.InjSubst.show_t !sid_map
        ^ "\n- aid_map: "
        ^ AbstractionId.InjSubst.show_t !aid_map
        ^ "\n\n- ctx0:\n"
        ^ eval_ctx_to_string_no_filter { ctx0 with env = List.rev env0 }
        ^ "\n\n- ctx1:\n"
        ^ eval_ctx_to_string_no_filter { ctx1 with env = List.rev env1 }
        ^ "\n\n"));

    match (env0, env1) with
    | EBinding (BDummy b0, v0) :: env0', EBinding (BDummy b1, v1) :: env1' ->
        (* Sanity check: if the dummy value is an old value, the bindings must
           be the same and their values equal (and the borrows/loans/symbolic *)
        if DummyVarId.Set.mem b0 fixed_ids.dids then (
          (* Fixed values: the values must be equal *)
          assert (b0 = b1);
          assert (v0 = v1);
          (* The ids present in the left value must be fixed *)
          let ids, _ = compute_typed_value_ids v0 in
          assert ((not S.check_equiv) || ids_are_fixed ids));
        (* We still match the values - allows to compute mappings (which
           are the identity actually) *)
        let _ = M.match_typed_values ctx v0 v1 in
        match_envs env0' env1'
    | EBinding (BVar b0, v0) :: env0', EBinding (BVar b1, v1) :: env1' ->
        assert (b0 = b1);
        (* Match the values *)
        let _ = M.match_typed_values ctx v0 v1 in
        (* Continue *)
        match_envs env0' env1'
    | EAbs abs0 :: env0', EAbs abs1 :: env1' ->
        log#ldebug (lazy "match_ctxs: match_envs: matching abs");
        (* Same as for the dummy values: there are two cases *)
        if AbstractionId.Set.mem abs0.abs_id fixed_ids.aids then (
          log#ldebug (lazy "match_ctxs: match_envs: matching abs: fixed abs");
          (* Still in the prefix: the abstractions must be the same *)
          assert (abs0 = abs1);
          (* Their ids must be fixed *)
          let ids, _ = compute_abs_ids abs0 in
          assert ((not S.check_equiv) || ids_are_fixed ids);
          (* Continue *)
          match_envs env0' env1')
        else (
          log#ldebug
            (lazy "match_ctxs: match_envs: matching abs: not fixed abs");
          (* Match the values *)
          match_abstractions abs0 abs1;
          (* Continue *)
          match_envs env0' env1')
    | [], [] ->
        (* Done *)
        ()
    | _ ->
        (* The elements don't match *)
        raise (Distinct "match_ctxs: match_envs: env elements don't match")
  in

  (* Match the environments.

     Rem.: we don't match the ended regions (would it make any sense actually?) *)
  try
    (* Remove the frame delimiter (the first element of an environment is a frame delimiter) *)
    let env0 = List.rev ctx0.env in
    let env1 = List.rev ctx1.env in
    let env0, env1 =
      match (env0, env1) with
      | EFrame :: env0, EFrame :: env1 -> (env0, env1)
      | _ -> raise (Failure "Unreachable")
    in

    match_envs env0 env1;
    let maps =
      {
        aid_map = !aid_map;
        blid_map = !blid_map;
        borrow_id_map = !borrow_id_map;
        loan_id_map = !loan_id_map;
        rid_map = !rid_map;
        sid_map = !sid_map;
        sid_to_value_map = !sid_to_value_map;
      }
    in
    Some maps
  with Distinct msg ->
    log#ldebug (lazy ("match_ctxs: distinct: " ^ msg));
    None

let ctxs_are_equivalent (fixed_ids : ids_sets) (ctx0 : eval_ctx)
    (ctx1 : eval_ctx) : bool =
  let check_equivalent = true in
  let lookup_shared_value _ = raise (Failure "Unreachable") in
  Option.is_some
    (match_ctxs check_equivalent fixed_ids lookup_shared_value
       lookup_shared_value ctx0 ctx1)

let match_ctx_with_target (config : config) (loop_id : LoopId.id)
    (is_loop_entry : bool) (fp_bl_maps : borrow_loan_corresp)
    (fp_input_svalues : SymbolicValueId.id list) (fixed_ids : ids_sets)
    (src_ctx : eval_ctx) : st_cm_fun =
 fun cf tgt_ctx ->
  (* Debug *)
  log#ldebug
    (lazy
      ("match_ctx_with_target:\n" ^ "\n- fixed_ids: " ^ show_ids_sets fixed_ids
     ^ "\n" ^ "\n- src_ctx: " ^ eval_ctx_to_string src_ctx ^ "\n- tgt_ctx: "
     ^ eval_ctx_to_string tgt_ctx));

  (* We first reorganize [tgt_ctx] so that we can match [src_ctx] with it (by
     ending loans for instance - remember that the [src_ctx] is the fixed point
     context, which results from joins during which we ended the loans which
     were introduced during the loop iterations)
  *)
  (* End the loans which lead to mismatches when joining *)
  let rec cf_reorganize_join_tgt : cm_fun =
   fun cf tgt_ctx ->
    (* Collect fixed values in the source and target contexts: end the loans in the
       source context which don't appear in the target context *)
    let filt_src_env, _, _ = ctx_split_fixed_new fixed_ids src_ctx in
    let filt_tgt_env, _, _ = ctx_split_fixed_new fixed_ids tgt_ctx in

    log#ldebug
      (lazy
        ("match_ctx_with_target:\n" ^ "\n- fixed_ids: "
       ^ show_ids_sets fixed_ids ^ "\n" ^ "\n- filt_src_ctx: "
        ^ env_to_string src_ctx filt_src_env
        ^ "\n- filt_tgt_ctx: "
        ^ env_to_string tgt_ctx filt_tgt_env));

    (* Remove the abstractions *)
    let filter (ee : env_elem) : bool =
      match ee with EBinding _ -> true | EAbs _ | EFrame -> false
    in
    let filt_src_env = List.filter filter filt_src_env in
    let filt_tgt_env = List.filter filter filt_tgt_env in

    (* Match the values to check if there are loans to eliminate *)

    (* We need to pick a context for some functions like [match_typed_values]:
       the context is only used to lookup module data, so we can pick whichever
       we want.
       TODO: this is not very clean. Maybe we should just carry this data around.
    *)
    let ctx = tgt_ctx in

    let nabs = ref [] in

    let module S : MatchJoinState = struct
      (* The context is only used to lookup module data: we can pick whichever we want *)
      let ctx = ctx
      let loop_id = loop_id
      let nabs = nabs
    end in
    let module JM = MakeJoinMatcher (S) in
    let module M = MakeMatcher (JM) in
    try
      let _ =
        List.iter
          (fun (var0, var1) ->
            match (var0, var1) with
            | EBinding (BDummy b0, v0), EBinding (BDummy b1, v1) ->
                assert (b0 = b1);
                let _ = M.match_typed_values ctx v0 v1 in
                ()
            | EBinding (BVar b0, v0), EBinding (BVar b1, v1) ->
                assert (b0 = b1);
                let _ = M.match_typed_values ctx v0 v1 in
                ()
            | _ -> raise (Failure "Unexpected"))
          (List.combine filt_src_env filt_tgt_env)
      in
      (* No exception was thrown: continue *)
      cf tgt_ctx
    with ValueMatchFailure e ->
      (* Exception: end the corresponding borrows, and continue *)
      let cc =
        match e with
        | LoanInRight bid -> InterpreterBorrows.end_borrow config bid
        | LoansInRight bids -> InterpreterBorrows.end_borrows config bids
        | AbsInRight _ | AbsInLeft _ | LoanInLeft _ | LoansInLeft _ ->
            raise (Failure "Unexpected")
      in
      comp cc cf_reorganize_join_tgt cf tgt_ctx
  in

  (* Introduce the "identity" abstractions for the loop reentry.

     Match the target context with the source context so as to compute how to
     map the borrows from the target context (i.e., the fixed point context)
     to the borrows in the source context.

     Substitute the *loans* in the abstractions introduced by the target context
     (the abstractions of the fixed point) to properly link those abstraction:
     we introduce *identity* abstractions (the loans are equal to the borrows):
     we substitute the loans and introduce fresh ids for the borrows, symbolic
     values, etc. About the *identity abstractions*, see the comments for
     [compute_fixed_point_id_correspondance].

     TODO: this whole thing is very technical and error-prone.
     We should rely on a more primitive and safer function
     [add_identity_abs] to add the identity abstractions one by one.
  *)
  let cf_introduce_loop_fp_abs : m_fun =
   fun tgt_ctx ->
    (* Match the source and target contexts *)
    let filt_tgt_env, _, _ = ctx_split_fixed_new fixed_ids tgt_ctx in
    let filt_src_env, new_absl, new_dummyl =
      ctx_split_fixed_new fixed_ids src_ctx
    in
    assert (new_dummyl = []);
    let filt_tgt_ctx = { tgt_ctx with env = filt_tgt_env } in
    let filt_src_ctx = { src_ctx with env = filt_src_env } in

    let src_to_tgt_maps =
      let check_equiv = false in
      let fixed_ids = ids_sets_empty_borrows_loans fixed_ids in
      let open InterpreterBorrowsCore in
      let lookup_shared_loan lid ctx : typed_value =
        match snd (lookup_loan ek_all lid ctx) with
        | Concrete (VSharedLoan (_, v)) -> v
        | Abstract (ASharedLoan (_, v, _)) -> v
        | _ -> raise (Failure "Unreachable")
      in
      let lookup_in_src id = lookup_shared_loan id src_ctx in
      let lookup_in_tgt id = lookup_shared_loan id tgt_ctx in
      (* Match *)
      Option.get
        (match_ctxs check_equiv fixed_ids lookup_in_src lookup_in_tgt
           filt_src_ctx filt_tgt_ctx)
    in
    let tgt_to_src_borrow_map =
      BorrowId.Map.of_list
        (List.map
           (fun (x, y) -> (y, x))
           (BorrowId.InjSubst.bindings src_to_tgt_maps.borrow_id_map))
    in

    (* Debug *)
    log#ldebug
      (lazy
        ("match_ctx_with_target: cf_introduce_loop_fp_abs:" ^ "\n\n- tgt_ctx: "
       ^ eval_ctx_to_string tgt_ctx ^ "\n\n- src_ctx: "
       ^ eval_ctx_to_string src_ctx ^ "\n\n- filt_tgt_ctx: "
        ^ eval_ctx_to_string_no_filter filt_tgt_ctx
        ^ "\n\n- filt_src_ctx: "
        ^ eval_ctx_to_string_no_filter filt_src_ctx
        ^ "\n\n- new_absl:\n"
        ^ eval_ctx_to_string
            { src_ctx with env = List.map (fun abs -> EAbs abs) new_absl }
        ^ "\n\n- fixed_ids:\n" ^ show_ids_sets fixed_ids ^ "\n\n- fp_bl_maps:\n"
        ^ show_borrow_loan_corresp fp_bl_maps
        ^ "\n\n- src_to_tgt_maps: "
        ^ show_ids_maps src_to_tgt_maps));

    (* Update the borrows and symbolic ids in the source context.

       Going back to the [list_nth_mut_example], the original environment upon
       re-entering the loop is:

       {[
         abs@0 { ML l0 }
         ls -> MB l5 (s@6 : loops::List<T>)
         i -> s@7 : u32
         _@1 -> MB l0 (loops::List::Cons (ML l1, ML l2))
         _@2 -> MB l2 (@Box (ML l4))                      // tail
         _@3 -> MB l1 (s@3 : T)                           // hd
         abs@1 { MB l4, ML l5 }
       ]}

       The fixed-point environment is:
       {[
         env_fp = {
           abs@0 { ML l0 }
           ls -> MB l1 (s3 : loops::List<T>)
           i -> s4 : u32
           abs@fp {
             MB l0 // this borrow appears in [env0]
             ML l1
           }
         }
       ]}

       Through matching, we detect that in [env_fp], [l1] is matched
       to [l5]. We introduce a fresh borrow [l6] for [l1], and remember
       in the map [src_fresh_borrows_map] that: [{ l1 -> l6}].

       We get:
       {[
         abs@0 { ML l0 }
         ls -> MB l6 (s@6 : loops::List<T>) // l6 is fresh and doesn't have a corresponding loan
         i -> s@7 : u32
         _@1 -> MB l0 (loops::List::Cons (ML l1, ML l2))
         _@2 -> MB l2 (@Box (ML l4))                      // tail
         _@3 -> MB l1 (s@3 : T)                           // hd
         abs@1 { MB l4, ML l5 }
       ]}

       Later, we will introduce the identity abstraction:
       {[
         abs@2 { MB l5, ML l6 }
       ]}
    *)
    (* First, compute the set of borrows which appear in the fresh abstractions
       of the fixed-point: we want to introduce fresh ids only for those. *)
    let new_absl_ids, _ = compute_absl_ids new_absl in
    let src_fresh_borrows_map = ref BorrowId.Map.empty in
    let visit_tgt =
      object
        inherit [_] map_eval_ctx

        method! visit_borrow_id _ id =
          (* Map the borrow, if it needs to be mapped *)
          if
            (* We map the borrows for which we computed a mapping *)
            BorrowId.InjSubst.Set.mem id
              (BorrowId.InjSubst.elements src_to_tgt_maps.borrow_id_map)
            (* And which have corresponding loans in the fresh fixed-point abstractions *)
            && BorrowId.Set.mem
                 (BorrowId.Map.find id tgt_to_src_borrow_map)
                 new_absl_ids.loan_ids
          then (
            let src_id = BorrowId.Map.find id tgt_to_src_borrow_map in
            let nid = fresh_borrow_id () in
            src_fresh_borrows_map :=
              BorrowId.Map.add src_id nid !src_fresh_borrows_map;
            nid)
          else id
      end
    in
    let tgt_ctx = visit_tgt#visit_eval_ctx () tgt_ctx in

    log#ldebug
      (lazy
        ("match_ctx_with_target: cf_introduce_loop_fp_abs: \
          src_fresh_borrows_map:\n"
        ^ BorrowId.Map.show BorrowId.to_string !src_fresh_borrows_map
        ^ "\n"));

    (* Rem.: we don't update the symbolic values. It is not necessary
       because there shouldn't be any symbolic value containing borrows.

       Rem.: we will need to do something about the symbolic values in the
       abstractions and in the *variable bindings* once we allow symbolic
       values containing borrows to not be eagerly expanded.
    *)
    assert Config.greedy_expand_symbolics_with_borrows;

    (* Update the borrows and loans in the abstractions of the target context.

       Going back to the [list_nth_mut] example and by using [src_fresh_borrows_map],
       we instantiate the fixed-point abstractions that we will insert into the
       context.
       The abstraction is [abs { MB l0, ML l1 }].
       Because of [src_fresh_borrows_map], we substitute [l1] with [l6].
       Because of the match between the contexts, we substitute [l0] with [l5].
       We get:
       {[
         abs@2 { MB l5, ML l6 }
       ]}
    *)
    let region_id_map = ref RegionId.Map.empty in
    let get_rid rid =
      match RegionId.Map.find_opt rid !region_id_map with
      | Some rid -> rid
      | None ->
          let nid = fresh_region_id () in
          region_id_map := RegionId.Map.add rid nid !region_id_map;
          nid
    in
    let visit_src =
      object
        inherit [_] map_eval_ctx as super

        method! visit_borrow_id _ bid =
          log#ldebug
            (lazy
              ("match_ctx_with_target: cf_introduce_loop_fp_abs: \
                visit_borrow_id: " ^ BorrowId.to_string bid ^ "\n"));

          (* Lookup the id of the loan corresponding to this borrow *)
          let src_lid =
            BorrowId.InjSubst.find bid fp_bl_maps.borrow_to_loan_id_map
          in

          log#ldebug
            (lazy
              ("match_ctx_with_target: cf_introduce_loop_fp_abs: looked up \
                src_lid: " ^ BorrowId.to_string src_lid ^ "\n"));

          (* Lookup the tgt borrow id to which this borrow was mapped *)
          let tgt_bid =
            BorrowId.InjSubst.find src_lid src_to_tgt_maps.borrow_id_map
          in

          log#ldebug
            (lazy
              ("match_ctx_with_target: cf_introduce_loop_fp_abs: looked up \
                tgt_bid: " ^ BorrowId.to_string tgt_bid ^ "\n"));

          tgt_bid

        method! visit_loan_id _ id =
          log#ldebug
            (lazy
              ("match_ctx_with_target: cf_introduce_loop_fp_abs: \
                visit_loan_id: " ^ BorrowId.to_string id ^ "\n"));
          (* Map the borrow - rem.: we mapped the borrows *in the values*,
             meaning we know how to map the *corresponding loans in the
             abstractions* *)
          match BorrowId.Map.find_opt id !src_fresh_borrows_map with
          | None ->
              (* No mapping: this means that the borrow was mapped when
                 we matched values (it doesn't come from a fresh abstraction)
                 and because of this, it should actually be mapped to itself *)
              assert (
                BorrowId.InjSubst.find id src_to_tgt_maps.borrow_id_map = id);
              id
          | Some id -> id

        method! visit_symbolic_value_id _ _ = fresh_symbolic_value_id ()
        method! visit_abstraction_id _ _ = fresh_abstraction_id ()
        method! visit_region_id _ id = get_rid id

        (** We also need to change the abstraction kind *)
        method! visit_abs env abs =
          match abs.kind with
          | Loop (loop_id', rg_id, kind) ->
              assert (loop_id' = loop_id);
              assert (kind = LoopSynthInput);
              let can_end = false in
              let kind : abs_kind = Loop (loop_id, rg_id, LoopCall) in
              let abs = { abs with kind; can_end } in
              super#visit_abs env abs
          | _ -> super#visit_abs env abs
      end
    in
    let new_absl = List.map (visit_src#visit_abs ()) new_absl in
    let new_absl = List.map (fun abs -> EAbs abs) new_absl in

    (* Add the abstractions from the target context to the source context *)
    let nenv = List.append new_absl tgt_ctx.env in
    let tgt_ctx = { tgt_ctx with env = nenv } in

    log#ldebug
      (lazy
        ("match_ctx_with_target:cf_introduce_loop_fp_abs:\n- result ctx:\n"
       ^ eval_ctx_to_string tgt_ctx));

    (* Sanity check *)
    if !Config.check_invariants then
      Invariants.check_borrowed_values_invariant tgt_ctx;

    (* End all the borrows which appear in the *new* abstractions *)
    let new_borrows =
      BorrowId.Set.of_list
        (List.map snd (BorrowId.Map.bindings !src_fresh_borrows_map))
    in
    let cc = InterpreterBorrows.end_borrows config new_borrows in

    (* Compute the loop input values *)
    let input_values =
      SymbolicValueId.Map.of_list
        (List.map
           (fun sid ->
             (sid, SymbolicValueId.Map.find sid src_to_tgt_maps.sid_to_value_map))
           fp_input_svalues)
    in

    (* Continue *)
    cc
      (cf
         (if is_loop_entry then EndEnterLoop (loop_id, input_values)
          else EndContinue (loop_id, input_values)))
      tgt_ctx
  in

  (* Compose and continue *)
  cf_reorganize_join_tgt cf_introduce_loop_fp_abs tgt_ctx