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

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

/**
 * var.c --
 *	Variable-handling functions
 *
 * Interface:
 *	Var_Set		Set the value of a variable in the given
 *			context. The variable is created if it doesn't
 *			yet exist. The value and variable name need not
 *			be preserved.
 *
 *	Var_Append	Append more characters to an existing variable
 *			in the given context. The variable needn't
 *			exist already -- it will be created if it doesn't.
 *			A space is placed between the old value and the
 *			new one.
 *
 *	Var_Exists	See if a variable exists.
 *
 *	Var_Value	Return the value of a variable in a context or
 *			NULL if the variable is undefined.
 *
 *	Var_Subst	Substitute named variable, or all variables if
 *			NULL in a string using
 *			the given context as the top-most one. If the
 *			third argument is non-zero, Parse_Error is
 *			called if any variables are undefined.
 *
 *	Var_Parse	Parse a variable expansion from a string and
 *			return the result and the number of characters
 *			consumed.
 *
 *	Var_Delete	Delete a variable in a context.
 *
 *	Var_Init	Initialize this module.
 *
 * Debugging:
 *	Var_Dump	Print out all variables defined in the given
 *			context.
 *
 * XXX: There's a lot of duplication in these functions.
 */

#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>

#include "buf.h"
#include "config.h"
#include "globals.h"
#include "GNode.h"
#include "job.h"
#include "lst.h"
#include "parse.h"
#include "str.h"
#include "targ.h"
#include "util.h"
#include "var.h"

/**
 *
 */
typedef struct VarParser {
	const char	*const input;	/* pointer to input string */
	const char	*ptr;		/* current parser pos in input str */
	GNode		*ctxt;
	Boolean		err;
	Boolean		execute;
} VarParser;

typedef struct Var {
	char		*name;	/* the variable's name */
	struct Buffer	*val;	/* its value */
	int		flags;	/* miscellaneous status flags */

#define	VAR_IN_USE	1	/* Variable's value currently being used.
				 * Used to avoid recursion */

#define	VAR_JUNK	4	/* Variable is a junk variable that
				 * should be destroyed when done with
				 * it. Used by Var_Parse for undefined,
				 * modified variables */

#define	VAR_TO_ENV	8	/* Place variable in environment */
} Var;

typedef struct {
	struct Buffer	*lhs;	/* String to match */
	struct Buffer	*rhs;	/* Replacement string (w/ &'s removed) */

	regex_t			re;
	int			nsub;
	regmatch_t		*matches;

	int	flags;
#define	VAR_SUB_GLOBAL	0x01	/* Apply substitution globally */
#define	VAR_SUB_ONE	0x02	/* Apply substitution to one word */
#define	VAR_SUB_MATCHED	0x04	/* There was a match */
#define	VAR_MATCH_START	0x08	/* Match at start of word */
#define	VAR_MATCH_END	0x10	/* Match at end of word */
} VarPattern;

typedef Boolean VarModifyProc(const char *, Boolean, struct Buffer *, void *);

static char *VarParse(VarParser *, Boolean *);

/*
 * This is a harmless return value for Var_Parse that can be used by Var_Subst
 * to determine if there was an error in parsing -- easier than returning
 * a flag, as things outside this module don't give a hoot.
 */
char	var_Error[] = "";

/*
 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
 * set false. Why not just use a constant? Well, gcc likes to condense
 * identical string instances...
 */
static char	varNoError[] = "";

/*
 * Internally, variables are contained in four different contexts.
 *	1) the environment. They may not be changed. If an environment
 *	   variable is appended-to, the result is placed in the global
 *	   context.
 *	2) the global context. Variables set in the Makefile are located in
 *	   the global context. It is the penultimate context searched when
 *	   substituting.
 *	3) the command-line context. All variables set on the command line
 *	   are placed in this context. They are UNALTERABLE once placed here.
 *	4) the local context. Each target has associated with it a context
 *	   list. On this list are located the structures describing such
 *	   local variables as $(@) and $(*)
 * The four contexts are searched in the reverse order from which they are
 * listed.
 */
static GNode	*VAR_ENV;	/* variables from the environment */
GNode		*VAR_GLOBAL;	/* variables from the makefile */
GNode		*VAR_CMD;	/* variables defined on the command-line */

Boolean		oldVars;	/* variable substitution style */
Boolean		checkEnvFirst;	/* -e flag */

#define	OPEN_PAREN		'('
#define	CLOSE_PAREN		')'
#define	OPEN_BRACE		'{'
#define	CLOSE_BRACE		'}'

/**
 * Create a Var object.
 *
 * Params:
 *	name		Name of variable (copied).
 *	value		Value of variable (copied) or NULL.
 *	flags		Flags set on variable.
 *
 * Returns:
 *	New variable.
 */
static Var *
VarCreate(const char name[], const char value[], int flags)
{
	Var *v;

	v = emalloc(sizeof(Var));
	v->name = estrdup(name);
	v->val = Buf_Init(0);
	v->flags = flags;

	if (value != NULL) {
		Buf_Append(v->val, value);
	}
	return (v);
}

/**
 * Destroy a Var object.
 *
 * Params:
 *	v	Object to destroy.
 *	f	True if internal buffer in Buffer object is to be removed.
 */
static void
VarDestroy(Var *v, Boolean f)
{

	Buf_Destroy(v->val, f);
	free(v->name);
	free(v);
}

/**
 * Remove the tail of the given word and place the result in the given
 * buffer.
 *
 * Results:
 *	TRUE if characters were added to the buffer (a space needs to be
 *	added to the buffer before the next word).
 *
 * Side Effects:
 *	The trimmed word is added to the buffer.
 */
static Boolean
VarHead(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
{
	char *slash;

	slash = strrchr(word, '/');
	if (slash != NULL) {
		if (addSpace) {
			Buf_AddByte(buf, (Byte)' ');
		}
		Buf_AppendRange(buf, word, slash);
	} else {
		/*
		 * If no directory part, give . (q.v. the POSIX standard)
		 */
		if (addSpace) {
			Buf_Append(buf, " .");
		} else {
			Buf_AddByte(buf, (Byte)'.');
		}
	}
	return (TRUE);
}

/**
 * Remove the head of the given word and place the result in the given
 * buffer.
 *
 * Results:
 *	TRUE if characters were added to the buffer (a space needs to be
 *	added to the buffer before the next word).
 *
 * Side Effects:
 *	The trimmed word is added to the buffer.
 */
static Boolean
VarTail(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
{
	const char *slash;

	if (addSpace) {
		Buf_AddByte (buf, (Byte)' ');
	}

	slash = strrchr(word, '/');
	if (slash != NULL) {
		slash++;
		Buf_Append(buf, slash);
	} else {
		Buf_Append(buf, word);
	}
	return (TRUE);
}

/**
 * Place the suffix of the given word in the given buffer.
 *
 * Results:
 *	TRUE if characters were added to the buffer (a space needs to be
 *	added to the buffer before the next word).
 *
 * Side Effects:
 *	The suffix from the word is placed in the buffer.
 */
static Boolean
VarSuffix(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
{
	const char *dot;

	dot = strrchr(word, '.');
	if (dot != NULL) {
		if (addSpace) {
			Buf_AddByte(buf, (Byte)' ');
		}
		dot++;
		Buf_Append(buf, dot);
		addSpace = TRUE;
	}
	return (addSpace);
}

/**
 * Remove the suffix of the given word and place the result in the
 * buffer.
 *
 * Results:
 *	TRUE if characters were added to the buffer (a space needs to be
 *	added to the buffer before the next word).
 *
 * Side Effects:
 *	The trimmed word is added to the buffer.
 */
static Boolean
VarRoot(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
{
	char *dot;

	if (addSpace) {
		Buf_AddByte(buf, (Byte)' ');
	}

	dot = strrchr(word, '.');
	if (dot != NULL) {
		Buf_AppendRange(buf, word, dot);
	} else {
		Buf_Append(buf, word);
	}
	return (TRUE);
}

/**
 * Place the word in the buffer if it matches the given pattern.
 * Callback function for VarModify to implement the :M modifier.
 * A space will be added if requested.  A pattern is supplied
 * which the word must match.
 *
 * Results:
 *	TRUE if a space should be placed in the buffer before the next
 *	word.
 *
 * Side Effects:
 *	The word may be copied to the buffer.
 */
static Boolean
VarMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
{

	if (Str_Match(word, pattern)) {
		if (addSpace) {
			Buf_AddByte(buf, (Byte)' ');
		}
		addSpace = TRUE;
		Buf_Append(buf, word);
	}
	return (addSpace);
}

#ifdef SYSVVARSUB
/**
 * Place the word in the buffer if it matches the given pattern.
 * Callback function for VarModify to implement the System V %
 * modifiers.  A space is added if requested.
 *
 * Results:
 *	TRUE if a space should be placed in the buffer before the next
 *	word.
 *
 * Side Effects:
 *	The word may be copied to the buffer.
 */
static Boolean
VarSYSVMatch(const char *word, Boolean addSpace, Buffer *buf, void *patp)
{
	int		len;
	const char	*ptr;
	VarPattern	*pat = (VarPattern *)patp;

	if (addSpace)
		Buf_AddByte(buf, (Byte)' ');

	addSpace = TRUE;

	if ((ptr = Str_SYSVMatch(word, Buf_Data(pat->lhs), &len)) != NULL)
		Str_SYSVSubst(buf, Buf_Data(pat->rhs), ptr, len);
	else
		Buf_Append(buf, word);

	return (addSpace);
}
#endif

/**
 * Place the word in the buffer if it doesn't match the given pattern.
 * Callback function for VarModify to implement the :N modifier.  A
 * space is added if requested.
 *
 * Results:
 *	TRUE if a space should be placed in the buffer before the next
 *	word.
 *
 * Side Effects:
 *	The word may be copied to the buffer.
 */
static Boolean
VarNoMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
{

	if (!Str_Match(word, pattern)) {
		if (addSpace) {
			Buf_AddByte(buf, (Byte)' ');
		}
		addSpace = TRUE;
		Buf_Append(buf, word);
	}
	return (addSpace);
}

/**
 * Perform a string-substitution on the given word, placing the
 * result in the passed buffer.  A space is added if requested.
 *
 * Results:
 *	TRUE if a space is needed before more characters are added.
 */
static Boolean
VarSubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
{
	size_t		wordLen;	/* Length of word */
	const char	*cp;		/* General pointer */
	VarPattern	*pattern = patternp;

	wordLen = strlen(word);
	if (1) { /* substitute in each word of the variable */
		/*
		 * Break substitution down into simple anchored cases
		 * and if none of them fits, perform the general substitution
		 * case.
		 */
		if ((pattern->flags & VAR_MATCH_START) &&
		   (strncmp(word, Buf_Data(pattern->lhs),
		    Buf_Size(pattern->lhs)) == 0)) {
			/*
			 * Anchored at start and beginning of word matches
			 * pattern.
			 */
			if ((pattern->flags & VAR_MATCH_END) &&
			    (wordLen == Buf_Size(pattern->lhs))) {
				/*
				 * Also anchored at end and matches to the end
				 * (word is same length as pattern) add space
				 * and rhs only if rhs is non-null.
				 */
				if (Buf_Size(pattern->rhs) != 0) {
					if (addSpace) {
						Buf_AddByte(buf, (Byte)' ');
					}
					addSpace = TRUE;
					Buf_AppendBuf(buf, pattern->rhs);
				}

			} else if (pattern->flags & VAR_MATCH_END) {
				/*
				 * Doesn't match to end -- copy word wholesale
				 */
				goto nosub;

			} else {
				/*
				 * Matches at start but need to copy in
				 * trailing characters.
				 */
				if ((Buf_Size(pattern->rhs) + wordLen -
				    Buf_Size(pattern->lhs)) != 0) {
					if (addSpace) {
						Buf_AddByte(buf, (Byte)' ');
					}
					addSpace = TRUE;
				}
				Buf_AppendBuf(buf, pattern->rhs);
				Buf_AddBytes(buf, wordLen -
				    Buf_Size(pattern->lhs),
				    (word + Buf_Size(pattern->lhs)));
			}

		} else if (pattern->flags & VAR_MATCH_START) {
			/*
			 * Had to match at start of word and didn't -- copy
			 * whole word.
			 */
			goto nosub;

		} else if (pattern->flags & VAR_MATCH_END) {
			/*
			 * Anchored at end, Find only place match could occur
			 * (leftLen characters from the end of the word) and
			 * see if it does. Note that because the $ will be
			 * left at the end of the lhs, we have to use strncmp.
			 */
			cp = word + (wordLen - Buf_Size(pattern->lhs));
			if ((cp >= word) && (strncmp(cp, Buf_Data(pattern->lhs),
			    Buf_Size(pattern->lhs)) == 0)) {
				/*
				 * Match found. If we will place characters in
				 * the buffer, add a space before hand as
				 * indicated by addSpace, then stuff in the
				 * initial, unmatched part of the word followed
				 * by the right-hand-side.
				 */
				if ((cp - word) + Buf_Size(pattern->rhs) != 0) {
					if (addSpace) {
						Buf_AddByte(buf, (Byte)' ');
					}
					addSpace = TRUE;
				}
				Buf_AppendRange(buf, word, cp);
				Buf_AppendBuf(buf, pattern->rhs);

			} else {
				/*
				 * Had to match at end and didn't. Copy entire
				 * word.
				 */
				goto nosub;
			}
		} else {
			/*
			 * Pattern is unanchored: search for the pattern in the
			 * word using strstr(3), copying unmatched portions and
			 * the right-hand-side for each match found, handling
			 * non-global substitutions correctly, etc. When the
			 * loop is done, any remaining part of the word (word
			 * and wordLen are adjusted accordingly through the
			 * loop) is copied straight into the buffer.
			 * addSpace is set FALSE as soon as a space is added
			 * to the buffer.
			 */
			Boolean done;
			size_t origSize;

			done = FALSE;
			origSize = Buf_Size(buf);
			while (!done) {
				cp = strstr(word, Buf_Data(pattern->lhs));
				if (cp != NULL) {
					if (addSpace && (((cp - word) +
					    Buf_Size(pattern->rhs)) != 0)) {
						Buf_AddByte(buf, (Byte)' ');
						addSpace = FALSE;
					}
					Buf_AppendRange(buf, word, cp);
					Buf_AppendBuf(buf, pattern->rhs);
					wordLen -= (cp - word) +
					    Buf_Size(pattern->lhs);
					word = cp + Buf_Size(pattern->lhs);
					if (wordLen == 0 || (pattern->flags &
					    VAR_SUB_GLOBAL) == 0) {
						done = TRUE;
					}
				} else {
					done = TRUE;
				}
			}
			if (wordLen != 0) {
				if (addSpace) {
					Buf_AddByte(buf, (Byte)' ');
				}
				Buf_AddBytes(buf, wordLen, (const Byte *)word);
			}

			/*
			 * If added characters to the buffer, need to add a
			 * space before we add any more. If we didn't add any,
			 * just return the previous value of addSpace.
			 */
			return ((Buf_Size(buf) != origSize) || addSpace);
		}
		/*
		 * Common code for anchored substitutions:
		 * addSpace was set TRUE if characters were added to the buffer.
		 */
		return (addSpace);
	}
  nosub:
	if (addSpace) {
		Buf_AddByte(buf, (Byte)' ');
	}
	Buf_AddBytes(buf, wordLen, (const Byte *)word);
	return (TRUE);
}

/**
 * Print the error caused by a regcomp or regexec call.
 *
 * Side Effects:
 *	An error gets printed.
 */
static void
VarREError(int err, regex_t *pat, const char *str)
{
	char   *errbuf;
	int     errlen;

	errlen = regerror(err, pat, 0, 0);
	errbuf = emalloc(errlen);
	regerror(err, pat, errbuf, errlen);
	Error("%s: %s", str, errbuf);
	free(errbuf);
}


/**
 * Perform a regex substitution on the given word, placing the
 * result in the passed buffer.  A space is added if requested.
 *
 * Results:
 *	TRUE if a space is needed before more characters are added.
 */
static Boolean
VarRESubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
{
	VarPattern	*pat;
	int		xrv;
	const char	*wp;
	char		*rp;
	int		added;
	int		flags = 0;

#define	MAYBE_ADD_SPACE()			\
	if (addSpace && !added)			\
		Buf_AddByte(buf, (Byte)' ');	\
	added = 1

	added = 0;
	wp = word;
	pat = patternp;

	if ((pat->flags & (VAR_SUB_ONE | VAR_SUB_MATCHED)) ==
	    (VAR_SUB_ONE | VAR_SUB_MATCHED)) {
		xrv = REG_NOMATCH;
	} else {
  tryagain:
		xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
	}

	switch (xrv) {
	  case 0:
		pat->flags |= VAR_SUB_MATCHED;
		if (pat->matches[0].rm_so > 0) {
			MAYBE_ADD_SPACE();
			Buf_AddBytes(buf, pat->matches[0].rm_so,
			    (const Byte *)wp);
		}

		for (rp = Buf_Data(pat->rhs); *rp; rp++) {
			if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
				MAYBE_ADD_SPACE();
				Buf_AddByte(buf, (Byte)rp[1]);
				rp++;

			} else if ((*rp == '&') ||
			    ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
				int	n;
				const char *subbuf;
				int	sublen;
				char	errstr[3];

				if (*rp == '&') {
					n = 0;
					errstr[0] = '&';
					errstr[1] = '\0';
				} else {
					n = rp[1] - '0';
					errstr[0] = '\\';
					errstr[1] = rp[1];
					errstr[2] = '\0';
					rp++;
				}

				if (n > pat->nsub) {
					Error("No subexpression %s",
					    &errstr[0]);
					subbuf = "";
					sublen = 0;

				} else if ((pat->matches[n].rm_so == -1) &&
				    (pat->matches[n].rm_eo == -1)) {
					Error("No match for subexpression %s",
					    &errstr[0]);
					subbuf = "";
					sublen = 0;

				} else {
					subbuf = wp + pat->matches[n].rm_so;
					sublen = pat->matches[n].rm_eo -
					    pat->matches[n].rm_so;
				}

				if (sublen > 0) {
					MAYBE_ADD_SPACE();
					Buf_AddBytes(buf, sublen,
					    (const Byte *)subbuf);
				}
			} else {
				MAYBE_ADD_SPACE();
				Buf_AddByte(buf, (Byte)*rp);
			}
		}
		wp += pat->matches[0].rm_eo;
		if (pat->flags & VAR_SUB_GLOBAL) {
			flags |= REG_NOTBOL;
			if (pat->matches[0].rm_so == 0 &&
			    pat->matches[0].rm_eo == 0) {
				MAYBE_ADD_SPACE();
				Buf_AddByte(buf, (Byte)*wp);
				wp++;
			}
			if (*wp)
				goto tryagain;
		}
		if (*wp) {
			MAYBE_ADD_SPACE();
			Buf_Append(buf, wp);
		}
		break;

	  default:
		VarREError(xrv, &pat->re, "Unexpected regex error");
		/* fall through */

	  case REG_NOMATCH:
		if (*wp) {
			MAYBE_ADD_SPACE();
			Buf_Append(buf, wp);
		}
		break;
	}
	return (addSpace || added);
}

/**
 * Find a variable in a variable list.
 */
static Var *
VarLookup(Lst *vlist, const char *name)
{
	LstNode	*ln;

	LST_FOREACH(ln, vlist)
		if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0)
			return (Lst_Datum(ln));
	return (NULL);
}

/**
 * Expand a variable name's embedded variables in the given context.
 *
 * Results:
 *	The contents of name, possibly expanded.
 */
static char *
VarPossiblyExpand(const char *name, GNode *ctxt)
{
	Buffer	*buf;

	if (strchr(name, '$') != NULL) {
		buf = Var_Subst(name, ctxt, 0);
		return (Buf_Peel(buf));
	} else {
		return estrdup(name);
	}
}

/**
 * If the variable name begins with a '.', it could very well be
 * one of the local ones.  We check the name against all the local
 * variables and substitute the short version in for 'name' if it
 * matches one of them.
 */
static const char *
VarLocal(const char name[])
{
	if (name[0] == '.') {
		switch (name[1]) {
		case 'A':
			if (!strcmp(name, ".ALLSRC"))
				return (ALLSRC);
			if (!strcmp(name, ".ARCHIVE"))
				return (ARCHIVE);
			break;
		case 'I':
			if (!strcmp(name, ".IMPSRC"))
				return (IMPSRC);
			break;
		case 'M':
			if (!strcmp(name, ".MEMBER"))
				return (MEMBER);
			break;
		case 'O':
			if (!strcmp(name, ".OODATE"))
				return (OODATE);
			break;
		case 'P':
			if (!strcmp(name, ".PREFIX"))
				return (PREFIX);
			break;
		case 'T':
			if (!strcmp(name, ".TARGET"))
				return (TARGET);
			break;
		default:
			break;
		}
	}
	return (name);
}

/**
 * Find the given variable in the given context and the environment.
 *
 * Results:
 *	A pointer to the structure describing the desired variable or
 *	NULL if the variable does not exist.
 */
static Var *
VarFindEnv(const char name[], GNode *ctxt)
{
	Var	*var;

	name = VarLocal(name);

	if ((var = VarLookup(&ctxt->context, name)) != NULL)
		return (var);

	if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
		return (var);

	return (NULL);
}

/**
 * Look for the variable in the given context.
 */
static Var *
VarFindOnly(const char name[], GNode *ctxt)
{
	Var	*var;

	name = VarLocal(name);

	if ((var = VarLookup(&ctxt->context, name)) != NULL)
		return (var);

	return (NULL);
}

/**
 * Look for the variable in all contexts.
 */
static Var *
VarFindAny(const char name[], GNode *ctxt)
{
	Boolean	localCheckEnvFirst;
	LstNode	*ln;
	Var	*var;

	name = VarLocal(name);

	/*
	 * Note whether this is one of the specific variables we were told
	 * through the -E flag to use environment-variable-override for.
	 */
	localCheckEnvFirst = FALSE;
	LST_FOREACH(ln, &envFirstVars) {
		if (strcmp(Lst_Datum(ln), name) == 0) {
			localCheckEnvFirst = TRUE;
			break;
		}
	}

	/*
	 * First look for the variable in the given context. If it's not there,
	 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
	 * in that order, depending on the FIND_* flags in 'flags'
	 */
	if ((var = VarLookup(&ctxt->context, name)) != NULL)
		return (var);

	/* not there - try command line context */
	if (ctxt != VAR_CMD) {
		if ((var = VarLookup(&VAR_CMD->context, name)) != NULL)
			return (var);
	}

	/* not there - try global context, but only if not -e/-E */
	if (ctxt != VAR_GLOBAL && (!checkEnvFirst && !localCheckEnvFirst)) {
		if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
			return (var);
	}

	if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
		return (var);

	/* deferred check for the environment (in case of -e/-E) */
	if ((ctxt != VAR_GLOBAL) && (checkEnvFirst || localCheckEnvFirst)) {
		if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
			return (var);
	}

	return (NULL);
}

/**
 * Add a new variable of name name and value val to the given context.
 *
 * Side Effects:
 *	The new variable is placed at the front of the given context
 *	The name and val arguments are duplicated so they may
 *	safely be freed.
 */
static Var *
VarAdd(const char *name, const char *val, GNode *ctxt)
{
	Var *v;

	Lst_AtFront(&ctxt->context, v = VarCreate(name, val, 0));
	DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
	return (v);
}

/**
 * Remove a variable from a context.
 *
 * Side Effects:
 *	The Var structure is removed and freed.
 */
void
Var_Delete(const char *name, GNode *ctxt)
{
	LstNode *ln;

	DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
	LST_FOREACH(ln, &ctxt->context) {
		if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0) {
			VarDestroy(Lst_Datum(ln), TRUE);
			Lst_Remove(&ctxt->context, ln);
			break;
		}
	}
}

/**
 * Set the variable name to the value val in the given context.
 *
 * Side Effects:
 *	If the variable doesn't yet exist, a new record is created for it.
 *	Else the old value is freed and the new one stuck in its place
 *
 * Notes:
 *	The variable is searched for only in its context before being
 *	created in that context. I.e. if the context is VAR_GLOBAL,
 *	only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
 *	VAR_CMD->context is searched. This is done to avoid the literally
 *	thousands of unnecessary strcmp's that used to be done to
 *	set, say, $(@) or $(<).
 */
void
Var_Set(const char *name, const char *val, GNode *ctxt)
{
	Var    *v;
	char   *n;

	/*
	 * We only look for a variable in the given context since anything
	 * set here will override anything in a lower context, so there's not
	 * much point in searching them all just to save a bit of memory...
	 */
	n = VarPossiblyExpand(name, ctxt);
	v = VarFindOnly(n, ctxt);
	if (v == NULL) {
		v = VarAdd(n, val, ctxt);
	} else {
		Buf_Clear(v->val);
		Buf_Append(v->val, val);
		DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
	}

	if (ctxt == VAR_CMD || (v->flags & VAR_TO_ENV)) {
		/*
		 * Any variables given on the command line
		 * are automatically exported to the
		 * environment (as per POSIX standard)
		 */
		setenv(n, val, 1);
	}

	free(n);
}

/**
 * Set the a global name variable to the value.
 */
void
Var_SetGlobal(const char name[], const char value[])
{

	Var_Set(name, value, VAR_GLOBAL);
}


/**
 * Set the VAR_TO_ENV flag on a variable
 */
void
Var_SetEnv(const char *name, GNode *ctxt)
{
	Var    *v;

	v = VarFindOnly(name, VAR_CMD);
	if (v != NULL) {
		/*
		 * Do not allow .EXPORT: to be set on variables
		 * from the comand line or MAKEFLAGS.
		 */
		Error(
		    "Warning: Did not set .EXPORTVAR: on %s because it "
		    "is from the comand line or MAKEFLAGS", name);
		return;
	}

	v = VarFindAny(name, ctxt);
	if (v == NULL) {
		Lst_AtFront(&VAR_ENV->context,
		    VarCreate(name, NULL, VAR_TO_ENV));
		setenv(name, "", 1);
		Error("Warning: .EXPORTVAR: set on undefined variable %s", name);
	} else {
		if ((v->flags & VAR_TO_ENV) == 0) {
			v->flags |= VAR_TO_ENV;
			setenv(v->name, Buf_Data(v->val), 1);
		}
	}
}

/**
 * The variable of the given name has the given value appended to it in
 * the given context.
 *
 * Side Effects:
 *	If the variable doesn't exist, it is created. Else the strings
 *	are concatenated (with a space in between).
 *
 * Notes:
 *	Only if the variable is being sought in the global context is the
 *	environment searched.
 *	XXX: Knows its calling circumstances in that if called with ctxt
 *	an actual target, it will only search that context since only
 *	a local variable could be being appended to. This is actually
 *	a big win and must be tolerated.
 */
void
Var_Append(const char *name, const char *val, GNode *ctxt)
{
	Var	*v;
	char	*n;

	n = VarPossiblyExpand(name, ctxt);
	if (ctxt == VAR_GLOBAL) {
		v = VarFindEnv(n, ctxt);
	} else {
		v = VarFindOnly(n, ctxt);
	}
	if (v == NULL) {
		VarAdd(n, val, ctxt);
	} else {
		Buf_AddByte(v->val, (Byte)' ');
		Buf_Append(v->val, val);
		DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
	}
	free(n);
}

/**
 * See if the given variable exists.
 *
 * Results:
 *	TRUE if it does, FALSE if it doesn't
 */
Boolean
Var_Exists(const char *name, GNode *ctxt)
{
	Var	*v;
	char	*n;

	n = VarPossiblyExpand(name, ctxt);
	v = VarFindAny(n, ctxt);
	if (v == NULL) {
		free(n);
		return (FALSE);
	} else {
		free(n);
		return (TRUE);
	}
}

/**
 * Return the value of the named variable in the given context
 *
 * Results:
 *	The value if the variable exists, NULL if it doesn't.
 */
const char *
Var_Value(const char name[], GNode *ctxt)
{
	Var	*v;
	char	*n;

	n = VarPossiblyExpand(name, ctxt);
	v = VarFindAny(n, ctxt);
	free(n);
	if (v == NULL) {
		return (NULL);
	} else {
		return (Buf_Data(v->val));
	}
}

/**
 * Modify each of the words of the passed string using the given
 * function. Used to implement all modifiers.
 *
 * Results:
 *	A string of all the words modified appropriately.
 *
 * Side Effects:
 *	Uses brk_string() so it invalidates any previous call to
 *	brk_string().
 */
static char *
VarModify(const char *str, VarModifyProc *modProc, void *datum)
{
	ArgArray	aa;
	Buffer		*buf;		/* Buffer for the new string */
	int		i;
	Boolean		addSpace;	/*
					 * TRUE if need to add a space to
					 * the buffer before adding the
					 * trimmed word
					 */

	brk_string(&aa, str, FALSE);

	addSpace = FALSE;
	buf = Buf_Init(0);
	for (i = 1; i < aa.argc; i++)
		addSpace = (*modProc)(aa.argv[i], addSpace, buf, datum);

	ArgArray_Done(&aa);
	return (Buf_Peel(buf));
}

/**
 * Sort the words in the string.
 *
 * Input:
 *	str		String whose words should be sorted
 *	cmp		A comparison function to control the ordering
 *
 * Results:
 *	A string containing the words sorted
 */
static char *
VarSortWords(const char *str, int (*cmp)(const void *, const void *))
{
	ArgArray	aa;
	Buffer		*buf;
	int		i;

	brk_string(&aa, str, FALSE);
	qsort(aa.argv + 1, aa.argc - 1, sizeof(char *), cmp);

	buf = Buf_Init(0);
	for (i = 1; i < aa.argc; i++) {
		Buf_Append(buf, aa.argv[i]);
		Buf_AddByte(buf, (Byte)((i < aa.argc - 1) ? ' ' : '\0'));
	}

	ArgArray_Done(&aa);
	return (Buf_Peel(buf));
}

static int
SortIncreasing(const void *l, const void *r)
{

	return (strcmp(*(const char* const*)l, *(const char* const*)r));
}

/**
 * Remove adjacent duplicate words.
 *
 * Results:
 *	A string containing the resulting words.
 */
static char *
VarUniq(const char *str)
{
	ArgArray	aa;
	Buffer		*buf;		    /* Buffer for new string */
	int		i, j;

	buf = Buf_Init(0);
	brk_string(&aa, str, FALSE);

	if (aa.argc > 2) {
		for (j = 1, i = 2; i < aa.argc; i++) {
			if (strcmp(aa.argv[i], aa.argv[j]) != 0 && (++j != i))
				aa.argv[j] = aa.argv[i];
		}
		aa.argc = j + 1;
	}

	for (i = 1; i < aa.argc; i++) {
		Buf_AddBytes(buf, strlen(aa.argv[i]), (Byte *)aa.argv[i]);
		if (i != aa.argc - 1)
			Buf_AddByte(buf, ' ');
	}
	Buf_AddByte(buf, '\0');

	ArgArray_Done(&aa);
	return (Buf_Peel(buf));
}

/**
 * Pass through the tstr looking for 1) escaped delimiters,
 * '$'s and backslashes (place the escaped character in
 * uninterpreted) and 2) unescaped $'s that aren't before
 * the delimiter (expand the variable substitution).
 * Return the expanded string or NULL if the delimiter was missing
 * If pattern is specified, handle escaped ampersands, and replace
 * unescaped ampersands with the lhs of the pattern.
 *
 * Results:
 *	A string of all the words modified appropriately.
 *	If length is specified, return the string length of the buffer
 *	If flags is specified and the last character of the pattern is a
 *	$ set the VAR_MATCH_END bit of flags.
 */
static Buffer *
VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
{
	Buffer		*buf;

	buf = Buf_Init(0);

	/*
	 * Skim through until the matching delimiter is found; pick up
	 * variable substitutions on the way. Also allow backslashes to quote
	 * the delimiter, $, and \, but don't touch other backslashes.
	 */
	while (*vp->ptr != '\0') {
		if (*vp->ptr == delim) {
			return (buf);

		} else if ((vp->ptr[0] == '\\') &&
		    ((vp->ptr[1] == delim) ||
		     (vp->ptr[1] == '\\') ||
		     (vp->ptr[1] == '$') ||
		     (vp->ptr[1] == '&' && patt != NULL))) {
			vp->ptr++;		/* consume backslash */
			Buf_AddByte(buf, (Byte)vp->ptr[0]);
			vp->ptr++;

		} else if (vp->ptr[0] == '$') {
			if (vp->ptr[1] == delim) {
				if (flags == NULL) {
					Buf_AddByte(buf, (Byte)vp->ptr[0]);
					vp->ptr++;
				} else {
					/*
					 * Unescaped $ at end of patt =>
					 * anchor patt at end.
					 */
					*flags |= VAR_MATCH_END;
					vp->ptr++;
				}
			} else {
				VarParser	subvp = {
					vp->ptr,
					vp->ptr,
					vp->ctxt,
					vp->err,
					vp->execute
				};
				char   *rval;
				Boolean rfree;

				/*
				 * If unescaped dollar sign not
				 * before the delimiter, assume it's
				 * a variable substitution and
				 * recurse.
				 */
				rval = VarParse(&subvp, &rfree);
				Buf_Append(buf, rval);
				if (rfree)
					free(rval);
				vp->ptr = subvp.ptr;
			}
		} else if (vp->ptr[0] == '&' && patt != NULL) {
			Buf_AppendBuf(buf, patt->lhs);
			vp->ptr++;
		} else {
			Buf_AddByte(buf, (Byte)vp->ptr[0]);
			vp->ptr++;
		}
	}

	Buf_Destroy(buf, TRUE);
	return (NULL);
}

/**
 * Make sure this variable is fully expanded.
 */
static char *
VarExpand(Var *v, VarParser *vp)
{
	char	*value;
	char	*result;

	if (v->flags & VAR_IN_USE) {
		Fatal("Variable %s is recursive.", v->name);
		/* NOTREACHED */
	}

	v->flags |= VAR_IN_USE;

	/*
	 * Before doing any modification, we have to make sure the
	 * value has been fully expanded. If it looks like recursion
	 * might be necessary (there's a dollar sign somewhere in the
	 * variable's value) we just call Var_Subst to do any other
	 * substitutions that are necessary. Note that the value
	 * returned by Var_Subst will have been
	 * dynamically-allocated, so it will need freeing when we
	 * return.
	 */
	value = Buf_Data(v->val);
	if (strchr(value, '$') == NULL) {
		result = strdup(value);
	} else {
		Buffer	*buf;

		buf = Var_Subst(value, vp->ctxt, vp->err);
		result = Buf_Peel(buf);
	}

	v->flags &= ~VAR_IN_USE;

	return (result);
}

/**
 * Select only those words in value that match the modifier.
 */
static char *
modifier_M(VarParser *vp, const char value[], char endc)
{
	char	*patt;
	char	*ptr;
	char	*newValue;
	char	modifier;

	modifier = vp->ptr[0];
	vp->ptr++;	/* consume 'M' or 'N' */

	/*
	 * Compress the \:'s out of the pattern, so allocate enough
	 * room to hold the uncompressed pattern and compress the
	 * pattern into that space.
	 */
	patt = estrdup(vp->ptr);
	ptr = patt;
	while (vp->ptr[0] != '\0') {
		if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
			break;
		}
		if (vp->ptr[0] == '\\' &&
		    (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
			vp->ptr++;	/* consume backslash */
		}
		*ptr = vp->ptr[0];
		ptr++;
		vp->ptr++;
	}
	*ptr = '\0';

	if (modifier == 'M') {
		newValue = VarModify(value, VarMatch, patt);
	} else {
		newValue = VarModify(value, VarNoMatch, patt);
	}
	free(patt);

	return (newValue);
}

/**
 * Substitute the replacement string for the pattern.  The substitution
 * is applied to each word in value.
 */
static char *
modifier_S(VarParser *vp, const char value[], Var *v)
{
	VarPattern	patt;
	char		delim;
	char		*newValue;

	patt.flags = 0;

	vp->ptr++;		/* consume 'S' */

	delim = *vp->ptr;	/* used to find end of pattern */
	vp->ptr++;		/* consume 1st delim */

	/*
	 * If pattern begins with '^', it is anchored to the start of the
	 * word -- skip over it and flag pattern.
	 */
	if (*vp->ptr == '^') {
		patt.flags |= VAR_MATCH_START;
		vp->ptr++;
	}

	patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
	if (patt.lhs == NULL) {
		/*
		 * LHS didn't end with the delim, complain and exit.
		 */
		Fatal("Unclosed substitution for %s (%c missing)",
		    v->name, delim);
	}

	vp->ptr++;	/* consume 2nd delim */

	patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
	if (patt.rhs == NULL) {
		/*
		 * RHS didn't end with the delim, complain and exit.
		 */
		Fatal("Unclosed substitution for %s (%c missing)",
		    v->name, delim);
	}

	vp->ptr++;	/* consume last delim */

	/*
	 * Check for global substitution. If 'g' after the final delimiter,
	 * substitution is global and is marked that way.
	 */
	if (vp->ptr[0] == 'g') {
		patt.flags |= VAR_SUB_GLOBAL;
		vp->ptr++;
	}

	/*
	 * Global substitution of the empty string causes an infinite number
	 * of matches, unless anchored by '^' (start of string) or '$' (end
	 * of string). Catch the infinite substitution here. Note that flags
	 * can only contain the 3 bits we're interested in so we don't have
	 * to mask unrelated bits. We can test for equality.
	 */
	if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
		Fatal("Global substitution of the empty string");

	newValue = VarModify(value, VarSubstitute, &patt);

	/*
	 * Free the two strings.
	 */
	free(patt.lhs);
	free(patt.rhs);

	return (newValue);
}

static char *
modifier_C(VarParser *vp, char value[], Var *v)
{
	VarPattern	patt;
	char		delim;
	int		error;
	char		*newValue;

	patt.flags = 0;

	vp->ptr++;		/* consume 'C' */

	delim = *vp->ptr;	/* delimiter between sections */

	vp->ptr++;		/* consume 1st delim */

	patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
	if (patt.lhs == NULL) {
		Fatal("Unclosed substitution for %s (%c missing)",
		     v->name, delim);
	}

	vp->ptr++;		/* consume 2st delim */

	patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
	if (patt.rhs == NULL) {
		Fatal("Unclosed substitution for %s (%c missing)",
		     v->name, delim);
	}

	vp->ptr++;		/* consume last delim */

	switch (*vp->ptr) {
	case 'g':
		patt.flags |= VAR_SUB_GLOBAL;
		vp->ptr++;		/* consume 'g' */
		break;
	case '1':
		patt.flags |= VAR_SUB_ONE;
		vp->ptr++;		/* consume '1' */
		break;
	default:
		break;
	}

	error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
	if (error) {
		VarREError(error, &patt.re, "RE substitution error");
		free(patt.rhs);
		free(patt.lhs);
		return (var_Error);
	}

	patt.nsub = patt.re.re_nsub + 1;
	if (patt.nsub < 1)
		patt.nsub = 1;
	if (patt.nsub > 10)
		patt.nsub = 10;
	patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));

	newValue = VarModify(value, VarRESubstitute, &patt);

	regfree(&patt.re);
	free(patt.matches);
	free(patt.rhs);
	free(patt.lhs);

	return (newValue);
}

static char *
sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
{
#ifdef SYSVVARSUB
	/*
	 * This can either be a bogus modifier or a System-V substitution
	 * command.
	 */
	char		endc;
	VarPattern	patt;
	Boolean		eqFound;
	int		cnt;
	char		*newStr;
	const char	*cp;

	endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;

	patt.flags = 0;

	/*
	 * First we make a pass through the string trying to verify it is a
	 * SYSV-make-style translation: it must be: <string1>=<string2>)
	 */
	eqFound = FALSE;
	cp = vp->ptr;
	cnt = 1;
	while (*cp != '\0' && cnt) {
		if (*cp == '=') {
			eqFound = TRUE;
			/* continue looking for endc */
		} else if (*cp == endc)
			cnt--;
		else if (*cp == startc)
			cnt++;
		if (cnt)
			cp++;
	}

	if (*cp == endc && eqFound) {
		/*
		 * Now we break this sucker into the lhs and rhs.
		 */
		patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
		if (patt.lhs == NULL) {
			Fatal("Unclosed substitution for %s (%c missing)",
			      v->name, '=');
		}
		vp->ptr++;	/* consume '=' */

		patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
		if (patt.rhs == NULL) {
			Fatal("Unclosed substitution for %s (%c missing)",
			      v->name, endc);
		}

		/*
		 * SYSV modifications happen through the whole string. Note
		 * the pattern is anchored at the end.
		 */
		newStr = VarModify(value, VarSYSVMatch, &patt);

		free(patt.lhs);
		free(patt.rhs);
	} else
#endif
	{
		Error("Unknown modifier '%c'\n", *vp->ptr);
		vp->ptr++;
		while (*vp->ptr != '\0') {
			if (*vp->ptr == endc && *vp->ptr == ':') {
				break;
			}
			vp->ptr++;
		}
		newStr = var_Error;
	}

	return (newStr);
}

/**
 * Quote shell meta-characters in the string
 *
 * Results:
 *	The quoted string
 */
static char *
Var_Quote(const char *str)
{
	Buffer *buf;
	/* This should cover most shells :-( */
	static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";

	buf = Buf_Init(MAKE_BSIZE);
	for (; *str; str++) {
		if (strchr(meta, *str) != NULL)
			Buf_AddByte(buf, (Byte)'\\');
		Buf_AddByte(buf, (Byte)*str);
	}

	return (Buf_Peel(buf));
}


/*
 * Now we need to apply any modifiers the user wants applied.
 * These are:
 *	:M<pattern>
 *		words which match the given <pattern>.
 *		<pattern> is of the standard file
 *		wildcarding form.
 *	:N<pattern>
 *		words which do not match the given <pattern>
 *		<pattern> is of the standard file
 *		wildcarding form.
 *	:S<d><pat1><d><pat2><d>[g]
 *		Substitute <pat2> for <pat1> in the value
 *	:C<d><pat1><d><pat2><d>[g]
 *		Substitute <pat2> for regex <pat1> in the value
 *	:H	Substitute the head of each word
 *	:T	Substitute the tail of each word
 *	:E	Substitute the extension (minus '.') of
 *		each word
 *	:R	Substitute the root of each word
 *		(pathname minus the suffix).
 *	:lhs=rhs
 *		Like :S, but the rhs goes to the end of
 *		the invocation.
 *	:U	Converts variable to upper-case.
 *	:L	Converts variable to lower-case.
 *	:O	("Order") Alphabeticaly sort words in variable.
 *	:u	("uniq") Remove adjacent duplicate words.
 */
static char *
ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
{
	char	*value;
	char	endc;

	value = VarExpand(v, vp);
	*freeResult = TRUE;

	endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;

	vp->ptr++;	/* consume first colon */

	while (*vp->ptr != '\0') {
		char	*newStr;	/* New value to return */

		if (*vp->ptr == endc) {
			return (value);
		}

		DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
		switch (*vp->ptr) {
		case 'N':
		case 'M':
			newStr = modifier_M(vp, value, endc);
			break;
		case 'S':
			newStr = modifier_S(vp, value, v);
			break;
		case 'C':
			newStr = modifier_C(vp, value, v);
			break;
		case 't':
			/* :tl :tu for OSF ODE & NetBSD make compatibility */
			switch (vp->ptr[1]) {
			case 'l':
				vp->ptr++;
				goto mod_lower;
				break;
			case 'u':
				vp->ptr++;
				goto mod_upper;
				break;
			}
			/* FALLTHROUGH */
		default:
			if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
#ifdef SUNSHCMD
				if ((vp->ptr[0] == 's') &&
				    (vp->ptr[1] == 'h') &&
				    (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
					const char	*error = NULL;

					if (vp->execute) {
						newStr = Buf_Peel(
						    Cmd_Exec(value, &error));
					} else {
						newStr = estrdup("");
					}

					if (error)
						Error(error, value);
					vp->ptr += 2;
				} else
#endif
				{
					newStr = sysVvarsub(vp, startc, v, value);
				}
				break;
			}

			switch (vp->ptr[0]) {
			case 'L':
			mod_lower:
				{
				const char	*cp;
				Buffer		*buf;
				buf = Buf_Init(MAKE_BSIZE);
				for (cp = value; *cp; cp++)
					Buf_AddByte(buf, (Byte)tolower(*cp));

				newStr = Buf_Peel(buf);

				vp->ptr++;
				break;
				}
			case 'O':
				newStr = VarSortWords(value, SortIncreasing);
				vp->ptr++;
				break;
			case 'Q':
				newStr = Var_Quote(value);
				vp->ptr++;
				break;
			case 'T':
				newStr = VarModify(value, VarTail, NULL);
				vp->ptr++;
				break;
			case 'U':
			mod_upper:
				{
				const char	*cp;
				Buffer		*buf;
				buf = Buf_Init(MAKE_BSIZE);
				for (cp = value; *cp; cp++)
					Buf_AddByte(buf, (Byte)toupper(*cp));

				newStr = Buf_Peel(buf);

				vp->ptr++;
				break;
				}
			case 'H':
				newStr = VarModify(value, VarHead, NULL);
				vp->ptr++;
				break;
			case 'E':
				newStr = VarModify(value, VarSuffix, NULL);
				vp->ptr++;
				break;
			case 'R':
				newStr = VarModify(value, VarRoot, NULL);
				vp->ptr++;
				break;
			case 'u':
				newStr = VarUniq(value);
				vp->ptr++;
				break;
			default:
				newStr = sysVvarsub(vp, startc, v, value);
				break;
			}
			break;
		}

		DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
		if (*freeResult) {
			free(value);
		}

		value = newStr;
		*freeResult = (value == var_Error) ? FALSE : TRUE;

		if (vp->ptr[0] == ':') {
			vp->ptr++;	/* consume colon */
		}
	}

	return (value);
}

static char *
ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
{
	const char	*vname;
	size_t		vlen;
	Var		*v;
	char		*value;

	vname = Buf_GetAll(buf, &vlen);

	v = VarFindAny(vname, vp->ctxt);
	if (v != NULL) {
		value = ParseModifier(vp, startc, v, freeResult);
		return (value);
	}

	if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
		size_t  consumed;
		/*
		 * Still need to get to the end of the variable
		 * specification, so kludge up a Var structure for the
		 * modifications
		 */
		v = VarCreate(vname, NULL, VAR_JUNK);
		value = ParseModifier(vp, startc, v, freeResult);
		if (*freeResult) {
			free(value);
		}
		VarDestroy(v, TRUE);

		consumed = vp->ptr - vp->input + 1;
		/*
		 * If substituting a local variable in a non-local context,
		 * assume it's for dynamic source stuff. We have to handle
		 * this specially and return the longhand for the variable
		 * with the dollar sign escaped so it makes it back to the
		 * caller. Only four of the local variables are treated
		 * specially as they are the only four that will be set when
		 * dynamic sources are expanded.
		 */
		if (vlen == 1 ||
		    (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
			if (strchr("!%*@", vname[0]) != NULL) {
				value = emalloc(consumed + 1);
				strncpy(value, vp->input, consumed);
				value[consumed] = '\0';

				*freeResult = TRUE;
				return (value);
			}
		}
		if (vlen > 2 &&
		    vname[0] == '.' &&
		    isupper((unsigned char)vname[1])) {
			if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
			    (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
			    (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
			    (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
				value = emalloc(consumed + 1);
				strncpy(value, vp->input, consumed);
				value[consumed] = '\0';

				*freeResult = TRUE;
				return (value);
			}
		}

		*freeResult = FALSE;
		return (vp->err ? var_Error : varNoError);
	} else {
		/*
		 * Check for D and F forms of local variables since we're in
		 * a local context and the name is the right length.
		 */
		if (vlen == 2 &&
		    (vname[1] == 'F' || vname[1] == 'D') &&
		    (strchr("!%*<>@", vname[0]) != NULL)) {
			char	name[2];

			name[0] = vname[0];
			name[1] = '\0';

			v = VarFindOnly(name, vp->ctxt);
			if (v != NULL) {
				value = ParseModifier(vp, startc, v, freeResult);
				return (value);
			}
		}

		/*
		 * Still need to get to the end of the variable
		 * specification, so kludge up a Var structure for the
		 * modifications
		 */
		v = VarCreate(vname, NULL, VAR_JUNK);
		value = ParseModifier(vp, startc, v, freeResult);
		if (*freeResult) {
			free(value);
		}
		VarDestroy(v, TRUE);

		*freeResult = FALSE;
		return (vp->err ? var_Error : varNoError);
	}
}

static char *
ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
{
	const char	*vname;
	size_t		vlen;
	Var		*v;
	char		*value;

	vname = Buf_GetAll(buf, &vlen);

	v = VarFindAny(vname, vp->ctxt);
	if (v != NULL) {
		value = VarExpand(v, vp);
		*freeResult = TRUE;
		return (value);
	}

	if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
		size_t	consumed = vp->ptr - vp->input + 1;

		/*
		 * If substituting a local variable in a non-local context,
		 * assume it's for dynamic source stuff. We have to handle
		 * this specially and return the longhand for the variable
		 * with the dollar sign escaped so it makes it back to the
		 * caller. Only four of the local variables are treated
		 * specially as they are the only four that will be set when
		 * dynamic sources are expanded.
		 */
		if (vlen == 1 ||
		    (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
			if (strchr("!%*@", vname[0]) != NULL) {
				value = emalloc(consumed + 1);
				strncpy(value, vp->input, consumed);
				value[consumed] = '\0';

				*freeResult = TRUE;
				return (value);
			}
		}
		if (vlen > 2 &&
		    vname[0] == '.' &&
		    isupper((unsigned char)vname[1])) {
			if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
			    (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
			    (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
			    (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
				value = emalloc(consumed + 1);
				strncpy(value, vp->input, consumed);
				value[consumed] = '\0';

				*freeResult = TRUE;
				return (value);
			}
		}
	} else {
		/*
		 * Check for D and F forms of local variables since we're in
		 * a local context and the name is the right length.
		 */
		if (vlen == 2 &&
		    (vname[1] == 'F' || vname[1] == 'D') &&
		    (strchr("!%*<>@", vname[0]) != NULL)) {
			char	name[2];

			name[0] = vname[0];
			name[1] = '\0';

			v = VarFindOnly(name, vp->ctxt);
			if (v != NULL) {
				char	*val;
				/*
				 * No need for nested expansion or anything,
				 * as we're the only one who sets these
				 * things and we sure don't put nested
				 * invocations in them...
				 */
				val = Buf_Data(v->val);

				if (vname[1] == 'D') {
					val = VarModify(val, VarHead, NULL);
				} else {
					val = VarModify(val, VarTail, NULL);
				}

				*freeResult = TRUE;
				return (val);
			}
		}
	}

	*freeResult = FALSE;
	return (vp->err ? var_Error : varNoError);
}

/**
 * Parse a multi letter variable name, and return it's value.
 */
static char *
VarParseLong(VarParser *vp, Boolean *freeResult)
{
	Buffer		*buf;
	char		startc;
	char		endc;
	char		*value;

	buf = Buf_Init(MAKE_BSIZE);

	startc = vp->ptr[0];
	vp->ptr++;		/* consume opening paren or brace */

	endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;

	/*
	 * Process characters until we reach an end character or a colon,
	 * replacing embedded variables as we go.
	 */
	while (*vp->ptr != '\0') {
		if (*vp->ptr == endc) {
			value = ParseRestEnd(vp, buf, freeResult);
			vp->ptr++;	/* consume closing paren or brace */
			Buf_Destroy(buf, TRUE);
			return (value);

		} else if (*vp->ptr == ':') {
			value = ParseRestModifier(vp, startc, buf, freeResult);
			vp->ptr++;	/* consume closing paren or brace */
			Buf_Destroy(buf, TRUE);
			return (value);

		} else if (*vp->ptr == '$') {
			VarParser	subvp = {
				vp->ptr,
				vp->ptr,
				vp->ctxt,
				vp->err,
				vp->execute
			};
			char	*rval;
			Boolean	rfree;

			rval = VarParse(&subvp, &rfree);
			if (rval == var_Error) {
				Fatal("Error expanding embedded variable.");
			}
			Buf_Append(buf, rval);
			if (rfree)
				free(rval);
			vp->ptr = subvp.ptr;
		} else {
			Buf_AddByte(buf, (Byte)*vp->ptr);
			vp->ptr++;
		}
	}

	/* If we did not find the end character, return var_Error */
	Buf_Destroy(buf, TRUE);
	*freeResult = FALSE;
	return (var_Error);
}

/**
 * Parse a single letter variable name, and return it's value.
 */
static char *
VarParseShort(VarParser *vp, Boolean *freeResult)
{
	char	vname[2];
	Var	*v;
	char	*value;

	vname[0] = vp->ptr[0];
	vname[1] = '\0';

	vp->ptr++;	/* consume single letter */

	v = VarFindAny(vname, vp->ctxt);
	if (v != NULL) {
		value = VarExpand(v, vp);
		*freeResult = TRUE;
		return (value);
	}

	/*
	 * If substituting a local variable in a non-local context, assume
	 * it's for dynamic source stuff. We have to handle this specially
	 * and return the longhand for the variable with the dollar sign
	 * escaped so it makes it back to the caller. Only four of the local
	 * variables are treated specially as they are the only four that
	 * will be set when dynamic sources are expanded.
	 */
	if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {

		/* XXX: It looks like $% and $! are reversed here */
		switch (vname[0]) {
		case '@':
			*freeResult = TRUE;
			return (estrdup("$(.TARGET)"));
		case '%':
			*freeResult = TRUE;
			return (estrdup("$(.ARCHIVE)"));
		case '*':
			*freeResult = TRUE;
			return (estrdup("$(.PREFIX)"));
		case '!':
			*freeResult = TRUE;
			return (estrdup("$(.MEMBER)"));
		default:
			*freeResult = FALSE;
			return (vp->err ? var_Error : varNoError);
		}
	}

	/* Variable name was not found. */
	*freeResult = FALSE;
	return (vp->err ? var_Error : varNoError);
}

static char *
VarParse(VarParser *vp, Boolean *freeResult)
{

	vp->ptr++;	/* consume '$' or last letter of conditional */

	if (vp->ptr[0] == '\0') {
		/* Error, there is only a dollar sign in the input string. */
		*freeResult = FALSE;
		return (vp->err ? var_Error : varNoError);

	} else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
		/* multi letter variable name */
		return (VarParseLong(vp, freeResult));

	} else {
		/* single letter variable name */
		return (VarParseShort(vp, freeResult));
	}
}

/**
 * Given the start of a variable invocation, extract the variable
 * name and find its value, then modify it according to the
 * specification.
 *
 * Results:
 *	The value of the variable or var_Error if the specification
 *	is invalid.  The number of characters in the specification
 *	is placed in the variable pointed to by consumed.  (for
 *	invalid specifications, this is just 2 to skip the '$' and
 *	the following letter, or 1 if '$' was the last character
 *	in the string).  A Boolean in *freeResult telling whether the
 *	returned string should be freed by the caller.
 */
char *
Var_Parse(const char input[], GNode *ctxt, Boolean err,
	size_t *consumed, Boolean *freeResult)
{
	VarParser	vp = {
		input,
		input,
		ctxt,
		err,
		TRUE
	};
	char		*value;

	value = VarParse(&vp, freeResult);
	*consumed += vp.ptr - vp.input;
	return (value);
}

/*
 * Given the start of a variable invocation, determine the length
 * of the specification.
 *
 * Results:
 *	The number of characters in the specification.  For invalid
 *	specifications, this is just 2 to skip the '$' and the
 *	following letter, or 1 if '$' was the last character in the
 *	string.
 */
size_t
Var_Match(const char input[], GNode *ctxt)
{
	VarParser	vp = {
		input,
		input,
		ctxt,
		FALSE,
		FALSE
	};
	char		*value;
	Boolean		freeResult;

	value = VarParse(&vp, &freeResult);
	if (freeResult) {
		free(value);
	}
	return (vp.ptr - vp.input);
}

static int
match_var(const char str[], const char var[])
{
	const char	*start = str;
	size_t		len;

	str++;			/* consume '$' */

	if (str[0] == OPEN_PAREN || str[0] == OPEN_BRACE) {
		str++;		/* consume opening paren or brace */

		while (str[0] != '\0') {
			if (str[0] == '$') {
				/*
				 * A variable inside the variable. We cannot
				 * expand the external variable yet.
				 */
				return (str - start);
			} else if (str[0] == ':' ||
				   str[0] == CLOSE_PAREN ||
				   str[0] == CLOSE_BRACE) {
				len = str - (start + 2);

				if (strncmp(var, start + 2, len) == 0 && var[len] == '\0') {
					return (0);	/* match */
				} else {
					/*
					 * Not the variable we want to
					 * expand.
					 */
					return (str - start);
				}
			} else {
				++str;
			}
		}
		return (str - start);
	} else {
		/* Single letter variable name */
		if (var[1] == '\0' && var[0] == str[0]) {
			return (0);	/* match */
		} else {
			str++;	/* consume variable name */
			return (str - start);
		}
	}
}

/**
 * Substitute for all variables in the given string in the given
 * context If err is TRUE, Parse_Error will be called when an
 * undefined variable is encountered.
 *
 * Results:
 *	The resulting string.
 *
 * Side Effects:
 *	None. The old string must be freed by the caller
 */
Buffer *
Var_Subst(const char *str, GNode *ctxt, Boolean err)
{
	Boolean	errorReported;
	Buffer *buf;		/* Buffer for forming things */

	/*
	 * Set TRUE if an error has already been reported to prevent a
	 * plethora of messages when recursing. XXXHB this comment sounds
	 * wrong.
	 */
	errorReported = FALSE;

	buf = Buf_Init(0);
	while (str[0] != '\0') {
		if ((str[0] == '$') && (str[1] == '$')) {
			/*
			 * A dollar sign may be escaped with another dollar
			 * sign.  In such a case, we skip over the escape
			 * character and store the dollar sign into the
			 * buffer directly.
			 */
			str++;
			Buf_AddByte(buf, (Byte)str[0]);
			str++;

		} else if (str[0] == '$') {
			/* Variable invocation. */
			VarParser subvp = {
				str,
				str,
				ctxt,
				err,
				TRUE
			};
			char	*rval;
			Boolean	rfree;

			rval = VarParse(&subvp, &rfree);

			/*
			 * When we come down here, val should either point to
			 * the value of this variable, suitably modified, or
			 * be NULL. Length should be the total length of the
			 * potential variable invocation (from $ to end
			 * character...)
			 */
			if (rval == var_Error || rval == varNoError) {
				/*
				 * If performing old-time variable
				 * substitution, skip over the variable and
				 * continue with the substitution. Otherwise,
				 * store the dollar sign and advance str so
				 * we continue with the string...
				 */
				if (oldVars) {
					str = subvp.ptr;
				} else if (err) {
					/*
					 * If variable is undefined, complain
					 * and skip the variable. The
					 * complaint will stop us from doing
					 * anything when the file is parsed.
					 */
					if (!errorReported) {
						Parse_Error(PARSE_FATAL,
							    "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
					}
					errorReported = TRUE;
					str = subvp.ptr;
				} else {
					Buf_AddByte(buf, (Byte)str[0]);
					str++;
				}
			} else {
				/*
				 * Copy all the characters from the variable
				 * value straight into the new string.
				 */
				Buf_Append(buf, rval);
				if (rfree) {
					free(rval);
				}
				str = subvp.ptr;
			}
		} else {
			Buf_AddByte(buf, (Byte)str[0]);
			str++;
		}
	}

	return (buf);
}

/**
 * Substitute for all variables except if it is the same as 'var',
 * in the given string in the given context.  If err is TRUE,
 * Parse_Error will be called when an undefined variable is
 * encountered.
 *
 * Results:
 *	The resulting string.
 *
 * Side Effects:
 *	None. The old string must be freed by the caller
 */
Buffer *
Var_SubstOnly(const char *var, const char *str, Boolean err)
{
	GNode *ctxt = VAR_GLOBAL;
	Boolean	errorReported;
	Buffer	*buf;		/* Buffer for forming things */

	/*
	 * Set TRUE if an error has already been reported to prevent a
	 * plethora of messages when recursing. XXXHB this comment sounds
	 * wrong.
	 */
	errorReported = FALSE;

	buf = Buf_Init(0);
	while (str[0] != '\0') {
		if (str[0] == '$') {
			int	skip;

			skip = match_var(str, var);
			if (skip > 0) {
				Buf_AddBytes(buf, skip, str);
				str += skip;
			} else {
				/* Variable invocation. */
				VarParser	subvp = {
					str,
					str,
					ctxt,
					err,
					TRUE
				};
				char	*rval;
				Boolean	rfree;

				rval = VarParse(&subvp, &rfree);

				/*
				 * When we get down here, rval should either
				 * point to the value of this variable, or be
				 * NULL.
				 */
				if (rval == var_Error || rval == varNoError) {
					/*
					 * If performing old-time variable
					 * substitution, skip over the
					 * variable and continue with the
					 * substitution. Otherwise, store the
					 * dollar sign and advance str so we
					 * continue with the string...
					 */
					if (oldVars) {
						str = subvp.ptr;
					} else if (err) {
						/*
						 * If variable is undefined,
						 * complain and skip the
						 * variable. The complaint
						 * will stop us from doing
						 * anything when the file is
						 * parsed.
						 */
						if (!errorReported) {
							Parse_Error(PARSE_FATAL,
								    "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
						}
						errorReported = TRUE;
						str = subvp.ptr;
					} else {
						Buf_AddByte(buf, (Byte)str[0]);
						str++;
					}
				} else {
					/*
					 * Copy all the characters from the
					 * variable value straight into the
					 * new string.
					 */
					Buf_Append(buf, rval);
					if (rfree) {
						free(rval);
					}
					str = subvp.ptr;
				}
			}
		} else {
			Buf_AddByte(buf, (Byte)str[0]);
			str++;
		}
	}

	return (buf);
}

/**
 * Initialize the module
 *
 * Side Effects:
 *	The VAR_CMD and VAR_GLOBAL contexts are created
 */
void
Var_Init(char **env)
{
	char	**ptr;

	VAR_CMD = Targ_NewGN("Command");
	VAR_ENV = Targ_NewGN("Environment");
	VAR_GLOBAL = Targ_NewGN("Global");

	/*
	 * Copy user environment variables into ENV context.
	 */
	for (ptr = env; *ptr != NULL; ++ptr) {
		char		*tmp = estrdup(*ptr);
		const char	*name = tmp;
		char		*sep = strchr(name, '=');
		const char	*value = sep + 1;

		if (sep != NULL) {
			*sep = '\0';
			VarAdd(name, value, VAR_ENV);
		}
		free(tmp);
	}
}

/**
 * Print all variables in global and command line contexts.
 */
void
Var_Dump(void)
{
	const LstNode	*ln;
	const Var	*v;

	printf("#*** Global Variables:\n");
	LST_FOREACH(ln, &VAR_GLOBAL->context) {
		v = Lst_Datum(ln);
		printf("%-16s = %s\n", v->name, Buf_Data(v->val));
	}

	printf("#*** Command-line Variables:\n");
	LST_FOREACH(ln, &VAR_CMD->context) {
		v = Lst_Datum(ln);
		printf("%-16s = %s\n", v->name, Buf_Data(v->val));
	}
}

/**
 * Print the values of any variables requested by
 * the user.
 */
void
Var_Print(Lst *vlist, Boolean expandVars)
{
	LstNode		*n;
	char		*name;

	LST_FOREACH(n, vlist) {
		name = Lst_Datum(n);
		if (expandVars) {
			char *value;
			char *v;

			if (*name == '$') {
				v = name;
			} else {
				v = emalloc(strlen(name) + 1 + 3);
				sprintf(v, "${%s}", name);
			}
			value = Buf_Peel(Var_Subst(v, VAR_GLOBAL, FALSE));
			printf("%s\n", value);

			if (v != name)
				free(v);
			free(value);
		} else {
			const char *value = Var_Value(name, VAR_GLOBAL);
			printf("%s\n", value != NULL ? value : "");
		}
	}
}

OpenPOWER on IntegriCloud