summaryrefslogtreecommitdiff
path: root/read.c
blob: aa13a217d54109d6f313f2439d16826dee1b4fb1 (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
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
/* Reading and parsing of makefiles for GNU Make.
Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software
Foundation, Inc.
This file is part of GNU Make.

GNU Make 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 3 of the License, or (at your option) any later
version.

GNU Make 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.  If not, see <http://www.gnu.org/licenses/>.  */

#include "make.h"

#include <assert.h>

#include <glob.h>

#include "dep.h"
#include "filedef.h"
#include "job.h"
#include "commands.h"
#include "variable.h"
#include "rule.h"
#include "debug.h"
#include "hash.h"


#ifndef WINDOWS32
#ifndef _AMIGA
#ifndef VMS
#include <pwd.h>
#else
struct passwd *getpwnam (char *name);
#endif
#endif
#endif /* !WINDOWS32 */

/* A 'struct ebuffer' controls the origin of the makefile we are currently
   eval'ing.
*/

struct ebuffer
  {
    char *buffer;       /* Start of the current line in the buffer.  */
    char *bufnext;      /* Start of the next line in the buffer.  */
    char *bufstart;     /* Start of the entire buffer.  */
    unsigned int size;  /* Malloc'd size of buffer. */
    FILE *fp;           /* File, or NULL if this is an internal buffer.  */
    struct floc floc;   /* Info on the file in fp (if any).  */
  };

/* Track the modifiers we can have on variable assignments */

struct vmodifiers
  {
    unsigned int assign_v:1;
    unsigned int define_v:1;
    unsigned int export_v:1;
    unsigned int override_v:1;
    unsigned int private_v:1;
  };

/* Types of "words" that can be read in a makefile.  */
enum make_word_type
  {
     w_bogus, w_eol, w_static, w_variable, w_colon, w_dcolon, w_semicolon,
     w_varassign
  };


/* A `struct conditionals' contains the information describing
   all the active conditionals in a makefile.

   The global variable `conditionals' contains the conditionals
   information for the current makefile.  It is initialized from
   the static structure `toplevel_conditionals' and is later changed
   to new structures for included makefiles.  */

struct conditionals
  {
    unsigned int if_cmds;	/* Depth of conditional nesting.  */
    unsigned int allocated;	/* Elts allocated in following arrays.  */
    char *ignoring;		/* Are we ignoring or interpreting?
                                   0=interpreting, 1=not yet interpreted,
                                   2=already interpreted */
    char *seen_else;		/* Have we already seen an `else'?  */
  };

static struct conditionals toplevel_conditionals;
static struct conditionals *conditionals = &toplevel_conditionals;


/* Default directories to search for include files in  */

static const char *default_include_directories[] =
  {
#if defined(WINDOWS32) && !defined(INCLUDEDIR)
/* This completely up to the user when they install MSVC or other packages.
   This is defined as a placeholder.  */
# define INCLUDEDIR "."
#endif
    INCLUDEDIR,
#ifndef _AMIGA
    "/usr/gnu/include",
    "/usr/local/include",
    "/usr/include",
#endif
    0
  };

/* List of directories to search for include files in  */

static const char **include_directories;

/* Maximum length of an element of the above.  */

static unsigned int max_incl_len;

/* The filename and pointer to line number of the
   makefile currently being read in.  */

const struct floc *reading_file = 0;

/* The chain of makefiles read by read_makefile.  */

static struct dep *read_makefiles = 0;

static int eval_makefile (const char *filename, int flags);
static int eval (struct ebuffer *buffer, int flags);

static long readline (struct ebuffer *ebuf);
static struct variable *do_define (char *name, enum variable_origin origin,
                                   struct ebuffer *ebuf);
static int conditional_line (char *line, int len, const struct floc *flocp);
static void record_files (struct nameseq *filenames, const char *pattern,
                          const char *pattern_percent, struct dep *deps,
                          unsigned int cmds_started, char *commands,
                          unsigned int commands_idx, int two_colon,
                          const struct floc *flocp);
static void record_target_var (struct nameseq *filenames, char *defn,
                               enum variable_origin origin,
                               struct vmodifiers *vmod,
                               const struct floc *flocp);
static enum make_word_type get_next_mword (char *buffer, char *delim,
                                           char **startp, unsigned int *length);
static void remove_comments (char *line);
static char *find_char_unquote (char *string, int stop1, int stop2,
                                int blank, int ignorevars);


/* Compare a word, both length and contents.
   P must point to the word to be tested, and WLEN must be the length.
*/
#define	word1eq(s)	(wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))


/* Read in all the makefiles and return the chain of their names.  */

struct dep *
read_all_makefiles (const char **makefiles)
{
  unsigned int num_makefiles = 0;

  /* Create *_LIST variables, to hold the makefiles, targets, and variables
     we will be reading. */

  define_variable ("MAKEFILE_LIST", sizeof ("MAKEFILE_LIST")-1, "", o_file, 0);

  DB (DB_BASIC, (_("Reading makefiles...\n")));

  /* If there's a non-null variable MAKEFILES, its value is a list of
     files to read first thing.  But don't let it prevent reading the
     default makefiles and don't let the default goal come from there.  */

  {
    char *value;
    char *name, *p;
    unsigned int length;

    {
      /* Turn off --warn-undefined-variables while we expand MAKEFILES.  */
      int save = warn_undefined_variables_flag;
      warn_undefined_variables_flag = 0;

      value = allocated_variable_expand ("$(MAKEFILES)");

      warn_undefined_variables_flag = save;
    }

    /* Set NAME to the start of next token and LENGTH to its length.
       MAKEFILES is updated for finding remaining tokens.  */
    p = value;

    while ((name = find_next_token ((const char **)&p, &length)) != 0)
      {
	if (*p != '\0')
	  *p++ = '\0';
	eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
      }

    free (value);
  }

  /* Read makefiles specified with -f switches.  */

  if (makefiles != 0)
    while (*makefiles != 0)
      {
	struct dep *tail = read_makefiles;
	register struct dep *d;

	if (! eval_makefile (*makefiles, 0))
	  perror_with_name ("", *makefiles);

	/* Find the right element of read_makefiles.  */
	d = read_makefiles;
	while (d->next != tail)
	  d = d->next;

	/* Use the storage read_makefile allocates.  */
	*makefiles = dep_name (d);
	++num_makefiles;
	++makefiles;
      }

  /* If there were no -f switches, try the default names.  */

  if (num_makefiles == 0)
    {
      static char *default_makefiles[] =
#ifdef VMS
	/* all lower case since readdir() (the vms version) 'lowercasifies' */
	{ "makefile.vms", "gnumakefile.", "makefile.", 0 };
#else
#ifdef _AMIGA
	{ "GNUmakefile", "Makefile", "SMakefile", 0 };
#else /* !Amiga && !VMS */
	{ "GNUmakefile", "makefile", "Makefile", 0 };
#endif /* AMIGA */
#endif /* VMS */
      register char **p = default_makefiles;
      while (*p != 0 && !file_exists_p (*p))
	++p;

      if (*p != 0)
	{
	  if (! eval_makefile (*p, 0))
	    perror_with_name ("", *p);
	}
      else
	{
	  /* No default makefile was found.  Add the default makefiles to the
	     `read_makefiles' chain so they will be updated if possible.  */
	  struct dep *tail = read_makefiles;
	  /* Add them to the tail, after any MAKEFILES variable makefiles.  */
	  while (tail != 0 && tail->next != 0)
	    tail = tail->next;
	  for (p = default_makefiles; *p != 0; ++p)
	    {
	      struct dep *d = alloc_dep ();
	      d->file = enter_file (strcache_add (*p));
	      d->file->dontcare = 1;
	      /* Tell update_goal_chain to bail out as soon as this file is
		 made, and main not to die if we can't make this file.  */
	      d->changed = RM_DONTCARE;
	      if (tail == 0)
		read_makefiles = d;
	      else
		tail->next = d;
	      tail = d;
	    }
	  if (tail != 0)
	    tail->next = 0;
	}
    }

  return read_makefiles;
}

/* Install a new conditional and return the previous one.  */

static struct conditionals *
install_conditionals (struct conditionals *new)
{
  struct conditionals *save = conditionals;

  memset (new, '\0', sizeof (*new));
  conditionals = new;

  return save;
}

/* Free the current conditionals and reinstate a saved one.  */

static void
restore_conditionals (struct conditionals *saved)
{
  /* Free any space allocated by conditional_line.  */
  if (conditionals->ignoring)
    free (conditionals->ignoring);
  if (conditionals->seen_else)
    free (conditionals->seen_else);

  /* Restore state.  */
  conditionals = saved;
}

static int
eval_makefile (const char *filename, int flags)
{
  struct dep *deps;
  struct ebuffer ebuf;
  const struct floc *curfile;
  char *expanded = 0;
  int makefile_errno;
  int r;

  filename = strcache_add (filename);
  ebuf.floc.filenm = filename;
  ebuf.floc.lineno = 1;

  if (ISDB (DB_VERBOSE))
    {
      printf (_("Reading makefile `%s'"), filename);
      if (flags & RM_NO_DEFAULT_GOAL)
	printf (_(" (no default goal)"));
      if (flags & RM_INCLUDED)
	printf (_(" (search path)"));
      if (flags & RM_DONTCARE)
	printf (_(" (don't care)"));
      if (flags & RM_NO_TILDE)
	printf (_(" (no ~ expansion)"));
      puts ("...");
    }

  /* First, get a stream to read.  */

  /* Expand ~ in FILENAME unless it came from `include',
     in which case it was already done.  */
  if (!(flags & RM_NO_TILDE) && filename[0] == '~')
    {
      expanded = tilde_expand (filename);
      if (expanded != 0)
	filename = expanded;
    }

  ebuf.fp = fopen (filename, "r");
  /* Save the error code so we print the right message later.  */
  makefile_errno = errno;

  /* If the makefile wasn't found and it's either a makefile from
     the `MAKEFILES' variable or an included makefile,
     search the included makefile search path for this makefile.  */
  if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
    {
      unsigned int i;
      for (i = 0; include_directories[i] != 0; ++i)
	{
	  const char *included = concat (include_directories[i], "/", filename);
	  ebuf.fp = fopen (included, "r");
	  if (ebuf.fp)
	    {
	      filename = strcache_add (included);
	      break;
	    }
	}
    }

  /* Add FILENAME to the chain of read makefiles.  */
  deps = alloc_dep ();
  deps->next = read_makefiles;
  read_makefiles = deps;
  deps->file = lookup_file (filename);
  if (deps->file == 0)
    deps->file = enter_file (filename);
  filename = deps->file->name;
  deps->changed = flags;
  if (flags & RM_DONTCARE)
    deps->file->dontcare = 1;

  if (expanded)
    free (expanded);

  /* If the makefile can't be found at all, give up entirely.  */

  if (ebuf.fp == 0)
    {
      /* If we did some searching, errno has the error from the last
	 attempt, rather from FILENAME itself.  Restore it in case the
	 caller wants to use it in a message.  */
      errno = makefile_errno;
      return 0;
    }

  /* Set close-on-exec to avoid leaking the makefile to children, such as
     $(shell ...).  */
#ifdef HAVE_FILENO
  CLOSE_ON_EXEC (fileno (ebuf.fp));
#endif

  /* Add this makefile to the list. */
  do_variable_definition (&ebuf.floc, "MAKEFILE_LIST", filename, o_file,
                          f_append, 0);

  /* Evaluate the makefile */

  ebuf.size = 200;
  ebuf.buffer = ebuf.bufnext = ebuf.bufstart = xmalloc (ebuf.size);

  curfile = reading_file;
  reading_file = &ebuf.floc;

  r = eval (&ebuf, !(flags & RM_NO_DEFAULT_GOAL));

  reading_file = curfile;

  fclose (ebuf.fp);

  free (ebuf.bufstart);
  alloca (0);
  return r;
}

int
eval_buffer (char *buffer)
{
  struct ebuffer ebuf;
  struct conditionals *saved;
  struct conditionals new;
  const struct floc *curfile;
  int r;

  /* Evaluate the buffer */

  ebuf.size = strlen (buffer);
  ebuf.buffer = ebuf.bufnext = ebuf.bufstart = buffer;
  ebuf.fp = NULL;

  if (reading_file)
    ebuf.floc = *reading_file;
  else
    ebuf.floc.filenm = NULL;

  curfile = reading_file;
  reading_file = &ebuf.floc;

  saved = install_conditionals (&new);

  r = eval (&ebuf, 1);

  restore_conditionals (saved);

  reading_file = curfile;

  alloca (0);
  return r;
}

/* Check LINE to see if it's a variable assignment.

   It might use one of the modifiers "export", "override", "private", or it
   might be one of the conditional tokens like "ifdef", "include", etc.

   If it's not a variable assignment, VMOD.V_ASSIGN is 0.  Returns LINE.

   Returns a pointer to the first non-modifier character, and sets VMOD
   based on the modifiers found if any, plus V_ASSIGN is 1.
 */
char *
parse_var_assignment (const char *line, struct vmodifiers *vmod)
{
  const char *p;
  memset (vmod, '\0', sizeof (*vmod));

  /* Find the start of the next token.  If there isn't one we're done.  */
  line = next_token (line);
  if (*line == '\0')
    return (char *)line;

  p = line;
  while (1)
    {
      int wlen;
      const char *p2;
      enum variable_flavor flavor;

      p2 = parse_variable_definition (p, &flavor);

      /* If this is a variable assignment, we're done.  */
      if (p2)
        break;

      /* It's not a variable; see if it's a modifier.  */
      p2 = end_of_token (p);
      wlen = p2 - p;

      if (word1eq ("export"))
        vmod->export_v = 1;
      else if (word1eq ("override"))
        vmod->override_v = 1;
      else if (word1eq ("private"))
        vmod->private_v = 1;
      else if (word1eq ("define"))
        {
          /* We can't have modifiers after 'define' */
          vmod->define_v = 1;
          p = next_token (p2);
          break;
        }
      else
        /* Not a variable or modifier: this is not a variable assignment.  */
        return (char *)line;

      /* It was a modifier.  Try the next word.  */
      p = next_token (p2);
      if (*p == '\0')
        return (char *)line;
    }

  /* Found a variable assignment.  */
  vmod->assign_v = 1;
  return (char *)p;
}



/* Read file FILENAME as a makefile and add its contents to the data base.

   SET_DEFAULT is true if we are allowed to set the default goal.  */


static int
eval (struct ebuffer *ebuf, int set_default)
{
  char *collapsed = 0;
  unsigned int collapsed_length = 0;
  unsigned int commands_len = 200;
  char *commands;
  unsigned int commands_idx = 0;
  unsigned int cmds_started, tgts_started;
  int ignoring = 0, in_ignored_define = 0;
  int no_targets = 0;		/* Set when reading a rule without targets.  */
  struct nameseq *filenames = 0;
  struct dep *deps = 0;
  long nlines = 0;
  int two_colon = 0;
  const char *pattern = 0;
  const char *pattern_percent;
  struct floc *fstart;
  struct floc fi;

#define record_waiting_files()						      \
  do									      \
    {									      \
      if (filenames != 0)						      \
        {                                                                     \
	  fi.lineno = tgts_started;                                           \
	  record_files (filenames, pattern, pattern_percent, deps,            \
                        cmds_started, commands, commands_idx, two_colon,      \
                        &fi);                                                 \
        }                                                                     \
      filenames = 0;							      \
      commands_idx = 0;							      \
      no_targets = 0;                                                         \
      pattern = 0;                                                            \
    } while (0)

  pattern_percent = 0;
  cmds_started = tgts_started = 1;

  fstart = &ebuf->floc;
  fi.filenm = ebuf->floc.filenm;

  /* Loop over lines in the file.
     The strategy is to accumulate target names in FILENAMES, dependencies
     in DEPS and commands in COMMANDS.  These are used to define a rule
     when the start of the next rule (or eof) is encountered.

     When you see a "continue" in the loop below, that means we are moving on
     to the next line _without_ ending any rule that we happen to be working
     with at the moment.  If you see a "goto rule_complete", then the
     statement we just parsed also finishes the previous rule.  */

  commands = xmalloc (200);

  while (1)
    {
      unsigned int linelen;
      char *line;
      unsigned int wlen;
      char *p;
      char *p2;
      struct vmodifiers vmod;

      /* At the top of this loop, we are starting a brand new line.  */
      /* Grab the next line to be evaluated */
      ebuf->floc.lineno += nlines;
      nlines = readline (ebuf);

      /* If there is nothing left to eval, we're done.  */
      if (nlines < 0)
        break;

      /* If this line is empty, skip it.  */
      line = ebuf->buffer;
      if (line[0] == '\0')
        continue;

      linelen = strlen (line);

      /* Check for a shell command line first.
	 If it is not one, we can stop treating tab specially.  */
      if (line[0] == cmd_prefix)
	{
	  if (no_targets)
	    /* Ignore the commands in a rule with no targets.  */
	    continue;

	  /* If there is no preceding rule line, don't treat this line
	     as a command, even though it begins with a recipe prefix.
	     SunOS 4 make appears to behave this way.  */

	  if (filenames != 0)
	    {
	      if (ignoring)
		/* Yep, this is a shell command, and we don't care.  */
		continue;

	      /* Append this command line to the line being accumulated.
                 Strip command prefix chars that appear after newlines.  */
	      if (commands_idx == 0)
		cmds_started = ebuf->floc.lineno;

	      if (linelen + commands_idx > commands_len)
		{
		  commands_len = (linelen + commands_idx) * 2;
		  commands = xrealloc (commands, commands_len);
		}
              p = &commands[commands_idx];
              p2 = line + 1;
              while (--linelen)
                {
                  ++commands_idx;
                  *(p++) = *p2;
                  if (p2[0] == '\n' && p2[1] == cmd_prefix)
                    {
                      ++p2;
                      --linelen;
                    }
                  ++p2;
                }
              *p = '\n';
              ++commands_idx;

	      continue;
	    }
	}

      /* This line is not a shell command line.  Don't worry about whitespace.
         Get more space if we need it; we don't need to preserve the current
         contents of the buffer.  */

      if (collapsed_length < linelen+1)
	{
	  collapsed_length = linelen+1;
          if (collapsed)
            free (collapsed);
          /* Don't need xrealloc: we don't need to preserve the content.  */
	  collapsed = xmalloc (collapsed_length);
	}
      strcpy (collapsed, line);
      /* Collapse continuation lines.  */
      collapse_continuations (collapsed);
      remove_comments (collapsed);

      /* Get rid if starting space (including formfeed, vtab, etc.)  */
      p = collapsed;
      while (isspace ((unsigned char)*p))
        ++p;

      /* See if this is a variable assignment.  We need to do this early, to
         allow variables with names like 'ifdef', 'export', 'private', etc.  */
      p = parse_var_assignment(p, &vmod);
      if (vmod.assign_v)
        {
          struct variable *v;
          enum variable_origin origin = vmod.override_v ? o_override : o_file;

          /* If we're ignoring then we're done now.  */
	  if (ignoring)
            {
              if (vmod.define_v)
                in_ignored_define = 1;
              continue;
            }

          if (vmod.define_v)
            v = do_define (p, origin, ebuf);
          else
            v = try_variable_definition (fstart, p, origin, 0);

          assert (v != NULL);

          if (vmod.export_v)
            v->export = v_export;
          if (vmod.private_v)
            v->private_var = 1;

          /* This line has been dealt with.  */
          goto rule_complete;
        }

      /* If this line is completely empty, ignore it.  */
      if (*p == '\0')
	continue;

      p2 = end_of_token (p);
      wlen = p2 - p;
      p2 = next_token (p2);

      /* If we're in an ignored define, skip this line (but maybe get out).  */
      if (in_ignored_define)
	{
          /* See if this is an endef line (plus optional comment).  */
          if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
            in_ignored_define = 0;

	  continue;
	}

      /* Check for conditional state changes.  */
      {
        int i = conditional_line (p, wlen, fstart);
        if (i != -2)
          {
            if (i == -1)
              fatal (fstart, _("invalid syntax in conditional"));

            ignoring = i;
            continue;
          }
      }

      /* Nothing to see here... move along.  */
      if (ignoring)
	continue;

      /* Manage the "export" keyword used outside of variable assignment
         as well as "unexport".  */
      if (word1eq ("export") || word1eq ("unexport"))
	{
          int exporting = *p == 'u' ? 0 : 1;

          /* (un)export by itself causes everything to be (un)exported. */
	  if (*p2 == '\0')
            export_all_variables = exporting;
          else
            {
              unsigned int l;
              const char *cp;
              char *ap;

              /* Expand the line so we can use indirect and constructed
                 variable names in an (un)export command.  */
              cp = ap = allocated_variable_expand (p2);

              for (p = find_next_token (&cp, &l); p != 0;
                   p = find_next_token (&cp, &l))
                {
                  struct variable *v = lookup_variable (p, l);
                  if (v == 0)
                    v = define_variable_loc (p, l, "", o_file, 0, fstart);
                  v->export = exporting ? v_export : v_noexport;
                }

              free (ap);
            }
          goto rule_complete;
	}

      /* Handle the special syntax for vpath.  */
      if (word1eq ("vpath"))
	{
          const char *cp;
	  char *vpat;
	  unsigned int l;
	  cp = variable_expand (p2);
	  p = find_next_token (&cp, &l);
	  if (p != 0)
	    {
	      vpat = xstrndup (p, l);
	      p = find_next_token (&cp, &l);
	      /* No searchpath means remove all previous
		 selective VPATH's with the same pattern.  */
	    }
	  else
	    /* No pattern means remove all previous selective VPATH's.  */
	    vpat = 0;
	  construct_vpath_list (vpat, p);
	  if (vpat != 0)
	    free (vpat);

          goto rule_complete;
	}

      /* Handle include and variants.  */
      if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
	{
	  /* We have found an `include' line specifying a nested
	     makefile to be read at this point.  */
	  struct conditionals *save;
          struct conditionals new_conditionals;
	  struct nameseq *files;
	  /* "-include" (vs "include") says no error if the file does not
	     exist.  "sinclude" is an alias for this from SGI.  */
	  int noerror = (p[0] != 'i');

	  p = allocated_variable_expand (p2);

          /* If no filenames, it's a no-op.  */
	  if (*p == '\0')
            {
              free (p);
              continue;
            }

	  /* Parse the list of file names.  */
	  p2 = p;
	  files = multi_glob (parse_file_seq (&p2, '\0',
					      sizeof (struct nameseq),
					      1),
			      sizeof (struct nameseq));
	  free (p);

	  /* Save the state of conditionals and start
	     the included makefile with a clean slate.  */
	  save = install_conditionals (&new_conditionals);

	  /* Record the rules that are waiting so they will determine
	     the default goal before those in the included makefile.  */
	  record_waiting_files ();

	  /* Read each included makefile.  */
	  while (files != 0)
	    {
	      struct nameseq *next = files->next;
	      const char *name = files->name;
              int r;

	      free (files);
	      files = next;

              r = eval_makefile (name, (RM_INCLUDED | RM_NO_TILDE
                                        | (noerror ? RM_DONTCARE : 0)));
	      if (!r && !noerror)
                error (fstart, "%s: %s", name, strerror (errno));
	    }

	  /* Restore conditional state.  */
	  restore_conditionals (save);

          goto rule_complete;
	}

      /* This line starts with a tab but was not caught above because there
         was no preceding target, and the line might have been usable as a
         variable definition.  But now we know it is definitely lossage.  */
      if (line[0] == cmd_prefix)
        fatal(fstart, _("recipe commences before first target"));

      /* This line describes some target files.  This is complicated by
         the existence of target-specific variables, because we can't
         expand the entire line until we know if we have one or not.  So
         we expand the line word by word until we find the first `:',
         then check to see if it's a target-specific variable.

         In this algorithm, `lb_next' will point to the beginning of the
         unexpanded parts of the input buffer, while `p2' points to the
         parts of the expanded buffer we haven't searched yet. */

      {
        enum make_word_type wtype;
        char *cmdleft, *semip, *lb_next;
        unsigned int plen = 0;
        char *colonp;
        const char *end, *beg; /* Helpers for whitespace stripping. */

        /* Record the previous rule.  */

        record_waiting_files ();
        tgts_started = fstart->lineno;

        /* Search the line for an unquoted ; that is not after an
           unquoted #.  */
        cmdleft = find_char_unquote (line, ';', '#', 0, 1);
        if (cmdleft != 0 && *cmdleft == '#')
          {
            /* We found a comment before a semicolon.  */
            *cmdleft = '\0';
            cmdleft = 0;
          }
        else if (cmdleft != 0)
          /* Found one.  Cut the line short there before expanding it.  */
          *(cmdleft++) = '\0';
        semip = cmdleft;

        collapse_continuations (line);

        /* We can't expand the entire line, since if it's a per-target
           variable we don't want to expand it.  So, walk from the
           beginning, expanding as we go, and looking for "interesting"
           chars.  The first word is always expandable.  */
        wtype = get_next_mword(line, NULL, &lb_next, &wlen);
        switch (wtype)
          {
          case w_eol:
            if (cmdleft != 0)
              fatal(fstart, _("missing rule before recipe"));
            /* This line contained something but turned out to be nothing
               but whitespace (a comment?).  */
            continue;

          case w_colon:
          case w_dcolon:
            /* We accept and ignore rules without targets for
               compatibility with SunOS 4 make.  */
            no_targets = 1;
            continue;

          default:
            break;
          }

        p2 = variable_expand_string(NULL, lb_next, wlen);

        while (1)
          {
            lb_next += wlen;
            if (cmdleft == 0)
              {
                /* Look for a semicolon in the expanded line.  */
                cmdleft = find_char_unquote (p2, ';', 0, 0, 0);

                if (cmdleft != 0)
                  {
                    unsigned long p2_off = p2 - variable_buffer;
                    unsigned long cmd_off = cmdleft - variable_buffer;
                    char *pend = p2 + strlen(p2);

                    /* Append any remnants of lb, then cut the line short
                       at the semicolon.  */
                    *cmdleft = '\0';

                    /* One school of thought says that you shouldn't expand
                       here, but merely copy, since now you're beyond a ";"
                       and into a command script.  However, the old parser
                       expanded the whole line, so we continue that for
                       backwards-compatiblity.  Also, it wouldn't be
                       entirely consistent, since we do an unconditional
                       expand below once we know we don't have a
                       target-specific variable. */
                    (void)variable_expand_string(pend, lb_next, (long)-1);
                    lb_next += strlen(lb_next);
                    p2 = variable_buffer + p2_off;
                    cmdleft = variable_buffer + cmd_off + 1;
                  }
              }

            colonp = find_char_unquote(p2, ':', 0, 0, 0);
#ifdef HAVE_DOS_PATHS
            /* The drive spec brain-damage strikes again...  */
            /* Note that the only separators of targets in this context
               are whitespace and a left paren.  If others are possible,
               they should be added to the string in the call to index.  */
            while (colonp && (colonp[1] == '/' || colonp[1] == '\\') &&
                   colonp > p2 && isalpha ((unsigned char)colonp[-1]) &&
                   (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
              colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
#endif
            if (colonp != 0)
              break;

            wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
            if (wtype == w_eol)
              break;

            p2 += strlen(p2);
            *(p2++) = ' ';
            p2 = variable_expand_string(p2, lb_next, wlen);
            /* We don't need to worry about cmdleft here, because if it was
               found in the variable_buffer the entire buffer has already
               been expanded... we'll never get here.  */
          }

        p2 = next_token (variable_buffer);

        /* If the word we're looking at is EOL, see if there's _anything_
           on the line.  If not, a variable expanded to nothing, so ignore
           it.  If so, we can't parse this line so punt.  */
        if (wtype == w_eol)
          {
            if (*p2 != '\0')
              /* There's no need to be ivory-tower about this: check for
                 one of the most common bugs found in makefiles...  */
              fatal (fstart, _("missing separator%s"),
                     (cmd_prefix == '\t' && !strneq(line, "        ", 8))
                     ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
            continue;
          }

        /* Make the colon the end-of-string so we know where to stop
           looking for targets.  */
        *colonp = '\0';
        filenames = multi_glob (parse_file_seq (&p2, '\0',
                                                sizeof (struct nameseq),
                                                1),
                                sizeof (struct nameseq));
        *p2 = ':';

        if (!filenames)
          {
            /* We accept and ignore rules without targets for
               compatibility with SunOS 4 make.  */
            no_targets = 1;
            continue;
          }
        /* This should never be possible; we handled it above.  */
        assert (*p2 != '\0');
        ++p2;

        /* Is this a one-colon or two-colon entry?  */
        two_colon = *p2 == ':';
        if (two_colon)
          p2++;

        /* Test to see if it's a target-specific variable.  Copy the rest
           of the buffer over, possibly temporarily (we'll expand it later
           if it's not a target-specific variable).  PLEN saves the length
           of the unparsed section of p2, for later.  */
        if (*lb_next != '\0')
          {
            unsigned int l = p2 - variable_buffer;
            plen = strlen (p2);
            variable_buffer_output (p2+plen, lb_next, strlen (lb_next)+1);
            p2 = variable_buffer + l;
          }

        p2 = parse_var_assignment (p2, &vmod);
        if (vmod.assign_v)
          {
            /* If there was a semicolon found, add it back, plus anything
               after it.  */
            if (semip)
              {
                unsigned int l = p - variable_buffer;
                *(--semip) = ';';
                variable_buffer_output (p2 + strlen (p2),
                                        semip, strlen (semip)+1);
                p = variable_buffer + l;
              }
            record_target_var (filenames, p2,
                               vmod.override_v ? o_override : o_file,
                               &vmod, fstart);
            filenames = 0;
            continue;
          }

        /* This is a normal target, _not_ a target-specific variable.
           Unquote any = in the dependency list.  */
        find_char_unquote (lb_next, '=', 0, 0, 0);

        /* We have some targets, so don't ignore the following commands.  */
        no_targets = 0;

        /* Expand the dependencies, etc.  */
        if (*lb_next != '\0')
          {
            unsigned int l = p2 - variable_buffer;
            (void) variable_expand_string (p2 + plen, lb_next, (long)-1);
            p2 = variable_buffer + l;

            /* Look for a semicolon in the expanded line.  */
            if (cmdleft == 0)
              {
                cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
                if (cmdleft != 0)
                  *(cmdleft++) = '\0';
              }
          }

        /* Is this a static pattern rule: `target: %targ: %dep; ...'?  */
        p = strchr (p2, ':');
        while (p != 0 && p[-1] == '\\')
          {
            register char *q = &p[-1];
            register int backslash = 0;
            while (*q-- == '\\')
              backslash = !backslash;
            if (backslash)
              p = strchr (p + 1, ':');
            else
              break;
          }
#ifdef _AMIGA
        /* Here, the situation is quite complicated. Let's have a look
           at a couple of targets:

           install: dev:make

           dev:make: make

           dev:make:: xyz

           The rule is that it's only a target, if there are TWO :'s
           OR a space around the :.
        */
        if (p && !(isspace ((unsigned char)p[1]) || !p[1]
                   || isspace ((unsigned char)p[-1])))
          p = 0;
#endif
#ifdef HAVE_DOS_PATHS
        {
          int check_again;
          do {
            check_again = 0;
            /* For DOS-style paths, skip a "C:\..." or a "C:/..." */
            if (p != 0 && (p[1] == '\\' || p[1] == '/') &&
                isalpha ((unsigned char)p[-1]) &&
                (p == p2 + 1 || strchr (" \t:(", p[-2]) != 0)) {
              p = strchr (p + 1, ':');
              check_again = 1;
            }
          } while (check_again);
        }
#endif
        if (p != 0)
          {
            struct nameseq *target;
            target = parse_file_seq (&p2, ':', sizeof (struct nameseq), 1);
            ++p2;
            if (target == 0)
              fatal (fstart, _("missing target pattern"));
            else if (target->next != 0)
              fatal (fstart, _("multiple target patterns"));
            pattern_percent = find_percent_cached (&target->name);
            pattern = target->name;
            if (pattern_percent == 0)
              fatal (fstart, _("target pattern contains no `%%'"));
            free (target);
          }
        else
          pattern = 0;

        /* Strip leading and trailing whitespaces. */
        beg = p2;
        end = beg + strlen (beg) - 1;
        strip_whitespace (&beg, &end);

        if (beg <= end && *beg != '\0')
          {
            /* Put all the prerequisites here; they'll be parsed later.  */
            deps = alloc_dep ();
            deps->name = strcache_add_len (beg, end - beg + 1);
          }
        else
          deps = 0;

        commands_idx = 0;
        if (cmdleft != 0)
          {
            /* Semicolon means rest of line is a command.  */
            unsigned int l = strlen (cmdleft);

            cmds_started = fstart->lineno;

            /* Add this command line to the buffer.  */
            if (l + 2 > commands_len)
              {
                commands_len = (l + 2) * 2;
                commands = xrealloc (commands, commands_len);
              }
            memcpy (commands, cmdleft, l);
            commands_idx += l;
            commands[commands_idx++] = '\n';
          }

        /* Determine if this target should be made default. We used to do
           this in record_files() but because of the delayed target recording
           and because preprocessor directives are legal in target's commands
           it is too late. Consider this fragment for example:

           foo:

           ifeq ($(.DEFAULT_GOAL),foo)
              ...
           endif

           Because the target is not recorded until after ifeq directive is
           evaluated the .DEFAULT_GOAL does not contain foo yet as one
           would expect. Because of this we have to move the logic here.  */

        if (set_default && default_goal_var->value[0] == '\0')
          {
            const char *name;
            struct dep *d;
            struct nameseq *t = filenames;

            for (; t != 0; t = t->next)
              {
                int reject = 0;
                name = t->name;

                /* We have nothing to do if this is an implicit rule. */
                if (strchr (name, '%') != 0)
                  break;

                /* See if this target's name does not start with a `.',
                   unless it contains a slash.  */
                if (*name == '.' && strchr (name, '/') == 0
#ifdef HAVE_DOS_PATHS
                    && strchr (name, '\\') == 0
#endif
                    )
                  continue;


                /* If this file is a suffix, don't let it be
                   the default goal file.  */
                for (d = suffix_file->deps; d != 0; d = d->next)
                  {
                    register struct dep *d2;
                    if (*dep_name (d) != '.' && streq (name, dep_name (d)))
                      {
                        reject = 1;
                        break;
                      }
                    for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
                      {
                        unsigned int l = strlen (dep_name (d2));
                        if (!strneq (name, dep_name (d2), l))
                          continue;
                        if (streq (name + l, dep_name (d)))
                          {
                            reject = 1;
                            break;
                          }
                      }

                    if (reject)
                      break;
                  }

                if (!reject)
                  {
                    define_variable_global (".DEFAULT_GOAL", 13, t->name,
                                            o_file, 0, NILF);
                    break;
                  }
              }
          }

        continue;
      }

      /* We get here except in the case that we just read a rule line.
	 Record now the last rule we read, so following spurious
	 commands are properly diagnosed.  */
 rule_complete:
      record_waiting_files ();
    }

#undef	word1eq

  if (conditionals->if_cmds)
    fatal (fstart, _("missing `endif'"));

  /* At eof, record the last rule.  */
  record_waiting_files ();

  if (collapsed)
    free (collapsed);
  free (commands);

  return 1;
}


/* Remove comments from LINE.
   This is done by copying the text at LINE onto itself.  */

static void
remove_comments (char *line)
{
  char *comment;

  comment = find_char_unquote (line, '#', 0, 0, 0);

  if (comment != 0)
    /* Cut off the line at the #.  */
    *comment = '\0';
}

/* Execute a `define' directive.
   The first line has already been read, and NAME is the name of
   the variable to be defined.  The following lines remain to be read.  */

static struct variable *
do_define (char *name, enum variable_origin origin, struct ebuffer *ebuf)
{
  struct variable *v;
  enum variable_flavor flavor;
  struct floc defstart;
  int nlevels = 1;
  unsigned int length = 100;
  char *definition = xmalloc (length);
  unsigned int idx = 0;
  char *p, *var;

  defstart = ebuf->floc;

  p = parse_variable_definition (name, &flavor);
  if (p == NULL)
    /* No assignment token, so assume recursive.  */
    flavor = f_recursive;
  else
    {
      if (*(next_token (p)) != '\0')
        error (&defstart, _("extraneous text after `define' directive"));

      /* Chop the string before the assignment token to get the name.  */
      p[flavor == f_recursive ? -1 : -2] = '\0';
    }

  /* Expand the variable name and find the beginning (NAME) and end.  */
  var = allocated_variable_expand (name);
  name = next_token (var);
  if (*name == '\0')
    fatal (&defstart, _("empty variable name"));
  p = name + strlen (name) - 1;
  while (p > name && isblank ((unsigned char)*p))
    --p;
  p[1] = '\0';

  /* Now read the value of the variable.  */
  while (1)
    {
      unsigned int len;
      char *line;
      long nlines = readline (ebuf);

      /* If there is nothing left to be eval'd, there's no 'endef'!!  */
      if (nlines < 0)
        fatal (&defstart, _("missing `endef', unterminated `define'"));

      ebuf->floc.lineno += nlines;
      line = ebuf->buffer;

      collapse_continuations (line);

      /* If the line doesn't begin with a tab, test to see if it introduces
         another define, or ends one.  Stop if we find an 'endef' */
      if (line[0] != cmd_prefix)
        {
          p = next_token (line);
          len = strlen (p);

          /* If this is another 'define', increment the level count.  */
          if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
              && strneq (p, "define", 6))
            ++nlevels;

          /* If this is an 'endef', decrement the count.  If it's now 0,
             we've found the last one.  */
          else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
                   && strneq (p, "endef", 5))
            {
              p += 5;
              remove_comments (p);
              if (*(next_token (p)) != '\0')
                error (&ebuf->floc,
                       _("extraneous text after `endef' directive"));

              if (--nlevels == 0)
                break;
            }
        }

      /* Add this line to the variable definition.  */
      len = strlen (line);
      if (idx + len + 1 > length)
        {
          length = (idx + len) * 2;
          definition = xrealloc (definition, length + 1);
        }

      memcpy (&definition[idx], line, len);
      idx += len;
      /* Separate lines with a newline.  */
      definition[idx++] = '\n';
    }

  /* We've got what we need; define the variable.  */
  if (idx == 0)
    definition[0] = '\0';
  else
    definition[idx - 1] = '\0';

  v = do_variable_definition (&defstart, name, definition, origin, flavor, 0);
  free (definition);
  free (var);
  return (v);
}

/* Interpret conditional commands "ifdef", "ifndef", "ifeq",
   "ifneq", "else" and "endif".
   LINE is the input line, with the command as its first word.

   FILENAME and LINENO are the filename and line number in the
   current makefile.  They are used for error messages.

   Value is -2 if the line is not a conditional at all,
   -1 if the line is an invalid conditional,
   0 if following text should be interpreted,
   1 if following text should be ignored.  */

static int
conditional_line (char *line, int len, const struct floc *flocp)
{
  char *cmdname;
  enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq, c_else, c_endif } cmdtype;
  unsigned int i;
  unsigned int o;

  /* Compare a word, both length and contents. */
#define	word1eq(s)      (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
#define	chkword(s, t)   if (word1eq (s)) { cmdtype = (t); cmdname = (s); }

  /* Make sure this line is a conditional.  */
  chkword ("ifdef", c_ifdef)
  else chkword ("ifndef", c_ifndef)
  else chkword ("ifeq", c_ifeq)
  else chkword ("ifneq", c_ifneq)
  else chkword ("else", c_else)
  else chkword ("endif", c_endif)
  else
    return -2;

  /* Found one: skip past it and any whitespace after it.  */
  line = next_token (line + len);

#define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)

  /* An 'endif' cannot contain extra text, and reduces the if-depth by 1  */
  if (cmdtype == c_endif)
    {
      if (*line != '\0')
	EXTRANEOUS ();

      if (!conditionals->if_cmds)
	fatal (flocp, _("extraneous `%s'"), cmdname);

      --conditionals->if_cmds;

      goto DONE;
    }

  /* An 'else' statement can either be simple, or it can have another
     conditional after it.  */
  if (cmdtype == c_else)
    {
      const char *p;

      if (!conditionals->if_cmds)
	fatal (flocp, _("extraneous `%s'"), cmdname);

      o = conditionals->if_cmds - 1;

      if (conditionals->seen_else[o])
        fatal (flocp, _("only one `else' per conditional"));

      /* Change the state of ignorance.  */
      switch (conditionals->ignoring[o])
        {
          case 0:
            /* We've just been interpreting.  Never do it again.  */
            conditionals->ignoring[o] = 2;
            break;
          case 1:
            /* We've never interpreted yet.  Maybe this time!  */
            conditionals->ignoring[o] = 0;
            break;
        }

      /* It's a simple 'else'.  */
      if (*line == '\0')
        {
          conditionals->seen_else[o] = 1;
          goto DONE;
        }

      /* The 'else' has extra text.  That text must be another conditional
         and cannot be an 'else' or 'endif'.  */

      /* Find the length of the next word.  */
      for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
        ;
      len = p - line;

      /* If it's 'else' or 'endif' or an illegal conditional, fail.  */
      if (word1eq("else") || word1eq("endif")
          || conditional_line (line, len, flocp) < 0)
	EXTRANEOUS ();
      else
        {
          /* conditional_line() created a new level of conditional.
             Raise it back to this level.  */
          if (conditionals->ignoring[o] < 2)
            conditionals->ignoring[o] = conditionals->ignoring[o+1];
          --conditionals->if_cmds;
        }

      goto DONE;
    }

  if (conditionals->allocated == 0)
    {
      conditionals->allocated = 5;
      conditionals->ignoring = xmalloc (conditionals->allocated);
      conditionals->seen_else = xmalloc (conditionals->allocated);
    }

  o = conditionals->if_cmds++;
  if (conditionals->if_cmds > conditionals->allocated)
    {
      conditionals->allocated += 5;
      conditionals->ignoring = xrealloc (conditionals->ignoring,
                                         conditionals->allocated);
      conditionals->seen_else = xrealloc (conditionals->seen_else,
                                          conditionals->allocated);
    }

  /* Record that we have seen an `if...' but no `else' so far.  */
  conditionals->seen_else[o] = 0;

  /* Search through the stack to see if we're already ignoring.  */
  for (i = 0; i < o; ++i)
    if (conditionals->ignoring[i])
      {
	/* We are already ignoring, so just push a level to match the next
	   "else" or "endif", and keep ignoring.  We don't want to expand
	   variables in the condition.  */
	conditionals->ignoring[o] = 1;
	return 1;
      }

  if (cmdtype == c_ifdef || cmdtype == c_ifndef)
    {
      char *var;
      struct variable *v;
      char *p;

      /* Expand the thing we're looking up, so we can use indirect and
         constructed variable names.  */
      var = allocated_variable_expand (line);

      /* Make sure there's only one variable name to test.  */
      p = end_of_token (var);
      i = p - var;
      p = next_token (p);
      if (*p != '\0')
	return -1;

      var[i] = '\0';
      v = lookup_variable (var, i);

      conditionals->ignoring[o] =
        ((v != 0 && *v->value != '\0') == (cmdtype == c_ifndef));

      free (var);
    }
  else
    {
      /* "ifeq" or "ifneq".  */
      char *s1, *s2;
      unsigned int l;
      char termin = *line == '(' ? ',' : *line;

      if (termin != ',' && termin != '"' && termin != '\'')
	return -1;

      s1 = ++line;
      /* Find the end of the first string.  */
      if (termin == ',')
	{
	  int count = 0;
	  for (; *line != '\0'; ++line)
	    if (*line == '(')
	      ++count;
	    else if (*line == ')')
	      --count;
	    else if (*line == ',' && count <= 0)
	      break;
	}
      else
	while (*line != '\0' && *line != termin)
	  ++line;

      if (*line == '\0')
	return -1;

      if (termin == ',')
	{
	  /* Strip blanks after the first string.  */
	  char *p = line++;
	  while (isblank ((unsigned char)p[-1]))
	    --p;
	  *p = '\0';
	}
      else
	*line++ = '\0';

      s2 = variable_expand (s1);
      /* We must allocate a new copy of the expanded string because
	 variable_expand re-uses the same buffer.  */
      l = strlen (s2);
      s1 = alloca (l + 1);
      memcpy (s1, s2, l + 1);

      if (termin != ',')
	/* Find the start of the second string.  */
	line = next_token (line);

      termin = termin == ',' ? ')' : *line;
      if (termin != ')' && termin != '"' && termin != '\'')
	return -1;

      /* Find the end of the second string.  */
      if (termin == ')')
	{
	  int count = 0;
	  s2 = next_token (line);
	  for (line = s2; *line != '\0'; ++line)
	    {
	      if (*line == '(')
		++count;
	      else if (*line == ')')
		{
		  if (count <= 0)
		    break;
		  else
		    --count;
		}
	    }
	}
      else
	{
	  ++line;
	  s2 = line;
	  while (*line != '\0' && *line != termin)
	    ++line;
	}

      if (*line == '\0')
	return -1;

      *line = '\0';
      line = next_token (++line);
      if (*line != '\0')
	EXTRANEOUS ();

      s2 = variable_expand (s2);
      conditionals->ignoring[o] = (streq (s1, s2) == (cmdtype == c_ifneq));
    }

 DONE:
  /* Search through the stack to see if we're ignoring.  */
  for (i = 0; i < conditionals->if_cmds; ++i)
    if (conditionals->ignoring[i])
      return 1;
  return 0;
}

/* Remove duplicate dependencies in CHAIN.  */

static unsigned long
dep_hash_1 (const void *key)
{
  return_STRING_HASH_1 (dep_name ((struct dep const *) key));
}

static unsigned long
dep_hash_2 (const void *key)
{
  return_STRING_HASH_2 (dep_name ((struct dep const *) key));
}

static int
dep_hash_cmp (const void *x, const void *y)
{
  struct dep *dx = (struct dep *) x;
  struct dep *dy = (struct dep *) y;
  int cmp = strcmp (dep_name (dx), dep_name (dy));

  /* If the names are the same but ignore_mtimes are not equal, one of these
     is an order-only prerequisite and one isn't.  That means that we should
     remove the one that isn't and keep the one that is.  */

  if (!cmp && dx->ignore_mtime != dy->ignore_mtime)
    dx->ignore_mtime = dy->ignore_mtime = 0;

  return cmp;
}


void
uniquize_deps (struct dep *chain)
{
  struct hash_table deps;
  register struct dep **depp;

  hash_init (&deps, 500, dep_hash_1, dep_hash_2, dep_hash_cmp);

  /* Make sure that no dependencies are repeated.  This does not
     really matter for the purpose of updating targets, but it
     might make some names be listed twice for $^ and $?.  */

  depp = &chain;
  while (*depp)
    {
      struct dep *dep = *depp;
      struct dep **dep_slot = (struct dep **) hash_find_slot (&deps, dep);
      if (HASH_VACANT (*dep_slot))
	{
	  hash_insert_at (&deps, dep, dep_slot);
	  depp = &dep->next;
	}
      else
	{
	  /* Don't bother freeing duplicates.
	     It's dangerous and little benefit accrues.  */
	  *depp = dep->next;
	}
    }

  hash_free (&deps, 0);
}

/* Record target-specific variable values for files FILENAMES.
   TWO_COLON is nonzero if a double colon was used.

   The links of FILENAMES are freed, and so are any names in it
   that are not incorporated into other data structures.

   If the target is a pattern, add the variable to the pattern-specific
   variable value list.  */

static void
record_target_var (struct nameseq *filenames, char *defn,
                   enum variable_origin origin, struct vmodifiers *vmod,
                   const struct floc *flocp)
{
  struct nameseq *nextf;
  struct variable_set_list *global;

  global = current_variable_set_list;

  /* If the variable is an append version, store that but treat it as a
     normal recursive variable.  */

  for (; filenames != 0; filenames = nextf)
    {
      struct variable *v;
      const char *name = filenames->name;
      const char *fname;
      const char *percent;
      struct pattern_var *p;

      nextf = filenames->next;
      free (filenames);

      /* If it's a pattern target, then add it to the pattern-specific
         variable list.  */
      percent = find_percent_cached (&name);
      if (percent)
        {
          /* Get a reference for this pattern-specific variable struct.  */
          p = create_pattern_var (name, percent);
          p->variable.fileinfo = *flocp;
          /* I don't think this can fail since we already determined it was a
             variable definition.  */
          v = assign_variable_definition (&p->variable, defn);
          assert (v != 0);

          v->origin = origin;
          if (v->flavor == f_simple)
            v->value = allocated_variable_expand (v->value);
          else
            v->value = xstrdup (v->value);

          fname = p->target;
        }
      else
        {
          struct file *f;

          /* Get a file reference for this file, and initialize it.
             We don't want to just call enter_file() because that allocates a
             new entry if the file is a double-colon, which we don't want in
             this situation.  */
          f = lookup_file (name);
          if (!f)
            f = enter_file (strcache_add (name));
          else if (f->double_colon)
            f = f->double_colon;

          initialize_file_variables (f, 1);
          fname = f->name;

          current_variable_set_list = f->variables;
          v = try_variable_definition (flocp, defn, origin, 1);
          if (!v)
            fatal (flocp, _("Malformed target-specific variable definition"));
          current_variable_set_list = global;
        }

      /* Set up the variable to be *-specific.  */
      v->per_target = 1;
      v->private_var = vmod->private_v;
      v->export = vmod->export_v ? v_export : v_default;

      /* If it's not an override, check to see if there was a command-line
         setting.  If so, reset the value.  */
      if (v->origin != o_override)
        {
          struct variable *gv;
          int len = strlen(v->name);

          gv = lookup_variable (v->name, len);
          if (gv && (gv->origin == o_env_override || gv->origin == o_command))
            {
              if (v->value != 0)
                free (v->value);
              v->value = xstrdup (gv->value);
              v->origin = gv->origin;
              v->recursive = gv->recursive;
              v->append = 0;
            }
        }
    }
}

/* Record a description line for files FILENAMES,
   with dependencies DEPS, commands to execute described
   by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
   TWO_COLON is nonzero if a double colon was used.
   If not nil, PATTERN is the `%' pattern to make this
   a static pattern rule, and PATTERN_PERCENT is a pointer
   to the `%' within it.

   The links of FILENAMES are freed, and so are any names in it
   that are not incorporated into other data structures.  */

static void
record_files (struct nameseq *filenames, const char *pattern,
              const char *pattern_percent, struct dep *deps,
              unsigned int cmds_started, char *commands,
              unsigned int commands_idx, int two_colon,
              const struct floc *flocp)
{
  struct nameseq *nextf;
  int implicit = 0;
  unsigned int max_targets = 0, target_idx = 0;
  const char **targets = 0, **target_percents = 0;
  struct commands *cmds;

  /* If we've already snapped deps, that means we're in an eval being
     resolved after the makefiles have been read in.  We can't add more rules
     at this time, since they won't get snapped and we'll get core dumps.
     See Savannah bug # 12124.  */
  if (snapped_deps)
    fatal (flocp, _("prerequisites cannot be defined in recipes"));

  if (commands_idx > 0)
    {
      cmds = xmalloc (sizeof (struct commands));
      cmds->fileinfo.filenm = flocp->filenm;
      cmds->fileinfo.lineno = cmds_started;
      cmds->commands = xstrndup (commands, commands_idx);
      cmds->command_lines = 0;
    }
  else
    cmds = 0;

  for (; filenames != 0; filenames = nextf)
    {
      const char *name = filenames->name;
      struct file *f;
      struct dep *this = 0;
      const char *implicit_percent;

      nextf = filenames->next;
      free (filenames);

      /* Check for special targets.  Do it here instead of, say, snap_deps()
         so that we can immediately use the value.  */

      if (streq (name, ".POSIX"))
        posix_pedantic = 1;
      else if (streq (name, ".SECONDEXPANSION"))
        second_expansion = 1;

      implicit_percent = find_percent_cached (&name);
      implicit |= implicit_percent != 0;

      if (implicit)
        {
          if (pattern != 0)
            fatal (flocp, _("mixed implicit and static pattern rules"));

          if (implicit_percent == 0)
            fatal (flocp, _("mixed implicit and normal rules"));

	  if (targets == 0)
	    {
	      max_targets = 5;
	      targets = xmalloc (5 * sizeof (char *));
	      target_percents = xmalloc (5 * sizeof (char *));
	      target_idx = 0;
	    }
	  else if (target_idx == max_targets - 1)
	    {
	      max_targets += 5;
	      targets = xrealloc (targets, max_targets * sizeof (char *));
	      target_percents = xrealloc (target_percents,
                                          max_targets * sizeof (char *));
	    }
	  targets[target_idx] = name;
	  target_percents[target_idx] = implicit_percent;
	  ++target_idx;
	  continue;
	}

      /* If this is a static pattern rule:
         `targets: target%pattern: dep%pattern; cmds',
         make sure the pattern matches this target name.  */
      if (pattern && !pattern_matches (pattern, pattern_percent, name))
        error (flocp, _("target `%s' doesn't match the target pattern"), name);
      else if (deps)
        {
          /* If there are multiple filenames, copy the chain DEPS for all but
             the last one.  It is not safe for the same deps to go in more
             than one place in the database.  */
          this = nextf != 0 ? copy_dep_chain (deps) : deps;
          this->need_2nd_expansion = (second_expansion
				      && strchr (this->name, '$'));
        }

      if (!two_colon)
	{
	  /* Single-colon.  Combine these dependencies
	     with others in file's existing record, if any.  */
	  f = enter_file (strcache_add (name));

	  if (f->double_colon)
	    fatal (flocp,
                   _("target file `%s' has both : and :: entries"), f->name);

	  /* If CMDS == F->CMDS, this target was listed in this rule
	     more than once.  Just give a warning since this is harmless.  */
	  if (cmds != 0 && cmds == f->cmds)
	    error (flocp,
                   _("target `%s' given more than once in the same rule."),
                   f->name);

	  /* Check for two single-colon entries both with commands.
	     Check is_target so that we don't lose on files such as .c.o
	     whose commands were preinitialized.  */
	  else if (cmds != 0 && f->cmds != 0 && f->is_target)
	    {
	      error (&cmds->fileinfo,
                     _("warning: overriding recipe for target `%s'"),
                     f->name);
	      error (&f->cmds->fileinfo,
                     _("warning: ignoring old recipe for target `%s'"),
                     f->name);
	    }

	  f->is_target = 1;

	  /* Defining .DEFAULT with no deps or cmds clears it.  */
	  if (f == default_file && this == 0 && cmds == 0)
	    f->cmds = 0;
	  if (cmds != 0)
	    f->cmds = cmds;

	  /* Defining .SUFFIXES with no dependencies clears out the list of
	     suffixes.  */
	  if (f == suffix_file && this == 0)
	    {
              free_dep_chain (f->deps);
	      f->deps = 0;
	    }
          else if (this != 0)
	    {
	      /* Add the file's old deps and the new ones in THIS together.  */

              if (f->deps != 0)
                {
                  struct dep **d_ptr = &f->deps;

                  while ((*d_ptr)->next != 0)
                    d_ptr = &(*d_ptr)->next;

                  if (cmds != 0)
                    /* This is the rule with commands, so put its deps
                       last. The rationale behind this is that $< expands to
                       the first dep in the chain, and commands use $<
                       expecting to get the dep that rule specifies.  However
                       the second expansion algorithm reverses the order thus
                       we need to make it last here.  */
                    (*d_ptr)->next = this;
                  else
                    {
                      /* This is the rule without commands. Put its
                         dependencies at the end but before dependencies from
                         the rule with commands (if any). This way everything
                         appears in makefile order.  */

                      if (f->cmds != 0)
                        {
                          this->next = *d_ptr;
                          *d_ptr = this;
                        }
                      else
                        (*d_ptr)->next = this;
                    }
                }
              else
                f->deps = this;

              /* This is a hack. I need a way to communicate to snap_deps()
                 that the last dependency line in this file came with commands
                 (so that logic in snap_deps() can put it in front and all
                 this $< -logic works). I cannot simply rely on file->cmds
                 being not 0 because of the cases like the following:

                 foo: bar
                 foo:
                     ...

                 I am going to temporarily "borrow" UPDATING member in
                 `struct file' for this.   */

              if (cmds != 0)
                f->updating = 1;
	    }
	}
      else
	{
	  /* Double-colon.  Make a new record even if there already is one.  */
	  f = lookup_file (name);

	  /* Check for both : and :: rules.  Check is_target so
	     we don't lose on default suffix rules or makefiles.  */
	  if (f != 0 && f->is_target && !f->double_colon)
	    fatal (flocp,
                   _("target file `%s' has both : and :: entries"), f->name);
	  f = enter_file (strcache_add (name));
	  /* If there was an existing entry and it was a double-colon entry,
	     enter_file will have returned a new one, making it the prev
	     pointer of the old one, and setting its double_colon pointer to
	     the first one.  */
	  if (f->double_colon == 0)
	    /* This is the first entry for this name, so we must set its
	       double_colon pointer to itself.  */
	    f->double_colon = f;
	  f->is_target = 1;
	  f->deps = this;
	  f->cmds = cmds;
	}

      /* If this is a static pattern rule, set the stem to the part of its
         name that matched the `%' in the pattern, so you can use $* in the
         commands.  */
      if (pattern)
        {
          static const char *percent = "%";
          char *buffer = variable_expand ("");
          char *o = patsubst_expand_pat (buffer, name, pattern, percent,
                                         pattern_percent+1, percent+1);
          f->stem = strcache_add_len (buffer, o - buffer);
          if (this)
            {
              this->staticpattern = 1;
              this->stem = f->stem;
            }
        }

      name = f->name;
    }

  if (implicit)
    {
      if (deps)
        deps->need_2nd_expansion = second_expansion;
      create_pattern_rule (targets, target_percents, target_idx,
                           two_colon, deps, cmds, 1);
    }
}

/* Search STRING for an unquoted STOPCHAR or blank (if BLANK is nonzero).
   Backslashes quote STOPCHAR, blanks if BLANK is nonzero, and backslash.
   Quoting backslashes are removed from STRING by compacting it into
   itself.  Returns a pointer to the first unquoted STOPCHAR if there is
   one, or nil if there are none.  STOPCHARs inside variable references are
   ignored if IGNOREVARS is true.

   STOPCHAR _cannot_ be '$' if IGNOREVARS is true.  */

static char *
find_char_unquote (char *string, int stop1, int stop2, int blank,
                   int ignorevars)
{
  unsigned int string_len = 0;
  char *p = string;

  if (ignorevars)
    ignorevars = '$';

  while (1)
    {
      if (stop2 && blank)
	while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2
	       && ! isblank ((unsigned char) *p))
	  ++p;
      else if (stop2)
	while (*p != '\0' && *p != ignorevars && *p != stop1 && *p != stop2)
	  ++p;
      else if (blank)
	while (*p != '\0' && *p != ignorevars && *p != stop1
	       && ! isblank ((unsigned char) *p))
	  ++p;
      else
	while (*p != '\0' && *p != ignorevars && *p != stop1)
	  ++p;

      if (*p == '\0')
	break;

      /* If we stopped due to a variable reference, skip over its contents.  */
      if (*p == ignorevars)
        {
          char openparen = p[1];

          p += 2;

          /* Skip the contents of a non-quoted, multi-char variable ref.  */
          if (openparen == '(' || openparen == '{')
            {
              unsigned int pcount = 1;
              char closeparen = (openparen == '(' ? ')' : '}');

              while (*p)
                {
                  if (*p == openparen)
                    ++pcount;
                  else if (*p == closeparen)
                    if (--pcount == 0)
                      {
                        ++p;
                        break;
                      }
                  ++p;
                }
            }

          /* Skipped the variable reference: look for STOPCHARS again.  */
          continue;
        }

      if (p > string && p[-1] == '\\')
	{
	  /* Search for more backslashes.  */
	  int i = -2;
	  while (&p[i] >= string && p[i] == '\\')
	    --i;
	  ++i;
	  /* Only compute the length if really needed.  */
	  if (string_len == 0)
	    string_len = strlen (string);
	  /* The number of backslashes is now -I.
	     Copy P over itself to swallow half of them.  */
	  memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
	  p += i/2;
	  if (i % 2 == 0)
	    /* All the backslashes quoted each other; the STOPCHAR was
	       unquoted.  */
	    return p;

	  /* The STOPCHAR was quoted by a backslash.  Look for another.  */
	}
      else
	/* No backslash in sight.  */
	return p;
    }

  /* Never hit a STOPCHAR or blank (with BLANK nonzero).  */
  return 0;
}

/* Search PATTERN for an unquoted % and handle quoting.  */

char *
find_percent (char *pattern)
{
  return find_char_unquote (pattern, '%', 0, 0, 0);
}

/* Search STRING for an unquoted % and handle quoting.  Returns a pointer to
   the % or NULL if no % was found.
   This version is used with strings in the string cache: if there's a need to
   modify the string a new version will be added to the string cache and
   *STRING will be set to that.  */

const char *
find_percent_cached (const char **string)
{
  const char *p = *string;
  char *new = 0;
  int slen;

  /* If the first char is a % return now.  This lets us avoid extra tests
     inside the loop.  */
  if (*p == '%')
    return p;

  while (1)
    {
      while (*p != '\0' && *p != '%')
        ++p;

      if (*p == '\0')
        break;

      /* See if this % is escaped with a backslash; if not we're done.  */
      if (p[-1] != '\\')
        break;

      {
        /* Search for more backslashes.  */
        char *pv;
        int i = -2;

        while (&p[i] >= *string && p[i] == '\\')
          --i;
        ++i;

        /* At this point we know we'll need to allocate a new string.
           Make a copy if we haven't yet done so.  */
        if (! new)
          {
            slen = strlen (*string);
            new = alloca (slen + 1);
            memcpy (new, *string, slen + 1);
            p = new + (p - *string);
            *string = new;
          }

        /* At this point *string, p, and new all point into the same string.
           Get a non-const version of p so we can modify new.  */
        pv = new + (p - *string);

        /* The number of backslashes is now -I.
           Copy P over itself to swallow half of them.  */
        memmove (&pv[i], &pv[i/2], (slen - (pv - new)) - (i/2) + 1);
        p += i/2;

        /* If the backslashes quoted each other; the % was unquoted.  */
        if (i % 2 == 0)
          break;
      }
    }

  /* If we had to change STRING, add it to the strcache.  */
  if (new)
    {
      *string = strcache_add (*string);
      p = *string + (p - new);
    }

  /* If we didn't find a %, return NULL.  Otherwise return a ptr to it.  */
  return (*p == '\0') ? NULL : p;
}

/* Parse a string into a sequence of filenames represented as a
   chain of struct nameseq's in reverse order and return that chain.

   The string is passed as STRINGP, the address of a string pointer.
   The string pointer is updated to point at the first character
   not parsed, which either is a null char or equals STOPCHAR.

   SIZE is how big to construct chain elements.
   This is useful if we want them actually to be other structures
   that have room for additional info.

   If STRIP is nonzero, strip `./'s off the beginning.  */

struct nameseq *
parse_file_seq (char **stringp, int stopchar, unsigned int size, int strip)
{
  struct nameseq *new = 0;
  struct nameseq *new1, *lastnew1;
  char *p = *stringp;

#ifdef VMS
# define VMS_COMMA ','
#else
# define VMS_COMMA 0
#endif

  while (1)
    {
      const char *name;
      char *q;

      /* Skip whitespace; see if any more names are left.  */
      p = next_token (p);
      if (*p == '\0')
	break;
      if (*p == stopchar)
	break;

      /* There are, so find the end of the next name.  */
      q = p;
      p = find_char_unquote (q, stopchar, VMS_COMMA, 1, 0);
#ifdef VMS
	/* convert comma separated list to space separated */
      if (p && *p == ',')
	*p =' ';
#endif
#ifdef _AMIGA
      if (stopchar == ':' && p && *p == ':'
          && !(isspace ((unsigned char)p[1]) || !p[1]
               || isspace ((unsigned char)p[-1])))
	p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
#endif
#ifdef HAVE_DOS_PATHS
    /* For DOS paths, skip a "C:\..." or a "C:/..." until we find the
       first colon which isn't followed by a slash or a backslash.
       Note that tokens separated by spaces should be treated as separate
       tokens since make doesn't allow path names with spaces */
    if (stopchar == ':')
      while (p != 0 && !isspace ((unsigned char)*p) &&
             (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
        p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
#endif
      if (p == 0)
	p = q + strlen (q);

      if (strip)
#ifdef VMS
	/* Skip leading `[]'s.  */
	while (p - q > 2 && q[0] == '[' && q[1] == ']')
#else
	/* Skip leading `./'s.  */
	while (p - q > 2 && q[0] == '.' && q[1] == '/')
#endif
	  {
	    q += 2;		/* Skip "./".  */
	    while (q < p && *q == '/')
	      /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
	      ++q;
	  }

      /* Extract the filename just found, and skip it.  */

      if (q == p)
	/* ".///" was stripped to "". */
#if defined(VMS)
	continue;
#elif defined(_AMIGA)
        name = "";
#else
	name = "./";
#endif
      else
#ifdef VMS
/* VMS filenames can have a ':' in them but they have to be '\'ed but we need
 *  to remove this '\' before we can use the filename.
 * xstrdup called because q may be read-only string constant.
 */
	{
	  char *qbase = xstrdup (q);
	  char *pbase = qbase + (p-q);
	  char *q1 = qbase;
	  char *q2 = q1;
	  char *p1 = pbase;

	  while (q1 != pbase)
	    {
	      if (*q1 == '\\' && *(q1+1) == ':')
		{
		  q1++;
		  p1--;
		}
	      *q2++ = *q1++;
	    }
	  name = strcache_add_len (qbase, p1 - qbase);
	  free (qbase);
	}
#else
	name = strcache_add_len (q, p - q);
#endif

      /* Add it to the front of the chain.  */
      new1 = xmalloc (size);
      memset (new1, '\0', size);
      new1->name = name;
      new1->next = new;
      new = new1;
    }

#ifndef NO_ARCHIVES

  /* Look for multi-word archive references.
     They are indicated by a elt ending with an unmatched `)' and
     an elt further down the chain (i.e., previous in the file list)
     with an unmatched `(' (e.g., "lib(mem").  */

  new1 = new;
  lastnew1 = 0;
  while (new1 != 0)
    if (new1->name[0] != '('	/* Don't catch "(%)" and suchlike.  */
	&& new1->name[strlen (new1->name) - 1] == ')'
	&& strchr (new1->name, '(') == 0)
      {
	/* NEW1 ends with a `)' but does not contain a `('.
	   Look back for an elt with an opening `(' but no closing `)'.  */

	struct nameseq *n = new1->next, *lastn = new1;
	char *paren = 0;
	while (n != 0 && (paren = strchr (n->name, '(')) == 0)
	  {
	    lastn = n;
	    n = n->next;
	  }
	if (n != 0
	    /* Ignore something starting with `(', as that cannot actually
	       be an archive-member reference (and treating it as such
	       results in an empty file name, which causes much lossage).  */
	    && n->name[0] != '(')
	  {
	    /* N is the first element in the archive group.
	       Its name looks like "lib(mem" (with no closing `)').  */

	    char *libname;

	    /* Copy "lib(" into LIBNAME.  */
	    ++paren;
	    libname = alloca (paren - n->name + 1);
	    memcpy (libname, n->name, paren - n->name);
	    libname[paren - n->name] = '\0';

	    if (*paren == '\0')
	      {
		/* N was just "lib(", part of something like "lib( a b)".
		   Edit it out of the chain and free its storage.  */
		lastn->next = n->next;
		free (n);
		/* LASTN->next is the new stopping elt for the loop below.  */
		n = lastn->next;
	      }
	    else
	      {
		/* Replace N's name with the full archive reference.  */
		n->name = strcache_add (concat (libname, paren, ")"));
	      }

	    if (new1->name[1] == '\0')
	      {
		/* NEW1 is just ")", part of something like "lib(a b )".
		   Omit it from the chain and free its storage.  */
		if (lastnew1 == 0)
		  new = new1->next;
		else
		  lastnew1->next = new1->next;
		lastn = new1;
		new1 = new1->next;
		free (lastn);
	      }
	    else
	      {
		/* Replace also NEW1->name, which already has closing `)'.  */
		new1->name = strcache_add (concat (libname, new1->name, ""));
		new1 = new1->next;
	      }

	    /* Trace back from NEW1 (the end of the list) until N
	       (the beginning of the list), rewriting each name
	       with the full archive reference.  */

	    while (new1 != n)
	      {
		new1->name = strcache_add (concat (libname, new1->name, ")"));
		lastnew1 = new1;
		new1 = new1->next;
	      }
	  }
	else
	  {
	    /* No frobnication happening.  Just step down the list.  */
	    lastnew1 = new1;
	    new1 = new1->next;
	  }
      }
    else
      {
	lastnew1 = new1;
	new1 = new1->next;
      }

#endif

  *stringp = p;
  return new;
}

/* Find the next line of text in an eval buffer, combining continuation lines
   into one line.
   Return the number of actual lines read (> 1 if continuation lines).
   Returns -1 if there's nothing left in the buffer.

   After this function, ebuf->buffer points to the first character of the
   line we just found.
 */

/* Read a line of text from a STRING.
   Since we aren't really reading from a file, don't bother with linenumbers.
 */

static unsigned long
readstring (struct ebuffer *ebuf)
{
  char *eol;

  /* If there is nothing left in this buffer, return 0.  */
  if (ebuf->bufnext >= ebuf->bufstart + ebuf->size)
    return -1;

  /* Set up a new starting point for the buffer, and find the end of the
     next logical line (taking into account backslash/newline pairs).  */

  eol = ebuf->buffer = ebuf->bufnext;

  while (1)
    {
      int backslash = 0;
      char *bol = eol;
      char *p;

      /* Find the next newline.  At EOS, stop.  */
      eol = p = strchr (eol , '\n');
      if (!eol)
        {
          ebuf->bufnext = ebuf->bufstart + ebuf->size + 1;
          return 0;
        }

      /* Found a newline; if it's escaped continue; else we're done.  */
      while (p > bol && *(--p) == '\\')
        backslash = !backslash;
      if (!backslash)
        break;
      ++eol;
    }

  /* Overwrite the newline char.  */
  *eol = '\0';
  ebuf->bufnext = eol+1;

  return 0;
}

static long
readline (struct ebuffer *ebuf)
{
  char *p;
  char *end;
  char *start;
  long nlines = 0;

  /* The behaviors between string and stream buffers are different enough to
     warrant different functions.  Do the Right Thing.  */

  if (!ebuf->fp)
    return readstring (ebuf);

  /* When reading from a file, we always start over at the beginning of the
     buffer for each new line.  */

  p = start = ebuf->bufstart;
  end = p + ebuf->size;
  *p = '\0';

  while (fgets (p, end - p, ebuf->fp) != 0)
    {
      char *p2;
      unsigned long len;
      int backslash;

      len = strlen (p);
      if (len == 0)
	{
	  /* This only happens when the first thing on the line is a '\0'.
	     It is a pretty hopeless case, but (wonder of wonders) Athena
	     lossage strikes again!  (xmkmf puts NULs in its makefiles.)
	     There is nothing really to be done; we synthesize a newline so
	     the following line doesn't appear to be part of this line.  */
	  error (&ebuf->floc,
                 _("warning: NUL character seen; rest of line ignored"));
	  p[0] = '\n';
	  len = 1;
	}

      /* Jump past the text we just read.  */
      p += len;

      /* If the last char isn't a newline, the whole line didn't fit into the
         buffer.  Get some more buffer and try again.  */
      if (p[-1] != '\n')
        goto more_buffer;

      /* We got a newline, so add one to the count of lines.  */
      ++nlines;

#if !defined(WINDOWS32) && !defined(__MSDOS__) && !defined(__EMX__)
      /* Check to see if the line was really ended with CRLF; if so ignore
         the CR.  */
      if ((p - start) > 1 && p[-2] == '\r')
        {
          --p;
          p[-1] = '\n';
        }
#endif

      backslash = 0;
      for (p2 = p - 2; p2 >= start; --p2)
	{
	  if (*p2 != '\\')
	    break;
          backslash = !backslash;
	}

      if (!backslash)
	{
	  p[-1] = '\0';
	  break;
	}

      /* It was a backslash/newline combo.  If we have more space, read
         another line.  */
      if (end - p >= 80)
        continue;

      /* We need more space at the end of our buffer, so realloc it.
         Make sure to preserve the current offset of p.  */
    more_buffer:
      {
        unsigned long off = p - start;
        ebuf->size *= 2;
        start = ebuf->buffer = ebuf->bufstart = xrealloc (start, ebuf->size);
        p = start + off;
        end = start + ebuf->size;
        *p = '\0';
      }
    }

  if (ferror (ebuf->fp))
    pfatal_with_name (ebuf->floc.filenm);

  /* If we found some lines, return how many.
     If we didn't, but we did find _something_, that indicates we read the last
     line of a file with no final newline; return 1.
     If we read nothing, we're at EOF; return -1.  */

  return nlines ? nlines : p == ebuf->bufstart ? -1 : 1;
}

/* Parse the next "makefile word" from the input buffer, and return info
   about it.

   A "makefile word" is one of:

     w_bogus        Should never happen
     w_eol          End of input
     w_static       A static word; cannot be expanded
     w_variable     A word containing one or more variables/functions
     w_colon        A colon
     w_dcolon       A double-colon
     w_semicolon    A semicolon
     w_varassign    A variable assignment operator (=, :=, +=, or ?=)

   Note that this function is only used when reading certain parts of the
   makefile.  Don't use it where special rules hold sway (RHS of a variable,
   in a command list, etc.)  */

static enum make_word_type
get_next_mword (char *buffer, char *delim, char **startp, unsigned int *length)
{
  enum make_word_type wtype = w_bogus;
  char *p = buffer, *beg;
  char c;

  /* Skip any leading whitespace.  */
  while (isblank ((unsigned char)*p))
    ++p;

  beg = p;
  c = *(p++);
  switch (c)
    {
    case '\0':
      wtype = w_eol;
      break;

    case ';':
      wtype = w_semicolon;
      break;

    case '=':
      wtype = w_varassign;
      break;

    case ':':
      wtype = w_colon;
      switch (*p)
        {
        case ':':
          ++p;
          wtype = w_dcolon;
          break;

        case '=':
          ++p;
          wtype = w_varassign;
          break;
        }
      break;

    case '+':
    case '?':
      if (*p == '=')
        {
          ++p;
          wtype = w_varassign;
          break;
        }

    default:
      if (delim && strchr (delim, c))
        wtype = w_static;
      break;
    }

  /* Did we find something?  If so, return now.  */
  if (wtype != w_bogus)
    goto done;

  /* This is some non-operator word.  A word consists of the longest
     string of characters that doesn't contain whitespace, one of [:=#],
     or [?+]=, or one of the chars in the DELIM string.  */

  /* We start out assuming a static word; if we see a variable we'll
     adjust our assumptions then.  */
  wtype = w_static;

  /* We already found the first value of "c", above.  */
  while (1)
    {
      char closeparen;
      int count;

      switch (c)
        {
        case '\0':
        case ' ':
        case '\t':
        case '=':
          goto done_word;

        case ':':
#ifdef HAVE_DOS_PATHS
	  /* A word CAN include a colon in its drive spec.  The drive
	     spec is allowed either at the beginning of a word, or as part
	     of the archive member name, like in "libfoo.a(d:/foo/bar.o)".  */
	  if (!(p - beg >= 2
		&& (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
		&& (p - beg == 2 || p[-3] == '(')))
#endif
	  goto done_word;

        case '$':
          c = *(p++);
          if (c == '$')
            break;

          /* This is a variable reference, so note that it's expandable.
             Then read it to the matching close paren.  */
          wtype = w_variable;

          if (c == '(')
            closeparen = ')';
          else if (c == '{')
            closeparen = '}';
          else
            /* This is a single-letter variable reference.  */
            break;

          for (count=0; *p != '\0'; ++p)
            {
              if (*p == c)
                ++count;
              else if (*p == closeparen && --count < 0)
                {
                  ++p;
                  break;
                }
            }
          break;

        case '?':
        case '+':
          if (*p == '=')
            goto done_word;
          break;

        case '\\':
          switch (*p)
            {
            case ':':
            case ';':
            case '=':
            case '\\':
              ++p;
              break;
            }
          break;

        default:
          if (delim && strchr (delim, c))
            goto done_word;
          break;
        }

      c = *(p++);
    }
 done_word:
  --p;

 done:
  if (startp)
    *startp = beg;
  if (length)
    *length = p - beg;
  return wtype;
}

/* Construct the list of include directories
   from the arguments and the default list.  */

void
construct_include_path (const char **arg_dirs)
{
#ifdef VAXC		/* just don't ask ... */
  stat_t stbuf;
#else
  struct stat stbuf;
#endif
  const char **dirs;
  const char **cpp;
  unsigned int idx;

  /* Compute the number of pointers we need in the table.  */
  idx = sizeof (default_include_directories) / sizeof (const char *);
  if (arg_dirs)
    for (cpp = arg_dirs; *cpp != 0; ++cpp)
      ++idx;

#ifdef  __MSDOS__
  /* Add one for $DJDIR.  */
  ++idx;
#endif

  dirs = xmalloc (idx * sizeof (const char *));

  idx = 0;
  max_incl_len = 0;

  /* First consider any dirs specified with -I switches.
     Ignore any that don't exist.  Remember the maximum string length.  */

  if (arg_dirs)
    while (*arg_dirs != 0)
      {
	const char *dir = *(arg_dirs++);
        char *expanded = 0;
        int e;

	if (dir[0] == '~')
	  {
	    expanded = tilde_expand (dir);
	    if (expanded != 0)
	      dir = expanded;
	  }

        EINTRLOOP (e, stat (dir, &stbuf));
	if (e == 0 && S_ISDIR (stbuf.st_mode))
          {
            unsigned int len = strlen (dir);
            /* If dir name is written with trailing slashes, discard them.  */
            while (len > 1 && dir[len - 1] == '/')
              --len;
            if (len > max_incl_len)
              max_incl_len = len;
            dirs[idx++] = strcache_add_len (dir, len);
          }

	if (expanded)
	  free (expanded);
      }

  /* Now add the standard default dirs at the end.  */

#ifdef  __MSDOS__
  {
    /* The environment variable $DJDIR holds the root of the DJGPP directory
       tree; add ${DJDIR}/include.  */
    struct variable *djdir = lookup_variable ("DJDIR", 5);

    if (djdir)
      {
        unsigned int len = strlen (djdir->value) + 8;
	char *defdir = alloca (len + 1);

	strcat (strcpy (defdir, djdir->value), "/include");
	dirs[idx++] = strcache_add (defdir);

        if (len > max_incl_len)
          max_incl_len = len;
      }
  }
#endif

  for (cpp = default_include_directories; *cpp != 0; ++cpp)
    {
      int e;

      EINTRLOOP (e, stat (*cpp, &stbuf));
      if (e == 0 && S_ISDIR (stbuf.st_mode))
        {
          unsigned int len = strlen (*cpp);
          /* If dir name is written with trailing slashes, discard them.  */
          while (len > 1 && (*cpp)[len - 1] == '/')
            --len;
          if (len > max_incl_len)
            max_incl_len = len;
          dirs[idx++] = strcache_add_len (*cpp, len);
        }
    }

  dirs[idx] = 0;

  /* Now add each dir to the .INCLUDE_DIRS variable.  */

  for (cpp = dirs; *cpp != 0; ++cpp)
    do_variable_definition (NILF, ".INCLUDE_DIRS", *cpp,
                            o_default, f_append, 0);

  include_directories = dirs;
}

/* Expand ~ or ~USER at the beginning of NAME.
   Return a newly malloc'd string or 0.  */

char *
tilde_expand (const char *name)
{
#ifndef VMS
  if (name[1] == '/' || name[1] == '\0')
    {
      extern char *getenv ();
      char *home_dir;
      int is_variable;

      {
	/* Turn off --warn-undefined-variables while we expand HOME.  */
	int save = warn_undefined_variables_flag;
	warn_undefined_variables_flag = 0;

	home_dir = allocated_variable_expand ("$(HOME)");

	warn_undefined_variables_flag = save;
      }

      is_variable = home_dir[0] != '\0';
      if (!is_variable)
	{
	  free (home_dir);
	  home_dir = getenv ("HOME");
	}
# if !defined(_AMIGA) && !defined(WINDOWS32)
      if (home_dir == 0 || home_dir[0] == '\0')
	{
	  extern char *getlogin ();
	  char *logname = getlogin ();
	  home_dir = 0;
	  if (logname != 0)
	    {
	      struct passwd *p = getpwnam (logname);
	      if (p != 0)
		home_dir = p->pw_dir;
	    }
	}
# endif /* !AMIGA && !WINDOWS32 */
      if (home_dir != 0)
	{
	  char *new = xstrdup (concat (home_dir, "", name + 1));
	  if (is_variable)
	    free (home_dir);
	  return new;
	}
    }
# if !defined(_AMIGA) && !defined(WINDOWS32)
  else
    {
      struct passwd *pwent;
      char *userend = strchr (name + 1, '/');
      if (userend != 0)
	*userend = '\0';
      pwent = getpwnam (name + 1);
      if (pwent != 0)
	{
	  if (userend == 0)
	    return xstrdup (pwent->pw_dir);
	  else
	    return xstrdup (concat (pwent->pw_dir, "/", userend + 1));
	}
      else if (userend != 0)
	*userend = '/';
    }
# endif /* !AMIGA && !WINDOWS32 */
#endif /* !VMS */
  return 0;
}

/* Given a chain of struct nameseq's describing a sequence of filenames,
   in reverse of the intended order, return a new chain describing the
   result of globbing the filenames.  The new chain is in forward order.
   The links of the old chain are freed or used in the new chain.
   Likewise for the names in the old chain.

   SIZE is how big to construct chain elements.
   This is useful if we want them actually to be other structures
   that have room for additional info.  */

struct nameseq *
multi_glob (struct nameseq *chain, unsigned int size)
{
  void dir_setup_glob (glob_t *);
  struct nameseq *new = 0;
  struct nameseq *old;
  struct nameseq *nexto;
  glob_t gl;

  dir_setup_glob (&gl);

  for (old = chain; old != 0; old = nexto)
    {
      const char *gname;
#ifndef NO_ARCHIVES
      char *arname = 0;
      char *memname = 0;
#endif
      nexto = old->next;
      gname = old->name;

      if (gname[0] == '~')
	{
	  char *newname = tilde_expand (old->name);
	  if (newname != 0)
            gname = newname;
	}

#ifndef NO_ARCHIVES
      if (ar_name (gname))
	{
	  /* OLD->name is an archive member reference.  Replace it with the
	     archive file name, and save the member name in MEMNAME.  We will
	     glob on the archive name and then reattach MEMNAME later.  */
	  ar_parse_name (gname, &arname, &memname);
	  gname = arname;
	}
#endif /* !NO_ARCHIVES */

      switch (glob (gname, GLOB_NOCHECK|GLOB_ALTDIRFUNC, NULL, &gl))
	{
	case 0:			/* Success.  */
	  {
	    int i = gl.gl_pathc;
	    while (i-- > 0)
	      {
#ifndef NO_ARCHIVES
		if (memname != 0)
		  {
		    /* Try to glob on MEMNAME within the archive.  */
		    struct nameseq *found
		      = ar_glob (gl.gl_pathv[i], memname, size);
		    if (! found)
		      {
			/* No matches.  Use MEMNAME as-is.  */
			unsigned int alen = strlen (gl.gl_pathv[i]);
			unsigned int mlen = strlen (memname);
                        char *name;
			struct nameseq *elt = xmalloc (size);
                        memset (elt, '\0', size);

                        name = alloca (alen + 1 + mlen + 2);
			memcpy (name, gl.gl_pathv[i], alen);
			name[alen] = '(';
			memcpy (name+alen+1, memname, mlen);
			name[alen + 1 + mlen] = ')';
			name[alen + 1 + mlen + 1] = '\0';
                        elt->name = strcache_add (name);
			elt->next = new;
			new = elt;
		      }
		    else
		      {
			/* Find the end of the FOUND chain.  */
			struct nameseq *f = found;
			while (f->next != 0)
			  f = f->next;

			/* Attach the chain being built to the end of the FOUND
			   chain, and make FOUND the new NEW chain.  */
			f->next = new;
			new = found;
		      }
		  }
		else
#endif /* !NO_ARCHIVES */
		  {
		    struct nameseq *elt = xmalloc (size);
                    memset (elt, '\0', size);
		    elt->name = strcache_add (gl.gl_pathv[i]);
		    elt->next = new;
		    new = elt;
		  }
	      }
	    globfree (&gl);
	    free (old);
	    break;
	  }

	case GLOB_NOSPACE:
	  fatal (NILF, _("virtual memory exhausted"));
	  break;

	default:
	  old->next = new;
	  new = old;
	  break;
	}

#ifndef NO_ARCHIVES
      if (arname)
        free (arname);
#endif
    }

  return new;
}