asis_2019.0.0_3ca32fa2/tools/gnattest/gnattest-environment.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
------------------------------------------------------------------------------
--                                                                          --
--                           GNATTEST COMPONENTS                            --
--                                                                          --
--                 G N A T T E S T . E N V I R O N M E N T                  --
--                                                                          --
--                                 B o d y                                  --
--                                                                          --
--                     Copyright (C) 2011-2019, AdaCore                     --
--                                                                          --
-- GNATTEST  is  free  software;  you  can redistribute it and/or modify it --
-- under terms of the  GNU  General Public License as published by the Free --
-- Software  Foundation;  either  version  2, or (at your option) any later --
-- version.  GNATTEST  is  distributed  in the hope that it will be useful, --
-- but  WITHOUT  ANY  WARRANTY;   without  even  the  implied  warranty  of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details.  You should have received a copy of the --
-- GNU  General  Public License distributed with GNAT; see file COPYING. If --
-- not, write to the  Free  Software  Foundation, 51 Franklin Street, Fifth --
-- Floor, Boston, MA 02110-1301, USA.,                                      --
--                                                                          --
-- GNATTEST is maintained by AdaCore (http://www.adacore.com).              --
--                                                                          --
------------------------------------------------------------------------------

pragma Ada_2012;

with Ada.Text_IO;                use Ada.Text_IO;
with Ada.Containers;             use Ada.Containers;

with Asis.Ada_Environments;      use Asis.Ada_Environments;

with Ada.Characters.Handling;    use Ada.Characters.Handling;
with Ada.Strings;                use Ada.Strings;
with Ada.Strings.Fixed;          use Ada.Strings.Fixed;

with Ada.Environment_Variables;  use Ada.Environment_Variables;

with GNAT.OS_Lib;                use GNAT.OS_Lib;
with GNAT.Command_Line;          use GNAT.Command_Line;
with GNAT.Directory_Operations;  use GNAT.Directory_Operations;

with System.Multiprocessors;

with ASIS_UL.Common;
with ASIS_UL.Compiler_Options;   use ASIS_UL.Compiler_Options;
with ASIS_UL.Debug;              use ASIS_UL.Debug;
with ASIS_UL.Output;             use ASIS_UL.Output;
with ASIS_UL.Projects;

with GNATtest.Options;              use GNATtest.Options;
with GNATtest.Common;               use GNATtest.Common;
with GNATtest.Skeleton.Source_Table;    use GNATtest.Skeleton.Source_Table;
with GNATtest.Harness.Source_Table; use GNATtest.Harness.Source_Table;

with GNATCOLL.Projects;          use GNATCOLL.Projects;
with GNATCOLL.Projects.Aux;
with GNATCOLL.VFS;               use GNATCOLL.VFS;
with GNATCOLL.Traces;            use GNATCOLL.Traces;

package body GNATtest.Environment is

   Me : constant Trace_Handle := Create ("Environment", Default => Off);

   Parameter_Error : exception;
   --  Is raised if the initialization is impossible or fails down because of
   --  any reason

   Output_M : Output_Mode := Default_Output_Mode;
   Output_M_Set : Boolean := False;

   Default_Skeletons_Set : Boolean := False;
   Show_Passed_Tests_Set : Boolean := False;
   Add_Exit_Status_Set   : Boolean := False;
   Inheritance_Check_Set : Boolean := False;
   U_Set, R_Set          : Boolean := False;
   Recursiveness_Set     : Boolean := False;

   Run_Dir : String_Access;
   --  Directory from which the tool was called.

   Env   : Project_Environment_Access;

   Root : Project_Type;

   Recursive_Sources : Boolean := True;

   Object_Dir : String_Access;

   Files_List          : String_Access := null;
   Excluded_Files_List : String_Access := null;

   --  Temporary source file name storage. After determining in which mode
   --  the tool works sources are to be transfered to corresponding source
   --  table.

   use List_Of_Strings;

   Source_Buffer  : List_Of_Strings.List;
   Ext_Var_Buffer : List_Of_Strings.List;
   SB_Cur         : List_Of_Strings.Cursor;

   --  Flags for default output dirs being set explicitly.
   Stub_Dir_Set   : Boolean := False;
   Tests_Dir_Set   : Boolean := False;
   Harness_Dir_Set : Boolean := False;

   Closure_Subdirs_To_Clean : List_Of_Strings.List;
   --  With on-the-fly closure computation we switch to object subdirs,
   --  that are in turn created for each project in the project tree.
   --  Although they bring no harm, they may be confusing for the user,
   --  so we store a list of those to clean them up at the end.

   -----------------------
   -- Local subprograms --
   -----------------------

   function Is_Comment (S : String) return Boolean is
     (S'Length >= 2 and then S (S'First .. S'First + 1) = "--");

   procedure Scan_Parameters;
   --  Scans the command-line parameters and sets the metrics to compute and
   --  sources to process.

   procedure Check_Parameters;
   --  Checks that parameter settings are compatible fo generation mode.
   --  Raises Parameter_Error and generates the diagnostic message
   --  if the check fails.

   procedure Check_Aggregation_Parameters;
   --  Checks that parameter settings are compatible for aggregation mode.
   --  Raises Parameter_Error and generates the diagnostic message
   --  if the check fails.

   procedure Create_Temp_Dir (Obj_Dir : String := "");
   --  Creates the temporary directory and stores its name in Temp_Dir.

   procedure Brief_Help;
   --  Prints out the brief help.

   procedure Check_Subdir;
   --  Checks if there are no intersections between target and source dirs. If
   --  so, tries to create all target subdirs.

   procedure Check_Separate_Root;
   --  Checks if there are no intersections between target and source dirs. If
   --  so, tries to create a directori hierarchy similar to one of the tested
   --  sources.

   procedure Check_Direct;
   --  Checks if there are no intersections between target and source dirs. If
   --  so, tries to create target dir.

   procedure Check_Stub;
   --  Checks if there are no intersections between stub and source dirs and
   --  between stub and test dirs.

   procedure Process_Exclusion_Lists;
   --  Process lists of units fo stub exclusion.

   function Is_Externally_Built (File : Virtual_File) return Boolean;
   --  Checks if the given source file belongs to an externally build library.

   function Non_Null_Intersection
     (Left  : File_Array_Access;
      Right : File_Array_Access)
      return Boolean;
   --  Returns True if two file arrays have at least one common file.

   function All_Source_Locations return File_Array_Access;
   --  Returns an array of all directories that may have source files.
   --  In case of project option, returns the list of recursively collected
   --  source dirs, otherwise collects the list from argument source files.

   procedure Get_Naming_Info
     (Source_Project_Tree : GNATCOLL.Projects.Project_Tree);
   --  Gathers all naming info and creates a file with corresponding pragmas.

   procedure Update_Path_With_Project (Dirs : GNATCOLL.VFS.File_Array);
   --  Treats all the source dirs from project as -I option parameters.
   --  Also sets the value of Source_Dirs_Conflict flag.

   procedure Register_Gnattest_Specific_Attributes;

   procedure Get_Gnattest_Specific_Attributes
     (Source_Project_Tree : GNATCOLL.Projects.Project_Tree);

   function Has_Command_Line_Support return Boolean;
   --  Checks whether current run-time library has command line support or not.

   ------------------------------
   -- Update_Path_With_Project --
   ------------------------------

   procedure Update_Path_With_Project (Dirs : GNATCOLL.VFS.File_Array) is
   begin
      for F in Dirs'Range loop
         Store_I_Option (Dirs (F).Display_Full_Name);
      end loop;
   end Update_Path_With_Project;

   --------------------------
   -- All_Source_Locations --
   --------------------------

   function All_Source_Locations return File_Array_Access is
      Source_Dirs : File_Array_Access := new File_Array'(Empty_File_Array);
      Tmp         : String_Access;
   begin
      if Source_Prj.all /= ("") then
         --  If we're here, than the project has been successfully loaded.

         Append
           (Source_Dirs,
            Source_Project_Tree.Root_Project.Source_Dirs (Recursive => True));
      else

         GNATtest.Skeleton.Source_Table.Reset_Location_Iterator;

         loop
            Tmp := new String'(Normalize_Pathname
              (Name           =>
                 GNATtest.Skeleton.Source_Table.Next_Source_Location,
               Case_Sensitive => False));
            exit when Tmp.all = "";

            Append (Source_Dirs, GNATCOLL.VFS.Create (+Tmp.all));
         end loop;

      end if;

      return Source_Dirs;
   end All_Source_Locations;

   ----------------
   -- Brief_Help --
   ----------------

   procedure Brief_Help is
   begin
      Put_Line ("Usage: gnattest -Pprj [opts] {filename} [-cargs switches]");
      Put_Line ("        - generates the unit testing framework");
      New_Line;
      Put_Line ("  or   gnattest test_drivers.list [opts]");
      Put_Line ("        - executes tests and aggregates the results");
      New_Line;

      Put_Line (" --version    Display version and exit");
      Put_Line (" --help       Display usage and exit");
      New_Line;

      Put_Line ("Framework generation mode options:");
      New_Line;
      Put_Line (" -Pprj        Name of the project for which to generate " &
                "the testing framework");
      Put_Line (" {filename}   " &
                "Only generate testing framework for these source files;");
      Put_Line ("              if omitted, consider all project sources");
      New_Line;

      Put_Line (" --strict     "
                & "Return error exit code if there are compilation errors");
      Put_Line (" -q           Quiet mode");
      Put_Line (" -v           Verbose mode");
      Put_Line (" -r           " &
                  "Consider recursively all sources from all projects");
      Put_Line (" -U main      "
                & "Process the closure of units rooted at unit main");
      New_Line;

      Put_Line (" --additional-tests=prj  " &
                "Treat sources from project prj as additional");
      Put_Line ("                         " &
                "manual tests to add to the test suite");
      Put_Line (" --harness-only          " &
                "Treat argument sources as tests to add to the suite");
      New_Line;
      Put_Line (" --separate-drivers[=unit|test]  " &
                  "Generate a separate test driver for each");
      Put_Line ("                                 unit or test, "
                & "unit being the default");
      Put_Line (" --stub                          " &
                  "Generate testing framework that uses stubs");
      New_Line;
      Put_Line (" --exclude-from-stubbing=file      - "
                & "list of sources whose bodies should not");
      Put_Line ("                                     be stubbed");
      Put_Line (" --exclude-from-stubbing:unit=file - "
                & "list of sources whose bodies should not ");
      Put_Line ("                                     be stubbed when"
                & " testing unit");
      New_Line;
      Put_Line (" --harness-dir=dirname   Output dir for test harness");
      Put_Line (" --tests-dir=dirname     Test files are put in dirname");
      Put_Line (" --subdirs=dirname       " &
                "Test files are put in subdirs dirname of source dirs");
      Put_Line (" --tests-root=dirname    " &
                "Test files are put in the same directory hierarchy");
      Put_Line ("                         as sources but rooted at dirname");
      Put_Line (" --stubs-dir=dirname     " &
                "Stub files are put in subdirs of dirname");
      New_Line;

      Put_Line (" --validate-type-extensions      "
                & "Run all tests from all parents to check LSP");
      Put_Line (" --inheritance-check             "
                & "Run inherited tests for descendants");
      Put_Line (" --no-inheritance-check          "
                & "Do not run inherited tests for descendants");
      Put_Line (" --test-case-only                "
                & "Create tests only when Test_Case is specified");
      Put_Line (" --skeleton-default=(pass|fail)  " &
                "Default behavior of unimplemented tests");
      Put_Line (" --passed-tests=(show|hide)      " &
                "Default output of passed tests");
      Put_Line (" --exit-status=(on|off)          " &
                "Default usage of the exit status");
      Put_Line (" --omit-sloc                     " &
                "Don't record subprogram sloc in test package");
      Put_Line (" --no-command-line               " &
                "Don't add command line support to test driver");
      Put_Line ("");
      Put_Line (" --test-duration                 " &
                "Show timing for each test");
      New_Line;
      New_Line;

      Put_Line ("Tests execution mode options:");
      New_Line;
      Put_Line (" --passed-tests=(show|hide)      " &
                "Default output of passed tests");
      Put_Line (" --queues=n, -jn                 " &
                "Run n tests in parallel (default n=1)");
      Put_Line (" --copy-environment=dir          "
                & "copy contents of dir to temp dirs where test");
      Put_Line ("                                 drivers are spawned");
      Put_Line (" --subdirs=dirname               " &
                "look for test drivers in subdirs");
   end Brief_Help;

   ----------------------------------
   -- Check_Aggregation_Parameters --
   ----------------------------------

   procedure Check_Aggregation_Parameters is
      Tmp : String_Access;
   begin

      if Source_Buffer.Is_Empty then
         Report_Err ("test driver list not specified");
         raise Parameter_Error;
      end if;

      if Source_Buffer.Length > Count_Type (1) then
         Report_Std
           ("warning: (gnattest) multiple argument files specified,"
            & " only first is processed");
      end if;

      Arg_File_Name := new String'(Source_Buffer.First_Element);

      if Arg_File_Name.all /= "" then
         if not Is_Regular_File (Arg_File_Name.all) then

            if Is_Regular_File (Arg_File_Name.all & ".list") then
               Tmp := new String'(Arg_File_Name.all & ".list");
               Free (Arg_File_Name);
               Arg_File_Name := Tmp;
               Tmp := null;
            else
               Report_Err ("gnattest: test driver list " &
                           Arg_File_Name.all & " does not exist");
               raise Parameter_Error;
            end if;
         end if;
      else
         Report_Err ("test driver list not specified");
         raise Parameter_Error;
      end if;

      Tmp := new String'(Normalize_Pathname
                         (Name           => Arg_File_Name.all,
                          Case_Sensitive => False));
      Free (Arg_File_Name);
      Arg_File_Name := new String'(Tmp.all);
      Free (Tmp);

      --  Dealing with environment dir to copy
      if Environment_Dir /= null then
         Tmp := new String'(Normalize_Pathname
                            (Name           => Environment_Dir.all,
                             Case_Sensitive => False));
         Free (Environment_Dir);
         Environment_Dir := new String'(Tmp.all);
         Free (Tmp);
         if not Is_Directory (Environment_Dir.all) then
            Report_Err ("gnattest: environment dir "
                        & Environment_Dir.all & " does not exist");
            raise Parameter_Error;
         end if;
      end if;

      Run_Dir := new String'
        (Normalize_Pathname (Name => Get_Current_Dir,
                             Case_Sensitive => False));

      Create_Temp_Dir;
      Change_Dir (Temp_Dir.all);

   end Check_Aggregation_Parameters;

   ----------------------
   -- Check_Parameters --
   ----------------------

   procedure Check_Parameters is

      Tmp : String_Access;

      --  Project support:
      Files : File_Array_Access;
      V_F   : Virtual_File;

      procedure Add_AUnit_Paths;
      --  Creates a dummy project file importing aunit, then trying to load it.
      --  If the attempt fails that means that AUnit is not on default project
      --  path.
      --  Sets Options.No_Comand_Line depending of default value of
      --  AUnit_Shared.Runtime.

      procedure Initialize_Environment;

      procedure Set_Gnattest_Generated_Present
        (Source_Project_Tree : GNATCOLL.Projects.Project_Tree);
      --  Checks if gnattest_generated.ads is already among sources.

      procedure Set_Ext_Values;
      --  Sets values of external variables passed to gnattest by -X options.
      --  Overwrites the value of Options.No_Comand_Line if RUNTIME is among
      --  scenario variables declared in the project or passed to the tool.

      procedure Set_Inherited_Switches
        (Source_Project_Tree : GNATCOLL.Projects.Project_Tree);

      procedure Set_Asis_Mode
        (Source_Project_Tree : GNATCOLL.Projects.Project_Tree);

      procedure Supress_Output (Msg : String);

      ---------------------
      -- Add_AUnit_Paths --
      ---------------------

      procedure Add_AUnit_Paths is
         Output_File : File_Type;
         SPT : GNATCOLL.Projects.Project_Tree;
         Local_Env : Project_Environment_Access;

         Config_Success : Boolean := True;

         procedure Misconfiguration (S : String);
         procedure Misconfiguration (S : String) is
         begin
            if Index (S, "no languages defined for this project") /= 0 then
               Report_Err ("gnattest: configuration error");
               Config_Success := False;
            else
               Report_Err (S);
            end if;
         end Misconfiguration;
      begin
         GNATCOLL.Traces.Parse_Config_File;
         Initialize (Local_Env);

         if RTS_Attribute_Val = null then
            Local_Env.Set_Target_And_Runtime
              (Target.all, GNATtest.Options.RTS_Path.all);
         else
            Local_Env.Set_Target_And_Runtime
              (Target.all, RTS_Attribute_Val.all);
         end if;

         Set_Automatic_Config_File (Local_Env.all);

         Create
           (Output_File,
            Out_File,
            Temp_Dir.all & Directory_Separator & "default.gpr");
         Put_Line (Output_File, "with ""aunit"";");
         Put_Line (Output_File, "project default is");
         Put_Line (Output_File, "end default;");
         Close (Output_File);

         SPT.Load
           (GNATCOLL.VFS.Create
              (+(Temp_Dir.all & Directory_Separator & "default.gpr")),
            Local_Env,
            Errors => Misconfiguration'Unrestricted_Access,
            Report_Missing_Dirs => False);
         if not Config_Success then
            raise Fatal_Error;
         end if;

         Update_Path_With_Project
           (SPT.Root_Project.Source_Dirs (Recursive => True));

         Aux.Delete_All_Temp_Files (SPT.Root_Project);

         SPT.Unload;

      exception
         when GNATCOLL.Projects.Invalid_Project =>
            Report_Err ("gnattest: aunit not installed");
            raise Parameter_Error;

      end Add_AUnit_Paths;

      procedure Set_Ext_Values is
         Var_Name, Var_Val : String_Access;
         GPR_TOOL_Set : Boolean := False;
      begin

         SB_Cur := Ext_Var_Buffer.First;
         loop
            exit when SB_Cur = List_Of_Strings.No_Element;

            declare
               S : constant String := List_Of_Strings.Element (SB_Cur);
               F_Idx : constant Integer := S'First;
               L_Idx : constant Integer := S'Last;
            begin
               for I in S'Range loop
                  if S (I) = '=' then
                     Var_Name := new String'(S (F_Idx .. I - 1));
                     Var_Val  := new String'(S (I + 1 .. L_Idx));
                  end if;
               end loop;

               if Var_Name = null then
                  Report_Std ("-X" & S & " is an illegal option");
                  raise Parameter_Error;
               end if;
            end;

            Env.Change_Environment (Var_Name.all, Var_Val.all);

            if Var_Name.all = "GPR_TOOL" then
               GPR_TOOL_Set := True;
            end if;

            List_Of_Strings.Next (SB_Cur);
            Free (Var_Name);
            Free (Var_Val);
         end loop;

         if not GPR_TOOL_Set
           and then not Ada.Environment_Variables.Exists ("GPR_TOOL")
         then
            Env.Change_Environment ("GPR_TOOL", "gnattest");
         end if;

      end Set_Ext_Values;

      procedure Supress_Output (Msg : String) is
      begin
         if Quiet then
            return;
         end if;

         if Index (Msg, "warning") /= 0
           and then Index (Msg, "directory") /= 0
           and then Index (Msg, "not found") /= 0
         then
            return;
         end if;

         if Index (Msg, "no languages defined for this project") /= 0 then
            return;
         end if;

         Report_Err (Msg);
      end Supress_Output;

      procedure Set_Gnattest_Generated_Present
        (Source_Project_Tree : GNATCOLL.Projects.Project_Tree)
      is
         Files : File_Array_Access;
      begin
         Files :=
           Source_Project_Tree.Root_Project.Source_Files (Recursive => True);

         for F in Files'Range loop
            if not Is_Externally_Built (Files (F)) then

               if Files (F).Display_Base_Name = "gnattest_generated.ads" then
                  Gnattest_Generated_Present := True;
                  exit;
               end if;

            end if;
         end loop;

      end Set_Gnattest_Generated_Present;

      procedure Set_Asis_Mode
        (Source_Project_Tree : GNATCOLL.Projects.Project_Tree)
      is
         Switches : String_List_Access;
         Proj : constant Project_Type := Source_Project_Tree.Root_Project;
      begin
         if Has_Attribute (Proj, Compiler_Default_Switches_Attribute) then
            Switches :=
              Attribute_Value
              (Proj,
               Compiler_Default_Switches_Attribute,
               "ada");
         end if;

         if Switches = null then
            return;
         end if;

         for I in Switches'Range loop
            if
              Switches (I).all = "-gnat95"
            then
               ASIS_UL.Compiler_Options.Store_Option ("-gnat95");
            end if;
            if
              Switches (I).all = "-gnat2005" or else
              Switches (I).all = "-gnat05"
            then
               ASIS_UL.Compiler_Options.Store_Option ("-gnat05");
            end if;
            if
              Switches (I).all = "-gnat12" or else
              Switches (I).all = "-gnat2012"
            then
               ASIS_UL.Compiler_Options.Store_Option ("-gnat12");
            end if;
            if Index (Switches (I).all, "-gnateD") /= 0 then
               ASIS_UL.Compiler_Options.Store_Option (Switches (I).all);
            end if;
         end loop;
      end Set_Asis_Mode;

      procedure Set_Inherited_Switches
        (Source_Project_Tree : GNATCOLL.Projects.Project_Tree)
      is
         Target_Switches : constant String_List :=
           (new String'("-gnatE"),
            new String'("-gnat12"),
            new String'("-gnat2012"));

         Switches : String_List_Access;

         Proj : constant Project_Type := Source_Project_Tree.Root_Project;
      begin
         if Has_Attribute (Proj, Compiler_Default_Switches_Attribute) then
            Switches :=
              Attribute_Value
              (Proj,
               Compiler_Default_Switches_Attribute,
               "ada");
         end if;

         if Switches = null then
            return;
         end if;

         for I in Switches'Range loop
            for J in Target_Switches'Range loop
               if Switches (I).all = Target_Switches (J).all then
                  Inherited_Switches.Append (Switches (I).all);
               end if;
            end loop;
         end loop;
      end Set_Inherited_Switches;

      procedure Initialize_Environment is
         Firts_Idx : constant Natural := ASIS_UL.Common.Tool_Name'First;
         Last_Idx  : constant Natural :=
        Index (ASIS_UL.Common.Tool_Name.all, "-", Ada.Strings.Backward);
      begin
         if Target.all = "" then
            Free (Target);
            Target := new String'
              (ASIS_UL.Common.Tool_Name (Firts_Idx .. Last_Idx - 1));
         end if;

         ASIS_UL.Common.Target := Target;

         Initialize (Env);

         Env.Set_Target_And_Runtime
           (Target.all, GNATtest.Options.RTS_Path.all);

         Set_Automatic_Config_File (Env.all);

      end Initialize_Environment;

   begin

      Register_Gnattest_Specific_Attributes;
      Initialize_Environment;

      Set_Ext_Values;

      declare
         procedure Errors (S : String);
         procedure Errors (S : String) is
         begin
            if Index (S, " not a regular file") /= 0 then
               Report_Err ("gnattest: project file "
                           & Source_Prj.all & " does not exist");
            elsif Index (S, "is illegal for typed string") /= 0 then
               Error (S);
               raise Parameter_Error;
            else
               Report_Err (S);
            end if;
         end Errors;
      begin
         Source_Project_Tree.Load
           (GNATCOLL.VFS.Create (+Source_Prj.all),
            Env,
            Packages_To_Check   =>
               new String_List'(1 => new String'("gnattest")),
            Recompute_View      => False,
            Errors              => Errors'Unrestricted_Access);
      exception
         when Invalid_Project =>
            raise Parameter_Error;
      end;
      Free (Source_Prj);
      Source_Prj := new String'
        (Source_Project_Tree.Root_Project.Project_Path.Display_Full_Name);

      if Is_Aggregate_Project (Source_Project_Tree.Root_Project) then
         Report_Err ("gnattest: aggregate projects are not supported");
         raise Parameter_Error;
      end if;

      Source_Project_Tree.Recompute_View
        (Errors => Supress_Output'Unrestricted_Access);

      if Target.all = "" then
         declare
            Target_From_Project : constant String :=
              Source_Project_Tree.Root_Project.Get_Target
                (Default_To_Host => False);
         begin
            if Target_From_Project /= "" then
               Free (Target);
               Target := new String'(Target_From_Project);
            end if;
         end;
      end if;

      Run_Dir := new String'
        (Normalize_Pathname (Name => Get_Current_Dir,
                             Case_Sensitive => False));
      Create_Temp_Dir
        (Source_Project_Tree.Root_Project.Object_Dir.Display_Full_Name);

      if
        GNATtest.Options.RTS_Path.all /= "" or else
        Attribute_Value
          (Source_Project_Tree.Root_Project, Runtime_Attribute, "ada") /= ""
      then
         if Env.Predefined_Object_Path = Empty_File_Array then
            if GNATtest.Options.RTS_Path.all /= "" then
               Report_Err
                 ("object path not found for runtime " &
                    GNATtest.Options.RTS_Path.all);
            else
               Report_Err
                 ("object path not found for runtime "
                  & Attribute_Value
                    (Source_Project_Tree.Root_Project,
                     Runtime_Attribute,
                     "ada"));
            end if;
            raise Fatal_Error;
         end if;
         declare
            Files : constant GNATCOLL.VFS.File_Array :=
              Env.Predefined_Object_Path;
            Obj_Path : constant String :=
              Files (Files'First).Display_Full_Name;
            Idx : Integer;
         begin
            Idx := Index (Obj_Path, Directory_Separator & "adalib");
            if Idx = 0 then
               Report_Err ("cannot locate runtime at " & Obj_Path);
               raise Fatal_Error;
            else
               ASIS_UL.Compiler_Options.Store_Option
                 ("--RTS="
                  & Obj_Path (Obj_Path'First .. Idx - 1));
               if GNATtest.Options.RTS_Path.all = "" then
                  --  We might as well update it.
                  Free (GNATtest.Options.RTS_Path);
                  GNATtest.Options.RTS_Path := new String'
                    (Obj_Path (Obj_Path'First .. Idx - 1));
                  RTS_Attribute_Val := new String'
                    (Attribute_Value
                       (Source_Project_Tree.Root_Project,
                        Runtime_Attribute,
                        "ada"));
               end if;
            end if;
         end;
      end if;

      Root := Source_Project_Tree.Root_Project;

      Update_Path_With_Project
        (Source_Project_Tree.Root_Project.Source_Dirs (Recursive => True));
      Set_Gnattest_Generated_Present (Source_Project_Tree);

      Get_Gnattest_Specific_Attributes (Source_Project_Tree);

      --  Gather the list of sources to exclude from processing.
      if Excluded_Files_List /= null then
         declare
            F : File_Type;
            S : String_Access;
            F_Path : constant String :=
              Normalize_Pathname
                (Name           => Excluded_Files_List.all,
                 Case_Sensitive => False);
         begin
            if not Is_Regular_File (F_Path) then
               Report_Err ("gnattest: cannot find " & F_Path);
               raise Parameter_Error;
            end if;
            Open (F, In_File, F_Path);
            while not End_Of_File (F) loop
               S := new String'(Get_Line (F));
               if not Is_Comment (S.all) then
                  Excluded_Files.Include (Trim (Base_Name (S.all), Both));
               end if;
               Free (S);
            end loop;
            Close (F);
         end;
      end if;

      --  Processing -files argument
      if Files_List /= null then
         declare
            F : File_Type;
            F_Path : constant String :=
              Normalize_Pathname
                (Name           => Files_List.all,
                 Case_Sensitive => False);
         begin
            if not Is_Regular_File (F_Path) then
               Report_Err ("gnattest: cannot find " & F_Path);
               raise Parameter_Error;
            end if;
            Open (F, In_File, F_Path);
            while not End_Of_File (F) loop
               Source_Buffer.Append (Get_Line (F));
            end loop;
            Close (F);
         end;
      end if;

      if Harness_Only and then U_Set and then not Source_Buffer.Is_Empty then
         Report_Err
           ("options --harness-only and -U <mains> are incompatible");
         raise Parameter_Error;
      end if;

      --  --additional-tests and --harness-only are not yet supported in
      --  --separate-drivers mode.
      --  --stub and --harness-only make no sense at the same time.
      --  --additional-tests is not (yet?) supported in --stub mode.
      if Stub_Mode_ON then
         if Harness_Only then
            Report_Err
              ("options --harness-only and --stub are incompatible");
            raise Parameter_Error;
         end if;
         if Additional_Tests_Prj /= null then
            Report_Err
              ("options --additional-tests and --stub are incompatible");
            raise Parameter_Error;
         end if;

         --  We also need to change default dirs is they have not been
         --  changed explicitly.
         if not Tests_Dir_Set then
            Free (Test_Dir_Name);
            Test_Dir_Name := new String'
              ("gnattest_stub" & Directory_Separator & "tests");
         end if;
         if not Stub_Dir_Set then
            Free (Stub_Dir_Name);
            Stub_Dir_Name := new String'
              ("gnattest_stub" & Directory_Separator & "stubs");
         end if;
         if not Harness_Dir_Set then
            Free (Harness_Dir);
            Harness_Dir := new String'
              ("gnattest_stub" & Directory_Separator & "harness");
         end if;
      end if;
      if Separate_Drivers then
         if Harness_Only then
            Report_Err
              ("options --harness-only and --separate-drivers "
               & "are incompatible");
            raise Parameter_Error;
         end if;
         if Additional_Tests_Prj /= null then
            Report_Err
              ("options --additional-tests and --separate-drivers "
               & "are incompatible");
            raise Parameter_Error;
         end if;
      end if;
      Add_AUnit_Paths;

      --  Checking if argument project has IDE package specified.
      declare
         S : constant Attribute_Pkg_String := Build (Ide_Package, "");
      begin
         if Has_Attribute (Source_Project_Tree.Root_Project, S) then
            IDE_Package_Present := True;
         else
            IDE_Package_Present := False;
         end if;
      end;

      --  Checking if argument project has Make package specified.
      declare
         S : constant Attribute_Pkg_String := Build ("make", "");
      begin
         if Has_Attribute (Source_Project_Tree.Root_Project, S) then
            Make_Package_Present := True;
         else
            Make_Package_Present := False;
         end if;
      end;

      if Stub_Mode_ON then
         GNATtest.Skeleton.Source_Table.Initialize_Project_Table;
      end if;

      Object_Dir := new String'
        (Source_Project_Tree.Root_Project.Object_Dir.Display_Full_Name);

      if Output_M = Separate_Root then
         if Separate_Root_Dir.all = Harness_Dir.all then
            Report_Err
              ("gnattest: harness dir and separate root"
               & " dir should not be the same");
            raise Parameter_Error;
         end if;
      end if;

      No_Command_Line := not Has_Command_Line_Support;

      --  need to check if given file is a source file of argument project
      Files := new File_Array'
        (Source_Project_Tree.Root_Project.Source_Dirs (True));

      SB_Cur := Source_Buffer.First;
      loop

         exit when SB_Cur = List_Of_Strings.No_Element;

         V_F := Locate_Regular_File
           (+(Base_Name (List_Of_Strings.Element (SB_Cur))),
            Files.all);

         if V_F = No_File then
            Report_Err
              (Base_Name (List_Of_Strings.Element (SB_Cur))
               & " is not part of "
               & Base_Name (Source_Prj.all)
               & " or its dependencies");
            raise Parameter_Error;
         elsif not
           Excluded_Files.Contains (List_Of_Strings.Element (SB_Cur))
         then

            --  In case there are different sources with same base name and
            --  one of the hides the other we need to take the proper one.
            V_F := Source_Project_Tree.Create
              (+List_Of_Strings.Element (SB_Cur));

            if Is_Externally_Built (V_F) then

               Report_Err
                 (Base_Name (List_Of_Strings.Element (SB_Cur))
                  & " is part of externally built project "
                  & Project (Source_Project_Tree.Info (V_F)).Name
                  & "; skipping");

            else

               if U_Set then
                  Main_Units.Include (V_F.Display_Full_Name);
               else
                  if Harness_Only then
                     GNATtest.Harness.Source_Table.Add_Source_To_Process
                       (V_F.Display_Full_Name);
                  else
                     GNATtest.Skeleton.Source_Table.Add_Source_To_Process
                       (V_F.Display_Full_Name);
                  end if;

               end if;

            end if;
         else

            Excluded_Files.Exclude (List_Of_Strings.Element (SB_Cur));

         end if;

         List_Of_Strings.Next (SB_Cur);
      end loop;

      Source_Buffer.Clear;

      --  Processing harness dir specification

      if not Is_Absolute_Path (GNATCOLL.VFS.Create (+Harness_Dir.all)) then
         Tmp := new String'(Object_Dir.all & Harness_Dir.all);
         Free (Harness_Dir);
         Harness_Dir := Tmp;
         Tmp := null;
      end if;

      if Is_Regular_File (Harness_Dir.all) then
         Report_Err ("gnattest: cannot create harness directory");
         raise Parameter_Error;
      elsif not Is_Directory (Harness_Dir.all) then

         declare
            Dir : File_Array_Access;
         begin
            Append (Dir, GNATCOLL.VFS.Create (+Harness_Dir.all));
            Create_Dirs (Dir);
         exception
            when Directory_Error =>
               Report_Err ("gnattest: cannot create harness directory");
               raise Parameter_Error;
         end;

      end if;

      Tmp := new String'(Normalize_Pathname
        (Name           => Harness_Dir.all,
         Case_Sensitive => False));
      Free (Harness_Dir);
      Harness_Dir := new String'(Tmp.all & Directory_Separator);
      Free (Tmp);

      Change_Dir (Temp_Dir.all);

      Set_Inherited_Switches (Source_Project_Tree);
      Set_Asis_Mode (Source_Project_Tree);

      if Harness_Only then
         --  Filling up harness source table.

         if GNATtest.Harness.Source_Table.SF_Table_Empty then

            if Source_Prj.all = "" then

               Report_Err ("No input source file set");
               raise Parameter_Error;

            else

               Files :=
                 Source_Project_Tree.Root_Project.Source_Files
                   (Recursive => False);

               --  If Files is still empty, that means that the given
               --  project does not have any source files.
               if Files'Length = 0 then
                  Report_Err
                    (Source_Prj.all & " doesn't contain source files");
                  raise Parameter_Error;
               end if;

               for F in Files'Range loop
                  if
                    not Is_Externally_Built (Files (F))
                    and then not Excluded_Files.Contains
                      (Files (F).Display_Base_Name)
                  then

                     declare
                        F_Info : constant File_Info :=
                          Source_Project_Tree.Info (Files (F));
                     begin
                        if
                          To_Lower (F_Info.Language) = "ada" and then
                          F_Info.Unit_Part = Unit_Spec
                        then
                           GNATtest.Harness.Source_Table.Add_Source_To_Process
                             (Files (F).Display_Full_Name);
                        end if;
                     end;

                  elsif
                    Excluded_Files.Contains (Files (F).Display_Base_Name)
                  then
                     Excluded_Files.Exclude (Files (F).Display_Base_Name);
                  end if;
               end loop;

               --  If SF_Table is still empty, that means that the given
               --  project does not have any testable source files.
               if GNATtest.Harness.Source_Table.SF_Table_Empty then
                  Report_Err
                    (Source_Prj.all &
                     " doesn't contain testable source files");
                  raise Parameter_Error;
               end if;

            end if;

         end if;
      else
         --  Filling up skeletons source table OR mains (if any).
         --  First we need to check if project has any Mains.

         --  need to check if there were argument sources!
         if
           GNATtest.Skeleton.Source_Table.SF_Table_Empty
           and then not U_Set and then not R_Set and then Recursive_Sources
           and then Root.Has_Attribute (Main_Attribute)
           and then Attribute_Value (Root, Main_Attribute) /= null
         then
            declare
               Mains : constant String_List :=
                 Attribute_Value (Root, Main_Attribute).all;

               V_F : Virtual_File;
            begin
               for Main of Mains loop
                  V_F := Source_Project_Tree.Create (+Main.all);
                  Main_Units.Include (V_F.Display_Full_Name);
               end loop;
            end;
         end if;

         if GNATtest.Skeleton.Source_Table.SF_Table_Empty
           and then Main_Units.Is_Empty
         then

            declare
               P : Project_Type := Source_Project_Tree.Root_Project;
            begin
               Files := P.Source_Files
                 (Recursive => Recursive_Sources);
               if not Recursive_Sources then
                  --  We need to add all sources from extended projects.
                  loop
                     P := Extended_Project (P);
                     exit when P = No_Project;

                     Append (Files, P.Source_Files.all);
                  end loop;
               end if;
            end;

            --  If Files is still empty, that means that the given
            --  project does not have any source files.
            if Files'Length = 0 then
               Report_Err
                 (Source_Prj.all & " doesn't contain source files");
               raise Parameter_Error;
            end if;

            for F in Files'Range loop
               if
                 not Is_Externally_Built (Files (F))
                 and then not Excluded_Files.Contains
                   (Files (F).Display_Base_Name)
               then

                  declare
                     F_Info : constant File_Info :=
                       Source_Project_Tree.Info (Files (F));
                  begin
                     if
                       To_Lower (F_Info.Language) = "ada" and then
                       F_Info.Unit_Part = Unit_Spec
                     then
                        GNATtest.Skeleton.Source_Table.Add_Source_To_Process
                          (Files (F).Display_Full_Name);
                     end if;
                  end;

               elsif
                 Excluded_Files.Contains (Files (F).Display_Base_Name)
               then
                  Excluded_Files.Exclude (Files (F).Display_Base_Name);
               end if;
            end loop;

            --  If SF_Table is still empty, that means that the given
            --  project does not have any testable source files.
            if GNATtest.Skeleton.Source_Table.SF_Table_Empty then
               Report_Err
                 (Source_Prj.all &
                    " doesn't contain testable source files");
               raise Parameter_Error;
            end if;

         end if;

         if Stub_Mode_ON or else not Main_Units.Is_Empty then
            Files := Source_Project_Tree.Root_Project.Source_Files
              (Recursive => True);

            for F in Files'Range loop
               if
                 To_Lower
                   (Source_Project_Tree.Info (Files (F)).Language) /= "ada"
                 or else Is_Externally_Built (Files (F))
               then
                  goto Next_File;
               end if;
               case Source_Project_Tree.Info (Files (F)).Unit_Part is
                  when Unit_Body =>
                     declare
                        P : Project_Type :=
                          Source_Project_Tree.Info (Files (F)).Project;
                     begin
                        --  The name of the project here will be used to create
                        --  stub projects. Those extend original projects, so
                        --  is a source belongs to an extended project we need
                        --  the extending on here instead, so that we do not
                        --  end up with different extensions of same project.
                        while Extending_Project (P) /= No_Project loop
                           P := Extending_Project (P);
                        end loop;

                        GNATtest.Skeleton.Source_Table.Add_Body_To_Process
                          (Files (F).Display_Full_Name,
                           P.Name,
                           Source_Project_Tree.Info (Files (F)).Unit_Name);
                     end;
                  when Unit_Spec =>
                     GNATtest.Skeleton.Source_Table.Add_Body_Reference
                       (Files (F).Display_Full_Name);
                  when others =>
                     null;
               end case;
               <<Next_File>>
            end loop;
         end if;

         case Output_M is
            when Subdir =>
               Check_Subdir;
            when Separate_Root =>
               Check_Separate_Root;
            when Direct =>
               Check_Direct;
         end case;

         if Stub_Mode_ON then
            Check_Stub;
            Process_Exclusion_Lists;
         end if;

         if not Main_Units.Is_Empty then
            --  We need to replace the project file with a dummy "extends all"
            --  wrapper.

            declare
               R : constant Project_Type := Source_Project_Tree.Root_Project;
               Dummy_Proj_File_Name : constant String :=
                 Temp_Dir.all & Directory_Separator & "gnattest_closure.gpr";
               Rel_Path : constant String :=
                 +Relative_Path
                 (R.Project_Path, Create (+Temp_Dir.all));
               F : File_Type;
            begin
               Trace
                 (Me,
                  "Creating closure project wrapper " & Dummy_Proj_File_Name);
               Ada.Text_IO.Create
                 (F, Out_File, Dummy_Proj_File_Name);
               Put_Line
                 (F,
                  "project gnattest_closure extends all """
                  & Rel_Path
                  & """ is");
               Put_Line (F, "end gnattest_closure;");
               Close (F);

               GNATCOLL.Projects.Aux.Delete_All_Temp_Files
                 (Source_Project_Tree.Root_Project);
               Source_Project_Tree.Unload;
               Env.Set_Object_Subdir (+Closure_Subdir_Name);
               Source_Project_Tree.Load (Create (+Dummy_Proj_File_Name), Env);

            exception
               when others =>
                  Report_Err ("gnattest: cannot create temp closure project");
                  raise Fatal_Error;
            end;

         end if;
      end if;

      Get_Naming_Info (Source_Project_Tree);

      if Additional_Tests_Prj /= null then

         Change_Dir (Run_Dir.all);
         Tmp := new String'(Normalize_Pathname
           (Name           => Additional_Tests_Prj.all,
            Case_Sensitive => False));
         Free (Additional_Tests_Prj);
         Additional_Tests_Prj := new String'(Tmp.all);
         Free (Tmp);
         Change_Dir (Temp_Dir.all);

         if not Is_Regular_File (Additional_Tests_Prj.all) then
            if Is_Regular_File (Additional_Tests_Prj.all & ".gpr") then
               Tmp := new String'(Additional_Tests_Prj.all & ".gpr");
               Free (Additional_Tests_Prj);
               Additional_Tests_Prj := Tmp;
               Tmp := null;
            else
               Report_Err ("gnattest: project file " &
                           Additional_Tests_Prj.all & " does not exist");
               raise Parameter_Error;
            end if;
         end if;

         declare
            Add_Map : constant String :=
              (Normalize_Pathname
                 (Name           =>
                      Dir_Name (Additional_Tests_Prj.all) & "gnattest_map.xml",
                  Case_Sensitive => False));
         begin
            if Is_Regular_File (Add_Map) then
               Additional_Tests_Map := new String'(Add_Map);
            end if;
         end;

         declare
            SPT : Project_Tree;
         begin
            SPT.Load
              (GNATCOLL.VFS.Create (+Additional_Tests_Prj.all), Env);
            Update_Path_With_Project
              (SPT.Root_Project.Source_Dirs (Recursive => True));

            Set_Gnattest_Generated_Present (SPT);

            Files := SPT.Root_Project.Source_Files
              (Recursive => False);

            for F in Files'Range loop
               if not Is_Externally_Built (Files (F)) then

                  if
                    SPT.Info (Files (F)).Unit_Part =
                      Unit_Spec
                  then
                     GNATtest.Harness.Source_Table.Add_Source_To_Process
                       (Files (F).Display_Full_Name);
                  end if;
               end if;
            end loop;

            GNATCOLL.Projects.Aux.Delete_All_Temp_Files (SPT.Root_Project);
            SPT.Unload;
         end;

      end if;

      if not Harness_Only then
         Store_I_Option (Harness_Dir.all & Directory_Separator & "common");
      end if;

      if Main_Units.Is_Empty then
         Report_Exclusions_Not_Found;
      end if;

      --  Disregard the fact that Process_cargs_Section calls Set_Arg_List and
      --  Process_ADA_PRJ_INCLUDE_FILE already, whithout their explicit call
      --  compiltaion dependancies for sources from imported projects are not
      --  resolved.
      --  Thay cannot be replaced with Process_cargs_Section here.
      Process_ADA_PRJ_INCLUDE_FILE;
      Store_I_Options;
      Set_Arg_List;

      declare
         type Dummy_Project_Type is new ASIS_UL.Projects.Arg_Project_Type
         with null record;
         procedure Print_Tool_Usage (My_Project : Dummy_Project_Type) is null;
         Dummy_Project : Dummy_Project_Type;
      begin
         Set_Tree_Creator (Dummy_Project);
      end;

      if not Main_Units.Is_Empty then
         declare
            VF : GNATCOLL.VFS.Virtual_File;

            Success : Boolean;
         begin
            for Main_Unit of Main_Units loop
               VF := Source_Project_Tree.Create (+Main_Unit);

               case Source_Project_Tree.Info (VF).Unit_Part is
                  when Unit_Spec =>
                     null;

                  when Unit_Body =>
                     Trace (Me, "We need a special tree creation call");
                     Change_Dir
                       (Temp_Dir.all
                        & Directory_Separator & Closure_Subdir_Name);
                     Create_ALI (Main_Unit, Success);
                     if not Success then
                        Report_Err
                          ("gnattest (error): "
                           & "cannot calculate closure");
                        raise Fatal_Error;
                     end if;
                     Change_Dir (Temp_Dir.all);

                  when others =>
                     Report_Err
                       ("gnattest (error): "
                        & "cannot calculate closure for a separate");
               end case;
            end loop;
         end;

         declare
            Iter : Project_Iterator :=
              Start (Source_Project_Tree.Root_Project,
                     Recursive        => True,
                     Direct_Only      => False,
                     Include_Extended => True);

            function Is_Temp_Subdir (VF : Virtual_File) return Boolean is
              (Index (VF.Display_Full_Name, Closure_Subdir_Name) /= 0);
            --  To be sure that we are not deleting anything not temporary.
         begin
            while Current (Iter) /= No_Project loop
               if Is_Temp_Subdir (Current (Iter).Object_Dir) then
                  Closure_Subdirs_To_Clean.Append
                    (Current (Iter).Object_Dir.Display_Full_Name);
               end if;
               if Is_Temp_Subdir (Current (Iter).Executables_Directory) then
                  Closure_Subdirs_To_Clean.Append
                    (Current (Iter).Executables_Directory.Display_Full_Name);
               end if;
               if Is_Temp_Subdir (Current (Iter).Library_Directory) then
                  Closure_Subdirs_To_Clean.Append
                    (Current (Iter).Library_Directory.Display_Full_Name);
               end if;
               Next (Iter);
            end loop;
         end;
         Update_Closure;
      end if;

   end Check_Parameters;

   ------------------
   -- Check_Direct --
   ------------------

   procedure Check_Direct is
      Tmp : String_Access;
      TD_Name : constant Virtual_File :=
        GNATCOLL.VFS.Create (+Test_Dir_Name.all);
      Future_Dirs : File_Array_Access := new File_Array'(Empty_File_Array);
      Harness_Dir_Ar : constant File_Array_Access :=
        new File_Array'(1 => Create (+(Harness_Dir.all)));

      Obj_Dir : String_Access;

      Project  : Project_Type;
      Iterator : Project_Iterator :=
        Start (Source_Project_Tree.Root_Project);
   begin

      if TD_Name.Is_Absolute_Path then
         Append (Future_Dirs, GNATCOLL.VFS.Create (+Test_Dir_Name.all));
      else
         loop
            Project := Current (Iterator);
            exit when Project = No_Project;

            Obj_Dir := new String'(Project.Object_Dir.Display_Full_Name);
            Tmp := new String'(Obj_Dir.all & Test_Dir_Name.all);
            Append (Future_Dirs, GNATCOLL.VFS.Create (+Tmp.all));
            Free (Tmp);
            Free (Obj_Dir);

            Next (Iterator);
         end loop;
      end if;

      if Non_Null_Intersection (Future_Dirs, All_Source_Locations) then
         Report_Err ("gnattest: invalid output directory, cannot mix up " &
                     "tests and sources");
         raise Parameter_Error;
      end if;

      if Non_Null_Intersection (Future_Dirs, Harness_Dir_Ar) then
         Report_Err ("gnattest: invalid output directory, cannot mix up " &
                     "tests and infrastructure");
         raise Parameter_Error;
      end if;

      Set_Direct_Output;
   end Check_Direct;

   ----------------
   -- Check_Stub --
   ----------------

   procedure Check_Stub is
      Tmp : String_Access;
      SD_Name : constant Virtual_File :=
        GNATCOLL.VFS.Create (+Stub_Dir_Name.all);
      Future_Dirs : File_Array_Access := new File_Array'(Empty_File_Array);

      Obj_Dir : String_Access;

      Project  : Project_Type;
      Iterator : Project_Iterator :=
        Start (Source_Project_Tree.Root_Project);
   begin

      --  look for collisions with source dirs
      if SD_Name.Is_Absolute_Path then
         Append (Future_Dirs, GNATCOLL.VFS.Create (+Test_Dir_Name.all));
      else
         loop
            Project := Current (Iterator);
            exit when Project = No_Project;

            Obj_Dir := new String'(Project.Object_Dir.Display_Full_Name);
            Tmp := new String'(Obj_Dir.all & Stub_Dir_Name.all);
            Append (Future_Dirs, GNATCOLL.VFS.Create (+Tmp.all));
            Free (Tmp);
            Free (Obj_Dir);

            Next (Iterator);
         end loop;
      end if;

      if Non_Null_Intersection (Future_Dirs, All_Source_Locations) then
         Report_Err ("gnattest: invalid stub directory, cannot mix up "
                     & "stubs and source files");
         raise Parameter_Error;
      end if;

      Set_Direct_Stub_Output;

      --  Once stub dirs are set we can compare them with test dirs per source.
      Skeleton.Source_Table.Reset_Source_Iterator;
      Tmp := new String'(Skeleton.Source_Table.Next_Source_Name);
      while Tmp.all /= "" loop
         if
           Skeleton.Source_Table.Get_Source_Output_Dir (Tmp.all) =
           Skeleton.Source_Table.Get_Source_Stub_Dir (Tmp.all)
         then
            Report_Err ("gnattest: invalid stub directory, cannot mix up "
                        & "stubs and tests");
            raise Parameter_Error;
         end if;
         Free (Tmp);
         Tmp := new String'(Skeleton.Source_Table.Next_Source_Name);
      end loop;

      Skeleton.Source_Table.Reset_Source_Iterator;
   end Check_Stub;

   -------------------------
   -- Check_Separate_Root --
   -------------------------

   procedure Check_Separate_Root is

      RD_Name : constant Virtual_File :=
        GNATCOLL.VFS.Create (+Separate_Root_Dir.all);

      Tmp, Buff    : String_Access;
      Maximin_Root : String_Access;
      Root_Length  : Integer;

      Future_Dirs : File_Array_Access := new File_Array'(Empty_File_Array);
      --  List of dirs to be generated. The list is checked for intersections
      --  with source dirs before any new directories are created.

      Harness_Dir_Ar : constant File_Array_Access :=
        new File_Array'(1 => Create (+(Harness_Dir.all)));

      Files : File_Array_Access;
      Project  : Project_Type;
      Iterator : Project_Iterator :=
        Start_Reversed (Source_Project_Tree.Root_Project,
               Recursive => Recursive_Sources);

      Ext_Bld : constant Attribute_Pkg_String :=
        Build ("", "externally_built");

      Obj_Dir                 : String_Access;
      Local_Separate_Root_Dir : String_Access;

      function Common_Root (Left : String; Right : String) return String;
      --  Returns the coincident beginning of both paths or an empty string.

      -------------------
      --  Common_Root  --
      -------------------

      function Common_Root (Left : String; Right : String) return String is
         Idxl : Integer := Left'First;
         Idxr : Integer := Right'First;

         Last_Dir_Sep_Index : Integer := Idxl - 1;
         --  We need to check for the following:
         --  ...somepath/dir/
         --  ...somepath/directory/

      begin
         if Left = "" or Right = "" then
            return "";
         end if;

         loop
            if Left (Idxl) = Directory_Separator
              and then Right (Idxr) = Directory_Separator
            then
               Last_Dir_Sep_Index := Idxl;
            end if;

            if Left (Idxl) /= Right (Idxr) then
               return Left (Left'First .. Last_Dir_Sep_Index);
            end if;

            exit when Idxl = Left'Last or Idxr = Right'Last;

            Idxl := Idxl + 1;
            Idxr := Idxr + 1;
         end loop;

         return Left (Left'First .. Idxl);
      end Common_Root;

   begin

      if RD_Name.Is_Absolute_Path then

         GNATtest.Skeleton.Source_Table.Reset_Location_Iterator;
         Tmp := new String'
           (GNATtest.Skeleton.Source_Table.Next_Source_Location);
         Maximin_Root := new String'(Tmp.all);

         loop
            Tmp := new String'
              (GNATtest.Skeleton.Source_Table.Next_Source_Location);
            exit when Tmp.all = "";

            Buff := new String'(Common_Root (Tmp.all, Maximin_Root.all));

            if Buff.all = "" then
               Report_Err ("gnattest: sources have different root dirs, " &
                           "cannot apply separate root output");
               raise Parameter_Error;
            end if;

            Free (Maximin_Root);
            Maximin_Root := new String'(Buff.all);
            Free (Buff);
            Free (Tmp);
         end loop;

         Root_Length := Maximin_Root.all'Length;

         Separate_Root_Dir := new String'
           (Normalize_Pathname (Name => Separate_Root_Dir.all,
                                Case_Sensitive => False));

         GNATtest.Skeleton.Source_Table.Reset_Location_Iterator;

         loop
            Tmp := new String'
              (GNATtest.Skeleton.Source_Table.Next_Source_Location);
            exit when Tmp.all = "";

            Append (Future_Dirs, GNATCOLL.VFS.Create
              (+(Separate_Root_Dir.all & Directory_Separator &
                 Tmp.all (Root_Length + 1 .. Tmp.all'Last))));

            Free (Tmp);
         end loop;

         if Non_Null_Intersection (Future_Dirs, All_Source_Locations) then
            Report_Err ("gnattest: invalid output directory, cannot mix up " &
                        "tests and sources");
            raise Parameter_Error;
         end if;

         if Non_Null_Intersection (Future_Dirs, Harness_Dir_Ar) then
            Report_Err ("gnattest: invalid output directory, cannot mix up " &
                          "tests and infrastructure");
            raise Parameter_Error;
         end if;

         Set_Separate_Root (Maximin_Root.all);
      else

         loop
            Project := Current (Iterator);
            exit when Project = No_Project;

            declare
               Dirs : constant File_Array := Project.Source_Dirs (False);

               Common_Root_Dir : String_Access;
            begin
               if Dirs'Length > 0 then
                  Common_Root_Dir := new String'
                    (Dirs (Dirs'First).Display_Full_Name);

                  for J in Dirs'Range loop
                     Tmp := new String'(Dirs (J).Display_Full_Name);
                     Buff := new String'
                       (Common_Root (Tmp.all, Common_Root_Dir.all));

                     if Buff.all = "" then
                        Report_Err
                          ("gnattest: sources have different root dirs, " &
                             "cannot apply separate root output");
                        raise Parameter_Error;
                     end if;

                     Free (Common_Root_Dir);
                     Common_Root_Dir := new String'(Buff.all);
                     Free (Buff);
                     Free (Tmp);
                  end loop;

                  for J in Dirs'Range loop
                     if Dirs (J).Display_Full_Name = Common_Root_Dir.all then
                        Maximin_Root := Common_Root_Dir;
                        exit;
                     end if;
                  end loop;
               end if;
            end;

            Files := Project.Source_Files;

            if Files'Length > 0 then
               if Maximin_Root = null then
                  Maximin_Root := new String'
                    (Files (Files'First).Display_Dir_Name);
               end if;

               for F in Files'Range loop
                  Tmp := new String'(Files (F).Display_Dir_Name);
                  Buff := new String'(Common_Root (Tmp.all, Maximin_Root.all));

                  if Buff.all = "" then
                     Report_Err
                       ("gnattest: sources have different root dirs, " &
                        "cannot apply separate root output");
                     raise Parameter_Error;
                  end if;

                  Free (Maximin_Root);
                  Maximin_Root := new String'(Buff.all);
                  Free (Buff);
                  Free (Tmp);
               end loop;

               Root_Length := Maximin_Root.all'Length;

               Obj_Dir := new String'(Project.Object_Dir.Display_Full_Name);

               Local_Separate_Root_Dir := new String'
                 (Normalize_Pathname
                    (Name => Obj_Dir.all & Separate_Root_Dir.all,
                     Case_Sensitive => False));

               for F in Files'Range loop

                  if
                    Source_Project_Tree.Info (Files (F)).Unit_Part = Unit_Spec
                  then
                     Tmp := new String'(Files (F).Display_Dir_Name);

                     Append (Future_Dirs, GNATCOLL.VFS.Create
                       (+(Local_Separate_Root_Dir.all & Directory_Separator &
                          Tmp.all (Root_Length + 1 .. Tmp.all'Last))));

                     Set_Output_Dir
                       (Files (F).Display_Full_Name,
                        Local_Separate_Root_Dir.all & Directory_Separator &
                        Tmp.all (Root_Length + 1 .. Tmp.all'Last));
                  end if;

               end loop;

            end if;

            --  Externally built projects should be skipped.
            loop
               Next (Iterator);

               if
                 Current (Iterator) = No_Project
                 or else (not Has_Attribute (Current (Iterator), Ext_Bld))
                 or else
                   To_Lower
                     (Attribute_Value (Current (Iterator), Ext_Bld)) /= "true"
               then
                  exit;
               end if;
            end loop;
         end loop;

         if Non_Null_Intersection (Future_Dirs, All_Source_Locations) then
            Report_Err ("gnattest: invalid output directory, cannot mix up " &
                        "tests and sources");
            raise Parameter_Error;
         end if;

         if Non_Null_Intersection (Future_Dirs, Harness_Dir_Ar) then
            Report_Err ("gnattest: invalid output directory, cannot mix up " &
                          "tests and infrastructure");
            raise Parameter_Error;
         end if;

      end if;

   end Check_Separate_Root;

   ------------------
   -- Check_Subdir --
   ------------------

   procedure Check_Subdir is
      Tmp : String_Access;

      Future_Dirs : File_Array_Access := new File_Array'(Empty_File_Array);
      --  List of dirs to be generated. The list is checked for intersections
      --  with source dirs before any new directories are created.

      Harness_Dir_Ar : constant File_Array_Access :=
        new File_Array'(1 => Create (+(Harness_Dir.all)));
   begin
      GNATtest.Skeleton.Source_Table.Reset_Location_Iterator;

      loop
         Tmp := new String'
           (GNATtest.Skeleton.Source_Table.Next_Source_Location);
         exit when Tmp.all = "";

         Append (Future_Dirs, GNATCOLL.VFS.Create
                 (+(Tmp.all & Directory_Separator & Test_Subdir_Name.all)));
      end loop;

      if Non_Null_Intersection (Future_Dirs, All_Source_Locations) then
         Report_Err ("gnattest: invalid output directory, cannot mix up " &
                     "tests and sources");
         raise Parameter_Error;
      end if;

      if Non_Null_Intersection (Future_Dirs, Harness_Dir_Ar) then
         Report_Err ("gnattest: invalid output directory, cannot mix up " &
                     "tests and infrastructure");
         raise Parameter_Error;
      end if;

      Set_Subdir_Output;
   end Check_Subdir;

   --------------
   -- Clean_Up --
   --------------

   procedure Clean_Up is
   begin
      if GNATtest_Mode = Generation
        and then Source_Project_Tree.Status /= Empty
      then
         GNATCOLL.Projects.Aux.Delete_All_Temp_Files
           (Source_Project_Tree.Root_Project);
         Source_Project_Tree.Unload;
         Free (Env);
      end if;
      Context_Clean_Up;

      --  Cleaning up temporary dir

      if Temp_Dir /= null then
         Change_Dir (Run_Dir.all);

         begin
            Remove_Dir (Temp_Dir.all, Recursive => True);
         exception
            when Directory_Error =>
               Free (Temp_Dir);  -- to avoid cycling
               Report_Err ("gnattest: cannot remove temporary directory");
               raise Fatal_Error;
         end;

         Free (Temp_Dir);
      end if;

      --  Cleaning up closure subdirs (if any)

      if not Closure_Subdirs_To_Clean.Is_Empty then
         declare
            Cur : List_Of_Strings.Cursor := Closure_Subdirs_To_Clean.First;
         begin
            while Cur /= No_Element loop
               if Is_Directory (List_Of_Strings.Element (Cur)) then
                  begin
                     Remove_Dir
                       (List_Of_Strings.Element (Cur), Recursive => True);
                  exception
                     when Directory_Error =>
                        Report_Std
                          ("gnattest (warning): "
                           & "cannot delete temp closure dir "
                           & List_Of_Strings.Element (Cur));
                  end;
               end if;
               Next (Cur);
            end loop;
         end;
      end if;
   end Clean_Up;

   ----------------------
   -- Context_Clean_Up --
   ----------------------

   procedure Context_Clean_Up is
   begin
      if Is_Open (The_Context) then
         Close (The_Context);
      end if;

      if Has_Associations (The_Context) then
         Dissociate (The_Context);
      end if;
   end Context_Clean_Up;

   ---------------------
   -- Create_Temp_Dir --
   ---------------------

   procedure Create_Temp_Dir (Obj_Dir : String := "") is
      FD        : File_Descriptor;
      Temp_Name : Temp_File_Name;
      Success   : Boolean;

      CD : constant String :=
        Normalize_Pathname (Name => Get_Current_Dir,
                            Case_Sensitive => False);
   begin
      --  Here we use exactly the same approach as in gnatelim

      --  ??? We create the temp dir by first creating the temp file, then
      --  closing and deleting it, then creating a dir with the same name.
      --  This is not atomary as another program can sneak in between file
      --  deletion and dir creation and snatch this name for itself. This is
      --  quite unlikely and anyway we don't have any other system-independent
      --  way at the moment
      if Obj_Dir /= "" then
         declare
            F : File_Array_Access;
         begin
            Append (F, Dir (GNATCOLL.VFS.Create (+(Obj_Dir))));
            Create_Dirs (F);
         end;
         Change_Dir (Obj_Dir);
      end if;
      Create_Temp_File (FD, Temp_Name);
      Close (FD);
      Delete_File (Temp_Name, Success);

      if not Success then
         Report_Err ("gnattest: cannot delete the temporary file that was "
                     & "just created");

         raise Fatal_Error;
      end if;

      Make_Dir (Temp_Name);

      Temp_Dir :=
        new String'
          (Obj_Dir & Temp_Name (Temp_Name'First .. Temp_Name'Last - 1));

      Change_Dir (CD);
   exception
      when Directory_Error =>
         Report_Err ("gnattest: cannot create the temporary directory");
         raise Fatal_Error;
   end Create_Temp_Dir;

   --------------------------------------
   -- Get_Gnattest_Specific_Attributes --
   --------------------------------------

   procedure Get_Gnattest_Specific_Attributes
     (Source_Project_Tree : GNATCOLL.Projects.Project_Tree)
   is
      Proj : constant Project_Type := Source_Project_Tree.Root_Project;
      GT_Package : constant String := "gnattest";

   begin

      declare
         Attr : constant Attribute_Pkg_String :=
           Build (GT_Package, "harness_dir");
      begin
         if Attribute_Value (Proj, Attr) /= "" then
            if not Harness_Set_By_Switch then
               Harness_Dir := new String'(Attribute_Value (Proj, Attr));
               Harness_Dir_Set := True;
            end if;
         end if;
      end;

      if not Output_M_Set then

         declare
            Attr1 : constant Attribute_Pkg_String :=
              Build (GT_Package, "subdir");
            Attr2 : constant Attribute_Pkg_String :=
              Build (GT_Package, "tests_root");
            Attr3 : constant Attribute_Pkg_String :=
              Build (GT_Package, "tests_dir");

            Output_Attr_Counter : Natural := 0;
         begin
            if Attribute_Value (Proj, Attr1) /= "" then
               Output_Attr_Counter := Output_Attr_Counter + 1;
            end if;
            if Attribute_Value (Proj, Attr2) /= "" then
               Output_Attr_Counter := Output_Attr_Counter + 1;
            end if;
            if Attribute_Value (Proj, Attr3) /= "" then
               Output_Attr_Counter := Output_Attr_Counter + 1;
            end if;

            if Output_Attr_Counter > 1 then
               Report_Err
                 ("invalid project file: " &
                  "more than one output mode specified");
               raise Fatal_Error;
            end if;
            if Attribute_Value (Proj, Attr1) /= "" then
               Output_M := Subdir;
               Test_Subdir_Name := new String'(Attribute_Value (Proj, Attr1));
               Tests_Dir_Set := True;
            end if;
            if Attribute_Value (Proj, Attr2) /= "" then
               Output_M := Separate_Root;
               Separate_Root_Dir := new String'(Attribute_Value (Proj, Attr2));
               Tests_Dir_Set := True;
            end if;
            if Attribute_Value (Proj, Attr3) /= "" then
               Output_M := Direct;
               Test_Dir_Name := new String'(Attribute_Value (Proj, Attr3));
               Tests_Dir_Set := True;
            end if;
         end;

      end if;

      if Additional_Tests_Prj = null then
         declare
            Attr : constant Attribute_Pkg_String :=
              Build (GT_Package, "additional_tests");
         begin
            if Attribute_Value (Proj, Attr) /= "" then
               Additional_Tests_Prj := new String'
                 (Attribute_Value (Proj, Attr));
            end if;
         end;
      end if;

      if not Default_Skeletons_Set then
         declare
            Attr : constant Attribute_Pkg_String :=
              Build (GT_Package, "skeletons_default");
         begin
            if Attribute_Value (Proj, Attr) /= "" then
               if Attribute_Value (Proj, Attr) = "pass" then
                  Skeletons_Fail := False;
               elsif Attribute_Value (Proj, Attr) = "fail" then
                  Skeletons_Fail := True;
               else
                  Report_Err
                    ("gnattest: skeletons_default " &
                     "should be either fail or pass");
                  raise Parameter_Error;
               end if;
            end if;
         end;
      end if;

      if not Stub_Dir_Set then
         declare
            Attr : constant Attribute_Pkg_String :=
              Build (GT_Package, "stubs_dir");
         begin
            if Attribute_Value (Proj, Attr) /= "" then
               Stub_Dir_Name := new String'(Attribute_Value (Proj, Attr));
               Stub_Dir_Set := True;
            end if;
         end;
      end if;

      declare
         Attr : constant Attribute_Pkg_List :=
           Build (GT_Package, "gnattest_switches");
         GT_Switches : String_List_Access;
      begin
         if Has_Attribute (Proj, Attr) then
            GT_Switches := Attribute_Value (Proj, Attr);
            for I in GT_Switches'Range loop
               if not Recursiveness_Set then
                  if GT_Switches (I).all in "-r" | "-U" then
                     Recursive_Sources := True;
                  end if;
                  if GT_Switches (I).all in "--no-subprojects" then
                     Recursive_Sources := False;
                  end if;
               end if;
               if GT_Switches (I).all = "-q" then
                  Quiet := True;
               end if;
               if GT_Switches (I).all = "--validate-type-extensions" then
                  Substitution_Suite := True;
               end if;
               if GT_Switches (I).all = "--harness-only" then
                  Harness_Only := True;
               end if;
               if GT_Switches (I).all = "-v" then
                  if not Verbose then
                     Verbose := True;
                     Print_Version_Info (2011);
                  end if;
               end if;
               if GT_Switches (I).all = "--omit-sloc" then
                  Omit_Sloc := True;
               end if;
               if GT_Switches (I).all = "--test-duration" then
                  Omit_Sloc := True;
               end if;
               if not Show_Passed_Tests_Set then
                  if GT_Switches (I).all = "--passed-tests=show" then
                     Show_Passed_Tests := True;
                  end if;
                  if GT_Switches (I).all = "--passed-tests=hide" then
                     Show_Passed_Tests := False;
                  end if;
               end if;
               if not Add_Exit_Status_Set then
                  if GT_Switches (I).all = "--exit_status=on" then
                     Add_Exit_Status := True;
                  end if;
                  if GT_Switches (I).all = "--passed-tests=off" then
                     Add_Exit_Status := False;
                  end if;
               end if;
               if not Separate_Drivers_Set_By_Switch then
                  if GT_Switches (I).all = "--separate-drivers" or else
                    GT_Switches (I).all = "--separate-drivers=unit"
                  then
                     Separate_Drivers := True;
                     Driver_Per_Unit := True;
                  end if;
                  if GT_Switches (I).all = "--separate-drivers=test" then
                     Separate_Drivers := False;
                     Driver_Per_Unit := False;
                  end if;
               end if;
               if not Inheritance_Check_Set then
                  if GT_Switches (I).all = "--inheritance-check" then
                     Inheritance_To_Suite := True;
                  end if;
                  if GT_Switches (I).all = "--no-inheritance-check" then
                     Inheritance_To_Suite := False;
                  end if;
               end if;
               if GT_Switches (I).all = "--test-case-only" then
                  Test_Case_Only := True;
               end if;
               if GT_Switches (I).all = "--strict" then
                  Strict_Execution := True;
               end if;
               if
                 Excluded_Files_List = null
                 and then Index (GT_Switches (I).all, "--ignore=") /= 0
               then
                  declare
                     Idx_L : constant Natural := GT_Switches (I).all'Last;
                     Idx   : constant Natural :=
                       Index (GT_Switches (I).all, "=") + 1;
                  begin
                     Excluded_Files_List :=
                       new String'(GT_Switches (I).all (Idx .. Idx_L));
                  end;
               end if;
            end loop;
         end if;
      end;

      if Default_Stub_Exclusion_List_File = null then
         declare
            Attr : constant Attribute_Pkg_String :=
              Build (GT_Package, "default_stub_exclusion_list");
         begin
            if Attribute_Value (Proj, Attr) /= "" then
               Default_Stub_Exclusion_List_File := new String'
                 (Attribute_Value (Proj, Attr));
            end if;
         end;
      end if;

      declare
         Attr    : constant Attribute_Pkg_String :=
           Build (GT_Package, "stub_exclusion_list");
         Indexes : constant String_List          :=
           Attribute_Indexes (Proj, Attr);
      begin
         for I in Indexes'Range loop
            if not Stub_Exclusion_List_Files.Contains (Indexes (I).all) then
               Stub_Exclusion_List_Files.Include
                 (Indexes (I).all,
                  Attribute_Value (Proj, Attr, Indexes (I).all));
            end if;
         end loop;
      end;

   end Get_Gnattest_Specific_Attributes;

   ---------------------
   -- Get_Naming_Info --
   ---------------------

   procedure Get_Naming_Info
     (Source_Project_Tree : GNATCOLL.Projects.Project_Tree)
   is
      Mapping_Name : constant String :=
        GNATCOLL.Projects.Aux.Create_Ada_Mapping_File
          (Source_Project_Tree.Root_Project);
      Config_Name : constant String :=
        GNATCOLL.Projects.Aux.Create_Config_Pragmas_File
          (Source_Project_Tree.Root_Project);
   begin
      Store_Option ("-gnatem=" & Mapping_Name);
      Store_Option ("-gnatec=" & Config_Name);
   end Get_Naming_Info;

   -------------------------
   -- Is_Externally_Built --
   -------------------------
   function Is_Externally_Built (File : Virtual_File) return Boolean is
      F_Info : constant File_Info    := Info (Source_Project_Tree, File);
      Proj   : constant Project_Type := Project (F_Info);
      Attr   : constant Attribute_Pkg_String := Build ("", "externally_built");
   begin
      if Has_Attribute (Proj, Attr) then
         if To_Lower (Attribute_Value (Proj, Attr)) = "true" then
            return True;
         end if;
      end if;
      return False;
   end Is_Externally_Built;

   ----------------
   -- Initialize --
   ----------------

   procedure Initialize is
   begin
      Parse_Config_File;
      Scan_Parameters;

      case GNATtest_Mode is
         when Generation =>
            Check_Parameters;
         when Aggregation =>
            Check_Aggregation_Parameters;
      end case;
   exception
      when Parameter_Error =>
         --  The diagnosis is already generated
         raise Fatal_Error;
      when others =>
         Report_Err ("gnattest: initialization failed");
         --  Exception info will be generated in main driver
         raise;
   end Initialize;

   ---------------------------
   -- Non_Null_Intersection --
   ---------------------------

   function Non_Null_Intersection
     (Left  : File_Array_Access;
      Right : File_Array_Access) return Boolean is
   begin
      for J in Left'Range loop
         declare
            Left_Str : constant String :=
                         Normalize_Pathname
                           (Name => Left.all (J).Display_Full_Name,
                            Case_Sensitive => False);
         begin
            for K in Right'Range loop
               if Left_Str =
                 Normalize_Pathname
                   (Name => Right.all (K).Display_Full_Name,
                    Case_Sensitive => False)
               then
                  Report_Std
                    ("gnattest: source dir "
                     & Left_Str & " is also an output dir");
                  return True;
               end if;
            end loop;
         end;
      end loop;

      return False;
   end Non_Null_Intersection;

   -----------------------------
   -- Process_Exclusion_Lists --
   -----------------------------

   procedure Process_Exclusion_Lists is
      F : File_Type;
      S : String_Access;

      use String_To_String_Map;
      Cur : String_To_String_Map.Cursor := Stub_Exclusion_List_Files.First;
   begin
      Change_Dir (Run_Dir.all);
      if Default_Stub_Exclusion_List_File /= null then
         declare
            F_Path : constant String :=
              Normalize_Pathname
                (Name           => Default_Stub_Exclusion_List_File.all,
                 Case_Sensitive => False);
         begin
            if not Is_Regular_File (F_Path) then
               Report_Err ("gnattest: cannot find " & F_Path);
               raise Parameter_Error;
            end if;
            Open (F, In_File, F_Path);
            while not End_Of_File (F) loop
               S := new String'(Get_Line (F));
               if not Is_Comment (S.all) then
                  Store_Default_Excluded_Stub (S.all);
               end if;
               Free (S);
            end loop;
            Close (F);
         end;
      end if;

      while Cur /= String_To_String_Map.No_Element loop
         declare
            Unit : constant String := Key (Cur);
            F_Path : constant String :=
              Normalize_Pathname
                (Name           => Element (Cur),
                 Case_Sensitive => False);
         begin
            if not Is_Regular_File (F_Path) then
               Report_Err ("gnattest: cannot find " & F_Path);
               raise Parameter_Error;
            end if;
            Open (F, In_File, F_Path);
            while not End_Of_File (F) loop
               S := new String'(Get_Line (F));
               if not Is_Comment (S.all) then
                  Store_Excluded_Stub (Unit, S.all);
               end if;
               Free (S);
            end loop;
            Close (F);
         end;

         Next (Cur);
      end loop;

      Change_Dir (Temp_Dir.all);
   end Process_Exclusion_Lists;

   -------------------------------------------
   -- Register_Gnattest_Specific_Attributes --
   -------------------------------------------

   procedure Register_Gnattest_Specific_Attributes is
      Dummy : String_Access;
   begin
      Dummy := new String'
        (Register_New_Attribute
           (Name => "harness_dir",
            Pkg  => "gnattest"));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

      Dummy := new String'
        (Register_New_Attribute
           (Name => "subdir",
            Pkg  => "gnattest"));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

      Dummy := new String'
        (Register_New_Attribute
           (Name => "tests_root",
            Pkg  => "gnattest"));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

      Dummy := new String'
        (Register_New_Attribute
           (Name => "tests_dir",
            Pkg  => "gnattest"));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

      Dummy := new String'
        (Register_New_Attribute
           (Name => "additional_tests",
            Pkg  => "gnattest"));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

      Dummy := new String'
        (Register_New_Attribute
           (Name => "skeletons_default",
            Pkg  => "gnattest"));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

      Dummy := new String'
        (Register_New_Attribute
           (Name => "gnattest_switches",
            Pkg  => "gnattest",
            Is_List => True));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

      Dummy := new String'
        (Register_New_Attribute
           (Name => "default_stub_exclusion_list",
            Pkg  => "gnattest"));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

      Dummy := new String'
        (Register_New_Attribute
           (Name    => "stub_exclusion_list",
            Pkg     => "gnattest",
            Indexed => True));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

      Dummy := new String'
        (Register_New_Attribute
           (Name    => "stubs_dir",
            Pkg     => "gnattest"));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

      --  Not really a gnattest specific attribute, but we still need to
      --  inherit makefile attribute in test driver.
      Dummy := new String'
        (Register_New_Attribute
           (Name => "makefile",
            Pkg  => "make"));
      if Dummy.all /= "" then
         Report_Err ("gnattest: cannot parse project file");
         Report_Err (Dummy.all);
         raise Fatal_Error;
      end if;
      Free (Dummy);

   end Register_Gnattest_Specific_Attributes;

   ---------------------
   -- Scan_Parameters --
   ---------------------

   procedure Scan_Parameters is
      Multiple_Output : Boolean := False;

      Possible_Switches : constant String :=
        "h d? P: q -tests-root= "
        & "-help -version "
        & "-separates "
        & "-no-separates "
        & "-transition "
        & "-subdir= -subdirs= r v X? U "
        & "-harness-only "
        & "-stub "
        & "-separate-drivers? "
        & "-skeleton-default= "
        & "-passed-tests= "
        & "-exit-status= "
        & "-omit-sloc "
        & "-test-duration "
        & "-validate-type-extensions "
        & "-inheritance-check "
        & "-no-inheritance-check "
        & "-additional-tests= "
        & "-harness-dir= "
        & "-tests-dir= "
        & "-stubs-dir= "
        & "-queues= j? "
        & "-RTS= -target= "
        & "-no-command-line "
        & "-exclude-from-stubbing? "
        & "files= "
        & "-ignore= "
        & "-reporter= "
        & "-test-case-only "
        & "-strict "
        & "-copy-environment= "
        & "-no-subprojects";

      Ignore_Arg : String_Access := new String'("");

      function Get_GNATtest_Mode return GNATtest_Modes;

      procedure Report_Switch (S : String; Expected_Mode : GNATtest_Modes);

      procedure Report_Multiple_Output (Second_Output_Mode : Output_Mode);

      procedure Process_Stub_Exclusion (S : String);

      function Get_GNATtest_Mode return GNATtest_Modes is
         Anything    : Boolean := False;
         Opt_Counter : Natural := 0;
         V_Set       : Boolean := False;
      begin
         Initialize_Option_Scan
           (Stop_At_First_Non_Switch => False,
            Section_Delimiters       => "cargs");

         loop
            case GNAT.Command_Line.Getopt (Possible_Switches) is
               when ASCII.NUL =>
                  exit;
               when 'P' =>
                  return Generation;
               when 'v' =>
                  Anything := True;
                  V_Set := True;
               when others =>
                  Opt_Counter := Opt_Counter + 1;
                  Anything := True;
            end case;
         end loop;

         Free (Ignore_Arg);
         Ignore_Arg := new String'(Get_Argument);

         if not Anything and then Ignore_Arg.all = "" then
            Brief_Help;
            raise Parameter_Error;
         end if;

         if File_Extension (Ignore_Arg.all) = ".gpr" then
            Source_Prj := new String'(Ignore_Arg.all);
            return Generation;
         end if;

         if File_Extension (Ignore_Arg.all) in ".adb" | ".ads" then
            Report_Err
              ("gnattest: project file not specified");
            raise Parameter_Error;
         end if;

         if V_Set and then Ignore_Arg.all = "" and then Opt_Counter = 0 then
            Print_Version_Info (2011);
            OS_Exit (0);
         end if;
         return Aggregation;
      end Get_GNATtest_Mode;

      procedure Process_Stub_Exclusion (S : String) is
         Idx : Natural;
         Valid_Format : constant Boolean :=
           S'Length > 1 and then
           ((S (S'First) = '=') or else
              (S (S'First) = ':' and then Index (S, "=") > S'First + 1));
      begin
         if not Valid_Format then
            Report_Err
              ("wrong parameter for --exclude-from-stubbing: " & S);
            raise Parameter_Error;
         end if;
         if S (S'First) = '=' then
            Default_Stub_Exclusion_List_File := new String'
              (S (S'First + 1 .. S'Last));
         elsif S (S'First) = ':' then
            Idx := Index (S, "=");
            Stub_Exclusion_List_Files.Include
              (S (S'First + 1 .. Idx - 1),  S (Idx + 1 .. S'Last));
         else
            Report_Err
              ("wrong parameter for --exclude-from-stubbing: " & S);
            raise Parameter_Error;
         end if;
      end Process_Stub_Exclusion;

      procedure Report_Switch (S : String; Expected_Mode : GNATtest_Modes) is
      begin
         if Expected_Mode /= GNATtest_Mode then
            case GNATtest_Mode is
               when Generation =>
                  Report_Std
                    ("warning: (gnattest) -"
                     & S
                     & " switch is not relevant in generation mode");
               when Aggregation =>
                  Report_Std
                    ("warning: (gnattest) -"
                     & S
                     & " switch is not relevant in aggregation mode");
            end case;
         end if;
      end Report_Switch;

      procedure Report_Multiple_Output (Second_Output_Mode : Output_Mode) is
         function Mode_Image (M : Output_Mode) return String is
           (case M is
               when Separate_Root => "--tests-root",
               when Subdir        => "--subdir",
               when Direct        => "--tests-dir");
      begin
         Report_Err ("gnattest: multiple output modes are not allowed");
         if Second_Output_Mode = Output_M then
            Report_Err
              ("gnattest: option "
               & Mode_Image (Output_M)
               & " specified more than once");
         else
            Report_Err
              ("gnattest: options "
               & Mode_Image (Output_M)
               & " and "
               & Mode_Image (Second_Output_Mode)
               & " are mutually exclusive");
         end if;
      end Report_Multiple_Output;

   begin
      GNATtest_Mode := Get_GNATtest_Mode;

      Initialize_Option_Scan
        (Stop_At_First_Non_Switch => False,
         Section_Delimiters       => "cargs");

      loop
         case GNAT.Command_Line.Getopt (Possible_Switches) is
            when ASCII.NUL =>
               exit;

            when 'U' =>
               Recursive_Sources := True;
               U_Set := True;
               Recursiveness_Set := True;
               Report_Switch (Full_Switch, Generation);

            when 'd' =>
               if Full_Switch = "d" then
                  Set_Debug_Options (Parameter);
               end if;

            when 'f' =>
               if Full_Switch = "files" then
                  Files_List := new String'(Parameter);
                  Report_Switch (Full_Switch, Generation);
               end if;

            when 'j' =>
               declare
                  N : Natural;
               begin
                  N := Positive'Value (Parameter);
                  if N = 0 then
                     Queues_Number :=
                       Positive (System.Multiprocessors.Number_Of_CPUs);
                  else
                     Queues_Number := N;
                  end if;
               exception
                  when Constraint_Error =>
                     Report_Err
                       ("wrong parameter for -j, "
                        & "should be a natural number");
                     raise Parameter_Error;
               end;
               Report_Switch (Full_Switch, Aggregation);

            when 'P' =>
               Source_Prj := new String'(Parameter);

            when 'q' =>
               Quiet := True;

            when 'v' =>
               Verbose := True;

               Print_Version_Info (2011);

            when 'r' =>
               Recursive_Sources := True;
               Report_Switch (Full_Switch, Generation);
               Recursiveness_Set := True;
               R_Set := True;

            when '-' =>
               if Full_Switch = "-additional-tests" then
                  Additional_Tests_Prj := new String'(Parameter);
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-passed-tests" then
                  if Parameter = "hide" then
                     Show_Passed_Tests := False;
                     Show_Passed_Tests_Set := True;
                  elsif Parameter = "show" then
                     Show_Passed_Tests := True;
                     Show_Passed_Tests_Set := True;
                  else
                     Report_Err
                       ("gnattest: --passed-tests " &
                        "should be either show or hide");
                     raise Parameter_Error;
                  end if;
               end if;

               if Full_Switch = "-skeleton-default" then
                  if Parameter = "pass" then
                     Skeletons_Fail := False;
                     Default_Skeletons_Set := True;
                  elsif Parameter = "fail" then
                     Skeletons_Fail := True;
                     Default_Skeletons_Set := True;
                  else
                     Report_Err
                       ("gnattest: --skeleton-default " &
                        "should be either fail or pass");
                     raise Parameter_Error;
                  end if;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-exit-status" then
                  if Parameter = "on" then
                     Add_Exit_Status := True;
                     Add_Exit_Status_Set := True;
                  elsif Parameter = "off" then
                     Add_Exit_Status := True;
                     Add_Exit_Status_Set := True;
                  else
                     Report_Err
                       ("gnattest: --exit-code " &
                        "should be either on or off");
                     raise Parameter_Error;
                  end if;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-tests-root" then
                  if not Multiple_Output then
                     Output_M := Separate_Root;
                     Output_M_Set := True;
                     Separate_Root_Dir := new String'(Parameter);
                     Multiple_Output := True;
                  else
                     Report_Multiple_Output (Separate_Root);
                     raise Parameter_Error;
                  end if;
                  Report_Switch (Full_Switch, Generation);
                  Tests_Dir_Set := True;
               end if;

               if Full_Switch in "-subdir" | "-subdirs" then

                  if GNATtest_Mode = Generation then
                     if not Multiple_Output then
                        Output_M := Subdir;
                        Output_M_Set := True;
                        Test_Subdir_Name := new String'(Parameter);
                        Multiple_Output := True;
                     else
                        Report_Multiple_Output (Subdir);
                        raise Parameter_Error;
                     end if;
                     Tests_Dir_Set := True;
                  else
                     Free (Aggregate_Subdir_Name);
                     Aggregate_Subdir_Name := new String'(Parameter);
                  end if;
               end if;

               if Full_Switch = "-tests-dir" then

                  if not Multiple_Output then
                     Output_M := Direct;
                     Output_M_Set := True;
                     Test_Dir_Name := new String'(Parameter);
                     Multiple_Output := True;
                  else
                     Report_Multiple_Output (Direct);
                     raise Parameter_Error;
                  end if;
                  Report_Switch (Full_Switch, Generation);
                  Tests_Dir_Set := True;
               end if;

               if Full_Switch = "-stubs-dir" then
                  Stub_Dir_Name := new String'(Parameter);
                  Report_Switch (Full_Switch, Generation);
                  Stub_Dir_Set := True;
               end if;

               if Full_Switch = "-validate-type-extensions" then
                  Substitution_Suite := True;
                  Report_Switch (Full_Switch, Generation);
                  if Stub_Mode_ON then
                     Report_Std
                       ("warning: --validate-type-extensions has no effect "
                        & "in --stub mode");
                  end if;
               end if;

               if Full_Switch = "-inheritance-check" then
                  Inheritance_To_Suite := True;
                  Inheritance_Check_Set := True;
                  Report_Switch (Full_Switch, Generation);
                  if Stub_Mode_ON then
                     Report_Std
                       ("warning: --inheritance-check has no effect "
                        & "in --stub mode");
                  end if;
               end if;

               if Full_Switch = "-no-inheritance-check" then
                  Inheritance_To_Suite := False;
                  Inheritance_Check_Set := True;
                  Report_Switch (Full_Switch, Generation);
                  if Stub_Mode_ON then
                     Report_Std
                       ("warning: --no-inheritance-check has no effect "
                        & "in --stub mode");
                  end if;
               end if;

               if Full_Switch = "-omit-sloc" then
                  Omit_Sloc := True;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-test-duration" then
                  Show_Test_Duration := True;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-harness-dir" then
                  Harness_Dir := new String'(Parameter);
                  Harness_Set_By_Switch := True;
                  Report_Switch (Full_Switch, Generation);
                  Harness_Dir_Set := True;
               end if;

               if Full_Switch = "-harness-only" then
                  Harness_Only := True;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-separates" then
                  Generate_Separates := True;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-no-separates" then
                  Generate_Separates := False;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-transition" then
                  Transition := True;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-stub" then
                  Stub_Mode_ON := True;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-separate-drivers" then
                  Separate_Drivers_Set_By_Switch := True;
                  declare
                     S : constant String := Parameter;
                  begin
                     Separate_Drivers := True;
                     if S = "" or else S = "=unit" then
                        Driver_Per_Unit := True;
                     elsif S = "=test" then
                        Driver_Per_Unit := False;
                     else
                        Report_Err
                          ("wrong parameter for --separate-drivers");
                        raise Parameter_Error;
                     end if;
                  end;

                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-version" then
                  Print_Tool_Version (2011);
                  OS_Exit (0);
               end if;

               if Full_Switch = "-help" then
                  Brief_Help;
                  raise Parameter_Error;
               end if;

               if Full_Switch = "-queues" then
                  declare
                     N : constant Natural := Positive'Value (Parameter);
                  begin
                     if N = 0 then
                        Queues_Number :=
                          Positive (System.Multiprocessors.Number_Of_CPUs);
                     else
                        Queues_Number := N;
                     end if;
                  exception
                     when Constraint_Error =>
                        Report_Err
                          ("wrong parameter for --queues, "
                           & "should be a natural number");
                        raise Parameter_Error;
                  end;
                  Report_Switch (Full_Switch, Aggregation);
               end if;

               if Full_Switch = "-RTS" then
                  Free (GNATtest.Options.RTS_Path);
                  GNATtest.Options.RTS_Path := new String'(Parameter);
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-target" then
                  Free (GNATtest.Options.Target);
                  GNATtest.Options.Target := new String'(Parameter);
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-no-command-line" then
                  No_Command_Line_Externally_Set := True;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-test-case-only" then
                  Test_Case_Only := True;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-exclude-from-stubbing" then
                  Process_Stub_Exclusion (Parameter);
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-ignore" then
                  Excluded_Files_List := new String'(Parameter);
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-reporter" then
                  Free (Reporter_Name);
                  Reporter_Name := new String'(Parameter);
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-strict" then
                  Strict_Execution := True;
                  Report_Switch (Full_Switch, Generation);
               end if;

               if Full_Switch = "-copy-environment" then
                  Environment_Dir := new String'(Parameter);
                  Report_Switch (Full_Switch, Aggregation);
               end if;

               if Full_Switch = "-no-subprojects" then
                  Recursive_Sources := False;
                  Report_Switch (Full_Switch, Generation);
                  Recursiveness_Set := False;
               end if;

            when 'X' =>
               Ext_Var_Buffer.Append (Parameter);

            when others =>
               raise Parameter_Error;
         end case;
      end loop;

      loop
         declare
            Temp : constant String := Get_Argument;
         begin
            if Temp = "" then
               exit;
            end if;
            if Temp /= Ignore_Arg.all or else GNATtest_Mode = Aggregation then
               Source_Buffer.Append (Temp);
            end if;
         end;
      end loop;

      Process_cargs_Section;

   exception
      when GNAT.Command_Line.Invalid_Switch =>
         Report_Err ("gnattest: invalid switch : " & Full_Switch);
         Report_Err ("Try `gnattest --help` for more information.");

         raise Parameter_Error;

      when GNAT.Command_Line.Invalid_Parameter =>
         Report_Err ("gnattest: missing parameter for: -" & Full_Switch);
         Report_Err ("Try `gnattest --help` for more information.");

         raise Parameter_Error;
   end Scan_Parameters;

   ------------------------------
   -- Has_Command_Line_Support --
   ------------------------------

   function Has_Command_Line_Support return Boolean is
      Files : constant GNATCOLL.VFS.File_Array :=
        Predefined_Source_Files (Env);
   begin
      if No_Command_Line_Externally_Set then
         return False;
      end if;
      for I in Files'Range loop
         if Files (I).Display_Base_Name = "a-comlin.ads" then
            return True;
         end if;
      end loop;
      return False;
   end Has_Command_Line_Support;

end GNATtest.Environment;