libgpr2_24.0.0_eda3c693/src/lib/gpr2-kb.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
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
--
--  Copyright (C) 2019-2023, AdaCore
--
--  SPDX-License-Identifier: Apache-2.0 WITH LLVM-Exception
--

with Ada.Command_Line;
with Ada.Directories;
with Ada.Exceptions;
with Ada.Text_IO;
with Ada.Strings.Fixed;

with GNAT.Directory_Operations;
with GNAT.OS_Lib;

with GNATCOLL.OS.Process;
with GNATCOLL.Traces;
with GNATCOLL.VFS;
with GNATCOLL.VFS_Utils;

with GPR2.KB.Compiler_Iterator;
with GPR2.KB.Parsing;
with GPR2.Message;

package body GPR2.KB is

   Main_Trace : constant GNATCOLL.Traces.Trace_Handle :=
                  GNATCOLL.Traces.Create
                    ("KNOWLEDGE_BASE",
                     GNATCOLL.Traces.Off);

   Match_Trace : constant GNATCOLL.Traces.Trace_Handle :=
                   GNATCOLL.Traces.Create
                     ("KNOWLEDGE_BASE.MATHCING",
                      GNATCOLL.Traces.Off);

   No_Compatible_Compilers : exception;
   --  Raised when any combination of compilers found can form a supported
   --  configuration.

   procedure Complete_Command_Line_Compilers
     (Self             : in out Object;
      On_Target        : Name_Type;
      Filters          : Compiler_Lists.List;
      Compilers        : in out Compiler_Lists.List;
      Selected_Target  : in out Unbounded_String;
      Fallback         : Boolean;
      Errors           : out Log.Object;
      Environment      : GPR2.Environment.Object);
   --  In batch mode, the configuration descriptions indicate what compilers
   --  should be selected. Each of these descriptions selects the first
   --  matching compiler available, and all descriptions must match a compiler.
   --  The information provided by the user does not have to be complete, and
   --  this procedure completes all missing information like version, runtime,
   --  and so on.
   --  Filters is the list specified by the user, and contains potentially
   --  partial information for each compiler. On output, Compilers is completed
   --  with the full information for all compilers in Filters.
   --  If any of the required compilers cannot be found corresponding
   --  diagnostic is passed through Errors.
   --  If no set of compatible compilers was found raises
   --  No_Compatible_Compilers.

   function Extra_Dirs_From_Filters
     (Filters : Compiler_Lists.List) return String;
   --  Compute the list of directories that should be prepended to the PATH
   --  when searching for compilers. These are all the directories that the
   --  user has explicitly specified in his filters.

   function Is_Language_With_No_Compiler
     (Self     : Object;
      Language : Language_Id) return Boolean;
   --  Given a language name (lower case), returns True if that language is
   --  known to require no compiler.

   function Is_Supported_Config
     (Self      : Object;
      Compilers : Compiler_Lists.List) return Boolean;
   --  Whether we know how to link code compiled with all the selected
   --  compilers.

   procedure Parse_All_Dirs
     (Processed_Value : out External_Value_Lists.List;
      Visited         : in out String_To_External_Value.Map;
      Current_Dir     : String;
      Path_To_Check   : String;
      Regexp          : Regpat.Pattern_Matcher;
      Regexp_Str      : String;
      Value_If_Match  : String;
      Group           : Integer;
      Group_Match     : String := "";
      Group_Count     : Natural := 0;
      Contents        : Pattern_Matcher_Holder;
      Merge_Same_Dirs : Boolean;
      Error_Sloc      : Source_Reference.Object;
      Messages        : in out Log.Object);
   --  Parses all subdirectories of Current_Dir for those that match
   --  Path_To_Check (see description of <directory>). When a match is found,
   --  the regexp is evaluated against the current directory, and the matching
   --  parenthesis group is appended to Append_To (comma-separated).
   --  If Group is -1, then Value_If_Match is used instead of the parenthesis
   --  group.
   --  Group_Match is the substring that matched Group (if it has been matched
   --  already). Group_Count is the number of parenthesis groups that have been
   --  processed so far. The idea is to compute the matching substring as we
   --  go, since the regexp might no longer match in the end, if for instance
   --  it includes ".." directories.
   --
   --  If Merge_Same_Dirs is True, then the values that come from a
   --  <directory> node will be merged (the last one is kept, other removed) if
   --  they point to the same physical directory (after normalizing names). In
   --  this case, Visited contains the list of normalized directory names.
   --
   --  Contents, if specified, is a regular expression. It indicates that any
   --  file matching the pattern should be parsed, and the first line matching
   --  that regexp should be used as the name of the file instead. This is a
   --  way to simulate symbolic links on platforms that do not use them.

   generic
      with function Callback (Var_Name, Index : String) return String;
   function Substitute_Variables
     (Str        : String;
      Error_Sloc : Source_Reference.Object;
      Messages   : in out Log.Object) return String;
   --  Substitutes variables in Str (their value is computed through Callback).
   --  Possible errors are stored in Messages.

   function Substitute_Variables_In_Compiler_Description
     (Str        : String;
      Comp       : Compiler;
      Error_Sloc : Source_Reference.Object;
      Messages   : in out Log.Object) return String;
   --  Substitutes the special "$..." names in compiler description

   package Ordered_Languages_Vectors is new
     Ada.Containers.Vectors (Positive, Language_Id);
   subtype Ordered_Languages is Ordered_Languages_Vectors.Vector;

   function Substitute_Variables_In_Configuration
     (Self       : Object;
      Str        : String;
      Comps      : Compiler_Lists.List;
      Langs      : Ordered_Languages;
      Error_Sloc : Source_Reference.Object;
      Messages   : in out Log.Object) return String;
   --  Substitutes the special "$..." names in configuration

   function Get_Variable_Value
     (Comp : Compiler;
      Name : String) return String;
   --  Returns the value of a predefined or user-defined variable.
   --  If the variable is not defined a warning is emitted and an empty
   --  string is returned.

   function Get_String_No_Adalib (Str : String) return String;
   --  Returns the name without "adalib" at the end

   function To_String (Comp : Compiler) return String;
   --  Return a string representing the compiler. Used for diagnostics.

   function To_String (Compilers  : Compiler_Lists.List) return String;
   --  Return a string representing the list of compilers. Only Selected
   --  compilers are taken into account. Used for diagnostics.

   procedure Set_Selection
     (Compilers : in out Compiler_Lists.List;
      Cursor    : Compiler_Lists.Cursor;
      Selected  : Boolean);

   function Match
     (Filter    : Compilers_Filter_Lists.List;
      Compilers : Compiler_Lists.List) return Boolean;
   --  Returns True if all elements of Filter matches against Compilers.
   --  Filter represents the list of nodes <configuration><compilers>.

   function Match
     (Filter    : Compilers_Filter;
      Compilers : Compiler_Lists.List) return Boolean;
   --  Returns True if at least one component of Filter matches against
   --  Compilers, taking into account the negate value.
   --  Filter represents a single node <configuration><compilers>.

   function Match
     (Filter    : Compiler_Filter;
      Compilers : Compiler_Lists.List) return Boolean;
   --  Returns True if at least on of the Compilers match the filter.
   --  Filter represents a single node <configuration><compilers><compiler>.

   function Match
     (Target_Filter : Double_String_Lists.List;
      Negate        : Boolean;
      Compilers     : Compiler_Lists.List) return Boolean;
   --  Return True if Filter matches the list of selected configurations

   function Generate_Configuration
     (Self      : Object;
      Compilers : Compiler_Lists.List;
      Target    : String;
      Langs     : Ordered_Languages;
      Errors    : in out Log.Object) return Unbounded_String;
   --  Generate the configuration string for the list of selected compilers

   package String_Maps is new Ada.Containers.Indefinite_Ordered_Maps
     (String, String);

   procedure Merge_Config
     (Self       : Object;
      Packages   : in out String_Maps.Map;
      Compilers  : Compiler_Lists.List;
      Config     : String;
      Langs      : Ordered_Languages;
      Error_Sloc : Source_Reference.Object;
      Errors     : in out Log.Object);
   --  Merge the contents of Config into Packages, so that each attributes ends
   --  up in the right package, and the packages are not duplicated.

   procedure Update_With_Compiler_Runtime
     (Self        : in out Object;
      Comp        : Compiler;
      Environment : GPR2.Environment.Object);
   --  Update the knowledge base with additional runtime specific chunks
   --  if a given compiler has any.

   function Create_Filter
     (Self  : Object;
      Descr : Project.Configuration.Description) return Compiler;
   --  Transform Description into Compiler object

   function Configuration_Node_Image
     (Config : Configuration_Type) return Unbounded_String;
   --  Returns partial image of <configuration> node that is used in verbose
   --  output to explain unsupported configuration.

   function GPR_Executable_Prefix_Path return String;
   --  Tries to find the installation location of gprtools.
   --  If current executable may be one of gprtools and is spawned with path
   --  prefix, returns corresponding prefix directory.
   --  Returns empty string if all approaches do not work.
   --  When a directory is returned, it is guaranteed to end with a directory
   --  separator.

   Default_Target_Parsed : Boolean := False;
   Default_Target_Val    : Unbounded_String;

   procedure Parse_Default_Target_Val;
   --  Tries to parse <gprtools directory>/share/gprconfig/default_target
   --  and sets Default_Target_Val.

   ---------
   -- Add --
   ---------

   procedure Add
     (Self        : in out Object;
      Flags       : Parsing_Flags;
      Location    : GPR2.Path_Name.Object;
      Environment : GPR2.Environment.Object :=
                      GPR2.Environment.Process_Environment) is
   begin
      if Self.Parsed_Directories.Contains (Location) then
         --  Do not parse several times the same database directory
         return;
      end if;

      Self.Parsed_Directories.Append (Location);
      Parsing.Parse_Knowledge_Base (Self, Location, Flags, Environment);
   end Add;

   ---------
   -- Add --
   ---------

   procedure Add
     (Self        : in out Object;
      Flags       : Parsing_Flags;
      Content     : Value_Not_Empty;
      Environment : GPR2.Environment.Object :=
                      GPR2.Environment.Process_Environment) is
   begin
      Parsing.Add (Self, Flags, Content, Environment);
   end Add;

   -------------------
   -- All_Compilers --
   -------------------

   function All_Compilers
     (Self        : in out Object;
      Settings    : Project.Configuration.Description_Set;
      Target      : Name_Type;
      Messages    : in out GPR2.Log.Object;
      Environment : GPR2.Environment.Object :=
                      GPR2.Environment.Process_Environment)
      return Compiler_Array
   is
      use Compiler_Lists;
      use Ada.Containers;
      use KB.Compiler_Iterator;
      use Project.Configuration;

      Compilers : Compiler_Lists.List;
      Filters   : Compiler_Lists.List;

      type Boolean_Array  is array (Count_Type range <>) of Boolean;

      type All_Iterator (Count : Count_Type) is new
        GPR2.KB.Compiler_Iterator.Object with record
         Filter_Matched : Boolean_Array (1 .. Count) := (others => False);
         Filters        : Compiler_Lists.List;
         Compilers      : Compiler_Lists.List;
      end record;

      overriding
      procedure Callback
        (Iterator          : in out All_Iterator;
         Base              : in out Object;
         Comp              : Compiler;
         Runtime_Specified : Boolean;
         From_Extra_Dir    : Boolean;
         Continue          : out Boolean);
      --  Search all compilers on path, preselecting the first one matching
      --  each of the filters.

      function Display_Before (Comp1, Comp2 : Compiler) return Boolean;
      --  Whether Comp1 should be displayed before Comp2 when displaying lists
      --  of compilers. This ensures that similar languages are grouped,
      --  among other things.

      package Compiler_Sort is
        new Compiler_Lists.Generic_Sorting (Display_Before);

      --------------
      -- Callback --
      --------------

      overriding
      procedure Callback
        (Iterator          : in out All_Iterator;
         Base              : in out Object;
         Comp              : Compiler;
         Runtime_Specified : Boolean;
         From_Extra_Dir    : Boolean;
         Continue          : out Boolean)
      is
         New_Comp : Compiler := Comp;
         C        : Compiler_Lists.Cursor;
         Index    : Count_Type := 1;
      begin
         --  Do nothing if a runtime needs to be specified, as this is only for
         --  interactive use.

         if not Runtime_Specified then
            if Iterator.Filter_Matched /=
              (Iterator.Filter_Matched'Range => True)
            then
               C := First (Iterator.Filters);
               while Has_Element (C) loop
                  if not Iterator.Filter_Matched (Index)
                    and then Filter_Match
                      (Base, Comp => Comp, Filter => Element (C))
                  then
                     Set_Selection (New_Comp, True);
                     Iterator.Filter_Matched (Index) := True;
                     exit;
                  end if;

                  Index := Index + 1;
                  Next (C);
               end loop;
            end if;

            --  Ignore compilers from extra directories, unless they have been
            --  selected because of a --config argument.

            if Is_Selected (New_Comp) or else not From_Extra_Dir then
               GNATCOLL.Traces.Trace
                 (Main_Trace,
                  "Adding compiler to interactive menu "
                  & To_String (Comp)
                  & " selected=" & Is_Selected (New_Comp)'Img);
               Append (Iterator.Compilers, New_Comp);
            end if;
         end if;

         Continue := True;
      end Callback;

      --------------------
      -- Display_Before --
      --------------------

      function Display_Before (Comp1, Comp2 : Compiler) return Boolean is

         type Compare_Type is (Before, Equal, After);
         function Compare
           (Name1, Name2 : Unbounded_String) return Compare_Type;
         --  Compare alphabetically two strings

         -------------
         -- Compare --
         -------------

         function Compare
           (Name1, Name2 : Unbounded_String) return Compare_Type is
         begin
            if Name1 = Null_Unbounded_String then
               if Name2 = Null_Unbounded_String then
                  return Equal;
               else
                  return Before;
               end if;

            elsif Name2 = Null_Unbounded_String then
               return After;
            end if;

            if Name1 < Name2 then
               return Before;
            elsif Name1 > Name2 then
               return After;
            else
               return Equal;
            end if;

         end Compare;
      begin
         if Comp1.Language /= Comp2.Language then
            return Name (Comp1.Language) < Name (Comp2.Language);

         else
            if Comp1.Path_Order < Comp2.Path_Order then
               return True;

            elsif Comp2.Path_Order < Comp1.Path_Order then
               return False;

            else
               --  If the "default" attribute was specified for <runtime>,
               --  this only impacts the batch mode. We still want to sort
               --  the runtimes alphabetically in the interactive display.

               case Compare (Comp1.Runtime, Comp2.Runtime) is
                  when Before =>
                     return True;
                  when After =>
                     return False;
                  when Equal =>
                     return Compare (Comp1.Version, Comp2.Version) = Before;
               end case;
            end if;
         end if;
      end Display_Before;

      Iter : All_Iterator (Settings'Length);
   begin
      for Setting of Settings loop
         if Is_Language_With_No_Compiler
           (Self, Language (Setting))
         then
            Compilers.Append (Create_Filter (Self, Setting));
         else
            Filters.Append (Create_Filter (Self, Setting));
         end if;
      end loop;

      Iter.Filters := Filters;
      Foreach_In_Path
        (Self        => Iter,
         Base        => Self,
         On_Target   => Target,
         Environment => Environment,
         Extra_Dirs  => Extra_Dirs_From_Filters (Filters));

      Splice (Target => Compilers,
              Before => Compiler_Lists.No_Element,
              Source => Iter.Compilers);

      if Compilers.Is_Empty then
         return No_Compilers;
      end if;

      Compiler_Sort.Sort (Compilers);

      return Res : Compiler_Array (1 .. Integer (Compilers.Length)) do
         for Idx in Res'Range loop
            Res (Idx) := Compilers.First_Element;
            Compilers.Delete_First;
         end loop;
      end return;
   exception
      when Invalid_KB =>
         return No_Compilers;
   end All_Compilers;

   -------------------------------------
   -- Complete_Command_Line_Compilers --
   -------------------------------------

   procedure Complete_Command_Line_Compilers
     (Self             : in out Object;
      On_Target        : Name_Type;
      Filters          : Compiler_Lists.List;
      Compilers        : in out Compiler_Lists.List;
      Selected_Target  : in out Unbounded_String;
      Fallback         : Boolean;
      Errors           : out Log.Object;
      Environment      : GPR2.Environment.Object)
   is
      use Compiler_Lists;
      use Ada.Containers;
      use GNATCOLL.Traces;

      type Cursor_Array
        is array (Count_Type range <>) of Compiler_Lists.Cursor;
      type Boolean_Array  is array (Count_Type range <>) of Boolean;

      type Batch_Iterator (Count : Count_Type) is new
        GPR2.KB.Compiler_Iterator.Object with record
         Found      : Count_Type := 0;
         Compilers  : Compiler_Lists.List;
         Matched    : Cursor_Array (1 .. Count) :=
                        (others => Compiler_Lists.No_Element);
         Filters    : Compiler_Lists.List;

         Found_One  : Boolean_Array (1 .. Count) := (others => False);
         --  Whether we found at least one matching compiler for each filter
      end record;

      overriding
      procedure Callback
        (Iterator          : in out Batch_Iterator;
         Base              : in out Object;
         Comp              : Compiler;
         Runtime_Specified : Boolean;
         From_Extra_Dir    : Boolean;
         Continue          : out Boolean);
      --  Search the first compiler matching each --config command line
      --  argument.
      --  It might be discovered either in a path added through a --config
      --  parameter (in which case From_Extra_Dir is True), or in a path
      --  specified in the environment variable $PATH (in which case it is
      --  False). If the directory is both in Extra_Dirs and in $PATH,
      --  From_Extra_Dir is set to False.
      --  If Runtime_Specified is True, only filters with a specified runtime
      --  are taken into account.
      --
      --  On exit, Continue should be set to False if there is no need
      --  to discover further compilers.

      Iterator : Batch_Iterator (Length (Filters));

      function Foreach_Nth_Compiler
        (Filter : Compiler_Lists.Cursor) return Boolean;
      --  For all possible compiler matching the filter, check whether we
      --  find a compatible set of compilers matching the next filters.
      --  Return True if one was found (in which case it is the current
      --  selection on exit).

      --------------
      -- Callback --
      --------------

      overriding
      procedure Callback
        (Iterator          : in out Batch_Iterator;
         Base              : in out Object;
         Comp              : Compiler;
         Runtime_Specified : Boolean;
         From_Extra_Dir    : Boolean;
         Continue          : out Boolean)
      is

         C     : Compiler_Lists.Cursor := First (Iterator.Filters);
         Index : Count_Type := 1;
         Ncomp : Compiler;
         El    : Compiler;

         use GPR2.Path_Name;
      begin
         while Has_Element (C) loop
            Ncomp := No_Compiler;
            El := Compiler_Lists.Element (C);

            --  A compiler in an "extra_dir" (ie specified on the command line)
            --  can only match if that directory was explicitly specified in
            --  --config. We do not want to find all compilers in /dir if that
            --  directory is not in $PATH

            if (not From_Extra_Dir or else El.Path = Comp.Path)
              and then Filter_Match (Base, Comp => Comp, Filter => El)
              and then (not Runtime_Specified
                         or else El.Runtime_Dir /= Null_Unbounded_String)
            then
               Ncomp := Comp;
               if El.Runtime_Dir /= Null_Unbounded_String then
                  Ncomp.Runtime_Dir := El.Runtime_Dir;
                  Ncomp.Runtime := El.Runtime;
               end if;

               if not Ncomp.Any_Runtime
                 and then Ncomp.Runtime = Null_Unbounded_String
                 and then El.Runtime /= Null_Unbounded_String
               then
                  Ncomp.Runtime := El.Runtime;
               end if;

               Append (Iterator.Compilers, Ncomp);

               Trace
                 (Match_Trace,
                  "Saving compiler for possible backtracking: "
                  & To_String (Ncomp)
                  & " (matches --config "
                  & To_String (El)
                  & ")");

               if Iterator.Matched (Index) = Compiler_Lists.No_Element then
                  Iterator.Found := Iterator.Found + 1;

                  Trace
                    (Match_Trace,
                     "Selecting it since this filter was not matched yet "
                     & Iterator.Found'Img & "/" & Iterator.Count'Img);

                  Iterator.Matched (Index) := Last (Iterator.Compilers);
                  Iterator.Found_One (Index) := True;
                  Set_Selection
                    (Iterator.Compilers, Iterator.Matched (Index),
                     True);

                  --  Only keep those compilers that are not incompatible
                  --  (according to the knowledge base). It might happen that
                  --  none is selected as a result, but appropriate action is
                  --  taken in Complete_Command_Line_Compilers. We ignore
                  --  incompatible sets as early as possible, in the hope to
                  --  limit the number of system calls if another set is found
                  --  before all directories are traversed.

                  if not Is_Supported_Config (Base, Iterator.Compilers) then
                     Set_Selection
                       (Iterator.Compilers, Iterator.Matched (Index), False);
                     Trace
                       (Match_Trace,
                        "Compilers are not compatible, canceling last"
                        & " compiler found");
                     Iterator.Matched (Index) := Compiler_Lists.No_Element;
                     Iterator.Found := Iterator.Found - 1;
                  end if;

               end if;
            end if;
            Index := Index + 1;
            Next (C);
         end loop;

         --  Stop at first compiler
         Continue := Iterator.Found /= Iterator.Count;
      end Callback;

      --------------------------
      -- Foreach_Nth_Compiler --
      --------------------------

      function Foreach_Nth_Compiler
        (Filter : Compiler_Lists.Cursor) return Boolean
      is
         C           : Compiler_Lists.Cursor := First (Iterator.Compilers);
         Comp_Filter : constant Compiler := Compiler_Lists.Element (Filter);
      begin
         while Has_Element (C) loop
            if Filter_Match
              (Self, Compiler_Lists.Element (C), Filter => Comp_Filter)
            then
               Set_Selection (Iterator.Compilers, C, True);

               if Next (Filter) = Compiler_Lists.No_Element then
                  Increase_Indent
                    (Match_Trace, "Testing the following compiler set:");
                  Trace (Match_Trace, To_String (Iterator.Compilers));

                  if Is_Supported_Config (Self, Iterator.Compilers) then
                     Decrease_Indent (Match_Trace, "They are compatible");
                     return True;
                  else
                     Decrease_Indent (Match_Trace);
                  end if;

               else
                  if Foreach_Nth_Compiler (Next (Filter)) then
                     return True;
                  end if;
               end if;

               Set_Selection (Iterator.Compilers, C, False);
            end if;

            Next (C);
         end loop;

         return False;
      end Foreach_Nth_Compiler;

      C                  : Compiler_Lists.Cursor;
      Extra_Dirs         : constant String :=
        Extra_Dirs_From_Filters (Filters);
      Found_All          : Boolean := True;
      Found_All_Fallback : Boolean := True;

   begin
      Iterator.Filters := Filters;
      Selected_Target  := To_Unbounded_String (String (On_Target));

      Increase_Indent
        (Main_Trace,
         "Completing info for --config parameters, extra_dirs=" & Extra_Dirs);

      --  Find all the compilers in PATH and Extra_Dirs

      Compiler_Iterator.Foreach_In_Path
        (Self        => Iterator,
         Base        => Self,
         On_Target   => On_Target,
         Environment => Environment,
         Extra_Dirs  => Extra_Dirs);

      Decrease_Indent (Main_Trace);

      --  Check that we could find at least one of each compiler

      if Fallback then
         --  Check to see if fallback targets are of interest
         C := First (Filters);
         for F in Iterator.Found_One'Range loop
            if not Iterator.Found_One (F) then
               if Self.Languages_Known.Contains
                 (Compiler_Lists.Element (C).Language)
               then
                  --  Fallback should not be triggered for unknown languages
                  Found_All_Fallback := False;
               end if;
               Found_All := False;
            end if;
            Next (C);
         end loop;

         if not Found_All_Fallback then
            --  Looking for corresponding fallback set
            declare
               FB_List  : GPR2.Containers.Name_List :=
                            Fallback_List (Self, On_Target);
               Cur      : GPR2.Containers.Name_Type_List.Cursor :=
                            FB_List.First;
               N_Target : constant Name_Type :=
                            Self.Normalized_Target (On_Target);
               use GPR2.Containers.Name_Type_List;
            begin
               while Cur /= GPR2.Containers.Name_Type_List.No_Element loop
                  if Element (Cur) = N_Target then
                     --  No point processing the same target again
                     FB_List.Delete (Cur);
                     exit;
                  end if;
                  Next (Cur);
               end loop;

               Cur := FB_List.First;
               while Cur /= GPR2.Containers.Name_Type_List.No_Element loop
                  Trace
                    (Match_Trace,
                     "Attempting to fall back to target "
                     & String (Element (Cur)));

                  declare
                     Local_Iter  : Batch_Iterator (Length (Filters));
                  begin
                     Local_Iter.Filters := Iterator.Filters;

                     Compiler_Iterator.Foreach_In_Path
                       (Self        => Local_Iter,
                        Base        => Self,
                        On_Target   => Element (Cur),
                        Environment => Environment,
                        Extra_Dirs  => Extra_Dirs);

                     Found_All := True;
                     C := First (Filters);
                     for F in Local_Iter.Found_One'Range loop
                        if not Local_Iter.Found_One (F)
                          and then Self.Languages_Known.Contains
                            (Compiler_Lists.Element (C).Language)
                        then
                           --  Not finding a compiler for an unknown language
                           --  should not invalidate fallback search.
                           Found_All := False;
                        end if;
                        Next (C);
                     end loop;

                     if Found_All then
                        Iterator := Local_Iter;
                        Selected_Target :=
                          To_Unbounded_String (String (Element (Cur)));
                        Trace
                          (Match_Trace,
                           String (Element (Cur))
                           & " fallback target selected");
                        exit;
                     end if;
                  end;

                  Next (Cur);
               end loop;
            end;
         end if;
      end if;

      C := First (Filters);
      for F in Iterator.Found_One'Range loop
         if not Iterator.Found_One (F) then
            declare
               Comp           : constant Compiler :=
                                  Compiler_Lists.Element (C);
               Language_Known : constant Boolean :=
                                  Self.Languages_Known.Contains
                                    (Comp.Language);
            begin

               if not Language_Known then
                  Errors.Append
                    (Message.Create
                       (Message.Information,
                        "unknown language '"
                        & Image (Comp.Language) & "'",
                        Source_Reference.Create ("embedded_kb/kb", 0, 0)));

               else

                  Errors.Append
                    (Message.Create
                       (Message.Warning,
                        "can't find a toolchain "
                        & "for the following configuration: language '"
                        & Image (Comp.Language) & "', target '"
                        & String (On_Target) & "'"
                        & (if Comp.Runtime = Null_Unbounded_String then
                              ", default runtime"
                           else ", runtime '" & To_String (Comp.Runtime) & "'")
                        & (if Comp.Version /= Null_Unbounded_String then
                               ", version '" & To_String (Comp.Version) & "'"
                          else "")
                        & (if Comp.Path.Is_Defined then
                               ", path '" & Comp.Path.Value & "'"
                           else "")
                        & (if Comp.Name /= Null_Unbounded_String then
                               ", name '" & To_String (Comp.Name) & "'"
                           else ""),
                        Source_Reference.Create ("embedded_kb/kb", 0, 0)));
               end if;
            end;

            Found_All := False;
         end if;
         Next (C);
      end loop;

      --  If we could find at least one of each compiler, but that our initial
      --  attempt returned incompatible sets of compiler, we do a more thorough
      --  attempt now

      if Found_All
        and then Iterator.Found /= Iterator.Count
      then
         --  If no compatible set was found, try all possible combinations, in
         --  the hope that we can finally find one. In the following algorithm,
         --  we end up checking again some set that were checked in Callback,
         --  but that would be hard to avoid since the compilers can be found
         --  in any order.

         Increase_Indent
           (Match_Trace,
            "Attempting to find a supported compiler set");

         --  Unselect all compilers

         C := First (Iterator.Compilers);
         while Has_Element (C) loop
            Set_Selection (Iterator.Compilers, C, False);
            Next (C);
         end loop;

         if not Foreach_Nth_Compiler (First (Iterator.Filters)) then
            Errors.Append
              (Message.Create
                 (Message.Error,
                  "no set of compatible compilers was found",
                  Source_Reference.Create ("embedded_kb/kb", 0, 0)));

            Decrease_Indent (Match_Trace);
            raise No_Compatible_Compilers;
         end if;
      end if;

      Splice (Target => Compilers,
              Before => Compiler_Lists.No_Element,
              Source => Iterator.Compilers);
   end Complete_Command_Line_Compilers;

   -------------------
   -- Configuration --
   -------------------

   function Configuration
     (Self        : in out Object;
      Settings    : Project.Configuration.Description_Set;
      Target      : Name_Type;
      Messages    : in out GPR2.Log.Object;
      Fallback    : Boolean := False;
      Environment : GPR2.Environment.Object :=
                      GPR2.Environment.Process_Environment)
      return Ada.Strings.Unbounded.Unbounded_String
   is
      use Project.Configuration;

      Filters              : Compiler_Lists.List;
      Compilers            : Compiler_Lists.List;
      Selected_Target      : Unbounded_String;
      Runtime_Specific_KB  : Object;
      Langs                : Ordered_Languages;

      Configuration_String : Unbounded_String;

   begin
      for Setting of Settings loop
         if Is_Language_With_No_Compiler (Self, Language (Setting)) then
            Compilers.Append (Create_Filter (Self, Setting));

         elsif not Self.Languages_Known.Contains (Language (Setting)) then
            Messages.Append
              (Message.Create
                 (Message.Information,
                  "unknown language '"
                  & Image (Language (Setting)) & "'",
                  Source_Reference.Create ("embedded_kb/kb", 0, 0)));

         else
            Filters.Append (Create_Filter (Self, Setting));
            Langs.Append (Language (Setting));
         end if;
      end loop;

      begin
         Complete_Command_Line_Compilers
           (Self             => Self,
            On_Target        => Target,
            Filters          => Filters,
            Compilers        => Compilers,
            Selected_Target  => Selected_Target,
            Fallback         => Fallback,
            Errors           => Messages,
            Environment      => Environment);
      exception
         when No_Compatible_Compilers | Invalid_KB =>
            return Null_Unbounded_String;
      end;

      --  Runtime dir may have additional knowledge base chunks specific to
      --  given runtime. We do not want to include them in Self, otherwise
      --  it becomes unusable for other runtimes/compilers.
      Runtime_Specific_KB := Self;

      for Comp of Compilers loop
         Update_With_Compiler_Runtime (Runtime_Specific_KB, Comp, Environment);
      end loop;

      Configuration_String := Runtime_Specific_KB.Generate_Configuration
        (Compilers, To_String (Selected_Target), Langs, Messages);

      return Configuration_String;
   end Configuration;

   -------------------
   -- Configuration --
   -------------------

   function Configuration
     (Self        : in out Object;
      Selection   : Compiler_Array;
      Target      : Name_Type;
      Messages    : in out GPR2.Log.Object;
      Environment : GPR2.Environment.Object :=
                      GPR2.Environment.Process_Environment)
      return Ada.Strings.Unbounded.Unbounded_String
   is
      Configuration_String : Unbounded_String;
      Runtime_Specific_KB  : Object;
      Compilers            : Compiler_Lists.List;

      --  ??? atm follow order of selection
      Langs                : Ordered_Languages;
   begin

      --  Runtime dir may have additional knowledge base chunks specific to
      --  given runtime. We do not want to include them in Self, otherwise
      --  it becomes unusable for other runtimes/compilers.
      Runtime_Specific_KB := Self;

      for Comp of Selection loop
         Update_With_Compiler_Runtime (Runtime_Specific_KB, Comp, Environment);
         Compilers.Append (Comp);
         Langs.Append (Comp.Language);
      end loop;

      Configuration_String := Runtime_Specific_KB.Generate_Configuration
        (Compilers, String (Target), Langs, Messages);

      return Configuration_String;

   end Configuration;

   ------------------------------
   -- Configuration_Node_Image --
   ------------------------------

   function Configuration_Node_Image
     (Config : Configuration_Type) return Unbounded_String
   is
      Result : Unbounded_String;
   begin
      for Comp_Filter of Config.Compilers_Filters loop
         Append
           (Result,
            "<compilers negate='" & Comp_Filter.Negate'Img & "'>" & ASCII.LF);

         for Filter of Comp_Filter.Compiler loop
            Append
              (Result,
               "  <compiler name='"
               & To_String (Filter.Name) & "' version='"
               & To_String (Filter.Version) & "' runtime='"
               & To_String (Filter.Runtime) & "' language='"
               & String (Name (Filter.Language)) & "' />"
               & ASCII.LF);
         end loop;

         Append (Result, "</compilers>" & ASCII.LF);
      end loop;

      Append (Result, "<config supported='" & Config.Supported'Img & "' />");

      return Result;
   end Configuration_Node_Image;

   ------------
   -- Create --
   ------------

   function Create
     (Flags       : Parsing_Flags := Targetset_Only_Flags;
      Default_KB  : Boolean := True;
      Custom_KB   : GPR2.Path_Name.Set.Object := GPR2.Path_Name.Set.Empty_Set;
      Environment : GPR2.Environment.Object :=
                      GPR2.Environment.Process_Environment)
      return Object
   is
      Result : Object;
   begin
      if Default_KB then
         Result := Create_Default (Flags => Flags, Environment => Environment);
      else
         Result := Create_Empty;
      end if;

      for Location of Custom_KB loop
         Result.Add (Flags, Location, Environment);
      end loop;

      return Result;
   end Create;

   ------------
   -- Create --
   ------------

   function Create
     (Content     : GPR2.Containers.Value_List;
      Flags       : Parsing_Flags;
      Environment : GPR2.Environment.Object :=
                      GPR2.Environment.Process_Environment) return Object
   is
      Result : Object := Create_Empty;
   begin
      for Cont of Content loop
         if Cont /= "" then
            Result.Add (Flags, Cont, Environment);
         end if;
      end loop;

      return Result;
   end Create;

   ------------
   -- Create --
   ------------

   function Create
     (Location    : GPR2.Path_Name.Object;
      Flags       : Parsing_Flags;
      Environment : GPR2.Environment.Object :=
                      GPR2.Environment.Process_Environment) return Object
   is
      Result    : Object := Create_Empty;
   begin
      Result.Parsed_Directories.Append (Location);
      Parsing.Parse_Knowledge_Base
        (Result, Location, Flags, Environment);

      return Result;
   end Create;

   --------------------
   -- Create_Default --
   --------------------

   function Create_Default
     (Flags       : Parsing_Flags;
      Environment : GPR2.Environment.Object :=
                      GPR2.Environment.Process_Environment) return Object
   is
      Ret : Object;
   begin
      Ret := Parsing.Parse_Default_Knowledge_Base
        (Flags, Environment);
      return Ret;
   end Create_Default;

   ------------------
   -- Create_Empty --
   ------------------

   function Create_Empty return Object
   is
      Result : Object;
   begin
      Result.Initialized := True;
      Result.Is_Default  := False;
      return Result;
   end Create_Empty;

   -------------------
   -- Create_Filter --
   -------------------

   function Create_Filter
     (Self  : Object;
      Descr : Project.Configuration.Description) return Compiler
   is
      use GNATCOLL.Traces;
      use Project.Configuration;

      Result : Compiler;

      Lang_Id       : Language_Id renames Language (Descr);
      Exec_Suffix   : constant String := Get_Executable_Suffix;

      function Legacy_Name_Support
        (Name : String; Lang : Language_Id) return String;
      --  For Ada, gnatmake was previously used to detect a GNAT compiler.
      --  However, as gnatmake may not be present in all the GNAT
      --  distributions, gnatls is now used. For upward compatibility,
      --  replace gnatmake with gnatls, so that a GNAT compiler may
      --  be detected.

      -------------------------
      -- Legacy_Name_Support --
      -------------------------

      function Legacy_Name_Support
        (Name : String; Lang : Language_Id) return String
      is
         use Ada.Strings.Fixed;

         Idx : constant Natural := Index (Name, "gnatmake");
      begin
         if Lang = Ada_Language and then Idx >= Name'First then
            return Replace_Slice (Name, Idx, Idx + 7, "gnatls");
         else
            return Name;
         end if;
      end Legacy_Name_Support;

   begin
      Result.Language := Lang_Id;

      if Is_Language_With_No_Compiler (Self, Language (Descr)) then
         Trace (Main_Trace,
                "Language " & Image (Lang_Id) &
                  " requires no compiler");
         Result.Complete := True;
         Result.Selected := True;
         Result.Targets_Set := All_Target_Sets;
         return Result;
      end if;

      Result.Version := To_Unbounded_String (String (Version (Descr)));
      Result.Runtime := To_Unbounded_String (String (Runtime (Descr)));

      if Result.Runtime /= Null_Unbounded_String
        and then GNAT.OS_Lib.Is_Absolute_Path (To_String (Result.Runtime))
      then
         --  If the runtime is a full path, set Runtime and
         --  Runtime_Dir to the same value.
         Result.Runtime_Dir := Result.Runtime;
      end if;

      if Path (Descr) /= No_Filename then
         Result.Path := Path_Name.Create_Directory
                          (Path (Descr), Resolve_Links => True);
      end if;

      if Name (Descr) /= No_Name then
         Result.Name :=
           To_Unbounded_String
             (GNAT.Directory_Operations.Base_Name
                (Legacy_Name_Support
                   (String (Name (Descr)), Lang_Id),
                 Exec_Suffix));
      end if;

      Result.Complete := False;

      Trace (Main_Trace,
             "Language " & Image (Lang_Id) & " requires a compiler");

      return Result;
   end Create_Filter;

   --------------------------------------
   -- Default_Knowledge_Base_Directory --
   --------------------------------------

   function Default_Location return GPR2.Path_Name.Object is
      use GNATCOLL.VFS;
      use GNATCOLL.VFS_Utils;

      GPRbuild : Filesystem_String_Access :=
                    Locate_Exec_On_Path ("gprbuild");
      Dir       : Virtual_File;
   begin
      if GPRbuild = null then
         raise Default_Location_Error;
      end if;

      Dir := Get_Parent (Create (Dir_Name (GPRbuild.all)));

      Free (GPRbuild);

      if Dir = No_File then
         raise Default_Location_Error;
      end if;

      Dir := Dir.Join ("share").Join ("gprconfig");

      if not OS_Lib.Is_Directory (Dir.Display_Full_Name) then
         raise Default_Location_Error;
      end if;

      return GPR2.Path_Name.Create_Directory
               (Filename_Type (Dir.Display_Full_Name));
   end Default_Location;

   --------------------
   -- Default_Target --
   --------------------

   function Default_Target return Name_Type is
   begin
      if not Default_Target_Parsed then
         Parse_Default_Target_Val;
      end if;

      if Default_Target_Val = Null_Unbounded_String then
         return Name_Type (System.OS_Constants.Target_Name);
      else
         return Name_Type (To_String (Default_Target_Val));
      end if;
   end Default_Target;

   -----------------------------
   -- Extra_Dirs_From_Filters --
   -----------------------------

   function Extra_Dirs_From_Filters
     (Filters : Compiler_Lists.List) return String
   is
      use Compiler_Lists;
      use GPR2.Path_Name;
      C          : Compiler_Lists.Cursor  := First (Filters);
      Extra_Dirs : Unbounded_String;
      Elem       : Compiler;
   begin
      while Has_Element (C) loop
         Elem := Compiler_Lists.Element (C);
         if Elem.Path /= GPR2.Path_Name.Undefined then
            Append
              (Extra_Dirs, Elem.Path.Value & GNAT.OS_Lib.Path_Separator);
         end if;
         Next (C);
      end loop;
      return To_String (Extra_Dirs);
   end Extra_Dirs_From_Filters;

   -------------------
   -- Fallback_List --
   -------------------

   function Fallback_List
     (Self   : Object;
      Target : Name_Type) return GPR2.Containers.Name_List
   is
      use GPR2.Containers.Name_Type_List;

      N_Target : constant Name_Type := Self.Normalized_Target (Target);
      Result   : GPR2.Containers.Name_List;
      Cur      : GPR2.Containers.Name_Type_List.Cursor;
   begin
      for Fallback_List of Self.Fallback_Targets_Sets loop
         Result := Fallback_List;
         Cur := Result.First;
         while Cur /= No_Element loop
            if Element (Cur) = N_Target then
               return Result;
            end if;
            Next (Cur);
         end loop;
      end loop;

      Result.Clear;
      Result.Append (N_Target);
      return Result;
   end Fallback_List;

   ---------------------------
   -- Filter_Compilers_List --
   ---------------------------

   procedure Filter_Compilers_List
     (Self       : Object;
      Compilers  : in out Compiler_Array;
      For_Target : Name_Type)
   is
      use GNATCOLL.Traces;

      For_Target_Set : constant Targets_Set_Id :=
                         Self.Query_Targets_Set (For_Target);
      Check_List     : Compiler_Lists.List;
   begin
      Increase_Indent (Main_Trace, "Filtering the list of compilers");

      for Idx in Compilers'Range loop

         if not Compilers (Idx).Selected then

            if For_Target_Set /= All_Target_Sets
              and then Compilers (Idx).Targets_Set /= All_Target_Sets
              and then Compilers (Idx).Targets_Set /= For_Target_Set
            then
               Compilers (Idx).Selectable := False;
               Trace
                 (Main_Trace,
                  "Incompatible target for: " & To_String (Compilers (Idx)));
               goto Next_Compiler;
            end if;

            for Other_Compiler of Compilers loop
               if Other_Compiler.Language = Compilers (Idx).Language
                 and then Other_Compiler.Selected
               then
                  Compilers (Idx).Selectable := False;
                  Trace
                    (Main_Trace,
                     "Already selected language for: "
                     & To_String (Compilers (Idx)));
                  goto Next_Compiler;
               end if;
            end loop;

            --  We need to check if the resulting selection would
            --  lead to a supported configuration.

            Compilers (Idx).Selected := True;
            for Comp of Compilers loop
               Check_List.Append (Comp);
            end loop;
            Compilers (Idx).Selected := False;

            if not Is_Supported_Config (Self, Check_List) then
               Compilers (Idx).Selectable := False;
               Trace
                 (Main_Trace,
                  "Unsupported config for: "
                  & To_String (Compilers (Idx)));
               goto Next_Compiler;
            end if;

            Compilers (Idx).Selectable := True;

         end if;

         <<Next_Compiler>>
         Check_List.Clear;
      end loop;

      Decrease_Indent (Main_Trace);
   end Filter_Compilers_List;

   ------------------
   -- Filter_Match --
   ------------------

   function Filter_Match
     (Self   : Object;
      Comp   : Compiler;
      Filter : Compiler) return Boolean
   is
      use GNATCOLL.Traces;
      use GPR2.Path_Name;
   begin
      if Filter.Name /= Null_Unbounded_String
        and then Comp.Name /= Filter.Name
        and then Comp.Base_Name /= Filter.Name
      then
         Trace
           (Match_Trace,
            "Filter=" & To_String (Filter) & ": name does not match");
         return False;
      end if;

      if Filter.Path.Is_Defined and then Filter.Path /= Comp.Path then
         Trace
           (Match_Trace,
            "Filter=" & To_String (Filter) & ": path does not match");
         return False;
      end if;

      if Filter.Version /= Null_Unbounded_String
        and then Filter.Version /= Comp.Version
      then
         Trace
           (Match_Trace,
            "Filter=" & To_String (Filter) & ": version does not match");
         return False;
      end if;

      if Comp.Any_Runtime then
         --  If compiler has no runtime node all runtimes should be accepted,
         --  no need to apply filter.
         if Filter.Runtime /= Null_Unbounded_String then

            if not GNAT.OS_Lib.Is_Absolute_Path (To_String (Filter.Runtime))
              and then Filter.Runtime /= Comp.Runtime
              and then Filter.Runtime /= Comp.Alt_Runtime
            then
               Trace
                 (Match_Trace,
                  "Filter=" & To_String (Filter) & ": runtime does not match");
               return False;
            end if;

         elsif not Comp.Default_Runtime then

            Trace
              (Match_Trace,
               "Filter=" & To_String (Filter) & ": no default runtime");
            return False;

         end if;

      end if;

      if Filter.Language /= No_Language
        and then Filter.Language /= Comp.Language
      then
         Trace
           (Match_Trace,
            "Filter=" & To_String (Filter) & ": language does not match");
         return False;
      end if;

      return True;
   end Filter_Match;

   ----------------------------
   -- Generate_Configuration --
   ----------------------------

   function Generate_Configuration
     (Self      : Object;
      Compilers : Compiler_Lists.List;
      Target    : String;
      Langs     : Ordered_Languages;
      Errors    : in out Log.Object) return Unbounded_String
   is
      Project_Name      : constant String := "Default";
      Packages          : String_Maps.Map;
      Result            : Unbounded_String;

      procedure Add_Line (S : String);
      --  Appends to result the given string and a line terminator. There is no
      --  actual need for the terminators but it makes it more readable in
      --  traces.

      procedure Gen (C : String_Maps.Cursor);
      --  C is a cursor of the map "Packages"
      --  Generate the chunk of the config file corresponding to the
      --  given package.

      procedure Gen_And_Remove (Name : String);
      --  Generate the chunk of the config file corresponding to the
      --  package name and remove it from the map.

      --------------
      -- Add_Line --
      --------------

      procedure Add_Line (S : String) is
      begin
         Append (Result, S & ASCII.LF);
      end Add_Line;

      ---------
      -- Gen --
      ---------

      procedure Gen (C : String_Maps.Cursor) is
         use String_Maps;
      begin
         if Key (C) /= "" then
            Add_Line ("");
            Add_Line ("   package " & Key (C) & " is");
         end if;
         Add_Line (String_Maps.Element (C));
         if Key (C) /= "" then
            Add_Line ("   end " & Key (C) & ";");
         end if;
      end Gen;

      --------------------
      -- Gen_And_Remove --
      --------------------

      procedure Gen_And_Remove (Name : String) is
         use String_Maps;
         C : String_Maps.Cursor := Find (Packages, Name);
      begin
         if Has_Element (C) then
            Gen (C);
            Delete (Packages, C);
         end if;
      end Gen_And_Remove;

   begin

      for Config of Self.Configurations loop

         if Match (Config.Compilers_Filters, Compilers)
           and then Match
             (Config.Targets_Filters, Config.Negate_Targets, Compilers)
         then
            if not Config.Supported then
               Errors.Append
                 (Message.Create
                    (Message.Error,
                     "Code generated by these compilers cannot be linked"
                     & " as far as we know.",
                     Sloc => Source_Reference.Create
                       ("embedded_kb/kb", 0, 0)));

               return Null_Unbounded_String;
            end if;

            Merge_Config
              (Self,
               Packages,
               Compilers,
               To_String (Config.Config),
               Langs,
               Config.Sloc,
               Errors);
         end if;

      end loop;

      if Packages.Is_Empty then
         Errors.Append
           (Message.Create
              (Message.Error,
               "No valid configuration found",
               Sloc => Source_Reference.Create
                 ("embedded_kb/kb", 0, 0)));

         return Null_Unbounded_String;
      end if;

      Add_Line ("configuration project " & Project_Name & " is");
      Add_Line ("   for Target use """ & Target & """;");
      Add_Line ("   for Canonical_Target use """
                & String (Self.Normalized_Target (Name_Type (Target)))
                & """;");

      --  Generate known packages in order.  This takes care of possible
      --  dependencies.

      Gen_And_Remove ("");
      Gen_And_Remove ("Builder");
      Gen_And_Remove ("Compiler");
      Gen_And_Remove ("Naming");
      Gen_And_Remove ("Binder");
      Gen_And_Remove ("Linker");

      --  Generate remaining packages

      Packages.Iterate (Gen'Access);

      Add_Line ("end " & Project_Name & ";");

      return Result;
   exception
      when Invalid_KB =>
         --  Errors have already been added to the log
         return Null_Unbounded_String;
   end Generate_Configuration;

   ------------------------
   -- Get_External_Value --
   ------------------------

   procedure Get_External_Value
     (Attribute        : String;
      Value            : External_Value;
      Comp             : Compiler;
      Environment      : GPR2.Environment.Object;
      Split_Into_Words : Boolean := True;
      Merge_Same_Dirs  : Boolean := False;
      Calls_Cache      : in out GPR2.Containers.Name_Value_Map;
      Messages         : in out Log.Object;
      Processed_Value  : out External_Value_Lists.List;
      Ignore_Compiler  : out Boolean)
   is
      use External_Value_Nodes;
      use GNAT.Regpat;

      use GNATCOLL.Traces;

      Error_Sloc : constant Source_Reference.Object := Value.Sloc;
      Saved_Path : constant String := Environment.Value ("PATH");
      Used_Env   : GPR2.Environment.Object := Environment;

      function Get_Command_Output_Cache
        (Path    : String;
         Command : String) return Unbounded_String;
      --  Spawns given command and caches results. When the same command
      --  (same full path and arguments) should be spawned again,
      --  returns output from cache instead.

      ------------------------------
      -- Get_Command_Output_Cache --
      ------------------------------

      function Get_Command_Output_Cache
        (Path    : String;
         Command : String) return Unbounded_String
      is
         use GNAT.OS_Lib;
         use GPR2.Containers.Name_Value_Map_Package;

         Path_Dir : constant String :=
                      GPR2.Path_Name.Create_Directory
                        (Filename_Type (Path)).Dir_Name;
         Key      : constant Name_Type := Name_Type (Path_Dir & Command);
         Cur      : constant GPR2.Containers.Name_Value_Map_Package.Cursor :=
                      Calls_Cache.Find (Key);

         Tmp_Result : Unbounded_String;
      begin
         if Cur = GPR2.Containers.Name_Value_Map_Package.No_Element then
            declare
               Args        : Argument_List_Access :=
                               Argument_String_To_List (Command);
               Args_Vector : GNATCOLL.OS.Process.Argument_List;
               Dummy       : Integer;
            begin
               Args_Vector.Append (Path_Dir & Args (Args'First).all);
               for J in Args'First + 1 .. Args'Last loop
                  Args_Vector.Append (Args (J).all);
               end loop;
               OS_Lib.Free (Args);
               Tmp_Result := GNATCOLL.OS.Process.Run
                 (Args        => Args_Vector,
                  Env         => Used_Env.To_GNATCOLL_Environment,
                  Stdin       => GNATCOLL.OS.Process.FS.Null_FD,
                  Stderr      => GNATCOLL.OS.Process.FS.To_Stdout,
                  Status      => Dummy,
                  Inherit_Env => Used_Env.Inherit);
               Args_Vector.Clear;
               Calls_Cache.Include (Key, To_String (Tmp_Result));
               return Tmp_Result;
            end;

         else
            return To_Unbounded_String (Calls_Cache.Element (Key));
         end if;
      end Get_Command_Output_Cache;

      Extracted_From : Unbounded_String := Null_Unbounded_String;
      Tmp_Result     : Unbounded_String;
      Node_Cursor    : External_Value_Nodes.Cursor := Value.EV.First;
      Node           : External_Value_Node;
      From_Static    : Boolean := False;

      Visited        : String_To_External_Value.Map;
   begin
      Processed_Value.Clear;
      Ignore_Compiler := False;

      while Has_Element (Node_Cursor) loop
         while Has_Element (Node_Cursor) loop
            Node := External_Value_Nodes.Element (Node_Cursor);

            case Node.Typ is
               when Value_Variable =>
                  Extracted_From := Node.Var_Name;

               when Value_Constant =>
                  if Node.Value = Null_Unbounded_String then
                     Tmp_Result := Null_Unbounded_String;
                  else
                     Tmp_Result := To_Unbounded_String
                       (Substitute_Variables_In_Compiler_Description
                          (To_String (Node.Value),
                           Comp,
                           Error_Sloc,
                           Messages));
                  end if;

                  From_Static := True;
                  Trace
                    (Main_Trace,
                     Attribute & ": constant := " & To_String (Tmp_Result));

               when Value_Shell =>
                  Used_Env.Insert
                    ("PATH",
                     Comp.Path.Value & OS_Lib.Path_Separator & Saved_Path);

                  declare
                     Command : constant String :=
                                 Substitute_Variables_In_Compiler_Description
                                   (To_String (Node.Command),
                                    Comp,
                                    Error_Sloc,
                                    Messages);
                  begin
                     Tmp_Result := Null_Unbounded_String;
                     Tmp_Result :=
                       Get_Command_Output_Cache (Comp.Path.Value, Command);
                     Used_Env := Environment;

                     Trace (Main_Trace,
                            Attribute & ": executing """ & Command
                            & """ output="""
                            & To_String (Tmp_Result) & """");
                  exception
                     when GNATCOLL.OS.OS_Error =>
                        Trace (Main_Trace, "Spawn failed for " & Command);
                  end;

               when Value_Directory =>
                  declare
                     Search : constant String :=
                                Substitute_Variables_In_Compiler_Description
                                  (To_String (Node.Directory),
                                   Comp,
                                   Error_Sloc,
                                   Messages);
                  begin
                     if Search (Search'First) = '/' then
                        Increase_Indent
                          (Main_Trace,
                           Attribute & ": search directories matching "
                           & Search & ", starting from /");

                        Parse_All_Dirs
                          (Processed_Value => Processed_Value,
                           Visited         => Visited,
                           Current_Dir     => "",
                           Path_To_Check   => Search,
                           Contents        => Node.Contents,
                           Regexp          =>
                             Compile (Search (Search'First + 1
                                              .. Search'Last)),
                           Regexp_Str      => Search,
                           Value_If_Match  => To_String (Node.Dir_If_Match),
                           Merge_Same_Dirs => Merge_Same_Dirs,
                           Group           => Node.Directory_Group,
                           Error_Sloc      => Error_Sloc,
                           Messages        => Messages);
                     else
                        Increase_Indent
                          (Main_Trace,
                           Attribute & ": search directories matching "
                           & Search & ", starting from "
                           & Comp.Path.Value);

                        Parse_All_Dirs
                          (Processed_Value => Processed_Value,
                           Visited         => Visited,
                           Current_Dir     => Comp.Path.Value,
                           Path_To_Check   => Search,
                           Contents        => Node.Contents,
                           Regexp          => Compile (Search),
                           Regexp_Str      => Search,
                           Value_If_Match  => To_String (Node.Dir_If_Match),
                           Merge_Same_Dirs => Merge_Same_Dirs,
                           Group           => Node.Directory_Group,
                           Error_Sloc      => Error_Sloc,
                           Messages        => Messages);
                     end if;

                     Decrease_Indent
                       (Main_Trace, "Done search directories");
                  end;

               when Value_Grep =>
                  declare
                     Tmp_Str : constant String := To_String (Tmp_Result);
                     Matched : Match_Array (0 .. Node.Group);
                  begin
                     Match (Node.Regexp_Re.Element, Tmp_Str, Matched);

                     if Matched (0) /= No_Match then
                        Tmp_Result := To_Unbounded_String
                          (Tmp_Str (Matched (Node.Group).First ..
                                    Matched (Node.Group).Last));
                        Trace
                          (Main_Trace,
                           Attribute & ": grep matched="""
                           & To_String (Tmp_Result) & """");
                     else
                        Tmp_Result := Null_Unbounded_String;
                        Trace (Main_Trace, Attribute & ": grep no match");
                     end if;
                  end;

               when Value_Nogrep =>
                  declare
                     Tmp_Str : constant String := To_String (Tmp_Result);
                     Matched : Match_Array (0 .. 0);
                  begin
                     Match (Node.Regexp_No.Element, Tmp_Str, Matched);

                     if Matched (0) /= No_Match then
                        Trace
                          (Main_Trace,
                           Attribute & ": nogrep matched=""" & Tmp_Str & """");
                        Ignore_Compiler := True;
                        return;

                     else
                        Trace (Main_Trace, Attribute & ": nogrep no match");
                     end if;
                  end;

               when Value_Must_Match =>
                  if not Match
                    (Expression => To_String (Node.Must_Match),
                     Data       => To_String (Tmp_Result))
                  then
                     Trace
                       (Main_Trace,
                        "Ignore compiler since external value """
                        & To_String (Tmp_Result) & """ must match "
                        & To_String (Node.Must_Match));

                     Tmp_Result := Null_Unbounded_String;
                     Ignore_Compiler := True;
                     return;
                  end if;

                  exit;

               when Value_Done | Value_Filter =>
                  exit;
            end case;

            Next (Node_Cursor);
         end loop;

         case Node.Typ is
            when Value_Done | Value_Filter | Value_Must_Match =>
               if Tmp_Result = Null_Unbounded_String then
                  --  Value could not be computed
                  if Extracted_From /= Null_Unbounded_String then
                     Processed_Value.Append
                        (External_Value_Item'
                          (Value          => Null_Unbounded_String,
                           Alternate      => Null_Unbounded_String,
                           Extracted_From => Extracted_From));
                  end if;

               elsif Split_Into_Words then
                  declare
                     Filter : constant String :=
                                (if Node.Typ = Value_Filter
                                 then To_String (Node.Filter)
                                 else "");
                     Split  : Containers.Value_List;
                  begin
                     --  When an external value is defined as a static string,
                     --  the only valid separator is ','. When computed
                     --  however, we also allow space as a separator.

                     if From_Static then
                        Get_Words
                          (Words                => To_String (Tmp_Result),
                           Filter               => Filter,
                           Separator1           => ',',
                           Separator2           => ',',
                           Map                  => Split,
                           Allow_Empty_Elements => False);

                     else
                        Get_Words
                          (Words                => To_String (Tmp_Result),
                           Filter               => Filter,
                           Separator1           => ' ',
                           Separator2           => ',',
                           Map                  => Split,
                           Allow_Empty_Elements => False);
                     end if;

                     for Elem of Split loop
                        Processed_Value.Append
                           (External_Value_Item'
                              (Value          =>
                                   To_Unbounded_String (String (Elem)),
                              Alternate      => Null_Unbounded_String,
                              Extracted_From => Extracted_From));
                     end loop;
                  end;

               else
                  Processed_Value.Append
                    (External_Value_Item'
                       (Value          => Tmp_Result,
                        Alternate      => Null_Unbounded_String,
                        Extracted_From => Extracted_From));
               end if;

            when others =>
               null;
         end case;

         Extracted_From := Null_Unbounded_String;

         Next (Node_Cursor);
      end loop;

   end Get_External_Value;

   --------------------------
   -- Get_String_No_Adalib --
   --------------------------

   function Get_String_No_Adalib (Str : String) return String is
      use GNAT.OS_Lib;

      Name : constant String (1 .. Str'Length) := Str;
      Last : Natural := Name'Last;
   begin
      if Last > 7
        and then (Name (Last) in Directory_Separator | '/')
      then
         Last := Last - 1;
      end if;

      if Last > 6
        and then Name (Last - 5 .. Last) = "adalib"
        and then (Name (Last - 6) in Directory_Separator | '/')
      then
         Last := Last - 6;
      else
         Last := Name'Last;
      end if;

      return Name (1 .. Last);
   end Get_String_No_Adalib;

   ------------------------
   -- Get_Variable_Value --
   ------------------------

   function Get_Variable_Value
     (Comp : Compiler;
      Name : String) return String
   is
      N : constant Unbounded_String := To_Unbounded_String (Name);
   begin
      if Variables_Maps.Contains (Comp.Variables, N) then
         return To_String (Variables_Maps.Element (Comp.Variables, N));
      elsif Name = "HOST" then
         return String (Default_Target);
      elsif Name = "TARGET" then
         return To_String (Comp.Target);
      elsif Name = "RUNTIME_DIR" then
         return Name_As_Directory (To_String (Comp.Runtime_Dir));
      elsif Name = "EXEC" then
         return To_String (Comp.Executable);
      elsif Name = "VERSION" then
         return To_String (Comp.Version);
      elsif Name = "LANGUAGE" then
         return String (GPR2.Name (Comp.Language));
      elsif Name = "RUNTIME" then
         return To_String (Comp.Runtime);
      elsif Name = "PREFIX" then
         return To_String (Comp.Prefix);
      elsif Name = "PATH" then
         return GNAT.OS_Lib.Normalize_Pathname
           (Comp.Path.Value, Case_Sensitive => False)
           & GNAT.OS_Lib.Directory_Separator;
      elsif Name = "GPRCONFIG_PREFIX" then
         return GPR_Executable_Prefix_Path;
      end if;

      raise Invalid_KB
        with "variable '" & Name & "' is not defined";
   end Get_Variable_Value;

   ---------------
   -- Get_Words --
   ---------------

   procedure Get_Words
     (Words                : String;
      Filter               : String;
      Separator1           : Character;
      Separator2           : Character;
      Map                  : out Containers.Value_List;
      Allow_Empty_Elements : Boolean)
   is
      First      : Integer := Words'First;
      Last       : Integer;
      Filter_Set : GPR2.Containers.Value_List;
   begin
      if Filter /= "" then
         Get_Words (Filter, "", Separator1,
                    Separator2, Filter_Set,
                    Allow_Empty_Elements => True);
      end if;

      if not Allow_Empty_Elements then
         while First <= Words'Last
           and then (Words (First) = Separator1
                     or else Words (First) = Separator2)
         loop
            First := First + 1;
         end loop;
      end if;

      while First <= Words'Last loop
         if Words (First) /= Separator1
           and then Words (First) /= Separator2
         then
            Last := First + 1;
            while Last <= Words'Last
              and then Words (Last) /= Separator1
              and then Words (Last) /= Separator2
            loop
               Last := Last + 1;
            end loop;
         else
            Last := First;
         end if;

         if (Allow_Empty_Elements or else First <= Last - 1)
           and then
             (Filter_Set.Is_Empty
              or else Filter_Set.Contains
                (Value_Type (Words (First .. Last - 1))))
         then
            Map.Append (Value_Type (Words (First .. Last - 1)));
         end if;

         First := Last + 1;
      end loop;
   end Get_Words;

   --------------------------------
   -- GPR_Executable_Prefix_Path --
   --------------------------------

   function GPR_Executable_Prefix_Path return String
   is
      use Ada.Directories;
      use Ada.Strings.Fixed;
      use GNAT.OS_Lib;

      Tools_Dir : constant String := Get_Tools_Directory;
      Exec_Name : constant String :=
                    Normalize_Pathname (Ada.Command_Line.Command_Name,
                                        Resolve_Links => True);
   begin

      if Has_Directory_Separator (Exec_Name)
        and then Head (Base_Name (Exec_Name), 3) = "gpr"
        and then Base_Name (Containing_Directory (Exec_Name)) = "bin"
      then
         --  A gprtool has been called with path prefix, we need
         --  to return the prefix of corresponding gprtools installation,
         --  in case it is not the first one on the path.

         return
           Containing_Directory (Containing_Directory (Exec_Name))
           & GNAT.OS_Lib.Directory_Separator;
      end if;

      --  It's either a gprtool called by base name or another kind of tool,
      --  in both cases we need to find gprtools on PATH.

      if Tools_Dir = "" then
         return "";
      else
         return Tools_Dir & GNAT.OS_Lib.Directory_Separator;
      end if;

   end GPR_Executable_Prefix_Path;

   ----------------------------------
   -- Is_Language_With_No_Compiler --
   ----------------------------------

   function Is_Language_With_No_Compiler
     (Self     : Object;
      Language : Language_Id) return Boolean is
   begin
      return Self.No_Compilers.Contains (Language);
   end Is_Language_With_No_Compiler;

   -------------------------
   -- Is_Supported_Config --
   -------------------------

   function Is_Supported_Config
     (Self      : Object;
      Compilers : Compiler_Lists.List) return Boolean
   is
      use Configuration_Lists;

      Config            : Configuration_Lists.Cursor :=
                            First (Self.Configurations);
      M                 : Boolean;
   begin
      while Has_Element (Config) loop
         M := Match (Configuration_Lists.Element (Config).Compilers_Filters,
                     Compilers);
         if M and then Match
           (Configuration_Lists.Element (Config).Targets_Filters,
            Configuration_Lists.Element (Config).Negate_Targets,
            Compilers)
         then
            if not Configuration_Lists.Element (Config).Supported then
               GNATCOLL.Traces.Trace
                 (Match_Trace,
                  "Selected compilers are not compatible, because of:");
               GNATCOLL.Traces.Trace
                 (Match_Trace,
                  To_String
                    (Configuration_Node_Image
                         (Configuration_Lists.Element (Config))));
               return False;
            end if;
         end if;
         Next (Config);
      end loop;
      return True;
   end Is_Supported_Config;

   --------------------------
   -- Known_Compiler_Names --
   --------------------------

   function Known_Compiler_Names (Self : Object) return Unbounded_String is
      use Compiler_Description_Maps;

      Result : Unbounded_String;
      Cur    : Compiler_Description_Maps.Cursor := Self.Compilers.First;
   begin
      while Has_Element (Cur) loop
         if Result /= Null_Unbounded_String then
            Append (Result, ",");
         end if;
         Append (Result, String (Key (Cur)));

         Next (Cur);
      end loop;

      return Result;
   end Known_Compiler_Names;

   -----------
   -- Match --
   -----------

   function Match
     (Filter    : Compilers_Filter_Lists.List;
      Compilers : Compiler_Lists.List) return Boolean
   is
      use Compilers_Filter_Lists;
      C : Compilers_Filter_Lists.Cursor := First (Filter);
      M : Boolean;
   begin
      while Has_Element (C) loop
         M := Match (Compilers_Filter_Lists.Element (C), Compilers);
         if not M then
            return False;
         end if;

         Next (C);
      end loop;

      return True;
   end Match;

   -----------
   -- Match --
   -----------

   function Match
     (Filter            : Compilers_Filter;
      Compilers         : Compiler_Lists.List) return Boolean
   is
      use Compiler_Filter_Lists;
      C : Compiler_Filter_Lists.Cursor := First (Filter.Compiler);
      M : Boolean;
   begin
      while Has_Element (C) loop
         M := Match (Compiler_Filter_Lists.Element (C), Compilers);
         if M then
            return not Filter.Negate;
         end if;
         Next (C);
      end loop;
      return Filter.Negate;
   end Match;

   -----------
   -- Match --
   -----------

   function Match
     (Filter    : Compiler_Filter;
      Compilers : Compiler_Lists.List) return Boolean
   is
      use Compiler_Lists;
      use GNAT.Regpat;
      C    : Compiler_Lists.Cursor := First (Compilers);
      Comp : Compiler;

      function Runtime_Base_Name (Rt : Unbounded_String) return String is
        (GNAT.Directory_Operations.Base_Name (To_String (Rt)));
      --  Runtime filters should only apply to the base name of runtime when
      --  full path is given, otherwise we can potentially match some unrelated
      --  patterns from enclosing directory names.

      function Name_Matches return Boolean;
      function Version_Matches return Boolean;
      function Runtime_Matches return Boolean;
      function Language_Matches return Boolean;
      --  Predicates checking matching of corresponding attributes

      ----------------------
      -- Language_Matches --
      ----------------------

      function Language_Matches return Boolean is
      begin
         if Filter.Language = No_Language
           or else Filter.Language = Comp.Language
         then
            return True;
         end if;

         return False;
      end Language_Matches;

      ------------------
      -- Name_Matches --
      ------------------

      function Name_Matches return Boolean is
      begin
         if Filter.Name = Null_Unbounded_String then
            return True;
         end if;

         if Comp.Name /= Null_Unbounded_String
           and then Match (Filter.Name_Re.Element, To_String (Comp.Name))
         then
            return True;
         end if;

         if Comp.Base_Name = Filter.Name then
            return True;
         end if;

         return False;
      end Name_Matches;

      ---------------------
      -- Runtime_Matches --
      ---------------------

      function Runtime_Matches return Boolean is
      begin
         if Filter.Runtime_Re.Is_Empty then
            return True;
         end if;

         if Comp.Runtime /= Null_Unbounded_String
           and then Match (Filter.Runtime_Re.Element,
                           Runtime_Base_Name (Comp.Runtime))
         then
            return True;
         end if;

         return False;
      end Runtime_Matches;

      ----------------------
      --  Version_Matches --
      ----------------------

      function Version_Matches return Boolean is
      begin
         if Filter.Version_Re.Is_Empty then
            return True;
         end if;

         if Comp.Version /= Null_Unbounded_String
           and then Match (Filter.Version_Re.Element, To_String (Comp.Version))
         then
            return True;
         end if;

         return False;
      end Version_Matches;

   begin
      while Has_Element (C) loop
         Comp := Compiler_Lists.Element (C);

         if Comp.Selected
           and then Name_Matches
           and then Version_Matches
           and then Runtime_Matches
           and then Language_Matches
         then
            return True;
         end if;
         Next (C);
      end loop;

      return False;
   end Match;

   -----------
   -- Match --
   -----------

   function Match
     (Target_Filter : Double_String_Lists.List;
      Negate        : Boolean;
      Compilers     : Compiler_Lists.List) return Boolean
   is
      use Compiler_Lists;
      use Double_String_Lists;
      use GNAT.Regpat;
      Target : Double_String_Lists.Cursor := First (Target_Filter);
      Comp   : Compiler_Lists.Cursor;
   begin
      if Is_Empty (Target_Filter) then
         return True;

      else
         while Has_Element (Target) loop
            declare
               Positive_Pattern : constant Pattern_Matcher :=
                 Compile
                   (To_String
                      (Double_String_Lists.Element (Target).Positive_Regexp),
                    GNAT.Regpat.Case_Insensitive);
               Negative_Pattern : constant Pattern_Matcher :=
                 Compile
                   (To_String
                      (Double_String_Lists.Element (Target).Negative_Regexp),
                    GNAT.Regpat.Case_Insensitive);

               Ignore_Negative : constant Boolean :=
                 Double_String_Lists.Element (Target).Negative_Regexp = "";
            begin
               Comp := First (Compilers);
               while Has_Element (Comp) loop
                  if Compiler_Lists.Element (Comp).Selected then
                     if Compiler_Lists.Element (Comp).Target =
                       Null_Unbounded_String
                     then
                        if Match (Positive_Pattern, "") then
                           return not Negate;
                        end if;

                     elsif Match
                       (Positive_Pattern,
                        To_String (Compiler_Lists.Element (Comp).Target))
                       and then
                         (Ignore_Negative or else not Match
                            (Negative_Pattern,
                             To_String
                               (Compiler_Lists.Element (Comp).Target)))
                     then
                        return not Negate;
                     end if;
                  end if;
                  Next (Comp);
               end loop;
            end;

            Next (Target);
         end loop;
         return Negate;
      end if;
   end Match;

   ------------------
   -- Merge_Config --
   ------------------

   procedure Merge_Config
     (Self       : Object;
      Packages   : in out String_Maps.Map;
      Compilers  : Compiler_Lists.List;
      Config     : String;
      Langs      : Ordered_Languages;
      Error_Sloc : Source_Reference.Object;
      Errors     : in out Log.Object)
   is
      procedure Add_Package
        (Name : String; Chunk : String; Prefix : String := "      ");
      --  Add the chunk in the appropriate package

      procedure Skip_Spaces (Str : String; Index : in out Integer);
      --  Move Index from its current position to the next non-whitespace
      --  character in Str

      procedure Skip_Spaces_Backward (Str : String; Index : in out Integer);
      --  Same as Skip_Spaces, but goes backward

      -----------------
      -- Add_Package --
      -----------------

      procedure Add_Package
        (Name : String; Chunk : String; Prefix : String := "      ")
      is
         use String_Maps;
         C        : constant String_Maps.Cursor :=
                      Find (Packages, Name);
         Replaced : constant String :=
                      Substitute_Variables_In_Configuration
                        (Self, Chunk, Compilers, Langs, Error_Sloc, Errors);
      begin
         if Replaced /= "" then
            if Has_Element (C) then
               Replace_Element
                 (Packages,
                  C,
                  Element (C) & ASCII.LF & Prefix & Replaced);
            else
               Insert
                 (Packages,
                  Name, Prefix & Replaced);
            end if;
         end if;
      end Add_Package;

      -----------------
      -- Skip_Spaces --
      -----------------

      procedure Skip_Spaces (Str : String; Index : in out Integer) is
      begin
         while Index <= Str'Last
           and then (Str (Index) = ' ' or else Str (Index) = ASCII.LF)
         loop
            Index := Index + 1;
         end loop;
      end Skip_Spaces;

      --------------------------
      -- Skip_Spaces_Backward --
      --------------------------

      procedure Skip_Spaces_Backward (Str : String; Index : in out Integer) is
      begin
         while Index >= Str'First
           and then (Str (Index) = ' ' or else Str (Index) = ASCII.LF)
         loop
            Index := Index - 1;
         end loop;
      end Skip_Spaces_Backward;

      First                         : Integer := Config'First;
      Pkg_Name_First, Pkg_Name_Last : Integer;
      Pkg_Content_First             : Integer;
      Last                          : Integer;

      use Ada.Strings.Fixed;
   begin
      while First /= 0 and then First <= Config'Last loop
         --  Do we have a top-level attribute ?
         Skip_Spaces (Config, First);
         Pkg_Name_First := Index (Config (First .. Config'Last), "package ");
         if Pkg_Name_First = 0 then
            Pkg_Name_First := Config'Last + 1;
         end if;

         Last := Pkg_Name_First - 1;
         Skip_Spaces_Backward (Config, Last);
         Add_Package
           (Name   => "",
            Chunk  => Config (First .. Last),
            Prefix => "   ");

         exit when Pkg_Name_First > Config'Last;

         --  Parse the current package

         Pkg_Name_First := Pkg_Name_First + 8;  --  skip "package "
         Skip_Spaces (Config, Pkg_Name_First);

         Pkg_Name_Last := Pkg_Name_First + 1;

         while Pkg_Name_Last <= Config'Last
           and then Config (Pkg_Name_Last) /= ' '
           and then Config (Pkg_Name_Last) /= ASCII.LF
         loop
            Pkg_Name_Last := Pkg_Name_Last + 1;
         end loop;

         Pkg_Content_First := Pkg_Name_Last + 1;
         Skip_Spaces (Config, Pkg_Content_First);
         Pkg_Content_First := Pkg_Content_First + 2; --  skip "is"
         Skip_Spaces (Config, Pkg_Content_First);

         Last := Index (Config (Pkg_Content_First .. Config'Last),
                        "end " & Config (Pkg_Name_First .. Pkg_Name_Last - 1));
         if Last /= 0 then
            First := Last - 1;
            Skip_Spaces_Backward (Config, First);
            Add_Package
              (Name  => Config (Pkg_Name_First .. Pkg_Name_Last - 1),
               Chunk => Config (Pkg_Content_First .. First));

            while Last <= Config'Last and then Config (Last) /= ';' loop
               Last := Last + 1;
            end loop;
            Last := Last + 1;
         end if;
         First := Last;
      end loop;
   end Merge_Config;

   -----------------------
   -- Name_As_Directory --
   -----------------------

   function Name_As_Directory (Dir : String) return String is
      use GNAT.OS_Lib;
   begin
      if Dir = ""
        or else Dir (Dir'Last) in Directory_Separator | '/'
      then
         return Dir;
      else
         return Dir & Directory_Separator;
      end if;
   end Name_As_Directory;

   -----------------------
   -- Normalized_Target --
   -----------------------

   function Normalized_Target
     (Self   : Object;
      Target : Name_Type) return Name_Type
   is
      Result : Target_Set_Description;
   begin
      Result := Targets_Set_Vectors.Element
        (Self.Targets_Sets, Self.Query_Targets_Set (Target));

      return Name_Type (To_String (Result.Name));
   exception
      when others =>
         return "unknown";
   end Normalized_Target;

   --------------------
   -- Parse_All_Dirs --
   --------------------

   procedure Parse_All_Dirs
     (Processed_Value : out External_Value_Lists.List;
      Visited         : in out String_To_External_Value.Map;
      Current_Dir     : String;
      Path_To_Check   : String;
      Regexp          : Regpat.Pattern_Matcher;
      Regexp_Str      : String;
      Value_If_Match  : String;
      Group           : Integer;
      Group_Match     : String := "";
      Group_Count     : Natural := 0;
      Contents        : Pattern_Matcher_Holder;
      Merge_Same_Dirs : Boolean;
      Error_Sloc      : Source_Reference.Object;
      Messages        : in out Log.Object)
   is
      use GNAT.Regpat;
      use GNAT.OS_Lib;
      use GNATCOLL.Traces;

      procedure Save_File (Current_Dir : String; Val : String);
      --  Mark the given directory as valid for the <directory> configuration.
      --  This takes care of removing duplicates if needed.

      function Is_Regexp (Str : String) return Boolean;
      --  Whether Str is a regular expression

      function Unquote_Regexp
        (Str : String; Remove_Quoted : Boolean := False) return String;
      --  Remove special '\' quoting characters from Str.
      --  As a special case, if Remove_Quoted is true, then '\'
      --  and the following char are simply omitted in the output.
      --  For instance:
      --      Str="A\." Remove_Quoted=False  => output is "A."
      --      Str="A\." Remove_Quoted=False  => output is "A"

      ---------------
      -- Is_Regexp --
      ---------------

      function Is_Regexp (Str : String) return Boolean is
         --  Take into account characters quoted by '\'. We just remove them
         --  for now, so that when we quote the regexp it won't see these
         --  potentially special characters.
         --  The goal is that for instance "\.\." is not considered
         --  as a regexp, but "\.." is.
         Str2 : constant String := Unquote_Regexp (Str, Remove_Quoted => True);
      begin
         return Regpat.Quote (Str2) /= Str2;
      end Is_Regexp;

      ---------------
      -- Save_File --
      ---------------

      procedure Save_File (Current_Dir : String; Val : String) is
      begin
         if not Merge_Same_Dirs then
            Trace (Main_Trace, "<dir>: SAVE " & Current_Dir);

            Processed_Value.Append
               ((Value          => To_Unbounded_String (Val),
                 Alternate      => Null_Unbounded_String,
                 Extracted_From =>
                   To_Unbounded_String (Get_String_No_Adalib (Current_Dir))));

         else
            declare
               use String_To_External_Value;

               Normalized : constant String := Normalize_Pathname
                              (Name           => Current_Dir,
                               Directory      => "",
                               Resolve_Links  => True,
                               Case_Sensitive => True);
               Prev       : External_Value_Lists.Cursor;
               Rec        : External_Value_Item;
            begin
               if Visited.Contains (Normalized) then
                  Trace
                    (Main_Trace,
                     "<dir>: ALREADY FOUND (" & Val & ") " & Current_Dir);

                  Prev          := Visited.Element (Normalized);
                  Rec           := External_Value_Lists.Element (Prev);
                  Rec.Alternate := To_Unbounded_String (Val);

                  External_Value_Lists.Replace_Element
                    (Container => Processed_Value,
                     Position  => Prev,
                     New_Item  => Rec);

               else
                  Trace
                    (Main_Trace, "<dir>: SAVE (" & Val & ") " & Current_Dir);

                  Processed_Value.Append
                    ((Value          => To_Unbounded_String (Val),
                      Alternate      => Null_Unbounded_String,
                      Extracted_From =>
                        To_Unbounded_String
                          (Get_String_No_Adalib (Current_Dir))));

                  Visited.Include
                    (Normalized, External_Value_Lists.Last (Processed_Value));
               end if;
            end;
         end if;
      end Save_File;

      --------------------
      -- Unquote_Regexp --
      --------------------

      function Unquote_Regexp
        (Str : String; Remove_Quoted : Boolean := False) return String
      is
         Str2  : String (Str'Range);
         S     : Integer := Str'First;
         Index : Integer := Str2'First;
      begin
         while S <= Str'Last loop
            if Str (S) = '\' then
               S := S + 1;

               if not Remove_Quoted then
                  Str2 (Index) := Str (S);
                  Index := Index + 1;
               end if;

            else
               Str2 (Index) := Str (S);
               Index := Index + 1;
            end if;

            S     := S + 1;
         end loop;

         return Str2 (Str2'First .. Index - 1);
      end Unquote_Regexp;

      First : constant Integer := Path_To_Check'First;
      Last  : Integer;
      Val   : Unbounded_String;

   begin
      if Path_To_Check'Length = 0
        or else Path_To_Check = "/"
        or else Path_To_Check = String'(1 => Directory_Separator)
      then
         if Group = -1 then
            Val := To_Unbounded_String (Value_If_Match);
         else
            Val := To_Unbounded_String (Group_Match);
         end if;

         if not Contents.Is_Empty
           and then Is_Regular_File (Current_Dir)
         then
            Trace (Main_Trace, "<dir>: Checking inside file " & Current_Dir);

            declare
               use Ada.Text_IO;
               use Directory_Operations;
               F : File_Type;
            begin
               Open (F, In_File, Current_Dir);

               while not End_Of_File (F) loop
                  declare
                     Line : constant String := Get_Line (F);
                  begin
                     Trace (Main_Trace, "<dir>: read line " & Line);

                     if Match (Contents.Element, Line) then
                        Save_File
                          (Normalize_Pathname
                             (Name => Line,
                              Directory => Dir_Name (Current_Dir),
                              Resolve_Links => True),
                           To_String (Val));
                        exit;
                     end if;
                  end;
               end loop;

               Close (F);
            end;

         else
            Save_File (Current_Dir, To_String (Val));
         end if;

      else
         --  Do not split on '\', since we document we only accept UNIX paths
         --  anyway. This leaves \ for regexp quotes.
         Last := First + 1;

         while Last <= Path_To_Check'Last
           and then Path_To_Check (Last) /= '/'
         loop
            Last := Last + 1;
         end loop;

         --  If we do not have a regexp

         if not Is_Regexp (Path_To_Check (First .. Last - 1)) then
            declare
               Dir     : constant String :=
                           Normalize_Pathname
                             (Current_Dir, Resolve_Links => False)
                           & Directory_Separator
                           & Unquote_Regexp
                              (Path_To_Check (First .. Last - 1));
               Remains : constant String :=
                           Path_To_Check (Last + 1 .. Path_To_Check'Last);
            begin
               if (Remains'Length = 0
                   or else Remains = "/"
                   or else Remains = String'(1 => Directory_Separator))
                 and then Is_Regular_File (Dir)
               then
                  Trace (Main_Trace, "<dir>: Found file " & Dir);
                  --  If there is such a subdir, keep checking

                  Parse_All_Dirs
                    (Processed_Value => Processed_Value,
                     Visited         => Visited,
                     Current_Dir     => Dir,
                     Path_To_Check   => Remains,
                     Regexp          => Regexp,
                     Regexp_Str      => Regexp_Str,
                     Value_If_Match  => Value_If_Match,
                     Group           => Group,
                     Group_Match     => Group_Match,
                     Group_Count     => Group_Count,
                     Contents        => Contents,
                     Merge_Same_Dirs => Merge_Same_Dirs,
                     Error_Sloc      => Error_Sloc,
                     Messages        => Messages);

               elsif Is_Directory (Dir) then
                  Trace (Main_Trace, "<dir>: Recurse into " & Dir);
                  --  If there is such a subdir, keep checking

                  Parse_All_Dirs
                    (Processed_Value => Processed_Value,
                     Visited         => Visited,
                     Current_Dir     => Dir & Directory_Separator,
                     Path_To_Check   => Remains,
                     Regexp          => Regexp,
                     Regexp_Str      => Regexp_Str,
                     Value_If_Match  => Value_If_Match,
                     Group           => Group,
                     Group_Match     => Group_Match,
                     Group_Count     => Group_Count,
                     Contents        => Contents,
                     Merge_Same_Dirs => Merge_Same_Dirs,
                     Error_Sloc      => Error_Sloc,
                     Messages        => Messages);
               else
                  Trace (Main_Trace, "<dir>: No such directory: " & Dir);
               end if;
            end;

         --  Else we have a regexp, check all files

         else
            declare
               use Ada.Directories;

               File_Re     : constant String :=
                               Path_To_Check (First .. Last - 1);
               File_Regexp : constant Pattern_Matcher := Compile (File_Re);
               Search      : Search_Type;
               File        : Directory_Entry_Type;
               Filter      : Ada.Directories.Filter_Type;
            begin
               if File_Re = ".." then
                  Trace
                    (Main_Trace,
                     "Potential error: .. is generally not meant as a regexp,"
                     & " and should be quoted in this case, as in \.\.");
               end if;

               if Path_To_Check (Last) = '/' then
                  Trace
                    (Main_Trace,
                     "<dir>: Check directories in " & Current_Dir
                     & " that match " & File_Re);
                  Filter := (Directory => True, others => False);

               else
                  Trace
                    (Main_Trace,
                     "<dir>: Check files in " & Current_Dir
                     & " that match " & File_Re);
                  Filter := (others => True);
               end if;

               Start_Search
                 (Search    => Search,
                  Directory => Current_Dir,
                  Filter    => Filter,
                  Pattern   => "");

               while More_Entries (Search) loop
                  begin
                     Get_Next_Entry (Search, File);
                  exception
                     when E : others =>
                        Trace
                          (Main_Trace,
                           "<dir>: ignoring entry, "
                           & Ada.Exceptions.Exception_Message (E));
                        goto Next_Entry;
                  end;

                  if Directories.Simple_Name (File) /= "."
                    and then Directories.Simple_Name (File) /= ".."
                  then
                     declare
                        Simple  : constant String :=
                                    Directories.Simple_Name (File);
                        Count   : constant Natural :=
                                    Paren_Count (File_Regexp);
                        Matched : Match_Array (0 .. Integer'Max (Group, 0));
                     begin
                        Match (File_Regexp, Simple, Matched);

                        if Matched (0) /= No_Match then
                           Trace
                             (Main_Trace,
                              "<dir>: Matched "
                              & Ada.Directories.Simple_Name (File));

                           if Group_Count < Group
                             and then Group_Count + Count >= Group
                           then
                              if Matched (Group - Group_Count) = No_Match then
                                 Trace
                                   (Main_Trace,
                                    "<dir>: Matched group is empty, skipping");
                                 return;
                              end if;
                              Trace
                                (Main_Trace,
                                 "<dir>: Found matched group: "
                                 & Simple (Matched (Group - Group_Count).First
                                   .. Matched (Group - Group_Count).Last));

                              Parse_All_Dirs
                                (Processed_Value => Processed_Value,
                                 Visited         => Visited,
                                 Current_Dir     =>
                                   Full_Name (File) & Directory_Separator,
                                 Path_To_Check   => Path_To_Check
                                   (Last + 1 .. Path_To_Check'Last),
                                 Regexp          => Regexp,
                                 Regexp_Str      => Regexp_Str,
                                 Value_If_Match  => Value_If_Match,
                                 Group           => Group,
                                 Group_Match     =>
                                   Simple (Matched (Group - Group_Count).First
                                       .. Matched (Group - Group_Count).Last),
                                 Group_Count     => Group_Count + Count,
                                 Contents        => Contents,
                                 Merge_Same_Dirs => Merge_Same_Dirs,
                                 Error_Sloc      => Error_Sloc,
                                 Messages        => Messages);

                           else
                              Parse_All_Dirs
                                (Processed_Value => Processed_Value,
                                 Visited         => Visited,
                                 Current_Dir     =>
                                   Full_Name (File) & Directory_Separator,
                                 Path_To_Check   => Path_To_Check
                                   (Last + 1 .. Path_To_Check'Last),
                                 Regexp          => Regexp,
                                 Regexp_Str      => Regexp_Str,
                                 Value_If_Match  => Value_If_Match,
                                 Group           => Group,
                                 Group_Match     => Group_Match,
                                 Group_Count     => Group_Count + Count,
                                 Contents        => Contents,
                                 Merge_Same_Dirs => Merge_Same_Dirs,
                                 Error_Sloc      => Error_Sloc,
                                 Messages        => Messages);
                           end if;
                        end if;
                     end;
                  end if;
                  << Next_Entry >>
               end loop;
            end;
         end if;
      end if;
   end Parse_All_Dirs;

   ------------------------------
   -- Parse_Default_Target_Val --
   ------------------------------

   procedure Parse_Default_Target_Val is
      use GNATCOLL.Traces;
      use GNAT.OS_Lib;

      Tgt_File_Base : constant String := "default_target";
      Tgt_File_Full : constant String :=
                        GPR_Executable_Prefix_Path
                        & "share" & Directory_Separator
                        & "gprconfig" & Directory_Separator & Tgt_File_Base;

      F : Ada.Text_IO.File_Type;
   begin
      Trace (Main_Trace, "Parsing default target");
      Default_Target_Parsed := True;

      if GPR_Executable_Prefix_Path = "" then
         Trace (Main_Trace, "Gprtools installation not found");
         return;
      end if;

      if not Is_Regular_File (Tgt_File_Full) then
         Trace (Main_Trace, Tgt_File_Full & " not found");
         return;
      end if;

      Ada.Text_IO.Open (F, Ada.Text_IO.In_File, Tgt_File_Full);
      Default_Target_Val := To_Unbounded_String (Ada.Text_IO.Get_Line (F));
      Ada.Text_IO.Close (F);
   exception
      when X : others =>
         Trace (Main_Trace, "Cannot parse " & Tgt_File_Full);
         Trace (Main_Trace, Ada.Exceptions.Exception_Information (X));
   end Parse_Default_Target_Val;

   -----------------------
   -- Query_Targets_Set --
   -----------------------

   function Query_Targets_Set
     (Self   : Object;
      Target : Name_Type) return Targets_Set_Id
   is
      use Targets_Set_Vectors;
      use Target_Lists;

      Tgt : constant String := String (Target);
   begin
      if Target = "all" then
         return All_Target_Sets;
      end if;

      for I in
        First_Index (Self.Targets_Sets) .. Last_Index (Self.Targets_Sets)
      loop
         declare
            Set : constant Target_Lists.List :=
                    Targets_Set_Vectors.Element
                      (Self.Targets_Sets, I).Patterns;
            C   : Target_Lists.Cursor := First (Set);
         begin
            while Has_Element (C) loop
               if GNAT.Regpat.Match
                 (Target_Lists.Element (C), Tgt) > Tgt'First - 1
               then
                  return I;
               end if;

               Next (C);
            end loop;
         end;
      end loop;

      return Unknown_Targets_Set;
   end Query_Targets_Set;

   -------------
   -- Release --
   -------------

   procedure Release (Self : in out Object) is
   begin
      null;
   end Release;

   -------------
   -- Runtime --
   -------------

   function Runtime
     (Comp      : Compiler;
      Alternate : Boolean := False) return Optional_Name_Type is
   begin
      if Alternate then
         if Comp.Runtime /= Null_Unbounded_String then
            if Comp.Alt_Runtime /= Null_Unbounded_String then
               return Optional_Name_Type
                 (To_String (Comp.Runtime)
                  & " ["
                  & To_String (Comp.Alt_Runtime)
                  & "]");
            else
               return Optional_Name_Type (To_String (Comp.Runtime));
            end if;
         else
            return No_Name;
         end if;
      end if;

      if Comp.Alt_Runtime /= Null_Unbounded_String then
         return Optional_Name_Type (To_String (Comp.Alt_Runtime));
      elsif Comp.Runtime /= Null_Unbounded_String then
         return Optional_Name_Type (To_String (Comp.Runtime));
      else
         return No_Name;
      end if;
   end Runtime;

   ------------------------
   -- Set_Default_Target --
   ------------------------

   procedure Set_Default_Target (New_Target : Name_Type) is
   begin
      Default_Target_Parsed := True;
      Default_Target_Val := To_Unbounded_String (String (New_Target));
   end Set_Default_Target;

   -------------------
   -- Set_Selection --
   -------------------

   procedure Set_Selection
     (Compilers : in out Compiler_Lists.List;
      Cursor    : Compiler_Lists.Cursor;
      Selected  : Boolean)
   is
      procedure Internal (Comp : in out Compiler);

      --------------
      -- Internal --
      --------------

      procedure Internal (Comp : in out Compiler) is
      begin
         Set_Selection (Comp, Selected);
      end Internal;

   begin
      Compiler_Lists.Update_Element (Compilers, Cursor, Internal'Access);
   end Set_Selection;

   -------------------
   -- Set_Selection --
   -------------------

   procedure Set_Selection
     (Comp     : in out Compiler;
      Selected : Boolean) is
   begin
      Comp.Selected := Selected;
   end Set_Selection;

   --------------------------
   -- Substitute_Variables --
   --------------------------

   function Substitute_Variables
     (Str        : String;
      Error_Sloc : Source_Reference.Object;
      Messages   : in out Log.Object) return String
   is
      use Ada.Characters.Handling;

      Str_Len              : constant Natural := Str'Last;
      Pos                  : Natural := Str'First;
      Last                 : Natural := Pos;
      Result               : Unbounded_String;
      Word_Start, Word_End : Natural;
      Tmp                  : Natural;
      Has_Index            : Boolean;

   begin
      while Pos < Str_Len loop
         if Str (Pos) = '$' and then Str (Pos + 1) = '$' then
            Append (Result, Str (Last .. Pos - 1));
            Append (Result, "$");
            Last := Pos + 2;
            Pos  := Last;

         elsif Str (Pos) = '$' then
            if Str (Pos + 1)  = '{' then
               Word_Start := Pos + 2;
               Tmp := Pos + 2;

               while Tmp <= Str_Len and then Str (Tmp) /= '}' loop
                  Tmp := Tmp + 1;
               end loop;

               Tmp := Tmp + 1;
               Word_End := Tmp - 2;

            else
               Word_Start := Pos + 1;
               Tmp := Pos + 1;

               while Tmp <= Str_Len
                 and then (Is_Alphanumeric (Str (Tmp)) or else Str (Tmp) = '_')
               loop
                  Tmp := Tmp + 1;
               end loop;

               Word_End := Tmp - 1;
            end if;

            Append (Result, Str (Last ..  Pos - 1));

            Has_Index := False;

            for W in Word_Start .. Word_End loop
               if Str (W) = '(' then
                  Has_Index := True;

                  if Str (Word_End) /= ')' then
                     Messages.Append
                       (Message.Create
                          (Message.Error,
                           "Missing closing parenthesis in variable name: "
                           & Str (Word_Start .. Word_End),
                           Sloc => Error_Sloc));
                     raise Invalid_KB;

                  else
                     Append
                       (Result,
                        Callback
                          (Var_Name => Str (Word_Start .. W - 1),
                           Index    => Str (W + 1 .. Word_End - 1)));
                  end if;

                  exit;
               end if;
            end loop;

            if not Has_Index then
               Append (Result, Callback (Str (Word_Start .. Word_End), ""));
            end if;

            Last := Tmp;
            Pos  := Last;
         else
            Pos := Pos + 1;
         end if;
      end loop;

      Append (Result, Str (Last .. Str_Len));
      return To_String (Result);
   end Substitute_Variables;

   --------------------------------------------------
   -- Substitute_Variables_In_Compiler_Description --
   --------------------------------------------------

   function Substitute_Variables_In_Compiler_Description
     (Str        : String;
      Comp       : Compiler;
      Error_Sloc : Source_Reference.Object;
      Messages   : in out Log.Object) return String
   is

      function Callback (Var_Name, Index : String) return String;
      --  Wraps Get_Variable_Value for <compiler_description> nodes
      --  and aborts KB parsing in case of improper use of indexed
      --  variables in those nodes.

      --------------
      -- Callback --
      --------------

      function Callback (Var_Name, Index : String) return String is
      begin
         if Index /= "" then
            Messages.Append
              (Message.Create
                 (Message.Error,
                  "Indexed variables only allowed in <configuration> (in "
                  & Var_Name & "(" & Index & ")",
                  Sloc => Error_Sloc));
            raise Invalid_KB;
         end if;

         begin
            return Get_Variable_Value (Comp, Var_Name);
         exception
            when Ex : Invalid_KB =>
               Messages.Append
                 (Message.Create
                    (Message.Error,
                     Ada.Exceptions.Exception_Message (Ex),
                     Sloc => Error_Sloc));
               raise Invalid_KB;
         end;
      end Callback;

      function Do_Substitute is new Substitute_Variables (Callback);

   begin
      return Do_Substitute (Str, Error_Sloc, Messages);
   end Substitute_Variables_In_Compiler_Description;

   -------------------------------------------
   -- Substitute_Variables_In_Configuration --
   -------------------------------------------

   function Substitute_Variables_In_Configuration
     (Self       : Object;
      Str        : String;
      Comps      : Compiler_Lists.List;
      Langs      : Ordered_Languages;
      Error_Sloc : Source_Reference.Object;
      Messages   : in out Log.Object) return String
   is
      function Callback (Var_Name, Index : String) return String;
      --  Wraps Get_Variable_Value for configuration> nodes
      --  and aborts configuration creation in case of improper use of indexed
      --  variables in those nodes.

      --------------
      -- Callback --
      --------------

      function Callback (Var_Name, Index : String) return String is

         function Do_Subst (Lang : Language_Id) return String;
         --  Performs substitution with a given language index

         --------------
         -- Do_Subst --
         --------------

         function Do_Subst (Lang : Language_Id) return String is
         begin
            for Comp of Comps loop
               if Comp.Selected
                 and then Comp.Language = Lang
               then
                  return Get_Variable_Value (Comp, Var_Name);
               end if;
            end loop;

            return "";
         end Do_Subst;

      begin
         if Var_Name = "GPRCONFIG_PREFIX" then
            return GPR_Executable_Prefix_Path;

         elsif Index = "" then

            if Var_Name = "TARGET"
              and then not Comps.Is_Empty
            then
               --  Can have an optional language index.
               --  If there is no index, all compilers share the same target,
               --  so just take that of the first compiler in the list

               return
                 String
                   (Self.Normalized_Target
                      (Name_Type (To_String (Comps.First_Element.Target))));

            else
               Messages.Append
                 (Message.Create
                    (Message.Error,
                     "Ambiguous variable substitution, need to specify the"
                     & " language (in " & Var_Name & ")",
                     Sloc => Error_Sloc));
               raise Invalid_KB;
            end if;

         else
            if Index = "*" then
               for Lang of Langs loop
                  begin
                     return Do_Subst (Lang);
                  exception
                     when Ex : Invalid_KB =>
                        GNATCOLL.Traces.Trace
                          (Main_Trace,
                           Ada.Exceptions.Exception_Message (Ex)
                           & " for language " & Image (Lang));
                  end;
               end loop;

               Messages.Append
                 (Message.Create
                    (Message.Error,
                     "variable '" & Var_Name
                     & "' is not defined for any language",
                     Sloc => Error_Sloc));
               raise Invalid_KB;
            else
               begin
                  return Do_Subst (+Name_Type (Index));
               exception
                  when Ex : Invalid_KB =>
                     Messages.Append
                       (Message.Create
                          (Message.Error,
                           Ada.Exceptions.Exception_Message (Ex),
                           Sloc => Error_Sloc));
                     raise Invalid_KB;
               end;
            end if;
         end if;
      end Callback;

      function Do_Substitute is new Substitute_Variables (Callback);
   begin
      return Do_Substitute (Str, Error_Sloc, Messages);
   end Substitute_Variables_In_Configuration;

   ---------------
   -- To_String --
   ---------------

   function To_String (Comp : Compiler) return String is
      function Get_String_Or_Empty (S : Unbounded_String) return String is
        (if S = Null_Unbounded_String then "" else To_String (S));

   begin
      return String (Name (Comp.Language))
           & ',' & Get_String_Or_Empty (Comp.Version)
           & ',' & Get_String_Or_Empty (Comp.Runtime)
           & ',' & (if Comp.Path.Is_Defined then Comp.Path.Value else "")
           & ',' & Get_String_Or_Empty (Comp.Name);
   end To_String;

   ---------------
   -- To_String --
   ---------------

   function To_String
     (Compilers : Compiler_Lists.List) return String
   is
      use Compiler_Lists;
      Comp   : Compiler_Lists.Cursor := First (Compilers);
      Result : Unbounded_String;
   begin
      while Has_Element (Comp) loop
         if Compiler_Lists.Element (Comp).Selected then
            Append (Result, To_String (Compiler_Lists.Element (Comp)));
            Append (Result, ASCII.LF);
         end if;

         Next (Comp);
      end loop;
      return To_String (Result);
   end To_String;

   ----------------------------------
   -- Update_With_Compiler_Runtime --
   ----------------------------------

   procedure Update_With_Compiler_Runtime
     (Self        : in out Object;
      Comp        : Compiler;
      Environment : GPR2.Environment.Object) is
   begin
      if Comp.Selected
        and then Comp.Runtime_Dir /= Null_Unbounded_String
      then
         declare
            RTS  : constant String := To_String (Comp.Runtime_Dir);
            Last : Natural := RTS'Last;
         begin
            if RTS (Last) = '/' or else
              RTS (Last) = GNAT.OS_Lib.Directory_Separator
            then
               Last := Last - 1;
            end if;

            if Last - RTS'First > 6 and then
              RTS (Last - 5 .. Last) = "adalib" and then
              (RTS (Last - 6) = GNAT.OS_Lib.Directory_Separator or else
                    (RTS (Last - 6) = '/'))
            then
               Last := Last - 6;
            else
               Last := RTS'Last;
            end if;

            if GNAT.OS_Lib.Is_Directory (RTS (RTS'First .. Last)) then
               GNATCOLL.Traces.Trace
                 (Main_Trace,
                  "Parsing runtime-specific KB chunks at "
                  & RTS (RTS'First .. Last));
               Self.Add
                 (Default_Flags,
                  GPR2.Path_Name.Create_Directory
                    (Filename_Type (RTS (RTS'First .. Last))),
                  Environment);
            end if;

         end;
      end if;
   end Update_With_Compiler_Runtime;

end GPR2.KB;