libgpr2_25.0.0_70fe0fcf/langkit/gen/src/gpr_parser-rewriting_implementation.adb

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
--
--  Copyright (C) 2019-2023, AdaCore
--  SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
--


with Ada.Containers.Hashed_Sets;
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;

with System;
with System.Memory;

with Gpr_Parser_Support.Generic_API; use Gpr_Parser_Support.Generic_API;
with Gpr_Parser_Support.Hashes;
with Gpr_Parser_Support.Slocs; use Gpr_Parser_Support.Slocs;
with Gpr_Parser_Support.Token_Data_Handlers;
use Gpr_Parser_Support.Token_Data_Handlers;

with Gpr_Parser.Common;       use Gpr_Parser.Common;
with Gpr_Parser.Generic_API;  use Gpr_Parser.Generic_API;
with Gpr_Parser.Generic_API.Introspection;
use Gpr_Parser.Generic_API.Introspection;
with Gpr_Parser.Implementation;
with Gpr_Parser.Lexer_Implementation;
use Gpr_Parser.Lexer_Implementation;

with Gpr_Parser.Unparsing_Implementation;
use Gpr_Parser.Unparsing_Implementation;

package body Gpr_Parser.Rewriting_Implementation is

   use type System.Memory.size_t;

   function Convert is new Ada.Unchecked_Conversion
     (Rewriting_Handle, Rewriting_Handle_Pointer);
   function Convert is new Ada.Unchecked_Conversion
     (Rewriting_Handle_Pointer, Rewriting_Handle);

   function Hash is new Gpr_Parser_Support.Hashes.Hash_Access
     (Node_Rewriting_Handle_Type, Node_Rewriting_Handle);
   package NRH_Sets is new Ada.Containers.Hashed_Sets
     (Element_Type        => Node_Rewriting_Handle,
      Equivalent_Elements => "=",
      Hash                => Hash);

   procedure Pre_Check (Value : Boolean; Msg : String);
   --  Raise a Precondition_Failure exception with the given message
   --  if the Value is False.

   function Parent_Is_List (Node : Node_Rewriting_Handle) return Boolean
   is (Node.Parent /= null and then Node.Parent.Children.Kind = Expanded_List);
   --  Return whether Node's parent is a list node.
   --
   --  Since a tied and non-root node rewriting handle can exist only when its
   --  parent is expanded, it is safe checking the parent's Children field.

   function Index_For
     (Handle : Node_Rewriting_Handle;
      Member : Struct_Member_Ref) return Positive;
   --  Return the 1-based index of the ``Member`` parse field in the node
   --  referenced ``Handle``. Raise a ``Precondition_Failure`` if there is no
   --  such member.

   function Index_In_Parent_List
     (Handle : Node_Rewriting_Handle) return Positive;
   --  Assuming ``Handle`` is a node whose parent is a list node, return its
   --  1-based index in that list node.

   procedure Set_Child
     (Handle : Node_Rewriting_Handle;
      Index  : Positive;
      Child  : Node_Rewriting_Handle);
   --  Assign ``Child`` to the child slot at the given ``Index`` in ``Handle``

   ---------------
   -- Pre_Check --
   ---------------

   procedure Pre_Check (Value : Boolean; Msg : String) is
   begin
      if not Value then
         raise Precondition_Failure with Msg;
      end if;
   end Pre_Check;

   ---------------
   -- Index_For --
   ---------------

   function Index_For
     (Handle : Node_Rewriting_Handle;
      Member : Struct_Member_Ref) return Positive
   is
      Result : Positive := 1;
   begin
      if Language (Owner (Member)) /= Self_Id then
         raise Precondition_Failure with "invalid member language";
      elsif Is_Property (Member) then
         raise Precondition_Failure with "got property, parse field expected";
      end if;

      declare
         T            : constant Type_Ref := Kind_To_Type (Handle.Kind);
         Node_Members : constant Struct_Member_Ref_Array := Members (T);
      begin
         if Is_Null_For (Member, T) then
            raise Precondition_Failure
              with "invalid reference to the node rewriting handle of a null"
                   & " field";
         end if;
         for M of Node_Members loop
            if M = Member then
               return Result;
            elsif not Is_Property (M) and not Is_Null_For (M, T) then
               Result := Result + 1;
            end if;
         end loop;
      end;

      return (raise Precondition_Failure with "no such member on this node");
   end Index_For;

   --------------------------
   -- Index_In_Parent_List --
   --------------------------

   function Index_In_Parent_List
     (Handle : Node_Rewriting_Handle) return Positive
   is
      Parent : constant Node_Rewriting_Handle := Handle.Parent;
   begin
      for I in 1 .. Natural (Parent.Children.Vector.Length) loop
         if Parent.Children.Vector.Element (I) = Handle then
            return I;
         end if;
      end loop;

      --  We should not be able to reach this point, as ``Handle`` should
      --  always be present in the list of children of ``Handle.Parent``
      --  (otherwise the tree of node rewriting handles is corrupted).

      return (raise Program_Error);
   end Index_In_Parent_List;

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   function Handle (Context : Internal_Context) return Rewriting_Handle is
     (Convert (Get_Rewriting_Handle (Context)));

   function Context (Handle : Rewriting_Handle) return Internal_Context is
   begin
      
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   
      return Handle.Context;
   end Context;

   function Allocate
     (Kind          : Gpr_Node_Kind_Type;
      Context       : Rewriting_Handle;
      Unit_Handle   : Unit_Rewriting_Handle;
      Parent_Handle : Node_Rewriting_Handle)
      return Node_Rewriting_Handle
      with Pre =>
         Context /= No_Rewriting_Handle
         and then (Unit_Handle = No_Unit_Rewriting_Handle
                   or else Unit_Handle.Context_Handle = Context)
         and then (Parent_Handle = No_Node_Rewriting_Handle
                   or else Parent_Handle.Context_Handle = Context);

   function Allocate
     (Node          : Bare_Gpr_Node;
      Context       : Rewriting_Handle;
      Unit_Handle   : Unit_Rewriting_Handle;
      Parent_Handle : Node_Rewriting_Handle)
      return Node_Rewriting_Handle
      with Pre =>
         Context /= No_Rewriting_Handle
         and then (Unit_Handle = No_Unit_Rewriting_Handle
                   or else Unit_Handle.Context_Handle = Context)
         and then (Parent_Handle = No_Node_Rewriting_Handle
                   or else Parent_Handle.Context_Handle = Context);
   --  Allocate a handle for Node and register it in Unit_Handle's map

   function Allocate_Stub
     (Context : Rewriting_Handle) return Node_Rewriting_Handle;
   --  Allocate a stub rewriting node in ``Context``, to be used as a temporary
   --  node in ``Rotate``.

   procedure Expand_Children (Node : Node_Rewriting_Handle)
      with Pre => Node /= No_Node_Rewriting_Handle;
   --  If Node.Children.Kind is Unexpanded, populate Node's list of Children to
   --  mimic the related bare AST node. Otherwise, do nothing.

   procedure Free_Handles (Handle : in out Rewriting_Handle);
   --  Free all resources tied to Handle. This also releases the rewriting
   --  handle singleton in Handle's Context.

   procedure Tie
     (Handle, Parent : Node_Rewriting_Handle;
      Unit           : Unit_Rewriting_Handle);
   --  Tie the node represented by handle so that either:
   --
   --    * it is the root of Unit (Parent is null);
   --    * it is a child of Parent (Unit is null).
   --
   --  Do nothing if Handle is null.

   procedure Untie (Handle : Node_Rewriting_Handle);
   --  Untie the node represented by Handle. Do nothing if Handle is null.

   -------------------------
   -- C_Context_To_Handle --
   -------------------------

   function C_Context_To_Handle
     (Context : Internal_Context) return Rewriting_Handle is
   begin
      Clear_Last_Exception;
      return Handle (Context);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Context_To_Handle;

   -------------------------
   -- C_Handle_To_Context --
   -------------------------

   function C_Handle_To_Context
     (Handle : Rewriting_Handle) return Internal_Context is
   begin
      Clear_Last_Exception;
      return Context (Handle);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Handle_To_Context;

   ---------------------
   -- Start_Rewriting --
   ---------------------

   function Start_Rewriting
     (Context : Internal_Context) return Rewriting_Handle is
   begin
      
      Pre_Check
        (Handle (Context) = No_Rewriting_Handle,
         "Handle (Context) must be null");
   

      declare
         Result : constant Rewriting_Handle := new Rewriting_Handle_Type'
           (Context   => Context,
            Units     => <>,
            Pool      => Create,
            New_Nodes => <>,
            Stubs     => <>);
      begin
         Result.New_Nodes := Nodes_Pools.Create (Result.Pool);
         Result.Stubs := Nodes_Pools.Create (Result.Pool);
         Set_Rewriting_Handle (Context, Convert (Result));
         return Result;
      end;
   end Start_Rewriting;

   -----------------------
   -- C_Start_Rewriting --
   -----------------------

   function C_Start_Rewriting
     (Context : Internal_Context) return Rewriting_Handle is
   begin
      Clear_Last_Exception;
      return Start_Rewriting (Context);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Start_Rewriting;

   ---------------------
   -- Abort_Rewriting --
   ---------------------

   procedure Abort_Rewriting (Handle : in out Rewriting_Handle) is
   begin
      
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   
      Free_Handles (Handle);
   end Abort_Rewriting;

   -----------------------
   -- C_Abort_Rewriting --
   -----------------------

   procedure C_Abort_Rewriting (Handle : Rewriting_Handle) is
      H : Rewriting_Handle := Handle;
   begin
      Clear_Last_Exception;
      Abort_Rewriting (H);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Abort_Rewriting;

   -----------
   -- Apply --
   -----------

   function Apply (Handle : in out Rewriting_Handle) return Apply_Result is

      type Processed_Unit_Record is record
         Unit     : Internal_Unit;
         New_Data : Reparsed_Unit;
      end record;
      type Processed_Unit is access Processed_Unit_Record;
      procedure Free is new Ada.Unchecked_Deallocation
        (Processed_Unit_Record, Processed_Unit);

      package Processed_Unit_Vectors is new Ada.Containers.Vectors
        (Positive, Processed_Unit);

      Units  : Processed_Unit_Vectors.Vector;
      Result : Apply_Result := (Success => True);

   begin
      
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

      --  Try to reparse all units that were potentially modified
      for Unit_Handle of Handle.Units loop
         declare
            PU    : constant Processed_Unit := new Processed_Unit_Record'
              (Unit     => Unit_Handle.Unit,
               New_Data => <>);
            Input : Internal_Lexer_Input :=
              (Kind        => Bytes_Buffer,
               Charset     => <>,
               Read_BOM    => False,
               Bytes       => System.Null_Address,
               Bytes_Count => 0);
            Bytes : String_Access;

            function Error_Result return Apply_Result
            is ((Success => False, Unit => PU.Unit, Diagnostics => <>));
         begin
            Units.Append (PU);

            --  Reparse (i.e. unparse and then parse) this rewritten unit
            begin
               Bytes := Unparse
                 (Create_Abstract_Node (Unit_Handle.Root),
                  PU.Unit,
                  Preserve_Formatting => True,
                  As_Unit             => True);
            exception
               when Exc : Malformed_Tree_Error =>
                  Result := Error_Result;
                  Append
                    (Result.Diagnostics,
                     No_Source_Location_Range,
                     To_Text (Exception_Message (Exc)));
                  exit;
            end;
            Input.Charset := Unit_Handle.Unit.Charset;
            Input.Bytes := Bytes.all'Address;
            Input.Bytes_Count := Bytes.all'Length;
            Do_Parsing (PU.Unit, Input, PU.New_Data);
            Free (Bytes);

            --  If there is a parsing error, abort the rewriting process
            if not PU.New_Data.Diagnostics.Is_Empty then
               Result := Error_Result;
               Result.Diagnostics.Move (PU.New_Data.Diagnostics);
               Destroy (PU.New_Data);
               exit;
            end if;
         end;
      end loop;

      --  If all reparsing went fine, actually replace the AST nodes all over
      --  the context and free all resources associated to Handle.
      if Result.Success then
         for PU of Units loop
            Update_After_Reparse (PU.Unit, PU.New_Data);
         end loop;
         Free_Handles (Handle);
      end if;

      --  Clean-up our local resources and return
      for PU of Units loop
         Free (PU);
      end loop;
      return Result;
   end Apply;

   -------------
   -- C_Apply --
   -------------

   procedure C_Apply
     (Handle : Rewriting_Handle;
      Result : access C_Apply_Result)
   is
      H          : Rewriting_Handle := Handle;
      Ada_Result : Apply_Result;
   begin
      Clear_Last_Exception;

      Ada_Result := Apply (H);
      Result.Success := (if Ada_Result.Success then 1 else 0);
      if not Ada_Result.Success then
         Result.Unit := Ada_Result.Unit;
         if Ada_Result.Diagnostics.Is_Empty then
            Result.Diagnostics_Count := 0;
            Result.Diagnostics := null;
         else
            Result.Diagnostics_Count :=
              Interfaces.C.int (Ada_Result.Diagnostics.Length);
            declare
               type Array_Type is
                 array (1 .. Natural (Result.Diagnostics_Count))
                 of gpr_diagnostic;
               Diagnostics_Address : constant System.Address :=
                 System.Memory.Alloc (Array_Type'Size / 8);
               Diagnostics         : Array_Type
                 with Import, Address => Diagnostics_Address;
            begin
               Result.Diagnostics :=
                 C_Diagnostic_Array.To_Pointer (Diagnostics_Address);
               for I in Diagnostics'Range loop
                  declare
                     D : Diagnostic renames Ada_Result.Diagnostics (I);
                  begin
                     Diagnostics (I).Sloc_Range := Wrap (D.Sloc_Range);
                     Diagnostics (I).Message :=
                       Wrap_Alloc (To_Text (D.Message));
                  end;
               end loop;
            end;
         end if;
      end if;

   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Apply;

   -----------------------
   -- Free_Apply_Result --
   -----------------------

   procedure Free_Apply_Result (Result : access C_Apply_Result) is
      use type Interfaces.C.int;
   begin
      Clear_Last_Exception;

      if Result.Success = 0 then
         if Result.Diagnostics_Count /= 0 then
            declare
               type Array_Type is
                 array (1 .. Natural (Result.Diagnostics_Count))
                 of gpr_diagnostic;
               Diagnostics_Address : constant System.Address :=
                 (C_Diagnostic_Array.To_Address (Result.Diagnostics));
               Diagnostics         : Array_Type
                 with Import, Address => Diagnostics_Address;
            begin
               for D of Diagnostics loop
                  gpr_destroy_text
                    (D.Message'Unrestricted_Access);
               end loop;
            end;
            System.Memory.Free
              (C_Diagnostic_Array.To_Address (Result.Diagnostics));
         end if;
      end if;

   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end Free_Apply_Result;

   ------------------
   -- Unit_Handles --
   ------------------

   function Unit_Handles
     (Handle : Rewriting_Handle) return Unit_Rewriting_Handle_Array is
   begin
      
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

      declare
         Count  : constant Natural := Natural (Handle.Units.Length);
         Result : Unit_Rewriting_Handle_Array (1 .. Count);
         I      : Positive := 1;
      begin
         for Unit of Handle.Units loop
            Result (I) := Unit;
            I := I + 1;
         end loop;
         return Result;
      end;
   end Unit_Handles;

   --------------------
   -- C_Unit_Handles --
   --------------------

   function C_Unit_Handles
     (Handle : Rewriting_Handle) return C_Unit_Array.Object_Pointer is
   begin
      Clear_Last_Exception;

      declare
         Units : constant Unit_Rewriting_Handle_Array := Unit_Handles (Handle);
         type Array_Type is
           array (Units'First .. Units'Last + 1)
           of Unit_Rewriting_Handle;
         Result_Address : constant System.Address :=
           System.Memory.Alloc (Array_Type'Size / 8);
         Result         : Array_Type
           with Import, Address => Result_Address;
      begin
         for I in Units'Range loop
            Result (I) := Units (I);
         end loop;
         Result (Result'Last) := null;
         return C_Unit_Array.To_Pointer (Result_Address);
      end;

   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Unit_Handles;

   ------------
   -- Handle --
   ------------

   function Handle (Unit : Internal_Unit) return Unit_Rewriting_Handle is
   begin
      
      Pre_Check
        (Handle (Context (Unit)) /= No_Rewriting_Handle,
         "Handle (Context (Unit)) should not be null");
   
      
      Pre_Check
        (not Has_Diagnostics (Unit),
         "Unit must not have diagnostics");
   

      declare
         use Unit_Maps;

         Context        : constant Internal_Context := Unit.Context;
         Context_Handle : constant Rewriting_Handle := Handle (Context);
         Filename       : constant Unbounded_String :=
            To_Unbounded_String (Get_Filename (Unit));

         Cur : constant Cursor := Context_Handle.Units.Find (Filename);
      begin
         if Cur /= No_Element then
            return Element (Cur);
         end if;

         declare
            Result : constant Unit_Rewriting_Handle :=
               new Unit_Rewriting_Handle_Type'(Context_Handle => Context_Handle,
                                               Unit           => Unit,
                                               Root           => <>,
                                               Nodes          => <>);
         begin
            Context_Handle.Units.Insert (Filename, Result);
            Result.Root := Handle (Root (Unit));
            return Result;
         end;
      end;
   end Handle;

   ----------
   -- Unit --
   ----------

   function Unit (Handle : Unit_Rewriting_Handle) return Internal_Unit
   is
   begin
      
      Pre_Check
        (Handle /= No_Unit_Rewriting_Handle,
         "Handle should not be null");
   
      return Handle.Unit;
   end Unit;

   ----------------------
   -- C_Unit_To_Handle --
   ----------------------

   function C_Unit_To_Handle
     (Unit : Internal_Unit) return Unit_Rewriting_Handle is
   begin
      Clear_Last_Exception;
      return Handle (Unit);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Unit_To_Handle;

   ----------------------
   -- C_Handle_To_Unit --
   ----------------------

   function C_Handle_To_Unit
     (Handle : Unit_Rewriting_Handle) return Internal_Unit is
   begin
      Clear_Last_Exception;
      return Unit (Handle);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Handle_To_Unit;

   ----------
   -- Root --
   ----------

   function Root (Handle : Unit_Rewriting_Handle) return Node_Rewriting_Handle
   is
   begin
      
      Pre_Check
        (Handle /= No_Unit_Rewriting_Handle,
         "Handle should not be null");
   
      return Handle.Root;
   end Root;

   ------------
   -- C_Root --
   ------------

   function C_Root
     (Handle : Unit_Rewriting_Handle) return Node_Rewriting_Handle is
   begin
      Clear_Last_Exception;
      return Root (Handle);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Root;

   --------------
   -- Set_Root --
   --------------

   procedure Set_Root
     (Handle : Unit_Rewriting_Handle;
      Root   : Node_Rewriting_Handle) is
   begin
      
      Pre_Check
        (Handle /= No_Unit_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Root = No_Node_Rewriting_Handle or else not Tied (Root),
         "Root must not be tied to another rewriting context.");
   

      Untie (Handle.Root);
      Handle.Root := Root;
      Tie (Root, No_Node_Rewriting_Handle, Handle);
   end Set_Root;

   ----------------
   -- C_Set_Root --
   ----------------

   procedure C_Set_Root
     (Handle : Unit_Rewriting_Handle;
      Root   : Node_Rewriting_Handle) is
   begin
      Clear_Last_Exception;
      Set_Root (Handle, Root);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Set_Root;

   -------------
   -- Unparse --
   -------------

   function Unparse
     (Handle : Unit_Rewriting_Handle) return Unbounded_Text_Type is
   begin
      
      Pre_Check
        (Handle /= No_Unit_Rewriting_Handle,
         "Handle should not be null");
   
      return Unparsing_Implementation.Unparse
        (Node                => Create_Abstract_Node (Handle.Root),
         Unit                => Handle.Unit,
         Preserve_Formatting => True,
         As_Unit             => True);
   end Unparse;

   ---------------
   -- C_Unparse --
   ---------------

   procedure C_Unparse
     (Handle : Unit_Rewriting_Handle; Result : access gpr_text)
   is
      Text : Unbounded_Text_Type;
   begin
      Clear_Last_Exception;
      Text := Unparse (Handle);
      Result.all := Wrap_Alloc (Text);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Unparse;

   ------------
   -- Handle --
   ------------

   function Handle (Node : Bare_Gpr_Node) return Node_Rewriting_Handle is
   begin
      
      Pre_Check
        (Handle (Context (Node.Unit)) /= No_Rewriting_Handle,
         "Handle (Context (Node.Unit)) should not be null");
   
      
      Pre_Check
        (not Has_Diagnostics (Node.Unit),
         "Node.Unit must not have diagnostics");
   

      if Node = null then
         return No_Node_Rewriting_Handle;
      end if;

      declare
         use Node_Maps;

         Unit_Handle : constant Unit_Rewriting_Handle :=
            Handle (Node.Unit);
         Cur         : constant Cursor := Unit_Handle.Nodes.Find (Node);
      begin
         --  If we have already built a handle for this node, just return it
         if Cur /= No_Element then
            return Element (Cur);

         --  Otherwise, if this node has a parent, make sure this parent has
         --  its own handle, then expand its children. This last must create
         --  the handle we are supposed to return.
         elsif Node.Parent /= null then
            Expand_Children (Handle (Node.Parent));
            return Element (Unit_Handle.Nodes.Find (Node));
         end if;

         --  Otherwise, we are dealing with the root node: just create its
         --  rewriting handle.
         return Allocate (Node, Unit_Handle.Context_Handle, Unit_Handle,
                          No_Node_Rewriting_Handle);
      end;
   end Handle;

   ----------------------
   -- C_Node_To_Handle --
   ----------------------

   function C_Node_To_Handle (Node : gpr_base_node) return Node_Rewriting_Handle
   is
      N : Bare_Gpr_Node;
   begin
      Clear_Last_Exception;
      N := Unwrap (Node);
      return Handle (N);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Node_To_Handle;

   ----------
   -- Node --
   ----------

   function Node
     (Handle : Node_Rewriting_Handle) return Bare_Gpr_Node is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      return Handle.Node;
   end Node;

   ----------------------
   -- C_Handle_To_Node --
   ----------------------

   function C_Handle_To_Node
     (Handle : Node_Rewriting_Handle) return gpr_base_node
   is
      N : Bare_Gpr_Node;
   begin
      Clear_Last_Exception;
      N := Node (Handle);
      return Wrap (N);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return Wrap (null);
   end C_Handle_To_Node;

   -------------
   -- Context --
   -------------

   function Context (Handle : Node_Rewriting_Handle) return Rewriting_Handle is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      return Handle.Context_Handle;
   end Context;

   -----------------------
   -- C_Node_To_Context --
   -----------------------

   function C_Node_To_Context
     (Node : Node_Rewriting_Handle) return Rewriting_Handle is
   begin
      Clear_Last_Exception;
      return Context (Node);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Node_To_Context;

   -------------
   -- Unparse --
   -------------

   function Unparse (Handle : Node_Rewriting_Handle) return Text_Type is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      return To_Wide_Wide_String
        (Unparsing_Implementation.Unparse
           (Create_Abstract_Node (Handle),
            Unit                => null,
            Preserve_Formatting => True,
            As_Unit             => False));
   end Unparse;

   ---------------
   -- C_Unparse --
   ---------------

   procedure C_Unparse
     (Handle : Node_Rewriting_Handle; Result : access gpr_text) is
   begin
      Clear_Last_Exception;
      declare
         Text : constant Text_Type := Unparse (Handle);
      begin
         Result.all := Wrap_Alloc (Text);
      end;
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Unparse;

   --------------
   -- Allocate --
   --------------

   function Allocate
     (Kind          : Gpr_Node_Kind_Type;
      Context       : Rewriting_Handle;
      Unit_Handle   : Unit_Rewriting_Handle;
      Parent_Handle : Node_Rewriting_Handle)
      return Node_Rewriting_Handle
   is
      Tied : constant Boolean := Unit_Handle /= No_Unit_Rewriting_Handle;
   begin
      return new Node_Rewriting_Handle_Type'
        (Context_Handle => Context,
         Node           => null,
         Parent         => Parent_Handle,
         Previous       => No_Node_Rewriting_Handle,
         Next           => No_Node_Rewriting_Handle,
         Kind           => Kind,
         Tied           => Tied,
         Root_Of        =>
           (if Tied and then Parent_Handle = No_Node_Rewriting_Handle
            then Unit_Handle
            else No_Unit_Rewriting_Handle),
         Children       => Unexpanded_Children);
   end Allocate;

   --------------
   -- Allocate --
   --------------

   function Allocate
     (Node          : Bare_Gpr_Node;
      Context       : Rewriting_Handle;
      Unit_Handle   : Unit_Rewriting_Handle;
      Parent_Handle : Node_Rewriting_Handle)
      return Node_Rewriting_Handle
   is
      Result : constant Node_Rewriting_Handle := Allocate
        (Node.Kind, Context, Unit_Handle, Parent_Handle);
   begin
      Result.Node := Node;
      if Result.Tied then
         Unit_Handle.Nodes.Insert (Node, Result);
      end if;
      return Result;
   end Allocate;

   -------------------
   -- Allocate_Stub --
   -------------------

   function Allocate_Stub
     (Context : Rewriting_Handle) return Node_Rewriting_Handle
   is
   begin
      return Allocate
        (Kind          => Gpr_Node_Kind_Type'First,
         Context       => Context,
         Unit_Handle   => No_Unit_Rewriting_Handle,
         Parent_Handle => No_Node_Rewriting_Handle);
   end Allocate_Stub;

   ---------------------
   -- Expand_Children --
   ---------------------

   procedure Expand_Children (Node : Node_Rewriting_Handle) is
      Children : Node_Children renames Node.Children;
   begin
      --  If this handle has already be expanded, there is nothing to do

      if Children.Kind /= Unexpanded then
         return;
      end if;

      --  Otherwise, expand to the appropriate children form

      declare
         N           : constant Bare_Gpr_Node := Node.Node;
         Unit_Handle : constant Unit_Rewriting_Handle :=
            Handle (N.Unit);

         function Allocate_Child
           (Child : Bare_Gpr_Node) return Node_Rewriting_Handle
         is (if Child = null
             then No_Node_Rewriting_Handle
             else Allocate
                   (Child, Unit_Handle.Context_Handle, Unit_Handle, Node));
      begin
         if Is_Token_Node (N) then

            --  N is a token node: its expanded form contains only its text

            Children := (Kind => Expanded_Token_Node,
                         Text => To_Unbounded_Wide_Wide_String (Text (N)));

         elsif Is_List_Node (N.Kind) then

            --  N is a list node: its expanded form contains a doubly linked
            --  list for its children.

            declare
               Count                : constant Natural := Children_Count (N);
               First, Last, Current : Node_Rewriting_Handle :=
                 No_Node_Rewriting_Handle;
            begin
               for I in 1 .. Count loop
                  Current := Allocate_Child (Implementation.Child (N, I));
                  if First = No_Node_Rewriting_Handle then
                     First := Current;
                     Last := Current;
                  else
                     Last.Next := Current;
                     Current.Previous := Last;
                     Last := Current;
                  end if;
               end loop;
               Children :=
                 (Kind  => Expanded_List,
                  First => First,
                  Last  => Last,
                  Count => Count);
            end;

         else
            --  N is a regular node: its expanded form contains a vector for
            --  all non-null syntax fields.

            Children := (Kind => Expanded_Regular, Vector => <>);
            declare
               Count : constant Natural := Children_Count (N);
            begin
               Children.Vector.Reserve_Capacity
                 (Ada.Containers.Count_Type (Count));
               for I in 1 .. Count loop
                  Children.Vector.Append
                    (Allocate_Child (Implementation.Child (N, I)));
               end loop;
            end;
         end if;
      end;
   end Expand_Children;

   ------------------
   -- Free_Handles --
   ------------------

   procedure Free_Handles (Handle : in out Rewriting_Handle) is

      procedure Free is new Ada.Unchecked_Deallocation
        (Rewriting_Handle_Type, Rewriting_Handle);
      procedure Free is new Ada.Unchecked_Deallocation
        (Unit_Rewriting_Handle_Type, Unit_Rewriting_Handle);
      procedure Free is new Ada.Unchecked_Deallocation
        (Node_Rewriting_Handle_Type, Node_Rewriting_Handle);

      Ctx : constant Internal_Context := Context (Handle);
   begin
      --  Free all resources tied to Handle
      for Unit of Handle.Units loop
         for Node of Unit.Nodes loop
            Free (Node);
         end loop;
         Free (Unit);
      end loop;
      for Node of Handle.New_Nodes loop
         declare
            N : Node_Rewriting_Handle := Node;
         begin
            Free (N);
         end;
      end loop;
      for Node of Handle.Stubs loop
         declare
            N : Node_Rewriting_Handle := Node;
         begin
            Free (N);
         end;
      end loop;
      Free (Handle.Pool);
      Free (Handle);

      --  Release the rewriting handle singleton for its context
      Set_Rewriting_Handle (Ctx, Convert (Handle));
   end Free_Handles;

   ---------
   -- Tie --
   ---------

   procedure Tie
     (Handle, Parent : Node_Rewriting_Handle;
      Unit           : Unit_Rewriting_Handle) is
   begin
      if Handle /= No_Node_Rewriting_Handle then
         Handle.Parent := Parent;
         Handle.Tied := True;
         if Parent = No_Node_Rewriting_Handle then
            Handle.Root_Of := Unit;
         end if;
      end if;
   end Tie;

   -----------
   -- Untie --
   -----------

   procedure Untie (Handle : Node_Rewriting_Handle) is
   begin
      if Handle /= No_Node_Rewriting_Handle then
         Handle.Parent := No_Node_Rewriting_Handle;
         Handle.Previous := No_Node_Rewriting_Handle;
         Handle.Next := No_Node_Rewriting_Handle;
         Handle.Tied := False;
         Handle.Root_Of := No_Unit_Rewriting_Handle;
      end if;
   end Untie;

   ----------
   -- Kind --
   ----------

   function Kind (Handle : Node_Rewriting_Handle) return Gpr_Node_Kind_Type is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      return Handle.Kind;
   end Kind;

   ------------
   -- C_Kind --
   ------------

   function C_Kind (Handle : Node_Rewriting_Handle) return gpr_node_kind_enum is
   begin
      Clear_Last_Exception;
      declare
         K : constant Gpr_Node_Kind_Type := Kind (Handle);
      begin
         return gpr_node_kind_enum (K'Enum_Rep);
      end;
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return 0;
   end C_Kind;

   -----------
   -- Image --
   -----------

   function Image (Handle : Node_Rewriting_Handle) return String is
   begin
      if Handle = No_Node_Rewriting_Handle then
         return "None";
      end if;

      declare
         Tied_Suffix : constant String :=
           (if Tied (Handle) then " (tied)" else "");
      begin
         if Node (Handle) = null then
            declare
               K          : constant Gpr_Node_Kind_Type := Kind (Handle);
               Tok_Suffix : constant String :=
                 (if Is_Token_Node (K)
                  then " " & Image (Text (Handle), With_Quotes => True)
                  else "");
            begin
               return "<" & K'Image & Tok_Suffix & Tied_Suffix & ">";
            end;
         else
            declare
               Ent : constant Internal_Entity :=
                 (Node => Node (Handle),
                  Info => No_Entity_Info);
               Img : constant String := Image (Ent);
            begin
               return Img (Img'First .. Img'Last - 1) & Tied_Suffix & ">";
            end;
         end if;
      end;
   end Image;

   -------------
   -- C_Image --
   -------------

   procedure C_Image
     (Handle : Node_Rewriting_Handle; Result : access gpr_text) is
   begin
      Clear_Last_Exception;
      declare
         Img : constant Text_Type := To_Text (Image (Handle));
      begin
         Result.all := Wrap_Alloc (Img);
      end;
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Image;

   ----------
   -- Tied --
   ----------

   function Tied (Handle : Node_Rewriting_Handle) return Boolean is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      return Handle.Tied;
   end Tied;

   ------------
   -- C_Tied --
   ------------

   function C_Tied (Handle : Node_Rewriting_Handle) return Interfaces.C.int is
   begin
      Clear_Last_Exception;
      return (if Tied (Handle) then 1 else 0);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return 0;
   end C_Tied;

   ------------
   -- Parent --
   ------------

   function Parent
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      return Handle.Parent;
   end Parent;

   --------------
   -- C_Parent --
   --------------

   function C_Parent
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle is
   begin
      Clear_Last_Exception;
      return Parent (Handle);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Parent;

   --------------------
   -- Children_Count --
   --------------------

   function Children_Count (Handle : Node_Rewriting_Handle) return Natural is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      return
        (case Handle.Children.Kind is
         when Unexpanded          => Children_Count (Handle.Node),
         when Expanded_Regular    => Natural (Handle.Children.Vector.Length),
         when Expanded_List       => Handle.Children.Count,
         when Expanded_Token_Node => 0);
   end Children_Count;

   ----------------------
   -- C_Children_Count --
   ----------------------

   function C_Children_Count
     (Handle : Node_Rewriting_Handle) return Interfaces.C.int is
   begin
      Clear_Last_Exception;
      return Interfaces.C.int (Children_Count (Handle));
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return 0;
   end C_Children_Count;

   -----------
   -- Child --
   -----------

   function Child
     (Handle : Node_Rewriting_Handle;
      Field  : Struct_Member_Ref) return Node_Rewriting_Handle
   is
      Index : Positive;
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   

      Index := Index_For (Handle, Field);

      --  If this handle represents an already existing node, make sure it is
      --  expanded so we have a handle to return.
      Expand_Children (Handle);
      return Handle.Children.Vector.Element (Index);
   end Child;

   -------------
   -- C_Child --
   -------------

   function C_Child
     (Handle : Node_Rewriting_Handle;
      Field  : Interfaces.C.int) return Node_Rewriting_Handle
   is
      F : Struct_Member_Ref;
   begin
      Clear_Last_Exception;
      F := From_Index (Self_Id, Struct_Member_Index (Field));
      return Child (Handle, F);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Child;

   --------------
   -- Children --
   --------------

   function Children
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle_Array
   is
      I : Positive := 1;
      N : Node_Rewriting_Handle;
   begin
      return Result : Node_Rewriting_Handle_Array
                        (1 .. Children_Count (Handle))
      do
         if Is_List_Node (Handle) then
            N := First_Child (Handle);
            while N /= No_Node_Rewriting_Handle loop
               Result (I) := N;
               I := I + 1;
               N := Next_Child (N);
            end loop;
         else
            declare
               T            : constant Type_Ref :=
                 Kind_To_Type (Kind (Handle));
               Node_Members : constant Struct_Member_Ref_Array := Members (T);
            begin
               for M of Node_Members loop
                  if Is_Field (M) and then not Is_Null_For (M, T) then
                     Result (I) := Child (Handle, M);
                     I := I + 1;
                  end if;
               end loop;
            end;
         end if;
      end return;
   end Children;

   ----------------
   -- C_Children --
   ----------------

   procedure C_Children
     (Handle   : Node_Rewriting_Handle;
      Children : access C_Node_Array.Object_Pointer;
      Count    : access Interfaces.C.int) is
   begin
      Clear_Last_Exception;

      declare
         Result : constant Node_Rewriting_Handle_Array :=
           Rewriting_Implementation.Children (Handle);

         subtype Array_Type is Node_Rewriting_Handle_Array (Result'Range);
         Children_Address : constant System.Address :=
           System.Memory.Alloc (Array_Type'Size / 8);
         Ada_Children     : Array_Type
           with Import, Address => Children_Address;
      begin
         Ada_Children := Result;
         Children.all := C_Node_Array.To_Pointer (Children_Address);
         Count.all := Result'Length;
      end;
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Children;

   ---------------
   -- Set_Child --
   ---------------

   procedure Set_Child
     (Handle : Node_Rewriting_Handle;
      Index  : Positive;
      Child  : Node_Rewriting_Handle) is
   begin
      --  If this handle represents an already existing node, make sure it is
      --  expanded so that its children vector can be modified.
      Expand_Children (Handle);

      declare
         Child_Slot : Node_Rewriting_Handle renames
            Handle.Children.Vector.Reference (Index);
      begin
         --  Untie the child to be replaced if it exists
         Untie (Child_Slot);

         --  Tie the new child if it exists
         Tie (Child, Handle, No_Unit_Rewriting_Handle);

         Child_Slot := Child;
      end;
   end Set_Child;

   ---------------
   -- Set_Child --
   ---------------

   procedure Set_Child
     (Handle : Node_Rewriting_Handle;
      Field  : Struct_Member_Ref;
      Child  : Node_Rewriting_Handle) is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Child = No_Node_Rewriting_Handle or else not Tied (Child),
         "Child must not be tied to another rewriting context.");
   

      Set_Child (Handle, Index_For (Handle, Field), Child);
   end Set_Child;

   -----------------
   -- C_Set_Child --
   -----------------

   procedure C_Set_Child
     (Handle : Node_Rewriting_Handle;
      Field  : Interfaces.C.int;
      Child  : Node_Rewriting_Handle)
   is
      F : Struct_Member_Ref;
   begin
      Clear_Last_Exception;
      F := From_Index (Self_Id, Struct_Member_Index (Field));
      Set_Child (Handle, F, Child);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Set_Child;

   ----------
   -- Text --
   ----------

   function Text (Handle : Node_Rewriting_Handle) return Text_Type is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Is_Token_Node (Kind (Handle)),
         "Expected a token node. Got " & Kind (Handle)'Image);
   

      case Handle.Children.Kind is
         when Unexpanded =>
            if Is_Token_Node (Handle.Kind) then
               return Text (Handle.Node);
            else
               raise Program_Error;
            end if;
         when Expanded_Regular | Expanded_List =>
            return (raise Program_Error);
         when Expanded_Token_Node =>
            return To_Wide_Wide_String (Handle.Children.Text);
      end case;
   end Text;

   ------------
   -- C_Text --
   ------------

   procedure C_Text
     (Handle : Node_Rewriting_Handle; Result : access gpr_text) is
   begin
      Clear_Last_Exception;
      declare
         T : constant Text_Type := Text (Handle);
      begin
         Result.all := Wrap_Alloc (T);
      end;
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Text;

   --------------
   -- Set_Text --
   --------------

   procedure Set_Text (Handle : Node_Rewriting_Handle; Text : Text_Type) is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Is_Token_Node (Kind (Handle)),
         "Expected a token node. Got " & Kind (Handle)'Image);
   

      --  Make sure Handle is expanded so we have a Text field to override
      Expand_Children (Handle);

      Handle.Children.Text := To_Unbounded_Wide_Wide_String (Text);
   end Set_Text;

   ----------------
   -- C_Set_Text --
   ----------------

   procedure C_Set_Text
     (Handle : Node_Rewriting_Handle; Text : access gpr_text)
   is
      T : constant Text_Type (1 .. Natural (Text.Length))
      with Import, Address => Text.Chars;
   begin
      Clear_Last_Exception;
      Set_Text (Handle, T);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Set_Text;

   -------------
   -- Replace --
   -------------

   procedure Replace (Handle, New_Node : Node_Rewriting_Handle) is
      Parent : Node_Rewriting_Handle;
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Tied (Handle),
         "Handle must be tied to an analysis unit.");
   
      
      Pre_Check
        (New_Node = No_Node_Rewriting_Handle or else not Tied (New_Node),
         "New_Node must not be tied to another rewriting context.");
   

      if Handle = New_Node then
         return;
      end if;

      if Handle.Root_Of = No_Unit_Rewriting_Handle then

         --  If Handle is not the root node of its owning unit, go replace it
         --  in its parent's children list.

         if Parent_Is_List (Handle) then
            if New_Node = No_Node_Rewriting_Handle then
               Remove_Child (Handle);
               return;
            end if;

            Parent := Handle.Parent;
            if Handle.Previous = No_Node_Rewriting_Handle then
               Parent.Children.First := New_Node;
            else
               Handle.Previous.Next := New_Node;
            end if;
            if Handle.Next = No_Node_Rewriting_Handle then
               Parent.Children.Last := New_Node;
            else
               Handle.Next.Previous := New_Node;
            end if;
            Tie (New_Node, Parent, No_Unit_Rewriting_Handle);
            New_Node.Previous := Handle.Previous;
            New_Node.Next := Handle.Next;
            Untie (Handle);
         else
            Set_Child (Handle.Parent, Index_In_Parent_List (Handle), New_Node);
         end if;

      else
         --  Otherwise, replace it as a root node
         Set_Root (Handle.Root_Of, New_Node);
      end if;
   end Replace;

   ---------------
   -- C_Replace --
   ---------------

   procedure C_Replace (Handle, New_Node : Node_Rewriting_Handle) is
   begin
      Clear_Last_Exception;
      Replace (Handle, New_Node);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Replace;

   ------------
   -- Rotate --
   ------------

   procedure Rotate (Handles : Node_Rewriting_Handle_Array) is

      function Non_Null_Tied (Handle : Node_Rewriting_Handle) return Boolean
      is (Handle /= No_Node_Rewriting_Handle and then Tied (Handle));

      RH : Rewriting_Handle := No_Rewriting_Handle;
   begin
      --  Rotate is a no-op if there are less than two handles or none is tied

      if Handles'Length < 2 then
         return;
      end if;

      for H of Handles loop
         if Non_Null_Tied (H) then
            RH := H.Context_Handle;
            exit;
         end if;
      end loop;
      if RH = No_Rewriting_Handle then
         return;
      end if;

      --  Check that each non-null handle is present at most once in the input
      --  list.

      declare
         Handle_Set : NRH_Sets.Set;
      begin
         for H of Handles loop
            if H /= No_Node_Rewriting_Handle then
               begin
                  Handle_Set.Insert (H);
               exception
                  when Constraint_Error =>
                     raise Precondition_Failure with
                       "non-null handles can be present at most once";
               end;
            end if;
         end loop;
      end;

      --  Now that inputs are validated, we can start the rotation. As a
      --  reminder: replace H1 by H2, H2 by H3, ... Or in other words: put H2
      --  in the location of H1, put H3 in the location of H1.

      declare
         Stubs       : array (Handles'Range) of Node_Rewriting_Handle;
         Stub_Cursor : Nodes_Pools.Cursor := Nodes_Pools.First (RH.Stubs);
      begin
         --  First create stubs to replace the nodes that will be replaced with
         --  other nodes.

         for I in Handles'Range loop
            declare
               Node : constant Node_Rewriting_Handle := Handles (I);
               Repl : constant Node_Rewriting_Handle :=
                 Handles (if I = Handles'Last then Handles'First else I + 1);
               Stub : Node_Rewriting_Handle renames Stubs (I);
            begin
               --  Get a stub if needed. If an already allocated stub is
               --  available, use it, otherwise allocate one.

               if Non_Null_Tied (Node) and then Non_Null_Tied (Repl) then
                  if Nodes_Pools.Has_Element (RH.Stubs, Stub_Cursor) then
                     Stub := Nodes_Pools.Get (RH.Stubs, Stub_Cursor);
                     Stub_Cursor := Nodes_Pools.Next (RH.Stubs, Stub_Cursor);
                  else
                     Stub := Allocate_Stub (RH);
                     Nodes_Pools.Append (RH.Stubs, Stub);
                  end if;
               else
                  Stub := No_Node_Rewriting_Handle;
               end if;
            end;
         end loop;

         --  Now replace nodes with their stubs. We have to do this as separate
         --  pass because the replacement affects the "Tied" predicate that is
         --  used in the first pass.

         for I in Handles'Range loop
            if Handles (I) /= No_Node_Rewriting_Handle then
               Replace (Handles (I), Stubs (I));
            end if;
         end loop;

         --  Now that all the nodes to rotate are untied, replace stubs with
         --  the definitive nodes.

         for I in Handles'Range loop
            declare
               Stub : constant Node_Rewriting_Handle := Stubs (I);
               Repl : Node_Rewriting_Handle;
            begin
               if Stub /= No_Node_Rewriting_Handle then
                  Repl := Handles
                    (if I = Handles'Last then Handles'First else I + 1);
                  Replace (Stub, Repl);
               end if;
            end;
         end loop;
      end;
   end Rotate;

   --------------
   -- C_Rotate --
   --------------

   procedure C_Rotate
     (Handles : C_Node_Array.Object_Pointer;
      Count   : Interfaces.C.int) is
   begin
      Clear_Last_Exception;

      declare
         subtype Array_Type is
           Node_Rewriting_Handle_Array (1 .. Natural (Count));
         Handles_Address : constant System.Address :=
           C_Node_Array.To_Address (Handles);
         Ada_Handles     : constant Array_Type
           with Import, Address => Handles_Address;
      begin
         Rotate (Ada_Handles);
      end;
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Rotate;

   ------------------
   -- Is_List_Node --
   ------------------

   function Is_List_Node (Handle : Node_Rewriting_Handle) return Boolean is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      return Is_List_Node (Kind (Handle));
   end Is_List_Node;

   -----------------
   -- First_Child --
   -----------------

   function First_Child
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle
   is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Is_List_Node (Kind (Handle)),
         "Expected a list node. Got " & Kind (Handle)'Image);
   

      Expand_Children (Handle);
      return Handle.Children.First;
   end First_Child;

   -------------------
   -- C_First_Child --
   -------------------

   function C_First_Child
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle is
   begin
      Clear_Last_Exception;
      return First_Child (Handle);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_First_Child;

   ----------------
   -- Last_Child --
   ----------------

   function Last_Child
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle
   is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Is_List_Node (Kind (Handle)),
         "Expected a list node. Got " & Kind (Handle)'Image);
   

      Expand_Children (Handle);
      return Handle.Children.Last;
   end Last_Child;

   ------------------
   -- C_Last_Child --
   ------------------

   function C_Last_Child
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle is
   begin
      Clear_Last_Exception;
      return Last_Child (Handle);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Last_Child;

   ----------------
   -- Next_Child --
   ----------------

   function Next_Child
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Handle.Parent /= No_Node_Rewriting_Handle,
         "Handle.Parent should not be null");
   
      
      Pre_Check
        (Is_List_Node (Kind (Handle.Parent)),
         "Expected a list node. Got " & Kind (Handle.Parent)'Image);
   

      return Handle.Next;
   end Next_Child;

   ------------------
   -- C_Next_Child --
   ------------------

   function C_Next_Child
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle
   is
   begin
      Clear_Last_Exception;
      return Next_Child (Handle);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Next_Child;

   --------------------
   -- Previous_Child --
   --------------------

   function Previous_Child
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Handle.Parent /= No_Node_Rewriting_Handle,
         "Handle.Parent should not be null");
   
      
      Pre_Check
        (Is_List_Node (Kind (Handle.Parent)),
         "Expected a list node. Got " & Kind (Handle.Parent)'Image);
   

      return Handle.Previous;
   end Previous_Child;

   ----------------------
   -- C_Previous_Child --
   ----------------------

   function C_Previous_Child
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle
   is
   begin
      Clear_Last_Exception;
      return Previous_Child (Handle);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Previous_Child;

   -------------------
   -- Insert_Before --
   -------------------

   procedure Insert_Before (Handle, New_Sibling : Node_Rewriting_Handle) is
      Old_Previous, Parent : Node_Rewriting_Handle;
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      Parent := Handle.Parent;
      
      Pre_Check
        (Parent /= No_Node_Rewriting_Handle,
         "Parent should not be null");
   
      
      Pre_Check
        (Is_List_Node (Kind (Parent)),
         "Expected a list node. Got " & Kind (Parent)'Image);
   
      
      Pre_Check
        (New_Sibling = No_Node_Rewriting_Handle or else not Tied (New_Sibling),
         "New_Sibling must not be tied to another rewriting context.");
   

      Old_Previous := Handle.Previous;
      if Old_Previous = No_Node_Rewriting_Handle then
         Handle.Parent.Children.First := New_Sibling;
      else
         Old_Previous.Next := New_Sibling;
      end if;
      New_Sibling.Previous := Old_Previous;
      New_Sibling.Next := Handle;
      Handle.Previous := New_Sibling;
      Tie (New_Sibling, Parent, No_Unit_Rewriting_Handle);
      Parent.Children.Count := Parent.Children.Count + 1;
   end Insert_Before;

   ---------------------
   -- C_Insert_Before --
   ---------------------

   procedure C_Insert_Before (Handle, New_Sibling : Node_Rewriting_Handle) is
   begin
      Clear_Last_Exception;
      Insert_Before (Handle, New_Sibling);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Insert_Before;

   ------------------
   -- Insert_After --
   ------------------

   procedure Insert_After (Handle, New_Sibling : Node_Rewriting_Handle) is
      Old_Next, Parent : Node_Rewriting_Handle;
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      Parent := Handle.Parent;
      
      Pre_Check
        (Parent /= No_Node_Rewriting_Handle,
         "Parent should not be null");
   
      
      Pre_Check
        (Is_List_Node (Kind (Parent)),
         "Expected a list node. Got " & Kind (Parent)'Image);
   
      
      Pre_Check
        (New_Sibling = No_Node_Rewriting_Handle or else not Tied (New_Sibling),
         "New_Sibling must not be tied to another rewriting context.");
   

      Old_Next := Handle.Next;
      if Old_Next = No_Node_Rewriting_Handle then
         Handle.Parent.Children.Last := New_Sibling;
      else
         Old_Next.Previous := New_Sibling;
      end if;
      New_Sibling.Next := Old_Next;
      New_Sibling.Previous := Handle;
      Handle.Next := New_Sibling;
      Tie (New_Sibling, Parent, No_Unit_Rewriting_Handle);
      Parent.Children.Count := Parent.Children.Count + 1;
   end Insert_After;

   --------------------
   -- C_Insert_After --
   --------------------

   procedure C_Insert_After (Handle, New_Sibling : Node_Rewriting_Handle) is
   begin
      Clear_Last_Exception;
      Insert_After (Handle, New_Sibling);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Insert_After;

   ------------------
   -- Insert_First --
   ------------------

   procedure Insert_First (Handle, New_Child : Node_Rewriting_Handle) is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Is_List_Node (Kind (Handle)),
         "Expected a list node. Got " & Kind (Handle)'Image);
   
      
      Pre_Check
        (New_Child = No_Node_Rewriting_Handle or else not Tied (New_Child),
         "New_Child must not be tied to another rewriting context.");
   

      Expand_Children (Handle);
      if Handle.Children.First /= No_Node_Rewriting_Handle then
         Handle.Children.First.Previous := New_Child;
         New_Child.Next := Handle.Children.First;
      end if;
      Handle.Children.First := New_Child;
      if Handle.Children.Last = No_Node_Rewriting_Handle then
         Handle.Children.Last := New_Child;
      end if;
      Tie (New_Child, Handle, No_Unit_Rewriting_Handle);
      Handle.Children.Count := Handle.Children.Count + 1;
   end Insert_First;

   --------------------
   -- C_Insert_First --
   --------------------

   procedure C_Insert_First (Handle, New_Sibling : Node_Rewriting_Handle) is
   begin
      Clear_Last_Exception;
      Insert_First (Handle, New_Sibling);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Insert_First;

   -----------------
   -- Insert_Last --
   -----------------

   procedure Insert_Last (Handle, New_Child : Node_Rewriting_Handle) is
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Is_List_Node (Kind (Handle)),
         "Expected a list node. Got " & Kind (Handle)'Image);
   
      
      Pre_Check
        (New_Child = No_Node_Rewriting_Handle or else not Tied (New_Child),
         "New_Child must not be tied to another rewriting context.");
   

      Expand_Children (Handle);
      if Handle.Children.Last /= No_Node_Rewriting_Handle then
         Handle.Children.Last.Next := New_Child;
         New_Child.Previous := Handle.Children.Last;
      end if;
      Handle.Children.Last := New_Child;
      if Handle.Children.First = No_Node_Rewriting_Handle then
         Handle.Children.First := New_Child;
      end if;
      Tie (New_Child, Handle, No_Unit_Rewriting_Handle);
      Handle.Children.Count := Handle.Children.Count + 1;
   end Insert_Last;

   -------------------
   -- C_Insert_Last --
   -------------------

   procedure C_Insert_Last (Handle, New_Sibling : Node_Rewriting_Handle) is
   begin
      Clear_Last_Exception;
      Insert_Last (Handle, New_Sibling);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Insert_Last;

   ------------------
   -- Remove_Child --
   ------------------

   procedure Remove_Child (Handle : Node_Rewriting_Handle) is
      Parent : Node_Rewriting_Handle;
   begin
      
      Pre_Check
        (Handle /= No_Node_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Handle.Parent /= No_Node_Rewriting_Handle,
         "Handle.Parent should not be null");
   
      
      Pre_Check
        (Is_List_Node (Kind (Handle.Parent)),
         "Expected a list node. Got " & Kind (Handle.Parent)'Image);
   

      Expand_Children (Handle);
      Parent := Handle.Parent;
      if Parent.Children.First = Handle then
         Parent.Children.First := Handle.Next;
         if Handle.Next = No_Node_Rewriting_Handle then
            Parent.Children.Last := No_Node_Rewriting_Handle;
         else
            Handle.Next.Previous := No_Node_Rewriting_Handle;
         end if;
      elsif Parent.Children.Last = Handle then
         Parent.Children.Last := Handle.Previous;
         Parent.Children.Last.Next := No_Node_Rewriting_Handle;
      else
         Handle.Previous.Next := Handle.Next;
         Handle.Next.Previous := Handle.Previous;
      end if;
      Untie (Handle);
      Parent.Children.Count := Parent.Children.Count - 1;
   end Remove_Child;

   --------------------
   -- C_Remove_Child --
   --------------------

   procedure C_Remove_Child (Handle : Node_Rewriting_Handle) is
   begin
      Clear_Last_Exception;
      Remove_Child (Handle);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
   end C_Remove_Child;

   -----------
   -- Clone --
   -----------

   function Clone
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle
   is
      Result : Node_Rewriting_Handle;
   begin
      if Handle = No_Node_Rewriting_Handle then
         return Handle;
      end if;

      --  Make sure the original handle is expanded so we can iterate on it
      Expand_Children (Handle);

      --  If the input handle is associated to a node, so should be the cloned
      --  handle, so that its formatting is copied as well.
      Result :=
        (if Handle.Node = null
         then Allocate (Handle.Kind, Handle.Context_Handle,
                        No_Unit_Rewriting_Handle, No_Node_Rewriting_Handle)
         else Allocate (Handle.Node, Handle.Context_Handle,
                        No_Unit_Rewriting_Handle, No_Node_Rewriting_Handle));
      Nodes_Pools.Append (Handle.Context_Handle.New_Nodes, Result);

      --  Recursively clone children
      case Handle.Children.Kind is
         when Unexpanded =>
            raise Program_Error;

         when Expanded_Token_Node =>
            Result.Children := (Kind => Expanded_Token_Node,
                                Text => Handle.Children.Text);

         when Expanded_List =>
            declare
               First, Last, Cloned : Node_Rewriting_Handle :=
                 No_Node_Rewriting_Handle;
               Current             : Node_Rewriting_Handle :=
                 Handle.Children.First;
            begin
               while Current /= No_Node_Rewriting_Handle loop
                  Cloned := Clone (Current);
                  Tie (Cloned, Result, No_Unit_Rewriting_Handle);
                  if First = No_Node_Rewriting_Handle then
                     First := Cloned;
                     Last := Cloned;
                  else
                     Last.Next := Cloned;
                     Cloned.Previous := Last;
                     Last := Cloned;
                  end if;
                  Current := Next_Child (Current);
               end loop;
               Result.Children :=
                 (Kind  => Expanded_List,
                  First => First,
                  Last  => Last,
                  Count => Handle.Children.Count);
            end;

         when Expanded_Regular =>
            Result.Children := (Kind => Expanded_Regular, Vector => <>);
            Result.Children.Vector.Reserve_Capacity
              (Handle.Children.Vector.Length);
            for I in 1 .. Handle.Children.Vector.Last_Index loop
               declare
                  Child : constant Node_Rewriting_Handle :=
                    Clone (Handle.Children.Vector.Element (I));
               begin
                  Tie (Child, Result, No_Unit_Rewriting_Handle);
                  Result.Children.Vector.Append (Child);
               end;
            end loop;
      end case;

      return Result;
   end Clone;

   -------------
   -- C_Clone --
   -------------

   function C_Clone
     (Handle : Node_Rewriting_Handle) return Node_Rewriting_Handle is
   begin
      Clear_Last_Exception;
      return Clone (Handle);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Clone;

   -----------------
   -- Create_Node --
   -----------------

   function Create_Node
     (Handle : Rewriting_Handle;
      Kind   : Gpr_Node_Kind_Type) return Node_Rewriting_Handle is
   begin
      
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (not Is_Error_Node (Kind),
         "Expected a non-error node. Got " & Kind'Image);
   

      if Is_Token_Node (Kind) then
         return Create_Token_Node (Handle, Kind, "");
      else
         declare
            Count    : constant Integer := Kind_To_Node_Children_Count (Kind);
            Children : constant Node_Rewriting_Handle_Array (1 ..  Count) :=
               (others => No_Node_Rewriting_Handle);
         begin
            return Create_Regular_Node (Handle, Kind, Children);
         end;
      end if;
   end Create_Node;

   -------------------
   -- C_Create_Node --
   -------------------

   function C_Create_Node
     (Handle : Rewriting_Handle;
      Kind   : gpr_node_kind_enum) return Node_Rewriting_Handle
   is
      K : Gpr_Node_Kind_Type;
   begin
      Clear_Last_Exception;
      K := Gpr_Node_Kind_Type'Enum_Val (Kind);
      return Create_Node (Handle, K);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Create_Node;

   -----------------------
   -- Create_Token_Node --
   -----------------------

   function Create_Token_Node
     (Handle : Rewriting_Handle;
      Kind   : Gpr_Node_Kind_Type;
      Text   : Text_Type) return Node_Rewriting_Handle is
   begin
      
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (Is_Token_Node (Kind),
         "Expected a token node. Got " & Kind'Image);
   

      declare
         Result : constant Node_Rewriting_Handle := Allocate
           (Kind, Handle, No_Unit_Rewriting_Handle, No_Node_Rewriting_Handle);
      begin
         Result.Children := (Kind => Expanded_Token_Node,
                             Text => To_Unbounded_Wide_Wide_String (Text));
         Nodes_Pools.Append (Handle.New_Nodes, Result);
         return Result;
      end;
   end Create_Token_Node;

   -------------------------
   -- C_Create_Token_Node --
   -------------------------

   function C_Create_Token_Node
     (Handle : Rewriting_Handle;
      Kind   : gpr_node_kind_enum;
      Text   : access gpr_text) return Node_Rewriting_Handle
   is
      K : Gpr_Node_Kind_Type;
      T : constant Text_Type (1 .. Natural (Text.Length))
      with Import, Address => Text.Chars;
   begin
      Clear_Last_Exception;
      K := Gpr_Node_Kind_Type'Enum_Val (Kind);
      return Create_Token_Node (Handle, K, T);
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Create_Token_Node;

   -------------------------
   -- Create_Regular_Node --
   -------------------------

   function Create_Regular_Node
     (Handle   : Rewriting_Handle;
      Kind     : Gpr_Node_Kind_Type;
      Children : Node_Rewriting_Handle_Array) return Node_Rewriting_Handle
   is
      List : Boolean;
   begin
      
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   
      
      Pre_Check
        (not Is_Token_Node (Kind),
         "Expected a token node. Got " & Kind'Image);
   
      
      Pre_Check
        (not Is_Error_Node (Kind),
         "Expected a non-error node. Got " & Kind'Image);
   
      List := Is_List_Node (Kind);
      for One_Child of Children loop
         if List then
            
      Pre_Check
        (One_Child /= No_Node_Rewriting_Handle and then not Tied (One_Child),
         "One_Child must not be tied to another rewriting context.");
   
         else
            
      Pre_Check
        (One_Child = No_Node_Rewriting_Handle or else not Tied (One_Child),
         "One_Child must not be tied to another rewriting context.");
   
         end if;
      end loop;

      declare
         Result : Node_Rewriting_Handle := Allocate
           (Kind, Handle, No_Unit_Rewriting_Handle, No_Node_Rewriting_Handle);
      begin
         if List then
            declare
               First, Last : Node_Rewriting_Handle := No_Node_Rewriting_Handle;
            begin
               for C of Children loop
                  if First = No_Node_Rewriting_Handle then
                     First := C;
                  else
                     Last.Next := C;
                     C.Previous := Last;
                  end if;
                  Last := C;
                  Tie (C, Result, No_Unit_Rewriting_Handle);
               end loop;
               Result.Children :=
                 (Kind  => Expanded_List,
                  First => First,
                  Last  => Last,
                  Count => Children'Length);
            end;
         else
            Result.Children := (Kind   => Expanded_Regular,
                                Vector => <>);
            Result.Children.Vector.Reserve_Capacity (Children'Length);
            for C of Children loop
               Result.Children.Vector.Append (C);
               if C /= No_Node_Rewriting_Handle then
                  Tie (C, Result, No_Unit_Rewriting_Handle);
               end if;
            end loop;
         end if;
         Nodes_Pools.Append (Handle.New_Nodes, Result);
         return Result;
      end;
   end Create_Regular_Node;

   ---------------------------
   -- C_Create_Regular_Node --
   ---------------------------

   function C_Create_Regular_Node
     (Handle   : Rewriting_Handle;
      Kind     : gpr_node_kind_enum;
      Children : C_Node_Array.Object_Pointer;
      Count    : Interfaces.C.int) return Node_Rewriting_Handle is
   begin
      Clear_Last_Exception;
      declare
         K : constant Gpr_Node_Kind_Type := Gpr_Node_Kind_Type'Enum_Val (Kind);

         subtype Array_Type is
           Node_Rewriting_Handle_Array (1 .. Natural (Count));
         Children_Address : constant System.Address :=
           C_Node_Array.To_Address (Children);
         Ada_Children     : constant Array_Type
           with Import, Address => Children_Address;
      begin
         return Create_Regular_Node (Handle, K, Ada_Children);
      end;
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Create_Regular_Node;

   --------------------------
   -- Create_From_Template --
   --------------------------

   function Create_From_Template
     (Handle    : Rewriting_Handle;
      Template  : Text_Type;
      Arguments : Node_Rewriting_Handle_Array;
      Rule      : Grammar_Rule) return Node_Rewriting_Handle
   is
      type State_Type is (
         Default,
         --  Default state: no meta character being processed

         Open_Brace,
         --  The previous character is a open brace: the current one
         --  determines what it means.

         Close_Brace
         --  The previous character is a closing brace: the current one must be
         --  another closing brace.
      );

      Buffer   : Unbounded_Wide_Wide_String;
      State    : State_Type := Default;
      Next_Arg : Positive := Arguments'First;
   begin
      for One_Argument of Arguments loop
         
      Pre_Check
        (One_Argument = No_Node_Rewriting_Handle
            or else Context (One_Argument) = Handle,
         "One_Argument should be associated to rewriting context Handle.");
   
      end loop;

      --  Interpret the template looping over its characters with a state
      --  machine.
      for C of Template loop
         case State is
         when Default =>
            case C is
            when '{' =>
               State := Open_Brace;
            when '}' =>
               State := Close_Brace;
            when others =>
               Append (Buffer, C);
            end case;

         when Open_Brace =>
            case C is
            when '{' =>
               State := Default;
               Append (Buffer, C);
            when '}' =>
               State := Default;
               if Next_Arg in Arguments'Range then
                  declare
                     Unparsed_Arg : constant Wide_Wide_String :=
                        Unparse (Arguments (Next_Arg));
                  begin
                     Next_Arg := Next_Arg + 1;
                     Append (Buffer, Unparsed_Arg);
                  end;
               else
                  raise Template_Args_Error with
                     "not enough arguments provided";
               end if;
            when others =>
               raise Template_Format_Error with
                  "standalone ""{"" character";
            end case;

         when Close_Brace =>
            case C is
            when '}' =>
               State := Default;
               Append (Buffer, C);
            when others =>
               raise Template_Format_Error with
                  "standalone ""}"" character";
            end case;
         end case;
      end loop;

      --  Make sure that there is no standalone metacharacter at the end of the
      --  template.
      case State is
         when Default => null;
         when Open_Brace =>
            raise Template_Format_Error with "standalone ""{"" character";
         when Close_Brace =>
            raise Template_Format_Error with "standalone ""}"" character";
      end case;

      --  Make sure all given arguments were consumed
      if Next_Arg in Arguments'Range then
         raise Template_Args_Error with "too many arguments provided";
      end if;

      --  Now parse the resulting buffer and create the corresponding tree of
      --  nodes.
      declare
         Context  : constant Internal_Context :=
           Rewriting_Implementation.Context (Handle);
         Unit     : constant Internal_Unit := Templates_Unit (Context);
         Reparsed : Reparsed_Unit;
         Text     : constant Text_Type := To_Wide_Wide_String (Buffer);
         Input    : constant Internal_Lexer_Input :=
           (Kind       => Text_Buffer,
            Text       => Text'Address,
            Text_Count => Text'Length);

         function Transform
           (Node   : Bare_Gpr_Node;
            Parent : Node_Rewriting_Handle) return Node_Rewriting_Handle;
         --  Turn a node from the Reparsed unit into a recursively expanded
         --  node rewriting handle.

         ---------------
         -- Transform --
         ---------------

         function Transform
           (Node   : Bare_Gpr_Node;
            Parent : Node_Rewriting_Handle) return Node_Rewriting_Handle
         is
            Result : Node_Rewriting_Handle;
         begin
            if Node = null then
               return No_Node_Rewriting_Handle;
            end if;

            --  Allocate the handle for Node, and don't forget to remove the
            --  backlink to Node itself as it exists only temporarily for
            --  template instantiation. Also, track the newly allocated node
            --  so that it is freed correctly upon destruction of the
            --  rewriting context.
            Result := Allocate (Node, Handle, No_Unit_Rewriting_Handle,
                                Parent);
            Result.Node := null;
            Nodes_Pools.Append (Handle.New_Nodes, Result);

            if Is_Token_Node (Node) then
               declare
                  Index : constant Natural := Natural (Node.Token_Start_Index);
                  Data  : constant Stored_Token_Data :=
                     Reparsed.TDH.Tokens.Get (Index);
                  Text  : constant Text_Type := Reparsed.TDH.Source_Buffer
                    (Data.Source_First .. Data.Source_Last);
               begin
                  Result.Children :=
                    (Kind => Expanded_Token_Node,
                     Text => To_Unbounded_Wide_Wide_String (Text));
               end;

            elsif Is_List_Node (Node.Kind) then
               declare
                  Count                : constant Natural :=
                    Children_Count (Node);
                  First, Last, Current : Node_Rewriting_Handle :=
                    No_Node_Rewriting_Handle;
               begin
                  for I in 1 .. Count loop
                     Current :=
                       Transform (Implementation.Child (Node, I), Result);
                     if First = No_Node_Rewriting_Handle then
                        First := Current;
                        Last := Current;
                     else
                        Last.Next := Current;
                        Current.Previous := Last;
                        Last := Current;
                     end if;
                     Tie (Current, Result, No_Unit_Rewriting_Handle);
                  end loop;
                  Result.Children :=
                    (Kind  => Expanded_List,
                     First => First,
                     Last  => Last,
                     Count => Count);
               end;

            else
               declare
                  Count : constant Natural := Children_Count (Node);
               begin
                  Result.Children := (Kind => Expanded_Regular, Vector => <>);
                  Result.Children.Vector.Reserve_Capacity
                    (Ada.Containers.Count_Type (Count));
                  for I in 1 .. Count loop
                     declare
                        C : constant Node_Rewriting_Handle :=
                          Transform (Child (Node, I), Result);
                     begin
                        Tie (C, Result, No_Unit_Rewriting_Handle);
                        Result.Children.Vector.Append (C);
                     end;
                  end loop;
               end;
            end if;
            return Result;
         end Transform;

      begin
         Set_Rule (Unit, Rule);
         Do_Parsing (Unit, Input, Reparsed);
         if not Reparsed.Diagnostics.Is_Empty then
            Destroy (Reparsed);
            raise Template_Instantiation_Error;
         end if;

         declare
            Result : constant Node_Rewriting_Handle :=
               Transform (Reparsed.Ast_Root, No_Node_Rewriting_Handle);
         begin
            Destroy (Reparsed);
            return Result;
         end;
      end;
   end Create_From_Template;

   ----------------------------
   -- C_Create_From_Template --
   ----------------------------

   function C_Create_From_Template
     (Handle    : Rewriting_Handle;
      Template  : access gpr_text;
      Arguments : C_Node_Array.Object_Pointer;
      Count     : Interfaces.C.int;
      Rule      : gpr_grammar_rule) return Node_Rewriting_Handle is
   begin
      Clear_Last_Exception;
      declare
         Ada_Template : constant Text_Type (1 .. Natural (Template.Length))
         with Import, Address => Template.Chars;

         subtype Array_Type is
           Node_Rewriting_Handle_Array (1 .. Natural (Count));
         Arguments_Address : constant System.Address :=
           C_Node_Array.To_Address (Arguments);
         Ada_Arguments     : constant Array_Type
           with Import, Address => Arguments_Address;
      begin
         return Create_From_Template
           (Handle, Ada_Template, Ada_Arguments, Rule);
      end;
   exception
      when Exc : others =>
         Set_Last_Exception (Exc);
         return null;
   end C_Create_From_Template;


         function Create_Attribute_Decl
           (Handle : Rewriting_Handle
               ; Attribute_Decl_F_Attr_Name : Node_Rewriting_Handle
               ; Attribute_Decl_F_Attr_Index : Node_Rewriting_Handle
               ; Attribute_Decl_F_Expr : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Attribute_Decl,
               (1 => Attribute_Decl_F_Attr_Name, 2 => Attribute_Decl_F_Attr_Index, 3 => Attribute_Decl_F_Expr));
         end;


         function Create_Attribute_Reference
           (Handle : Rewriting_Handle
               ; Attribute_Reference_F_Attribute_Name : Node_Rewriting_Handle
               ; Attribute_Reference_F_Attribute_Index : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Attribute_Reference,
               (1 => Attribute_Reference_F_Attribute_Name, 2 => Attribute_Reference_F_Attribute_Index));
         end;


         function Create_Builtin_Function_Call
           (Handle : Rewriting_Handle
               ; Builtin_Function_Call_F_Function_Name : Node_Rewriting_Handle
               ; Builtin_Function_Call_F_Parameters : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Builtin_Function_Call,
               (1 => Builtin_Function_Call_F_Function_Name, 2 => Builtin_Function_Call_F_Parameters));
         end;


         function Create_Case_Construction
           (Handle : Rewriting_Handle
               ; Case_Construction_F_Var_Ref : Node_Rewriting_Handle
               ; Case_Construction_F_Items : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Case_Construction,
               (1 => Case_Construction_F_Var_Ref, 2 => Case_Construction_F_Items));
         end;


         function Create_Case_Item
           (Handle : Rewriting_Handle
               ; Case_Item_F_Choice : Node_Rewriting_Handle
               ; Case_Item_F_Decls : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Case_Item,
               (1 => Case_Item_F_Choice, 2 => Case_Item_F_Decls));
         end;


         function Create_Compilation_Unit
           (Handle : Rewriting_Handle
               ; Compilation_Unit_F_Project : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Compilation_Unit,
               (1 => Compilation_Unit_F_Project));
         end;


         function Create_Prefix
           (Handle : Rewriting_Handle
               ; Prefix_F_Prefix : Node_Rewriting_Handle
               ; Prefix_F_Suffix : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Prefix,
               (1 => Prefix_F_Prefix, 2 => Prefix_F_Suffix));
         end;


         function Create_Package_Decl
           (Handle : Rewriting_Handle
               ; Package_Decl_F_Pkg_Name : Node_Rewriting_Handle
               ; Package_Decl_F_Pkg_Spec : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Package_Decl,
               (1 => Package_Decl_F_Pkg_Name, 2 => Package_Decl_F_Pkg_Spec));
         end;


         function Create_Package_Extension
           (Handle : Rewriting_Handle
               ; Package_Extension_F_Extended_Name : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Package_Extension,
               (1 => Package_Extension_F_Extended_Name));
         end;


         function Create_Package_Renaming
           (Handle : Rewriting_Handle
               ; Package_Renaming_F_Renamed_Name : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Package_Renaming,
               (1 => Package_Renaming_F_Renamed_Name));
         end;


         function Create_Package_Spec
           (Handle : Rewriting_Handle
               ; Package_Spec_F_Extension : Node_Rewriting_Handle
               ; Package_Spec_F_Decls : Node_Rewriting_Handle
               ; Package_Spec_F_End_Name : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Package_Spec,
               (1 => Package_Spec_F_Extension, 2 => Package_Spec_F_Decls, 3 => Package_Spec_F_End_Name));
         end;


         function Create_Project
           (Handle : Rewriting_Handle
               ; Project_F_Context_Clauses : Node_Rewriting_Handle
               ; Project_F_Project_Decl : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Project,
               (1 => Project_F_Context_Clauses, 2 => Project_F_Project_Decl));
         end;


         function Create_Project_Declaration
           (Handle : Rewriting_Handle
               ; Project_Declaration_F_Qualifier : Node_Rewriting_Handle
               ; Project_Declaration_F_Project_Name : Node_Rewriting_Handle
               ; Project_Declaration_F_Extension : Node_Rewriting_Handle
               ; Project_Declaration_F_Decls : Node_Rewriting_Handle
               ; Project_Declaration_F_End_Name : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Project_Declaration,
               (1 => Project_Declaration_F_Qualifier, 2 => Project_Declaration_F_Project_Name, 3 => Project_Declaration_F_Extension, 4 => Project_Declaration_F_Decls, 5 => Project_Declaration_F_End_Name));
         end;


         function Create_Project_Extension
           (Handle : Rewriting_Handle
               ; Project_Extension_F_Is_All : Node_Rewriting_Handle
               ; Project_Extension_F_Path_Name : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Project_Extension,
               (1 => Project_Extension_F_Is_All, 2 => Project_Extension_F_Path_Name));
         end;


         function Create_String_Literal_At
           (Handle : Rewriting_Handle
               ; String_Literal_At_F_Str_Lit : Node_Rewriting_Handle
               ; String_Literal_At_F_At_Lit : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_String_Literal_At,
               (1 => String_Literal_At_F_Str_Lit, 2 => String_Literal_At_F_At_Lit));
         end;


         function Create_Terms
           (Handle : Rewriting_Handle
               ; Terms_F_Terms : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Terms,
               (1 => Terms_F_Terms));
         end;


         function Create_Type_Reference
           (Handle : Rewriting_Handle
               ; Type_Reference_F_Var_Type_Name : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Type_Reference,
               (1 => Type_Reference_F_Var_Type_Name));
         end;


         function Create_Typed_String_Decl
           (Handle : Rewriting_Handle
               ; Typed_String_Decl_F_Type_Id : Node_Rewriting_Handle
               ; Typed_String_Decl_F_String_Literals : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Typed_String_Decl,
               (1 => Typed_String_Decl_F_Type_Id, 2 => Typed_String_Decl_F_String_Literals));
         end;


         function Create_Variable_Decl
           (Handle : Rewriting_Handle
               ; Variable_Decl_F_Var_Name : Node_Rewriting_Handle
               ; Variable_Decl_F_Var_Type : Node_Rewriting_Handle
               ; Variable_Decl_F_Expr : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Variable_Decl,
               (1 => Variable_Decl_F_Var_Name, 2 => Variable_Decl_F_Var_Type, 3 => Variable_Decl_F_Expr));
         end;


         function Create_Variable_Reference
           (Handle : Rewriting_Handle
               ; Variable_Reference_F_Variable_Name : Node_Rewriting_Handle
               ; Variable_Reference_F_Attribute_Ref : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_Variable_Reference,
               (1 => Variable_Reference_F_Variable_Name, 2 => Variable_Reference_F_Attribute_Ref));
         end;


         function Create_With_Decl
           (Handle : Rewriting_Handle
               ; With_Decl_F_Is_Limited : Node_Rewriting_Handle
               ; With_Decl_F_Path_Names : Node_Rewriting_Handle
            ) return Node_Rewriting_Handle is
         begin
            
      Pre_Check
        (Handle /= No_Rewriting_Handle,
         "Handle should not be null");
   

            return Create_Regular_Node
              (Handle, Gpr_With_Decl,
               (1 => With_Decl_F_Is_Limited, 2 => With_Decl_F_Path_Names));
         end;

end Gpr_Parser.Rewriting_Implementation;