quake /quake3/trunk/code/unix/cons

Language Perl Lines 6829
MD5 Hash df595a1e2f7398f2271e10cde70603d4 Estimated Cost $75,111 (why?)
Repository https://quake.svn.sourceforge.net/svnroot/quake View Raw File
   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
#!/usr/bin/env perl

# NOTE:  Cons intentionally does not use the "perl -w" option or
# "use strict."  Because Cons "configuration files" are actually
# Perl scripts, enabling those restrictions here would force them
# on every user's config files, wanted or not.  Would users write
# "better" Construct and Conscript files if we forced "use strict"
# on them?  Probably.  But we want people to use Cons to get work
# done, not force everyone to become a Perl guru to use it, so we
# don't insist.
#
# That said, Cons' code is both "perl -w" and "use strict" clean.
# Regression tests keep the code honest by checking for warnings
# and "use strict" failures.

use vars qw( $CVS_id $CVS_ver $ver_num $ver_rev $version );

$CVS_id = 'Id';
$CVS_ver = (split(/\s+/, $CVS_id))[2];

$ver_num = "2.3";
$ver_rev = ".1";

$version = "This is Cons $ver_num$ver_rev ($CVS_id)\n";

# Cons: A Software Construction Tool.
# Copyright (c) 1996-2001 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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
# along with this program; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

require 5.003;
# See the NOTE above about why Cons doesn't "use strict".
use integer;
use Cwd;
use File::Copy;

use vars qw( $_WIN32 $_a $_exe $_o $_so );

#------------------------------------------------------------------
# Determine if running on win32 platform - either Windows NT or 95
#------------------------------------------------------------------

use vars qw( $PATH_SEPARATOR $iswin32 $_WIN32 $usage $indent @targets );

BEGIN {
    use Config;

    # if the version is 5.003, we can check $^O
    if ($] <  5.003) {
	eval("require Win32");
	$_WIN32 = (!$@);
    } else {
	$_WIN32 = ($^O eq "MSWin32") ? 1 : 0;
    }

    # Fetch the PATH separator from Config;
    # provide our old defaults in case it's not set.
    $PATH_SEPARATOR = $Config{path_sep};
    $PATH_SEPARATOR = $_WIN32 ? ';' : ':' if ! defined $PATH_SEPARATOR;

    # Fetch file suffixes from Config,
    # accomodating differences in the Config variables
    # used by different Perl versions.
    $_exe = $Config{_exe};
    $_exe = $Config{exe_ext} if ! defined $_exe;
    $_exe = $_WIN32 ? '.exe' : '' if ! defined $_exe;
    $_o = $Config{_o};
    $_o = $Config{obj_ext}  if ! defined $_o;
    $_o = $_WIN32 ? '.obj' : '.o' if ! defined $_o;
    $_a = $Config{_a};
    $_a = $Config{lib_ext} if ! defined $_a;
    $_a = $_WIN32 ? '.lib' : '.a' if ! defined $_a;
    $_so = ".$Config{so}";
    $_so = $_WIN32 ? '.dll' : '.so' if ! defined $_so;
}

# Flush stdout each time.
$| = 1;

# Seed random number generator.
srand(time . $$); # this works better than time ^ $$ in perlfunc manpage.

$usage = q(
Usage: cons <arguments> -- <construct-args>

Arguments can be any of the following, in any order:

  <targets>	Build the specified targets. If <target> is a directory
		recursively build everything within that directory.

  +<pattern>	Limit the cons scripts considered to just those that
		match <pattern>. Multiple + arguments are accepted.

  <name>=<val>	Sets <name> to value <val> in the ARG hash passed to the
		top-level Construct file.

  -cc           Show command that would have been executed, when
		retrieving from cache. No indication that the file
		has been retrieved is given; this is useful for
		generating build logs that can be compared with
		real build logs.

  -cd           Disable all caching. Do not retrieve from cache nor
		flush to cache.

  -cr           Build dependencies in random order. This is useful when
		building multiple similar trees with caching enabled.

  -cs           Synchronize existing build targets that are found to be
		up-to-date with cache. This is useful if caching has
		been disabled with -cc or just recently enabled with
		UseCache.

  -d            Enable dependency debugging.

  -f <file>	Use the specified file instead of "Construct" (but first
		change to containing directory of <file>).

  -h            Show a help message local to the current build if
		one such is defined,  and exit.

  -k		Keep going as far as possible after errors.

  -o <file>	Read override file <file>.

  -p		Show construction products in specified trees.
  -pa		Show construction products and associated actions.
  -pw		Show products and where they are defined.

  -q		Be quiet; multiple -q flags increase quietness level:
		1: quiet about Installing and Removing targets
		2: quiet about build commands, up-to-date targets

  -r		Remove construction products associated with <targets>

  -R <repos>	Search for files in <repos>.  Multiple -R <repos>
		directories are searched in the order specified.

  -S <pkg>	Use package sig::<pkg> to calculate file signatures.
		Currently supported values are "md5" for MD5
		signatures (the default) and "md5::debug" for MD5
		signature debug information.

  -t            Traverse up the directory hierarchy looking for a
		Construct file, if none exists in the current directory.
		(Targets will be modified to be relative to the
		Construct file.)

  -v		Show cons version and continue processing.
  -V            Show cons version and exit.

  -wf <file>    Write all filenames considered into <file>.

  -x		Show this message and exit.


   Please report any suggestions through the cons-discuss@gnu.org mailing
   list.

   To subscribe, send mail to cons-discuss-request@gnu.org with body
   'subscribe'.

   If you find a bug, please report it through the bug-cons@gnu.org
   mailing list.

   Information about CONS can be obtained from the official cons web site
   http://www.dsmit.com/cons/ or its mirrors (listed there).

   The cons maintainers can be contacted by email at cons-maintainers@gnu.org

   User documentation of cons is contained in cons and can be obtained
   by doing 'perldoc /path/to/cons'.

);

# Simplify program name, if it is a path.
{
    my ($vol, $dir, $file) = File::Spec->splitpath(File::Spec->canonpath($0));
    $0 = $file;
}

# Default parameters.
$param::topfile = 'Construct';	# Top-level construction file.
$param::install = 1;		# Show installations
$param::build = 1;		# Build targets
### $param::show = 1;		# Show building of targets.
$param::sigpro = 'md5';		# Signature protocol.
$param::depfile = '';		# Write all deps out to this file
$param::salt = '';		# Salt derived file signatures with this.
$param::sourcesig = ['*' => 'content'];# Source file signature calculation
$param::rep_sig_times_ok = 1;	# Repository .consign times are in sync
				#   w/files.
$param::conscript_chdir = 0;	# Change dir to Conscript directory
$param::quiet = 0;		# should we show the command being executed.

@param::defaults = ();

#
$indent = '';

# Display a command while executing or otherwise. This
# should be called by command builder action methods.
sub showcom {
    print($indent . $_[0] . "\n") if ($param::quiet < 2);
}

# Default environment.
# This contains only the completely platform-independent information
# we can figure out.  Platform-specific information (UNIX, Win32)
# gets added below.
@param::base = (
     'SIGNATURE'    => [ '*' => 'build' ],
     'SUFEXE'	    => $_exe,				# '' on UNIX systems
     'SUFLIB'	    => $_a,				# '.a' on UNIX systems
     'SUFLIBS'      => "$_so:$_a",			# '.so:.a' on UNIX
     'SUFOBJ'	    => $_o,				# '.o' on UNIX systems
     'SUFMAP'       => {
	 '.c'  => 'build::command::cc',
	 '.s'  => 'build::command::cc',
	 '.S'  => 'build::command::cc',
	 '.C'  => 'build::command::cxx',
	 '.cc' => 'build::command::cxx',
	 '.cxx'=> 'build::command::cxx',
	 '.cpp'=> 'build::command::cxx',
	 '.c++'=> 'build::command::cxx',
	 '.C++'=> 'build::command::cxx',
     },
     'PERL'	    => $^X,
);

%param::rulesets =
    (
     # Defaults for Win32.
     # Defined for VC++ 6.0 by Greg Spencer <greg_spencer@acm.org>
     # Your mileage may vary.
     'msvc' => [
		'CC'             => 'cl',
		'CFLAGS'         => '/nologo',
		'CCCOM'          => '%CC %CFLAGS %_IFLAGS /c %< /Fo%>',
		'CXX'            => '%CC',
		'CXXFLAGS'       => '%CFLAGS',
		'CXXCOM'         => '%CXX %CXXFLAGS %_IFLAGS /c %< /Fo%>',
		'INCDIRPREFIX'   => '/I',
		'INCDIRSUFFIX'   => '',
		'LINK'           => 'link',
		'LINKCOM'        => '%LINK %LDFLAGS /out:%> %< %_LDIRS %LIBS',
		'LINKMODULECOM'  => '%LD /r /o %> %<',
		'LIBDIRPREFIX'   => '/LIBPATH:',
		'LIBDIRSUFFIX'   => '',
		'AR'             => 'lib',
		'ARFLAGS'        => '/nologo ',
		'ARCOM'          => "%AR %ARFLAGS /out:%> %<",
		'RANLIB'         => '',
		'LD'             => 'link',
		'LDFLAGS'        => '/nologo ',
		'PREFLIB'        => '',
		],
     # Defaults for a typical (?) UNIX platform.
     # Your mileage may vary.
     'unix' => [
		'CC'             => 'cc',
		'CFLAGS'         => '',
		'CCCOM'          => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
		'CXX'            => '%CC',
		'CXXFLAGS'       => '%CFLAGS',
		'CXXCOM'         => '%CXX %CXXFLAGS %_IFLAGS -c %< -o %>',
		'INCDIRPREFIX'   => '-I',
		'INCDIRSUFFIX'   => '',
		'LINK'           => '%CXX',
		'LINKCOM'        => '%LINK %LDFLAGS -o %> %< %_LDIRS %LIBS',
		'LINKMODULECOM'  => '%LD -r -o %> %<',
		'LIBDIRPREFIX'   => '-L',
		'LIBDIRSUFFIX'   => '',
		'AR'             => 'ar',
		'ARFLAGS'        => 'r', # rs?
		'ARCOM'          => ['%AR %ARFLAGS %> %<', '%RANLIB %>'],
		'RANLIB'         => 'ranlib',
		'AS'             => 'as',
		'ASFLAGS'        => '',
		'ASCOM'          => '%AS %ASFLAGS %< -o %>',
		'LD'             => 'ld',
		'LDFLAGS'        => '',
		'PREFLIB'        => 'lib',
		'ENV'            => { 'PATH' => '/bin:/usr/bin' },
		],
     );

# Set the rules based on the platform.
script::DefaultRules(script::RuleSet($_WIN32 ? 'msvc' : 'unix'));

# Handle command line arguments.
while (@ARGV) {
    $_ = shift @ARGV;
    last if /^--$/;		# Argument passing to Construct.
    &option, next			if s/^-//;
    push (@param::include, $_), next	if s/^\+//;
    &equate, next			if /=/;
    push (@targets, $_), next;
}

sub option {
    my %opt = (
		    'cc' =>   sub { $param::cachecom = 1; },
		    'cd' =>   sub { $param::cachedisable = 1; },
		    'cr' =>   sub { $param::random = 1; },
		    'cs' =>   sub { $param::cachesync = 1; },
		    'd' =>    sub { $param::depends = 1; },
		    'h' =>    sub { $param::localhelp = 1; },
		    'k' =>    sub { $param::kflag = 1; },
		    'p' =>    sub { $param::pflag = 1;
				    $param::build = 0; },
		    'pa' =>   sub { $param::pflag = 1;
				    $param::aflag = 1;
				    $indent = "... ";
				    $param::build = 0; },
		    'pw' =>   sub { $param::pflag = 1;
				    $param::wflag = 1;
				    $param::build = 0; },
		    'q' =>    sub { $param::quiet++; },
		    'r' =>    sub { $param::rflag = 1;
				    $param::build = 0; },
		    't' =>    sub { $param::traverse = 1; },
		    'v' =>    sub { print($version); },
		    'V' =>    sub { print($version), exit(0); },
		    'x' =>    sub { print($usage), exit 0; },
		);

    my %opt_arg = (
		    'f' =>    sub { $param::topfile = $_[0]; },
		    'o' =>    sub { $param::overfile = $_[0]; },
		    'R' =>    sub { script::Repository($_[0]); },
		    'S' =>    sub { $param::sigpro = $_[0]; },
		    'wf' =>   sub { $param::depfile = $_[0]; },
		);

    if (defined $opt{$_}) {
	&{$opt{$_}}();
	return;
    }
    while ($_) {
	$_  =~ m/(.)(.*)/;
	if (defined $opt{$1}) {
	    &{$opt{$1}}();
	    $_ = $2;
	    next;
	}
	if (defined $opt_arg{$1}) {
	    if (! $2) {
		$_ = shift @ARGV;
		die("$0: -$1 option requires an argument.\n") if ! $_;
	    }
	    &{$opt_arg{$1}}($2 || $_);
	    return;
	}
	$_  =~ m/(..)(.*)/;
	if (defined $opt_arg{$1}) {
	    if (! $2) {
		$_ = shift @ARGV;
		die("$0: -$1 option requires an argument.\n") if ! $_;
	    }
	    &{$opt_arg{$1}}($2 || $_);
	    return;
	}
	if ($_) {
	    die qq($0: unrecognized option "-$_".  Use -x for a usage message.\n);
	}
    }
}

# Process an equate argument (var=val).
sub equate {
    my($var, $val) = /([^=]*)=(.*)/;
    $script::ARG{$var} = $val;
}

# Define file signature protocol.
'sig'->select($param::sigpro);

# Cleanup after an interrupt.
$SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub {
    $SIG{PIPE} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'IGNORE';
    $SIG{HUP} = $SIG{INT} if ! $main::_WIN32;
    warn("\n$0: killed\n");
    # Call this first, to make sure that this processing
    # occurs even if a child process does not die (and we
    # hang on the wait).
    sig::hash::END();
    wait();
    exit(1);
};
$SIG{HUP} = $SIG{INT} if ! $main::_WIN32;

# Cleanup after a broken pipe (someone piped our stdout?)
$SIG{PIPE} = sub {
    $SIG{PIPE} = $SIG{HUP} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'IGNORE';
    warn("\n$0: broken pipe\n");
    sig::hash::END();
    wait();
    exit(1);
};

if ($param::depfile) {
  open (main::DEPFILE, ">".$param::depfile) ||
    die ("$0: couldn't open $param::depfile ($!)\n");
}

# If the supplied top-level Conscript file is not in the
# current directory, then change to that directory.
{
    my ($vol, $dir, $file) =
      File::Spec->splitpath(File::Spec->canonpath($param::topfile));
    if ($vol || $dir) {
	my($cd) = File::Spec->catpath($vol, $dir, undef);
	chdir($cd) || die("$0: couldn't change to directory $cd ($!)\n");
	$param::topfile = $file;
    }
}

# Walk up the directory hierarchy looking for a Conscript file (if -t set).
my($target_top);
my(@targetdir) = ();
if ($param::traverse && ! -f $param::topfile) {
    my($vol, $dirs, $file) = File::Spec->splitpath(cwd());
    my(@dirs) = (File::Spec->splitdir($dirs), $file);
    while (! -f File::Spec->catpath($vol, File::Spec->catdir(@dirs),
				    $param::topfile)) {
	die("$0: unable to find $param::topfile.\n") if ! @dirs;
	unshift(@targetdir, pop(@dirs));
    }
    my($cwd) = File::Spec->catpath($vol, File::Spec->catdir(@dirs), '');
    print "$0: Entering directory `$cwd'\n";
    chdir($cwd);
    @targets = map {File::Spec->catdir(@targetdir, $_)} @targets;
}

# Set up $dir::top and $dir::cwd, now that we are in the right directory.
dir::init();

#
if (@targetdir) {
    $target_top = $dir::top->lookupdir(File::Spec->catdir(@targetdir));
}

# Now handle override file.
package override;
if ($param::overfile) {
    my($ov) = $param::overfile;
    die qq($0: can\'t read override file "$ov" ($!)\n) if ! -f $ov; #'
    do $ov;
    if ($@) {
	chop($@);
	die qq($0: errors in override file "$ov" ($@)\n);
    }
}

# Provide this to user to setup override patterns.
sub Override {
    my($re, @env) = @_;
    return if $param::overrides{$re}; # if identical, first will win.
    $param::overrides = 1;
    $param::overrides{$re} = \@env;
    push(@param::overrides, $re);
}

package main;

use vars qw( %priority $errors );

# Check script inclusion regexps
my $re;
for $re (@param::include) {
    if (! defined eval {"" =~ /$re/}) {
	my($err) = $@;
	$err =~ s/in regexp at .*$//;
	die("$0: error in regexp $err");
    }
}

# Read the top-level construct file and its included scripts.
doscripts($param::topfile);

# Status priorities. This lets us aggregate status for directories
# and print an appropriate message (at the top-level).
%priority =
    ('none' => 1, 'handled' => 2, 'built' => 3, 'unknown' => 4, 'errors' => 5);

# If no targets were specified, supply default targets (if any).
@targets = @param::default_targets if ! @targets;

$errors = 0;

# Build the supplied target patterns.
my $tgt;
for $tgt (map($dir::top->lookup($_), @targets)) {
    if ($target_top && ! $tgt->is_under($target_top)) {
	# A -t option was used, and this target is not underneath
	# the directory where we were invoked via -t.
	# If the target is a directory and the -t directory
	# is underneath it, then build the -t directory.
	if (ref $tgt ne "dir" || ! $target_top->is_under($tgt)) {
	    next;
	}
	$tgt = $target_top;
    }
    buildtoptarget($tgt);
}

exit 0 + ($errors != 0);

sub buildtoptarget {
    my($tgt) = @_;
    return if ! $tgt;
    my($status) = buildtarget($tgt);
    if ($status ne 'built') {
	my($path) = $tgt->path;
	if ($status eq "errors") {
	    print qq($0: "$path" not remade because of errors.\n);
	    $errors++;
	} elsif ($status eq "handled") {
	    print qq($0: "$path" is up-to-date.\n) if ($param::quiet < 2);
	} elsif ($status eq "unknown") {
	    # cons error already reported.
	    $errors++;
	} elsif ($status eq "none") {
	    # search for targets that may be linked to the given path.
	    my @linked = dir::linked_targets($tgt) if $target_top;
	    if (@linked) {
		my @names = map($_->path, @linked);
		print "Linked targets: @names\n" if ($param::quiet < 1);
		map(buildtoptarget($_), @linked);
	    } else {
		print qq($0: nothing to be built in "$path".\n)
		      if $param::build && ($param::quiet < 2);
	    }
	} else {
	    print qq($0: don\'t know how to construct "$path".\n); #'
	    $errors++;
	}
    }
}

# Build the supplied target directory or files. Return aggregated status.
sub buildtarget {
    my($tgt) = @_;
    if (ref($tgt) eq "dir") {
	my($result) = "none";
	my($priority) = $priority{$result};
	if (exists $tgt->{member}) {
	    my($members) = $tgt->{member};
	    my $entry;
	    for $entry (sort keys %$members) {
		next if $entry eq $dir::CURDIR || $entry eq $dir::UPDIR;
		my($tgt) = $members->{$entry};
		next if ref($tgt) ne "dir" && !exists($tgt->{builder});
		my($stat) = buildtarget($members->{$entry});
		my($pri) = $priority{$stat};
		if ($pri > $priority) {
		    $priority = $pri;
		    $result = $stat;
		}
	    }
	}
	return $result;
    }
    if ($param::depends) {
	my($path) = $tgt->path;
	if ($tgt->{builder}) {
	    my(@dep) = (@{$tgt->{dep}}, @{$tgt->{sources}});
	    my($dep) = join(' ',map($_->path, @dep));
	    print("Target $path: $dep\n");
	} else {
	    print("Target $path: not a derived file\n");
	}
    }
    if ($param::build) {
	return build $tgt;
    } elsif ($param::pflag || $param::wflag || $param::aflag) {
	if ($tgt->{builder}) {
	    if ($param::wflag) {
		print qq(${\$tgt->path}: $tgt->{script}\n);
	    } elsif ($param::pflag) {
		print qq(${\$tgt->path}:\n) if $param::aflag;
		print qq(${\$tgt->path}\n) if !$param::aflag;
	    }
	    if ($param::aflag) {
		$tgt->{builder}->action($tgt);
	    }
	}
    } elsif ($param::rflag && $tgt->{builder}) {
	my($path) = $tgt->path;
	if (-f $path) {
	    if (unlink($path)) {
		print("Removed $path\n") if ($param::quiet < 1);
	    } else {
		warn("$0: couldn't remove $path\n");
	    }
	}
    }

    return "none";
}

package NameSpace;

# Return a hash that maps the name of symbols in a namespace to an
# array of refs for all types for which the name has a defined value.
# A list of symbols may be specified; default is all symbols in the
# name space.
sub save {
    my $package = shift;
    my(%namerefs, $var, $type);
    no strict 'refs';
    @_ = keys %{$package."::"} if ! @_;
    foreach $var (@_) {
	$namerefs{$var} = [];
	my $fqvar = $package."::".$var;
	# If the scalar for this variable name doesn't already
	# exist, *foo{SCALAR} will autovivify the reference
	# instead of returning undef, so unlike the other types,
	# we have to dereference to find out if it exists.
	push(@{$namerefs{$var}}, *{$fqvar}{SCALAR})
		    if defined ${*{$fqvar}{SCALAR}};
	foreach $type (qw(ARRAY HASH CODE IO)) {
	    push(@{$namerefs{$var}}, *{$fqvar}{$type})
			  if defined *{$fqvar}{$type};
	}
    }
    return \%namerefs;
}

# Remove the specified symbols from the namespace.
# Default is to remove all.
sub remove {
    my $package = shift;
    my(%namerefs, $var);
    no strict 'refs';
    @_ = keys %{$package."::"} if ! @_;
    foreach $var (@_) {
	delete ${$package."::"}{$var};
    }
}

# Restore values to symbols specified in a hash as returned
# by NameSpace::save.
sub restore {
    my($package, $namerefs) = @_;
    my($var, $ref);
    no strict 'refs';
    foreach $var (keys %$namerefs) {
	my $fqvar = $package."::".$var;
	foreach $ref (@{$namerefs->{$var}}) {
	    *{$fqvar} = $ref;
	}
    }
}

# Support for "building" scripts, importing and exporting variables.
# With the exception of the top-level routine here (invoked from the
# main package by cons), these are all invoked by user scripts.
package script;

use vars qw( $ARG $caller_dir_path %special_var );

BEGIN {
    # We can't Export or Import the following variables because Perl always
    # treats them as part of the "main::" package (see perlvar(1)).
    %special_var = map {$_ => 1} qw(ENV INC ARGV ARGVOUT SIG
				    STDIN STDOUT STDERR);
}

# This is called from main to interpret/run the top-level Construct
# file, passed in as the single argument.
sub main::doscripts {
    my($script) = @_;
    Build($script);
    # Now set up the includes/excludes (after the Construct file is read).
    $param::include = join('|', @param::include);

    # Save the original variable names from the script package.
    # These will stay intact, but any other "script::" variables
    # defined in a Conscript file will get saved, deleted,
    # and (when necessary) restored.
    my(%orig_script_var) = map {$_ => 1} keys %script::;
    $caller_dir_path = undef;
    my $cwd = Cwd::cwd();
    my(@scripts) = pop(@priv::scripts);
    while ($priv::self = shift(@scripts)) {
	my($path) = $priv::self->{script}->rsrcpath;
	if (-f $path) {
	    $dir::cwd = $priv::self->{script}->{dir};
	    # Handle chdir to the Conscript file directory, if necessary.
	    my ($vol, $dir, $file);
	    if ($param::conscript_chdir) {
		($vol, $dir, $file) =
		  File::Spec->splitpath(File::Spec->canonpath($path));
		if ($vol ne '' || $dir ne '') {
		    $caller_dir_path = File::Spec->catpath($vol, $dir, undef);
		    chdir($caller_dir_path) ||
			die "Could not chdir to $caller_dir_path: $!\n";
		}
	    } else {
		$file = $path;
	    }
	    # Actually process the Conscript file.
	    do $file;
	    # Save any variables defined by the Conscript file
	    # so we can restore them later, if needed;
	    # then delete them from the script:: namespace.
	    my(@del) = grep(! $orig_script_var{$_}, keys %script::);
	    if (@del) {
		$priv::self->{script}->{pkgvars} = NameSpace::save('script',
								   @del);
		NameSpace::remove('script', @del);
	    }
	    if ($caller_dir_path) {
		chdir($cwd);
		$caller_dir_path = undef;
	    }
	    if ($@) {
		chomp($@);
		my $err = ($@ =~ /\n/ms) ? ":\n$@" : " ($@)";
		print qq($0: error in file "$path"$err\n);
		$run::errors++;
	    } else {
		# Only process subsidiary scripts if no errors in parent.
		unshift(@scripts, @priv::scripts);
	    }
	    undef @priv::scripts;
	} else {
	    my $where = '';
	    my $cref = $priv::self->{script}->creator;
	    if (defined $cref) {
		my($_foo, $script, $line, $sub) = @$cref;
		$where = " ($sub in $script, line $line)";
	    }
	    warn qq(Ignoring missing script "$path"$where);
	}
    }
    die("$0: script errors encountered: construction aborted\n")
	if $run::errors;
}

# Return caller info about the method being invoked.
# This is everything from the Perl "caller" builtin function,
# including which Construct/Conscript file, line number,
# subroutine name, etc.
sub caller_info {
    my($lev) = 1;
    my(@frame);
    do {
	@frame = caller ++$lev;
	if (defined($frame[3]) && $frame[3] eq '(eval)') {
	    @frame = caller --$lev;
	    if ($caller_dir_path) {
		$frame[1] = File::Spec->catfile($caller_dir_path, $frame[1]);
	    }
	    return @frame;
	}
    } while ($frame[3]);
    return;
}

# Link a directory to another. This simply means set up the *source*
# for the directory to be the other directory.
sub Link {
    dir::link(@_);
}

# Add directories to the repository search path for files.
# Strip our current directory from the list so Repository
# (or -R options) can be used from within the repository.
sub Repository {
    my($my_dir) = Cwd::cwd();
    my $dir;
    foreach $dir (@_) {
	# The following more direct call isn't available in
	# Cwd.pm until some time after 5.003...
	#	my($d) = Cwd::abs_path($dir);
	chdir($dir);
	my($d) = Cwd::cwd();
	chdir($my_dir);
	#
	next if ! $d || ! -d $d || $d eq $my_dir;
	# We know we can get away with passing undef to lookupdir
	# as the directory because $dir is an absolute path.
	push(@param::rpath, dir::lookupdir(undef, $dir));
	push @INC, $d;
    }
}

# Return the list of Repository directories specified.
sub Repository_List {
    map($_->path, @param::rpath);
}

# Specify whether the .consign signature times in repository files are,
# in fact, consistent with the times on the files themselves.
sub Repository_Sig_Times_OK {
    $param::rep_sig_times_ok = shift;
}

sub SourceSignature {
    $param::sourcesig = [@_];
}

# Specify whether we should chdir to the containing directories
# of Conscript files.
sub Conscript_chdir {
    $param::conscript_chdir = shift;
}

# Specify files/targets that must be present and built locally,
# even if they exist already-built in a Repository.
sub Local {
    my(@files) = map($dir::cwd->lookupfile($_), @_);
    map($_->local(1), @files);
}

# Export variables to any scripts invoked from this one.
sub Export {
    my(@illegal) = grep($special_var{$_}, @_);
    if (@illegal) {
	die qq($0: cannot Export special Perl variables: @illegal\n);
    }
    @{$priv::self->{exports}} = grep(! defined $special_var{$_}, @_);
}

# Import variables from the export list of the caller
# of the current script.
sub Import {
    my(@illegal) = grep($special_var{$_}, @_);
    if (@illegal) {
	die qq($0: cannot Import special Perl variables: @illegal\n);
    }
    my($parent) = $priv::self->{parent};
    my($imports) = $priv::self->{imports};
    @{$priv::self->{exports}} = keys %$imports;
    my($var);
    foreach $var (grep(! defined $special_var{$_}, @_)) {
	if (!exists $imports->{$var}) {
	    my($path) = $parent->{script}->path;
	    die qq($0: variable "$var" not exported by file "$path"\n);
	}
	if (!defined $imports->{$var}) {
	    my $path = $parent->{script}->path;
	    my $err = "$0: variable \"$var\" exported but not " .
		      "defined by file \"$path\"\n";
	    die $err;
	}
	${"script::$var"} = $imports->{$var};
    }
}

# Build an inferior script. That is, arrange to read and execute
# the specified script, passing to it any exported variables from
# the current script.
sub Build {
    my(@files) = map($dir::cwd->lookupfile($_), @_);
    my(%imports) = map {$_ => ${"script::$_"}} @{$priv::self->{exports}};
    my $file;
    for $file (@files) {
	next if $param::include && $file->path !~ /$param::include/o;
	my($self) = {'script' => $file,
		     'parent' => $priv::self,
		     'imports' => \%imports};
	bless $self;  # may want to bless into class of parent in future
	push(@priv::scripts, $self);
    }
}

# Set up regexps dependencies to ignore. Should only be called once.
sub Ignore {
    die("Ignore called more than once\n") if $param::ignore;
    $param::ignore = join("|", map("($_)", @_)) if @_;
}

# Specification of default targets.
sub Default {
    push(@param::default_targets, map($dir::cwd->lookup($_)->path, @_));
}

# Local Help.  Should only be called once.
sub Help {
    if ($param::localhelp) {
	print "@_\n";
	exit 2;
    }
}

# For windows platforms which use unix tool sets, the msvc defaults may
# not be useful. Also, in the future, other platforms (Mac?) may have the
# same problem.
sub RuleSet {
    my $style = shift;
    my @rulesets = sort keys %param::rulesets;
    die "Unknown style for rules: $style.\n" .
	"Supported rules are: (" . join(" ", @rulesets) . ")"
	    unless eval(join("||", map("\$style eq '$_'", @rulesets)));
    return @param::base, @{$param::rulesets{$style}};
}

sub DefaultRules {
    @param::defaults = ();
    push @param::defaults, @_;
}

# Return the build name(s) of a file or file list.
sub FilePath {
    wantarray
	? map($dir::cwd->lookupfile($_)->path, @_)
	: $dir::cwd->lookupfile($_[0])->path;
}

# Return the build name(s) of a directory or directory list.
sub DirPath {
    wantarray
	? map($dir::cwd->lookupdir($_)->path, @_)
	: $dir::cwd->lookupdir($_[0])->path;
}

# Split the search path provided into components. Look each up
# relative to the current directory.
# The usual path separator problems abound; for now we'll use :
sub SplitPath {
    my($dirs) = @_;
    if (ref($dirs) ne "ARRAY") {
	$dirs = [ split(/$main::PATH_SEPARATOR/o, $dirs) ];
    }
    map { DirPath($_) } @$dirs;
}

# Return true if the supplied path is available as a source file
# or is buildable (by rules seen to-date in the build).
sub ConsPath {
    my($path) = @_;
    my($file) = $dir::cwd->lookup($path);
    return $file->accessible;
}

# Return the source path of the supplied path.
sub SourcePath {
    wantarray
	? map($dir::cwd->lookupfile($_)->rsrcpath, @_)
	: $dir::cwd->lookupfile($_[0])->rsrcpath;
}

# Search up the tree for the specified cache directory, starting with
# the current directory. Returns undef if not found, 1 otherwise.
# If the directory is found, then caching is enabled. The directory
# must be readable and writable. If the argument "mixtargets" is provided,
# then targets may be mixed in the cache (two targets may share the same
# cache file--not recommended).
sub UseCache($@) {
    my($dir, @args) = @_;
    # NOTE: it's important to process arguments here regardless of whether
    # the cache is disabled temporarily, since the mixtargets option affects
    # the salt for derived signatures.
    for (@args) {
	if ($_ eq "mixtargets") {
	    # When mixtargets is enabled, we salt the target signatures.
	    # This is done purely to avoid a scenario whereby if
	    # mixtargets is turned on or off after doing builds, and
	    # if cache synchronization with -cs is used, then
	    # cache files may be shared in the cache itself (linked
	    # under more than one name in the cache). This is not bad,
	    # per se, but simply would mean that a cache cleaning algorithm
	    # that looked for a link count of 1 would never find those
	    # particular files; they would always appear to be in use.
	    $param::salt = 'M' . $param::salt;
	    $param::mixtargets = 1;
	} else {
	    die qq($0: UseCache unrecognized option "$_"\n);
	}
    }
    if ($param::cachedisable) {
	warn("Note: caching disabled by -cd flag\n");
	return 1;
    }
    my($depth) = 15;
    while ($depth-- && ! -d $dir) {
	$dir = File::Spec->catdir($dir::UPDIR, $dir);
    }
    if (-d $dir) {
	$param::cache = $dir;
	return 1;
    }
    return undef;
}

# Salt the signature generator. The salt (a number of string) is added
# into the signature of each derived file. Changing the salt will
# force recompilation of all derived files.
sub Salt($) {
    # We append the value, so that UseCache and Salt may be used
    # in either order without changing the signature calculation.
    $param::salt .= $_[0];
}

# Mark files (or directories) to not be removed before building.
sub Precious {
    map($_->{precious} = 1, map($dir::cwd->lookup($_), @_));
}


# These methods are callable from Conscript files, via a cons
# object. Procs beginning with _ are intended for internal use.
package cons;

use vars qw( %envcache );

# This is passed the name of the base environment to instantiate.
# Overrides to the base environment may also be passed in
# as key/value pairs.
sub new {
    my($package) = shift;
    my ($env) = {@param::defaults, @_};
    @{$env->{_envcopy}} = %$env; # Note: we never change PATH
    $env->{_cwd} = $dir::cwd; # Save directory of environment for
    bless $env, $package;	# any deferred name interpretation.
}

# Clone an environment.
# Note that the working directory will be the initial directory
# of the original environment.
sub clone {
    my($env) = shift;
    my $clone = {@{$env->{_envcopy}}, @_};
    @{$clone->{_envcopy}} = %$clone; # Note: we never change PATH
    $clone->{_cwd} = $env->{_cwd};
    bless $clone, ref $env;
}

# Create a flattened hash representing the environment.
# It also contains a copy of the PATH, so that the path
# may be modified if it is converted back to a hash.
sub copy {
    my($env) = shift;
    (@{$env->{_envcopy}}, 'ENV' => {%{$env->{ENV}}}, @_)
}

# Resolve which environment to actually use for a given
# target. This is just used for simple overrides.
sub _resolve {
    return $_[0] if !$param::overrides;
    my($env, $tgt) = @_;
    my($path) = $tgt->path;
    my $re;
    for $re (@param::overrides) {
	next if $path !~ /$re/;
	# Found one. Return a combination of the original environment
	# and the override.
	my($ovr) = $param::overrides{$re};
	return $envcache{$env,$re} if $envcache{$env,$re};
	my($newenv) = {@{$env->{_envcopy}}, @$ovr};
	@{$newenv->{_envcopy}} = %$env;
	$newenv->{_cwd} = $env->{_cwd};
	return $envcache{$env,$re} = bless $newenv, ref $env;
    }
    return $env;
}

# Substitute construction environment variables into a string.
# Internal function/method.
sub _subst {
    my($env, $str) = @_;
    if (! defined $str) {
	return undef;
    } elsif (ref($str) eq "ARRAY") {
	return [ map($env->_subst($_), @$str) ];
    } else {
	# % expansion.  %% gets converted to % later, so expand any
	# %keyword construction that doesn't have a % in front of it,
	# modulo multiple %% pairs in between.
	# In Perl 5.005 and later, we could actually do this in one regex
	# using a conditional expression as follows,
	#	while ($str =~ s/($pre)\%(\{)?([_a-zA-Z]\w*)(?(2)\})/"$1".
	#                      $env->{$3}/ge) {}
	# The following two-step approach is backwards-compatible
	# to (at least) Perl5.003.
	my $pre = '^|[^\%](?:\%\%)*';
	while (($str =~ s/($pre)\%([_a-zA-Z]\w*)/$1.($env->{$2}||'')/ge) ||
	       ($str =~ s/($pre)\%\{([_a-zA-Z]\w*)\}/$1.($env->{$2}||'')/ge)) {
	}
	return $str;
    }
}

sub AfterBuild {
    my($env) = shift;
    my($perl_eval_str) = pop(@_);
    my $file;
    for $file (map($dir::cwd->lookup($_), @_)) {
	$file->{after_build_func} = $perl_eval_str;
    }
}

sub Install {
    my($env) = shift;
    my($tgtdir) = $dir::cwd->lookupdir($env->_subst(shift));
    my $file;
    for $file (map($dir::cwd->lookupfile($env->_subst($_)), @_)) {
	my($tgt) = $tgtdir->lookupfile($file->{entry});
	$tgt->bind(find build::install($env), $file);
    }
}

sub InstallAs {
    my $env = shift;
    my $tgt = shift;
    my $src = shift;
    my @sources = ();
    my @targets = ();

    if (ref $tgt) {
	die "InstallAs: Source is a file and target is a list!\n"
	    if (!ref($src));
	@sources = @$src;
	@targets = @$tgt;
    } elsif (ref $src) {
	die "InstallAs: Target is a file and source is a list!\n";
    } else {
	push @sources, $src;
	push @targets, $tgt;
    }

    if ($#sources != $#targets) {
	my $tn = $#targets+1;
	my $sn = $#sources+1;
	die "InstallAs: Source file list ($sn) and target file list ($tn) " .
	    "are inconsistent in length!\n";
    } else {
	foreach (0..$#sources) {
	    my $tfile = $dir::cwd->lookupfile($env->_subst($targets[$_]));
	    my $sfile = $dir::cwd->lookupfile($env->_subst($sources[$_]));
	    $tfile->bind(find build::install($env), $sfile);
	}
    }
}

# Installation in a local build directory,
# copying from the repository if it's already built there.
# Functionally equivalent to:
#	Install $env $dir, $file;
#	Local "$dir/$file";
sub Install_Local {
    my($env) = shift;
    my($tgtdir) = $dir::cwd->lookupdir($env->_subst(shift));
    my $file;
    for $file (map($dir::cwd->lookupfile($env->_subst($_)), @_)) {
	my($tgt) = $tgtdir->lookupfile($file->{entry});
	$tgt->bind(find build::install($env), $file);
	$tgt->local(1);
    }
}

sub Objects {
    my($env) = shift;
    map($dir::cwd->relpath($_), $env->_Objects(@_));
}

# Called with multiple source file references (or object files).
# Returns corresponding object files references.
sub _Objects {
    my($env) = shift;
    my($suffix) = $env->{SUFOBJ};
    map($env->_Object($_, $_->{dir}->lookupfile($_->base_suf($suffix))),
	map { ref $_ ? $_ : $dir::cwd->lookupfile($env->_subst($_)) }
		grep(defined $_, @_));
}

# Called with an object and source reference.  If no object reference
# is supplied, then the object file is determined implicitly from the
# source file's extension. Sets up the appropriate rules for creating
# the object from the source.  Returns the object reference.
sub _Object {
    my($env, $src, $obj) = @_;
    return $obj if $src eq $obj; # don't need to build self from self.
    my($objenv) = $env->_resolve($obj);
    my($suffix) = $src->suffix;

    my($builder) = $env->{SUFMAP}{$suffix};

    if ($builder) {
	$obj->bind((find $builder($objenv)), $src);
    } else {
	die("don't know how to construct ${\$obj->path} from " .
	    "${\$src->path}.\n");
    }
    $obj
}

sub Program {
    my($env) = shift;
    my($tgt) = $dir::cwd->lookupfile(file::addsuffix($env->_subst(shift),
						 $env->{SUFEXE}));
    my($progenv) = $env->_resolve($tgt);
    $tgt->bind(find build::command::link($progenv, $progenv->{LINKCOM}),
	       $env->_Objects(@_));
}

sub Module {
    my($env) = shift;
    my($tgt) = $dir::cwd->lookupfile($env->_subst(shift));
    my($modenv) = $env->_resolve($tgt);
    my($com) = pop(@_);
    $tgt->bind(find build::command::link($modenv, $com), $env->_Objects(@_));
}

sub LinkedModule {
    my($env) = shift;
    my($tgt) = $dir::cwd->lookupfile($env->_subst(shift));
    my($progenv) = $env->_resolve($tgt);
    $tgt->bind(find build::command::linkedmodule
	       ($progenv, $progenv->{LINKMODULECOM}),
	       $env->_Objects(@_));
}

sub Library {
    my($env) = shift;
    my($lib) = $dir::cwd->lookupfile(file::addsuffix($env->_subst(shift),
						 $env->{SUFLIB}));
    my($libenv) = $env->_resolve($lib);
    $lib->bind(find build::command::library($libenv), $env->_Objects(@_));
}

# Simple derivation: you provide target, source(s), command.
# Special variables substitute into the rule.
# Target may be a reference, in which case it is taken
# to be a multiple target (all targets built at once).
sub Command {
    my($env) = shift;
    my($tgt) = $env->_subst(shift);
    my($builder) = find build::command::user($env, pop(@_), 'script');
    my(@sources) = map($dir::cwd->lookupfile($env->_subst($_)), @_);
    if (ref($tgt)) {
	# A multi-target command.
	my(@tgts) = map($dir::cwd->lookupfile($_), @$tgt);
	die("empty target list in multi-target command\n") if !@tgts;
	$env = $env->_resolve($tgts[0]);
	my($multi) = build::multiple->new($builder, \@tgts);
	for $tgt (@tgts) {
	    $tgt->bind($multi, @sources);
	}
    } else {
	$tgt = $dir::cwd->lookupfile($tgt);
	$env = $env->_resolve($tgt);
	$tgt->bind($builder, @sources);
    }
}

sub Depends {
    my($env) = shift;
    my($tgt) = $env->_subst(shift);
    my(@deps) = map($dir::cwd->lookup($env->_subst($_)), @_);
    if (! ref($tgt)) {
	$tgt = [ $tgt ];
    }
    my($t);
    foreach $t (map($dir::cwd->lookupfile($_), @$tgt)) {
	push(@{$t->{dep}}, @deps);
    }
}

# Setup a quick scanner for the specified input file, for the
# associated environment. Any use of the input file will cause the
# scanner to be invoked, once only. The scanner sees just one line at
# a time of the file, and is expected to return a list of
# dependencies.
sub QuickScan {
    my($env, $code, $file, $path) = @_;
    $dir::cwd->lookup($env->_subst($file))->{'srcscan',$env} =
	find scan::quickscan($code, $env, $env->_subst($path));
}

# Generic builder module. Just a few default methods.  Every derivable
# file must have a builder object of some sort attached.  Usually
# builder objects are shared.
package build;

use vars qw( %builder );

# Every builder must now have at least an associated environment,
# so we can find its sigarray and calculate the proper signature.
sub find {
    my($class, $env) = @_;
    $builder{$env} || do {
	my $self = { env => $env };
	$builder{$env} = bless $self, $class;
    }
}

# Null signature for dynamic includes.
sub includes { () }

# Null signature for build script.
sub scriptsig { () }

# Not compatible with any other builder, by default.
sub compatible { 0 }


# Builder module for the Install command.
package build::install;

use vars qw( @ISA );

BEGIN { @ISA = qw(build) }

# Caching not supported for Install: generally install is trivial anyway,
# and we don't want to clutter the cache.
sub cachin { undef }
sub cachout { }

# Do the installation.
sub action {
    my($self, $tgt) = @_;
    my($src) = $tgt->{sources}[0];
    main::showcom("Install ${\$src->rpath} as ${\$tgt->path}")
	if ($param::install && $param::quiet < 1);
    return unless $param::build;
    futil::install($src->rpath, $tgt);
    return 1;
}


# Builder module for generic UNIX commands.
package build::command;

use vars qw( @ISA %com );

BEGIN { @ISA = qw(build) }

sub find {
    my($class, $env, $cmd, $package) = @_;
    my($act) = action::new($env, $cmd);
    $package ||= '';
    $com{$env,$act,$package} || do {
	my $self = { env => $env, act => $act, 'package' => $package };
	$com{$env,$act,$package} = bless $self, $class;
    }
}

# Default cache in function.
sub cachin {
    my($self, $tgt, $sig) = @_;
    if (cache::in($tgt, $sig)) {
	if ($param::cachecom) {
	    $self->{act}->show($self->{env}, $tgt);
	} else {
	    printf("Retrieved %s from cache\n", $tgt->path)
		if ($param::quiet < 1);
	}
	return 1;
    }
    return undef;
}

# Default cache out function.
sub cachout {
    my($self, $tgt, $sig) = @_;
    cache::out($tgt, $sig);
}

# Build the target using the previously specified commands.
sub action {
    my($self, $tgt) = @_;
    $self->{act}->execute($self->{env}, $tgt, $self->{'package'});
}

# Return script signature.
sub scriptsig {
    $_[0]->{act}->scriptsig
}


# Create a linked module.
package build::command::link;

use vars qw( @ISA );

BEGIN { @ISA = qw(build::command) }

# Find an appropriate linker.
sub find {
    my($class, $env, $command) = @_;
    if (!exists $env->{_LDIRS}) {
	my($ldirs) = '';
	my($wd) = $env->{_cwd};
	my($pdirs) = $env->{LIBPATH};
	if (! defined $pdirs) {
	    $pdirs = [ ];
	} elsif (ref($pdirs) ne 'ARRAY') {
	    $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
	}
	my($dir, $dpath);
	for $dir (map($wd->lookupdir($env->_subst($_)), @$pdirs)) {
	    $dpath = $dir->path;
	    # Add the (presumably local) directory to the -L flags
	    # if we're not using repositories, the directory exists,
	    # or it's Linked to a source directory (that is, it *will*
	    # exist by the time the link occurs).
	    $ldirs .= " ".$env->{LIBDIRPREFIX}.$dpath.$env->{LIBDIRSUFFIX}
			if ! @param::rpath || -d $dpath || $dir->is_linked;
	    next if File::Spec->file_name_is_absolute($dpath);
	    if (@param::rpath) {
		my $d;
		if ($dpath eq $dir::CURDIR) {
		    foreach $d (map($_->path, @param::rpath)) {
			$ldirs .= " " . $env->{LIBDIRPREFIX} .
				  $d . $env->{LIBDIRSUFFIX};
		    }
		} else {
		    my($rpath);
		    foreach $d (map($_->path, @param::rpath)) {
			$rpath = File::Spec->catfile($d, $dpath);
			$ldirs .= " ". $env->{LIBDIRPREFIX} .
				  $rpath . $env->{LIBDIRSUFFIX} if -d $rpath;
		    }
		}
	    }
	}
	$env->{_LDIRS} = "%($ldirs%)";
    }

    # Introduce a new magic _LIBS symbol which allows to use the
    # Unix-style -lNAME syntax for Win32 only. -lNAME will be replaced
    # with %{PREFLIB}NAME%{SUFLIB}. <schwarze@isa.de> 1998-06-18

    if ($main::_WIN32 && !exists $env->{_LIBS}) {
	my $libs;
	my $name;
	for $name (split(' ', $env->_subst($env->{LIBS} || ''))) {
	    if ($name =~ /^-l(.*)/) {
		$name = "$env->{PREFLIB}$1$env->{SUFLIB}";
	    }
	    $libs .= ' ' . $name;
	}
	$env->{_LIBS} = $libs ? "%($libs%)" : '';
    }
    bless find build::command($env, $command);
}

# Called from file::build. Make sure any libraries needed by the
# environment are built, and return the collected signatures
# of the libraries in the path.
sub includes {
    return $_[0]->{'bsig'} if exists $_[0]->{'bsig'};
    my($self, $tgt) = @_;
    my($env) = $self->{env};
    my($ewd) = $env->{_cwd};
    my $ldirs = $env->{LIBPATH};
    if (! defined $ldirs) {
	$ldirs = [ ];
    } elsif (ref($ldirs) ne 'ARRAY') {
	$ldirs = [ split(/$main::PATH_SEPARATOR/o, $ldirs) ];
    }
    my @lpath = map($ewd->lookupdir($_), @$ldirs);
    my(@sigs);
    my(@names);

    # Pass %LIBS symbol through %-substituition
    # <schwarze@isa.de> 1998-06-18
    @names = split(' ', $env->_subst($env->{LIBS} || ''));
    my $name;
    for $name (@names) {
	my ($lpath, @allnames);
	if ($name =~ /^-l(.*)/) {
	    # -l style names are looked up on LIBPATH, using all
	    # possible lib suffixes in the same search order the
	    # linker uses (according to SUFLIBS).
	    # Recognize new PREFLIB symbol, which should be 'lib' on
	    # Unix, and empty on Win32. TODO: What about shared
	    # library suffixes?  <schwarze@isa.de> 1998-05-13
	   @allnames = map("$env->{PREFLIB}$1$_",
			   split(/:/, $env->{SUFLIBS}));
	    $lpath = \@lpath;
	} else {
	    @allnames = ($name);
	    # On Win32, all library names are looked up in LIBPATH
	    # <schwarze@isa.de> 1998-05-13
	    if ($main::_WIN32) {
		$lpath = [$dir::top, @lpath];
	    }
	    else {
		$lpath = [$dir::top];
	    }
	}
	my $dir;
	DIR: for $dir (@$lpath) {
	    my $n;
	    for $n (@allnames) {
		my($lib) = $dir->lookup_accessible($n);
		if ($lib) {
		    last DIR if $lib->ignore;
		    if ((build $lib) eq 'errors') {
			$tgt->{status} = 'errors';
			return undef;
		    }
		    push(@sigs, 'sig'->signature($lib));
		    last DIR;
		}
	    }
	}
    }
    $self->{'bsig'} = 'sig'->collect(@sigs);
}

# Always compatible with other such builders, so the user
# can define a single program or module from multiple places.
sub compatible {
    my($self, $other) = @_;
    ref($other) eq "build::command::link";
}

# Link a program.
package build::command::linkedmodule;

use vars qw( @ISA );

BEGIN { @ISA = qw(build::command) }

# Always compatible with other such builders, so the user
# can define a single linked module from multiple places.
sub compatible {
    my($self, $other) = @_;
    ref($other) eq "build::command::linkedmodule";
}

# Builder for a C module
package build::command::cc;

use vars qw( @ISA );

BEGIN { @ISA = qw(build::command) }

sub find {
    $_[1]->{_cc} || do {
	my($class, $env) = @_;
	my($cpppath) = $env->_subst($env->{CPPPATH});
	my($cscanner) = find scan::cpp($env->{_cwd}, $cpppath);
	$env->{_IFLAGS} = "%(" . $cscanner->iflags($env) . "%)";
	my($self) = find build::command($env, $env->{CCCOM});
	$self->{scanner} = $cscanner;
	bless $env->{_cc} = $self;
    }
}

# Invoke the associated	 C scanner to get signature of included files.
sub includes {
    my($self, $tgt) = @_;
    $self->{scanner}->includes($tgt, $tgt->{sources}[0]);
}

# Builder for a C++ module
package build::command::cxx;

use vars qw( @ISA );

BEGIN { @ISA = qw(build::command) }

sub find {
    $_[1]->{_cxx} || do {
	my($class, $env) = @_;
	my($cpppath) = $env->_subst($env->{CPPPATH});
	my($cscanner) = find scan::cpp($env->{_cwd}, $cpppath);
	$env->{_IFLAGS} = "%(" . $cscanner->iflags($env) . "%)";
	my($self) = find build::command($env, $env->{CXXCOM});
	$self->{scanner} = $cscanner;
	bless $env->{_cxx} = $self;
    }
}

# Invoke the associated	 C scanner to get signature of included files.
sub includes {
    my($self, $tgt) = @_;
    $self->{scanner}->includes($tgt, $tgt->{sources}[0]);
}

# Builder for a user command (cons::Command).  We assume that a user
# command might be built and implement the appropriate dependencies on
# the command itself (actually, just on the first word of the command
# line).
package build::command::user;

use vars qw( @ISA );

BEGIN { @ISA = qw(build::command) }

sub includes {
    my($self, $tgt) = @_;
    my($sig) = '';

    # Check for any quick scanners attached to source files.
    my $dep;
    for $dep (@{$tgt->{dep}}, @{$tgt->{sources}}) {
	my($scanner) = $dep->{'srcscan',$self->{env}};
	if ($scanner) {
	    $sig .= $scanner->includes($tgt, $dep);
	}
    }

    # XXX Optimize this to not use ignored paths.
    if (! exists $self->{_comsig}) {
	my($env) = $self->{env};
	$self->{_comsig} = '';
	my($com, $dir);
      com:
	for $com ($self->{act}->commands) {
	    my($pdirs) = $env->{ENV}->{PATH};
	    if (! defined $pdirs) {
		$pdirs = [ ];
	    } elsif (ref($pdirs) ne 'ARRAY') {
		$pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
	    }
	    for $dir (map($dir::top->lookupdir($_), @$pdirs)) {
		my($prog) = $dir->lookup_accessible($com);
		if ($prog) { # XXX Not checking execute permission.
		    if ((build $prog) eq 'errors') {
			$tgt->{status} = 'errors';
			return $sig;
		    }
		    next com if $prog->ignore;
		    $self->{_comsig} .= 'sig'->signature($prog);
		    next com;
		}
	    }
	}
    }

    return $self->{_comsig} . $sig
}


# Builder for a library module (archive).
# We assume that a user command might be built and implement the
# appropriate dependencies on the command itself.
package build::command::library;

use vars qw( @ISA );

BEGIN { @ISA = qw(build::command) }

sub find {
    my($class, $env) = @_;
    bless find build::command($env, $env->{ARCOM})
}

# Always compatible with other library builders, so the user
# can define a single library from multiple places.
sub compatible {
    my($self, $other) = @_;
    ref($other) eq "build::command::library";
}

# A multi-target builder.
# This allows multiple targets to be associated with a single build
# script, without forcing all the code to be aware of multiple targets.
package build::multiple;

sub new {
    my($class, $builder, $tgts) = @_;
    bless { 'builder' => $builder, 'env' => $builder->{env}, 'tgts' => $tgts };
}

sub scriptsig {
    my($self, $tgt) = @_;
    $self->{builder}->scriptsig($tgt);
}

sub includes {
    my($self, $tgt) = @_;
    $self->{builder}->includes($tgt);
}

sub compatible {
    my($self, $tgt) = @_;
    $self->{builder}->compatible($tgt);
}

sub cachin {
    my($self, $tgt, $sig) = @_;
    $self->{builder}->cachin($tgt, $sig);
}

sub cachout {
    my($self, $tgt, $sig) = @_;
    $self->{builder}->cachout($tgt, $sig);
}

sub action {
    my($self, $invoked_tgt) = @_;
    return $self->{built} if exists $self->{built};

    # Make sure all targets in the group are unlinked before building any.
    my($tgts) = $self->{tgts};
    my $tgt;
    for $tgt (@$tgts) {
	futil::mkdir($tgt->{dir});
	unlink($tgt->path) if ! $tgt->precious;
    }

    # Now do the action to build all the targets. For consistency
    # we always call the action on the first target, just so that
    # $> is deterministic.
    $self->{built} = $self->{builder}->action($tgts->[0]);

    # Now "build" all the other targets (except for the one
    # we were called with). This guarantees that the signature
    # of each target is updated appropriately. We force the
    # targets to be built even if they have been previously
    # considered and found to be OK; the only effect this
    # has is to make sure that signature files are updated
    # correctly.
    for $tgt (@$tgts) {
	if ($tgt ne $invoked_tgt) {
	    delete $tgt->{status};
	    'sig'->invalidate($tgt);
	    build $tgt;
	}
    }

    # Status of action.
    $self->{built};
}

package action;

sub new {
    my($env, $act) = @_;
    if (ref($act) eq 'CODE') {
	return action::perl->new($act);
    } else {
	return action::command->new($env, $act);
    }
}

package action::command;

use vars qw( @ISA %cmd %_varopts $_varletters );

BEGIN {
    @ISA = $main::_WIN32 ? 'action::command::win32' : 'action::command::unix';

    # Internal hash for processing variable options.
    # f: return file part
    # d: return directory part
    # F: return file part, but strip any suffix
    # b: return full path, but strip any suffix (a.k.a. return basename)
    # s: return only the suffix (or an empty string, if no suffix is there)
    # a: return the absolute path to the file
    # S: return the absolute path to a Linked source file
    %_varopts = (
	'f' => sub { return $_[0]->{entry}; },
	'd' => sub { return $_[0]->{dir}->path; },
	'F' => sub { my $subst = $_[0]->{entry};
		     $subst =~ s/\.[^\.]+$//;
		     return $subst; },
	'b' => sub { my $subst =  $_[0]->path;
		     $subst =~ s/\.[^\.]+$//;
		     return $subst; },
	's' => sub { my $subst = $_[0]->{entry};
		     $subst =~ m/(\.[^\.]+)$/;
		     return $1; },
	'a' => sub { my $path = $_[0]->path;
		     if (! File::Spec->file_name_is_absolute($path)) {
			$path = File::Spec->catfile(Cwd::cwd(), $path);
		     }
		     return $path; },
	'S' => sub { my $path = $_[0]->srcpath;
		     if (! File::Spec->file_name_is_absolute($path)) {
			my $cwd = File::Spec->canonpath(Cwd::cwd());
			$path = File::Spec->catfile($cwd, $path);
		     }
		     return $path; },
    );

    $_varletters = join('', keys %_varopts);
}

# Internal routine for processing variable options.
# Options are specified in hash in the BEGIN block above.
# no option: return path to file (relative to top,
# or absolute if it's outside)
sub _variant {
    my($opt, $file) = @_;
    $opt = '' if ! defined $opt;
    if (defined $_varopts{$opt}) {
	return &{$_varopts{$opt}}($file);
    }
    return $file->path;
}

sub new {
    my($class, $env, $cmd) = @_;
    $cmd = $env->_subst($cmd);
    $cmd{$env,$cmd} || do {
	# Remove unwanted bits from signature -- those bracketed by %( ... %)
	my $sigs = $cmd;
	my $sig = '';
	if (ref($sigs) eq 'ARRAY') {
	    # This is an array of commands..
	    my $f;
	    foreach $f (@$sigs) {
		$sig .= _strip($f);
	    }
	} else {
	    $sig = _strip($sigs);
	}
	my $self = { cmd => $cmd, cmdsig => 'sig'->cmdsig($sig) };
	$cmd{$env,$cmd} = bless $self, $class;
    }
}

sub _strip {
    my $sig = shift;
    $sig =~ s/^\@\s*//mg;
    while ($sig =~ s/%\(([^%]|%[^\(])*?%\)//g) { }
    $sig;
}

sub scriptsig {
    $_[0]->{cmdsig};
}

# Return an array of all the commands (first word on each line).
sub commands {
    my($self) = @_;
    my(@cmds) = ();
    my $com;
    my $cmd = $self->{'cmd'};
    my @allcoms;

    push @allcoms, ref $cmd ? @{$cmd} : split(/\n/, $cmd);

    for $com (@allcoms) {
	$com =~ s/^\s*//;
	$com =~ s/\s.*//;
	next if ! $com; # blank line
	push @cmds, $com;
    }
    @cmds;
}

# For the signature of a basic command, we don't bother
# including the command itself. This is not strictly correct,
# and if we wanted to be rigorous, we might want to insist
# that the command was checked for all the basic commands
# like gcc, etc. For this reason we don't have an includes
# method.

# Call this to get the command line script: an array of
# fully substituted commands.
sub getcoms {
    my($self, $env, $tgt) = @_;
    my(@coms);
    my $com;
    my @allcoms = ();
    my $cmd = $self->{'cmd'};

    push @allcoms, ref $cmd ? @{$cmd} : split(/\n/, $cmd);

    for $com (@allcoms) {
	my(@src) = (undef, @{$tgt->{sources}});
	my(@src1) = @src;

	next if $com =~ /^\s*$/;

	# NOTE: we used to have a more elegant s//.../e solution
	# for the items below, but this caused a bus error...

	# Remove %( and %) -- those are only used to bracket parts
	# of the command that we don't depend on.
	$com =~ s/%[()]//g;

	# Deal with %n, n=1,9 and variants.
	while ($com =~ /%([1-9])(:([$_varletters]?))?/o) {
	    my($match) = $&;
	    my($src) = $src1[$1];
	    my($subst) = _variant($3, $src1[$1]->rfile);
	    undef $src[$1];
	    $com =~ s/$match/$subst/;
	}

	# Deal with %0 aka %> and variants.
	while ($com =~ /%[0>](:([$_varletters]?))?/o) {
	    my($match) = $&;
	    my($subst) = _variant($2, $tgt);
	    $com =~ s/$match/$subst/;
	}

	# Deal with %< (all sources except %n's already used)
	while ($com =~ /%<(:([$_varletters]?))?/o) {
	    my($match) = $&;
	    my @list = ();
	    foreach (@src) {
		push(@list, _variant($2, $_->rfile)) if $_;
	    }
	    my($subst) = join(' ', @list);
	    $com =~ s/$match/$subst/;
	}

	# Deal with %[ %].
	$com =~ s{%\[(.*?)%\]}{
	    my($func, @args) = grep { $_ ne '' } split(/\s+/, $1);
	    die("$0: \"$func\" is not defined.\n")
		unless ($env->{$func});
	    &{$env->{$func}}(@args);
	}gex;

	# Convert left-over %% into %.
	$com =~ s/%%/%/g;

	# White space cleanup. XXX NO WAY FOR USER TO HAVE QUOTED SPACES
	$com = join(' ', split(' ', $com));
	next if $com =~ /^:/ && $com !~ /^:\S/;
	push(@coms, $com);
    }
    @coms
}

# Build the target using the previously specified commands.
sub execute {
    my($self, $env, $tgt, $package) = @_;

    if ($param::build) {
	futil::mkdir($tgt->{dir});
	unlink($tgt->path) if ! $tgt->precious;
    }

    # Set environment.
    map(delete $ENV{$_}, keys %ENV);
    %ENV = %{$env->{ENV}};

    # Handle multi-line commands.
    my $com;
    for $com ($self->getcoms($env, $tgt)) {
	if ($com !~ s/^\@\s*//) {
	    main::showcom($com);
	}
	next if ! $param::build;

	if ($com =~ /^\[perl\]\s*/) {
	    my $perlcmd = $';
	    my $status;
	    {
		# Restore the script package variables that were defined
		# in the Conscript file that defined this [perl] build,
		# so the code executes with the expected variables.
		# Then actually execute (eval) the [perl] command to build
		# the target, followed by cleaning up the name space
		# by deleting the package variables we just restored.
		my($pkgvars) = $tgt->{conscript}->{pkgvars};
		NameSpace::restore($package, $pkgvars) if $pkgvars;
		$status = eval "package $package; $perlcmd";
		NameSpace::remove($package, keys %$pkgvars) if $pkgvars;
	    }
	    if (!defined($status)) {
		warn "$0: *** Error during perl command eval: $@.\n";
		return undef;
	    } elsif ($status == 0) {
		warn "$0: *** Perl command returned $status "
		   . "(this indicates an error).\n";
		return undef;
	    }
	    next;
	}
	if (! $self->do_command($com, $tgt->path)) {
		return undef;
	}
    }

    # success.
    return 1;
}

sub show {
    my($self, $env, $tgt) = @_;
    my $com;
    for $com ($self->getcoms($env, $tgt)) {
	if ($com !~ /^\@\s*/) {
	    main::showcom($com);
	}
    }
}

package action::command::unix;

sub do_command {
    my($class, $com, $path) = @_;
    my($pid) = fork();
    die("$0: unable to fork child process ($!)\n") if !defined $pid;
    if (!$pid) {
	# This is the child.  We eval the command to suppress -w
	# warnings about not reaching the statements afterwards.
	eval 'exec($com)';
	$com =~ s/\s.*//;
	die qq($0: failed to execute "$com" ($!). )
	  . qq(Is this an executable on path "$ENV{PATH}"?\n);
    }
    for (;;) {
	do {} until wait() == $pid;
	my ($b0, $b1) = ($? & 0xFF, $? >> 8);
	# Don't actually see 0177 on stopped process; is this necessary?
	next if $b0 == 0177; # process stopped; we can wait.
	if ($b0) {
	    my($core, $sig) = ($b0 & 0200, $b0 & 0177);
	    my($coremsg) = $core ? "; core dumped" : "";
	    $com =~ s/\s.*//;
	    my $err = "$0: *** \[$path\] $com terminated by signal " .
		  "$sig$coremsg\n";
	    warn $err;
	    return undef;
	}
	if ($b1) {
	    warn qq($0: *** [$path] Error $b1\n); # trying to be like make.
	    return undef;
	}
	last;
    }
    return 1;
}

package action::command::win32;

sub do_command {
    my($class, $com, $path) = @_;
    system($com);
    if ($?) {
	my ($b0, $b1) = ($? & 0xFF, $? >> 8);
	my $err = $b1 || $?;
	my $warn = qq($0: *** [$path] Error $err);
	$warn .= " (executable not found in path?)" if $b1 == 0xFF;
	warn "$warn\n";
	return undef;
    }
    return 1;
}

package action::perl;

# THIS IS AN EXPERIMENTAL PACKAGE.  It's entirely possible that the
# interface may change as this gets completed, so use at your own risk.
#
# There are (at least) two issues that need to be solved before blessing
# this as a real, fully-supported feature:
#
#   --	We need to calculate a signature value for a Perl code ref, in
#	order to rebuild the target if there's a change to the Perl code
#	used to generate it.
#
#	This is not straightforward.  A B::Deparse package exists that
#	decompiles a coderef into text.  It's reportedly not completely
#	reliable for closures; it misses which variables are global, and
#	the values of private lexicals.  Nevertheless, it'd probably
#	be perfect for our purposes, except that it wasn't added until
#	some time between Perl 5.00502 and 5.00554, and doesn't seem to
#	really work until Perl 5.6.0, so by relying on it, we'd lose
#	support for Perl versions back to 5.003*.
#
#   --	Ideally, a code ref should be able to use something like
#	$env->_subst to fetch values from the construction environment
#	to modify its behavior without having to cut-and-paste code.
#	(Actually, since we pass the environment to the executed code
#	ref, there's no reason you can't do this with the code as it
#	stands today.)  But this REALLY complicates the signature
#	calculation, because now the actual signature would depend not
#	just on the code contents, but on the construction variables (or
#	maybe just the environment).
#
# A potentially valid workaround would be to use the contents of the
# Conscript file in which the code reference is defined as the code
# ref's signature.  This has the drawback of causing a recompilation of
# the target file even in response to unrelated changes in the Conscript
# file, but it would ensure correct builds without having to solve the
# messy issues of generating a signature directly from a code ref.
#
# Nevertheless, this seemed a useful enough skeleton of a feature that
# it made sense to release it in hopes that some practical experience
# will encourage someone to figure out how to solve the signature
# issues.  Or maybe we'll discover these aren't big issues in practice
# and end up blessing it as is.

use vars qw( %code );

sub new {
    my($class, $cref) = @_;
    $code{$cref} || do {
	my $sig = '';
	# Generating a code signature using B::Deparse doesn't really
	# work for us until Perl 5.6.0.  Here's the code in case
	# someone wants to use it.
	#use B::Deparse;
	#my $deparse = B::Deparse->new();
	#my $body = $deparse->coderef2text($cref);
	#$sig = $body;	# should be an MD5 sig
	my($self) = { cref => $cref, crefsig => $sig };
	$code{$cref} = bless $self, $class;
    }
}

sub scriptsig {
    $_[0]->{crefsig}
}

sub execute {
    my($self, $env, $tgt) = @_;
    if ($param::build) {
	futil::mkdir($tgt->{dir});
	unlink($tgt->path) if ! $tgt->precious;
	my($cref) = $self->{cref};
	&$cref($env, $tgt->path, map($_->rpath, @{$tgt->{sources}}));
    }
}

sub commands {
    return ();
}


# Generic scanning module.
package scan;

# Returns the signature of files included by the specified files on
# behalf of the associated target. Any errors in handling the included
# files are propagated to the target on whose behalf this processing
# is being done. Signatures are cached for each unique file/scanner
# pair.
sub includes {
    my($self, $tgt, @files) = @_;
    my(%files, $file);
    my($inc) = $self->{includes} || ($self->{includes} = {});
    while ($file = pop @files) {
	next if exists $files{$file};
	if ($inc->{$file}) {
	    push(@files, @{$inc->{$file}});
	    $files{$file} = 'sig'->signature($file->rfile);
	} else {
	    if ((build $file) eq 'errors') {
		$tgt->{status} = 'errors'; # tgt inherits build status
		return ();
	    }
	    $files{$file} = 'sig'->signature($file->rfile);
	    my(@includes) = $self->scan($file);
	    $inc->{$file} = \@includes;
	    push(@files, @includes);
	}
    }
    'sig'->collect(sort values %files)
}


# A simple scanner. This is used by the QuickScanfunction, to setup
# one-time target and environment-independent scanning for a source
# file. Only used for commands run by the Command method.
package scan::quickscan;

use vars qw( @ISA %scanner );

BEGIN { @ISA = qw(scan) }

sub find {
    my($class, $code, $env, $pdirs) = @_;
    if (! defined $pdirs) {
	$pdirs = [ ] ;
    } elsif (ref($pdirs) ne 'ARRAY') {
	$pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
    }
    my(@path) = map { $dir::cwd->lookupdir($_) } @$pdirs;
    my($spath) = "@path";
    $scanner{$code,$env,$spath} || do {
	my($self) = { code => $code, env => $env, path => \@path };
	$scanner{$code,$env,$spath} = bless $self;
    }
}

# Scan the specified file for included file names.
sub scan {
    my($self, $file) = @_;
    my($code) = $self->{code};
    my(@includes);
    # File should have been built by now. If not, we'll ignore it.
    return () unless open(SCAN, $file->rpath);
    while(<SCAN>) {
	push(@includes, grep($_ ne '', &$code));
    }
    close(SCAN);
    my($wd) = $file->{dir};
    my(@files);
    my $name;
    for $name (@includes) {
	my $dir;
	for $dir ($file->{dir}, @{$self->{path}}) {
	    my($include) = $dir->lookup_accessible($name);
	    if ($include) {
		push(@files, $include) unless $include->ignore;
		last;
	    }
	}
    }
    @files
}


# CPP (C preprocessor) scanning module
package scan::cpp;

use vars qw( @ISA %scanner );

BEGIN { @ISA = qw(scan) }

# For this constructor, provide the include path argument (colon
# separated). Each path is taken relative to the provided directory.

# Note: a particular scanning object is assumed to always return the
# same result for the same input. This is why the search path is a
# parameter to the constructor for a CPP scanning object. We go to
# some pains to make sure that we return the same scanner object
# for the same path: otherwise we will unecessarily scan files.
sub find {
    my($class, $dir, $pdirs) = @
Back to Top