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
|
/*
* Anarres C Preprocessor
* Copyright (c) 2007-2008, Shevek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.anarres.cpp;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.anarres.cpp.PreprocessorCommand.*;
import org.anarres.cpp.PreprocessorListener.SourceChangeEvent;
import static org.anarres.cpp.Token.*;
/**
* A C Preprocessor.
* The Preprocessor outputs a token stream which does not need
* re-lexing for C or C++. Alternatively, the output text may be
* reconstructed by concatenating the {@link Token#getText() text}
* values of the returned {@link Token Tokens}. (See
* {@link CppReader}, which does this.)
*/
/*
* Source file name and line number information is conveyed by lines of the form
*
* # linenum filename flags
*
* These are called linemarkers. They are inserted as needed into
* the output (but never within a string or character constant). They
* mean that the following line originated in file filename at line
* linenum. filename will never contain any non-printing characters;
* they are replaced with octal escape sequences.
*
* After the file name comes zero or more flags, which are `1', `2',
* `3', or `4'. If there are multiple flags, spaces separate them. Here
* is what the flags mean:
*
* `1'
* This indicates the start of a new file.
* `2'
* This indicates returning to a file (after having included another
* file).
* `3'
* This indicates that the following text comes from a system header
* file, so certain warnings should be suppressed.
* `4'
* This indicates that the following text should be treated as being
* wrapped in an implicit extern "C" block.
*/
public class Preprocessor implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(Preprocessor.class);
private static final Source INTERNAL = new Source() {
@Override
public Token token()
throws IOException,
LexerException {
throw new LexerException("Cannot read from " + getName());
}
@Override
public String getPath() {
return "<internal-data>";
}
@Override
public String getName() {
return "internal data";
}
};
private static final Macro __LINE__ = new Macro(INTERNAL, "__LINE__");
private static final Macro __FILE__ = new Macro(INTERNAL, "__FILE__");
private static final Macro __COUNTER__ = new Macro(INTERNAL, "__COUNTER__");
private final List<Source> inputs;
/* The fundamental engine. */
private final Map<String, Macro> macros;
private final Stack<State> states;
private Source source;
/* Miscellaneous support. */
private int counter;
private final Set<String> onceseenpaths = new HashSet<String>();
private final List<VirtualFile> includes = new ArrayList<VirtualFile>();
/* Support junk to make it work like cpp */
private List<String> quoteincludepath; /* -iquote */
private List<String> sysincludepath; /* -I */
private List<String> frameworkspath;
private final Set<Feature> features;
private final Set<Warning> warnings;
private VirtualFileSystem filesystem;
private PreprocessorListener listener;
public Preprocessor() {
this.inputs = new ArrayList<Source>();
this.macros = new HashMap<String, Macro>();
macros.put(__LINE__.getName(), __LINE__);
macros.put(__FILE__.getName(), __FILE__);
macros.put(__COUNTER__.getName(), __COUNTER__);
this.states = new Stack<State>();
states.push(new State());
this.source = null;
this.counter = 0;
this.quoteincludepath = new ArrayList<String>();
this.sysincludepath = new ArrayList<String>();
this.frameworkspath = new ArrayList<String>();
this.features = EnumSet.noneOf(Feature.class);
this.warnings = EnumSet.noneOf(Warning.class);
this.filesystem = new JavaFileSystem();
this.listener = null;
}
public Preprocessor(@Nonnull Source initial) {
this();
addInput(initial);
}
/** Equivalent to
* 'new Preprocessor(new {@link FileLexerSource}(file))'
*/
public Preprocessor(@Nonnull File file)
throws IOException {
this(new FileLexerSource(file));
}
/**
* Sets the VirtualFileSystem used by this Preprocessor.
*/
public void setFileSystem(@Nonnull VirtualFileSystem filesystem) {
this.filesystem = filesystem;
}
/**
* Returns the VirtualFileSystem used by this Preprocessor.
*/
@Nonnull
public VirtualFileSystem getFileSystem() {
return filesystem;
}
/**
* Sets the PreprocessorListener which handles events for
* this Preprocessor.
*
* The listener is notified of warnings, errors and source
* changes, amongst other things.
*/
public void setListener(@Nonnull PreprocessorListener listener) {
this.listener = listener;
Source s = source;
while (s != null) {
// s.setListener(listener);
s.init(this);
s = s.getParent();
}
}
/**
* Returns the PreprocessorListener which handles events for
* this Preprocessor.
*/
@Nonnull
public PreprocessorListener getListener() {
return listener;
}
/**
* Returns the feature-set for this Preprocessor.
*
* This set may be freely modified by user code.
*/
@Nonnull
public Set<Feature> getFeatures() {
return features;
}
/**
* Adds a feature to the feature-set of this Preprocessor.
*/
public void addFeature(@Nonnull Feature f) {
features.add(f);
}
/**
* Adds features to the feature-set of this Preprocessor.
*/
public void addFeatures(@Nonnull Collection<Feature> f) {
features.addAll(f);
}
/**
* Adds features to the feature-set of this Preprocessor.
*/
public void addFeatures(Feature... f) {
addFeatures(Arrays.asList(f));
}
/**
* Returns true if the given feature is in
* the feature-set of this Preprocessor.
*/
public boolean getFeature(@Nonnull Feature f) {
return features.contains(f);
}
/**
* Returns the warning-set for this Preprocessor.
*
* This set may be freely modified by user code.
*/
@Nonnull
public Set<Warning> getWarnings() {
return warnings;
}
/**
* Adds a warning to the warning-set of this Preprocessor.
*/
public void addWarning(@Nonnull Warning w) {
warnings.add(w);
}
/**
* Adds warnings to the warning-set of this Preprocessor.
*/
public void addWarnings(@Nonnull Collection<Warning> w) {
warnings.addAll(w);
}
/**
* Returns true if the given warning is in
* the warning-set of this Preprocessor.
*/
public boolean getWarning(@Nonnull Warning w) {
return warnings.contains(w);
}
/**
* Adds input for the Preprocessor.
*
* Inputs are processed in the order in which they are added.
*/
public void addInput(@Nonnull Source source) {
source.init(this);
inputs.add(source);
}
/**
* Adds input for the Preprocessor.
*
* @see #addInput(Source)
*/
public void addInput(@Nonnull File file)
throws IOException {
addInput(new FileLexerSource(file));
}
/**
* Handles an error.
*
* If a PreprocessorListener is installed, it receives the
* error. Otherwise, an exception is thrown.
*/
protected void error(int line, int column, @Nonnull String msg)
throws LexerException {
if (listener != null)
listener.handleError(source, line, column, msg);
else
throw new LexerException("Error at " + line + ":" + column + ": " + msg);
}
/**
* Handles an error.
*
* If a PreprocessorListener is installed, it receives the
* error. Otherwise, an exception is thrown.
*
* @see #error(int, int, String)
*/
protected void error(@Nonnull Token tok, @Nonnull String msg)
throws LexerException {
error(tok.getLine(), tok.getColumn(), msg);
}
/**
* Handles a warning.
*
* If a PreprocessorListener is installed, it receives the
* warning. Otherwise, an exception is thrown.
*/
protected void warning(int line, int column, @Nonnull String msg)
throws LexerException {
if (warnings.contains(Warning.ERROR))
error(line, column, msg);
else if (listener != null)
listener.handleWarning(source, line, column, msg);
else
throw new LexerException("Warning at " + line + ":" + column + ": " + msg);
}
/**
* Handles a warning.
*
* If a PreprocessorListener is installed, it receives the
* warning. Otherwise, an exception is thrown.
*
* @see #warning(int, int, String)
*/
protected void warning(@Nonnull Token tok, @Nonnull String msg)
throws LexerException {
warning(tok.getLine(), tok.getColumn(), msg);
}
/**
* Adds a Macro to this Preprocessor.
*
* The given {@link Macro} object encapsulates both the name
* and the expansion.
*
* @throws LexerException if the definition fails or is otherwise illegal.
*/
public void addMacro(@Nonnull Macro m) throws LexerException {
// System.out.println("Macro " + m);
String name = m.getName();
/* Already handled as a source error in macro(). */
if ("defined".equals(name))
throw new LexerException("Cannot redefine name 'defined'");
macros.put(m.getName(), m);
}
/**
* Defines the given name as a macro.
*
* The String value is lexed into a token stream, which is
* used as the macro expansion.
*
* @throws LexerException if the definition fails or is otherwise illegal.
*/
public void addMacro(@Nonnull String name, @Nonnull String value)
throws LexerException {
try {
Macro m = new Macro(name);
StringLexerSource s = new StringLexerSource(value);
for (;;) {
Token tok = s.token();
if (tok.getType() == EOF)
break;
m.addToken(tok);
}
addMacro(m);
} catch (IOException e) {
throw new LexerException(e);
}
}
/**
* Defines the given name as a macro, with the value <code>1</code>.
*
* This is a convnience method, and is equivalent to
* <code>addMacro(name, "1")</code>.
*
* @throws LexerException if the definition fails or is otherwise illegal.
*/
public void addMacro(@Nonnull String name)
throws LexerException {
addMacro(name, "1");
}
/**
* Sets the user include path used by this Preprocessor.
*/
/* Note for future: Create an IncludeHandler? */
public void setQuoteIncludePath(@Nonnull List<String> path) {
this.quoteincludepath = path;
}
/**
* Returns the user include-path of this Preprocessor.
*
* This list may be freely modified by user code.
*/
@Nonnull
public List<String> getQuoteIncludePath() {
return quoteincludepath;
}
/**
* Sets the system include path used by this Preprocessor.
*/
/* Note for future: Create an IncludeHandler? */
public void setSystemIncludePath(@Nonnull List<String> path) {
this.sysincludepath = path;
}
/**
* Returns the system include-path of this Preprocessor.
*
* This list may be freely modified by user code.
*/
@Nonnull
public List<String> getSystemIncludePath() {
return sysincludepath;
}
/**
* Sets the Objective-C frameworks path used by this Preprocessor.
*/
/* Note for future: Create an IncludeHandler? */
public void setFrameworksPath(@Nonnull List<String> path) {
this.frameworkspath = path;
}
/**
* Returns the Objective-C frameworks path used by this
* Preprocessor.
*
* This list may be freely modified by user code.
*/
@Nonnull
public List<String> getFrameworksPath() {
return frameworkspath;
}
/**
* Returns the Map of Macros parsed during the run of this
* Preprocessor.
*
* @return The {@link Map} of macros currently defined.
*/
@Nonnull
public Map<String, Macro> getMacros() {
return macros;
}
/**
* Returns the named macro.
*
* While you can modify the returned object, unexpected things
* might happen if you do.
*
* @return the Macro object, or null if not found.
*/
@CheckForNull
public Macro getMacro(@Nonnull String name) {
return macros.get(name);
}
/**
* Returns the list of {@link VirtualFile VirtualFiles} which have been
* included by this Preprocessor.
*
* This does not include any {@link Source} provided to the constructor
* or {@link #addInput(java.io.File)} or {@link #addInput(Source)}.
*/
@Nonnull
public List<? extends VirtualFile> getIncludes() {
return includes;
}
/* States */
private void push_state() {
State top = states.peek();
states.push(new State(top));
}
private void pop_state()
throws LexerException {
State s = states.pop();
if (states.isEmpty()) {
error(0, 0, "#" + "endif without #" + "if");
states.push(s);
}
}
private boolean isActive() {
State state = states.peek();
return state.isParentActive() && state.isActive();
}
/* Sources */
/**
* Returns the top Source on the input stack.
*
* @see Source
* @see #push_source(Source,boolean)
* @see #pop_source()
*
* @return the top Source on the input stack.
*/
// @CheckForNull
protected Source getSource() {
return source;
}
/**
* Pushes a Source onto the input stack.
*
* @param source the new Source to push onto the top of the input stack.
* @param autopop if true, the Source is automatically removed from the input stack at EOF.
* @see #getSource()
* @see #pop_source()
*/
protected void push_source(@Nonnull Source source, boolean autopop) {
source.init(this);
source.setParent(this.source, autopop);
// source.setListener(listener);
if (listener != null)
listener.handleSourceChange(this.source, SourceChangeEvent.SUSPEND);
this.source = source;
if (listener != null)
listener.handleSourceChange(this.source, SourceChangeEvent.PUSH);
}
/**
* Pops a Source from the input stack.
*
* @see #getSource()
* @see #push_source(Source,boolean)
*
* @param linemarker TODO: currently ignored, might be a bug?
* @throws IOException if an I/O error occurs.
*/
@CheckForNull
protected Token pop_source(boolean linemarker)
throws IOException {
if (listener != null)
listener.handleSourceChange(this.source, SourceChangeEvent.POP);
Source s = this.source;
this.source = s.getParent();
/* Always a noop unless called externally. */
s.close();
if (listener != null && this.source != null)
listener.handleSourceChange(this.source, SourceChangeEvent.RESUME);
Source t = getSource();
if (getFeature(Feature.LINEMARKERS)
&& s.isNumbered()
&& t != null) {
/* We actually want 'did the nested source
* contain a newline token', which isNumbered()
* approximates. This is not perfect, but works. */
return line_token(t.getLine(), t.getName(), " 2");
}
return null;
}
protected void pop_source()
throws IOException {
pop_source(false);
}
@Nonnull
private Token next_source() {
if (inputs.isEmpty())
return new Token(EOF);
Source s = inputs.remove(0);
push_source(s, true);
return line_token(s.getLine(), s.getName(), " 1");
}
/* Source tokens */
private Token source_token;
/* XXX Make this include the NL, and make all cpp directives eat
* their own NL. */
@Nonnull
private Token line_token(int line, @CheckForNull String name, @Nonnull String extra) {
StringBuilder buf = new StringBuilder();
buf.append("#line ").append(line)
.append(" \"");
/* XXX This call to escape(name) is correct but ugly. */
if (name == null)
buf.append("<no file>");
else
MacroTokenSource.escape(buf, name);
buf.append("\"").append(extra).append("\n");
return new Token(P_LINE, line, 0, buf.toString(), null);
}
@Nonnull
private Token source_token()
throws IOException,
LexerException {
if (source_token != null) {
Token tok = source_token;
source_token = null;
if (getFeature(Feature.DEBUG))
LOG.debug("Returning unget token " + tok);
return tok;
}
for (;;) {
Source s = getSource();
if (s == null) {
Token t = next_source();
if (t.getType() == P_LINE && !getFeature(Feature.LINEMARKERS))
continue;
return t;
}
Token tok = s.token();
/* XXX Refactor with skipline() */
if (tok.getType() == EOF && s.isAutopop()) {
// System.out.println("Autopop " + s);
Token mark = pop_source(true);
if (mark != null)
return mark;
continue;
}
if (getFeature(Feature.DEBUG))
LOG.debug("Returning fresh token " + tok);
return tok;
}
}
private void source_untoken(Token tok) {
if (this.source_token != null)
throw new IllegalStateException("Cannot return two tokens");
this.source_token = tok;
}
private boolean isWhite(Token tok) {
int type = tok.getType();
return (type == WHITESPACE)
|| (type == CCOMMENT)
|| (type == CPPCOMMENT);
}
private Token source_token_nonwhite()
throws IOException,
LexerException {
Token tok;
do {
tok = source_token();
} while (isWhite(tok));
return tok;
}
/**
* Returns an NL or an EOF token.
*
* The metadata on the token will be correct, which is better
* than generating a new one.
*
* This method can, as of recent patches, return a P_LINE token.
*/
private Token source_skipline(boolean white)
throws IOException,
LexerException {
// (new Exception("skipping line")).printStackTrace(System.out);
Source s = getSource();
Token tok = s.skipline(white);
/* XXX Refactor with source_token() */
if (tok.getType() == EOF && s.isAutopop()) {
// System.out.println("Autopop " + s);
Token mark = pop_source(true);
if (mark != null)
return mark;
}
return tok;
}
/* processes and expands a macro. */
private boolean macro(Macro m, Token orig)
throws IOException,
LexerException {
Token tok;
List<Argument> args;
// System.out.println("pp: expanding " + m);
if (m.isFunctionLike()) {
OPEN:
for (;;) {
tok = source_token();
// System.out.println("pp: open: token is " + tok);
switch (tok.getType()) {
case WHITESPACE: /* XXX Really? */
case CCOMMENT:
case CPPCOMMENT:
case NL:
break; /* continue */
case '(':
break OPEN;
default:
source_untoken(tok);
return false;
}
}
// tok = expanded_token_nonwhite();
tok = source_token_nonwhite();
/* We either have, or we should have args.
* This deals elegantly with the case that we have
* one empty arg. */
if (tok.getType() != ')' || m.getArgs() > 0) {
args = new ArrayList<Argument>();
Argument arg = new Argument();
int depth = 0;
boolean space = false;
ARGS:
for (;;) {
// System.out.println("pp: arg: token is " + tok);
switch (tok.getType()) {
case EOF:
error(tok, "EOF in macro args");
return false;
case ',':
if (depth == 0) {
if (m.isVariadic()
&& /* We are building the last arg. */ args.size() == m.getArgs() - 1) {
/* Just add the comma. */
arg.addToken(tok);
} else {
args.add(arg);
arg = new Argument();
}
} else {
arg.addToken(tok);
}
space = false;
break;
case ')':
if (depth == 0) {
args.add(arg);
break ARGS;
} else {
depth--;
arg.addToken(tok);
}
space = false;
break;
case '(':
depth++;
arg.addToken(tok);
space = false;
break;
case WHITESPACE:
case CCOMMENT:
case CPPCOMMENT:
case NL:
/* Avoid duplicating spaces. */
space = true;
break;
default:
/* Do not put space on the beginning of
* an argument token. */
if (space && !arg.isEmpty())
arg.addToken(Token.space);
arg.addToken(tok);
space = false;
break;
}
// tok = expanded_token();
tok = source_token();
}
/* space may still be true here, thus trailing space
* is stripped from arguments. */
if (args.size() != m.getArgs()) {
if (m.isVariadic()) {
if (args.size() == m.getArgs() - 1) {
args.add(new Argument());
} else {
error(tok,
"variadic macro " + m.getName()
+ " has at least " + (m.getArgs() - 1) + " parameters "
+ "but given " + args.size() + " args");
return false;
}
} else {
error(tok,
"macro " + m.getName()
+ " has " + m.getArgs() + " parameters "
+ "but given " + args.size() + " args");
/* We could replay the arg tokens, but I
* note that GNU cpp does exactly what we do,
* i.e. output the macro name and chew the args.
*/
return false;
}
}
for (Argument a : args) {
a.expand(this);
}
// System.out.println("Macro " + m + " args " + args);
} else {
/* nargs == 0 and we (correctly) got () */
args = null;
}
} else {
/* Macro without args. */
args = null;
}
if (m == __LINE__) {
push_source(new FixedTokenSource(
new Token[]{new Token(NUMBER,
orig.getLine(), orig.getColumn(),
Integer.toString(orig.getLine()),
new NumericValue(10, Integer.toString(orig.getLine())))}
), true);
} else if (m == __FILE__) {
StringBuilder buf = new StringBuilder("\"");
String name = getSource().getName();
if (name == null)
name = "<no file>";
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
switch (c) {
case '\\':
buf.append("\\\\");
break;
case '"':
buf.append("\\\"");
break;
default:
buf.append(c);
break;
}
}
buf.append("\"");
String text = buf.toString();
push_source(new FixedTokenSource(
new Token[]{new Token(STRING,
orig.getLine(), orig.getColumn(),
text, text)}
), true);
} else if (m == __COUNTER__) {
/* This could equivalently have been done by adding
* a special Macro subclass which overrides getTokens(). */
int value = this.counter++;
push_source(new FixedTokenSource(
new Token[]{new Token(NUMBER,
orig.getLine(), orig.getColumn(),
Integer.toString(value),
new NumericValue(10, Integer.toString(value)))}
), true);
} else {
push_source(new MacroTokenSource(m, args), true);
}
return true;
}
/**
* Expands an argument.
*/
/* I'd rather this were done lazily, but doing so breaks spec. */
@Nonnull
/* pp */ List<Token> expand(@Nonnull List<Token> arg)
throws IOException,
LexerException {
List<Token> expansion = new ArrayList<Token>();
boolean space = false;
push_source(new FixedTokenSource(arg), false);
EXPANSION:
for (;;) {
Token tok = expanded_token();
switch (tok.getType()) {
case EOF:
break EXPANSION;
case WHITESPACE:
case CCOMMENT:
case CPPCOMMENT:
space = true;
break;
default:
if (space && !expansion.isEmpty())
expansion.add(Token.space);
expansion.add(tok);
space = false;
break;
}
}
// Always returns null.
pop_source(false);
return expansion;
}
/* processes a #define directive */
private Token define()
throws IOException,
LexerException {
Token tok = source_token_nonwhite();
if (tok.getType() != IDENTIFIER) {
error(tok, "Expected identifier");
return source_skipline(false);
}
/* if predefined */
String name = tok.getText();
if ("defined".equals(name)) {
error(tok, "Cannot redefine name 'defined'");
return source_skipline(false);
}
Macro m = new Macro(getSource(), name);
List<String> args;
tok = source_token();
if (tok.getType() == '(') {
tok = source_token_nonwhite();
if (tok.getType() != ')') {
args = new ArrayList<String>();
ARGS:
for (;;) {
switch (tok.getType()) {
case IDENTIFIER:
args.add(tok.getText());
break;
case ELLIPSIS:
// Unnamed Variadic macro
args.add("__VA_ARGS__");
// We just named the ellipsis, but we unget the token
// to allow the ELLIPSIS handling below to process it.
source_untoken(tok);
break;
case NL:
case EOF:
error(tok,
"Unterminated macro parameter list");
return tok;
default:
error(tok,
"error in macro parameters: "
+ tok.getText());
return source_skipline(false);
}
tok = source_token_nonwhite();
switch (tok.getType()) {
case ',':
break;
case ELLIPSIS:
tok = source_token_nonwhite();
if (tok.getType() != ')')
error(tok,
"ellipsis must be on last argument");
m.setVariadic(true);
break ARGS;
case ')':
break ARGS;
case NL:
case EOF:
/* Do not skip line. */
error(tok,
"Unterminated macro parameters");
return tok;
default:
error(tok,
"Bad token in macro parameters: "
+ tok.getText());
return source_skipline(false);
}
tok = source_token_nonwhite();
}
} else {
assert tok.getType() == ')' : "Expected ')'";
args = Collections.emptyList();
}
m.setArgs(args);
} else {
/* For searching. */
args = Collections.emptyList();
source_untoken(tok);
}
/* Get an expansion for the macro, using indexOf. */
boolean space = false;
boolean paste = false;
int idx;
/* Ensure no space at start. */
tok = source_token_nonwhite();
EXPANSION:
for (;;) {
switch (tok.getType()) {
case EOF:
break EXPANSION;
case NL:
break EXPANSION;
case CCOMMENT:
case CPPCOMMENT:
/* XXX This is where we implement GNU's cpp -CC. */
// break;
case WHITESPACE:
if (!paste)
space = true;
break;
/* Paste. */
case PASTE:
space = false;
paste = true;
m.addPaste(new Token(M_PASTE,
tok.getLine(), tok.getColumn(),
"#" + "#", null));
break;
/* Stringify. */
case '#':
if (space)
m.addToken(Token.space);
space = false;
Token la = source_token_nonwhite();
if (la.getType() == IDENTIFIER
&& ((idx = args.indexOf(la.getText())) != -1)) {
m.addToken(new Token(M_STRING,
la.getLine(), la.getColumn(),
"#" + la.getText(),
Integer.valueOf(idx)));
} else {
m.addToken(tok);
/* Allow for special processing. */
source_untoken(la);
}
break;
case IDENTIFIER:
if (space)
m.addToken(Token.space);
space = false;
paste = false;
idx = args.indexOf(tok.getText());
if (idx == -1)
m.addToken(tok);
else
m.addToken(new Token(M_ARG,
tok.getLine(), tok.getColumn(),
tok.getText(),
Integer.valueOf(idx)));
break;
default:
if (space)
m.addToken(Token.space);
space = false;
paste = false;
m.addToken(tok);
break;
}
tok = source_token();
}
if (getFeature(Feature.DEBUG))
LOG.debug("Defined macro " + m);
addMacro(m);
return tok; /* NL or EOF. */
}
@Nonnull
private Token undef()
throws IOException,
LexerException {
Token tok = source_token_nonwhite();
if (tok.getType() != IDENTIFIER) {
error(tok,
"Expected identifier, not " + tok.getText());
if (tok.getType() == NL || tok.getType() == EOF)
return tok;
} else {
Macro m = getMacro(tok.getText());
if (m != null) {
/* XXX error if predefined */
macros.remove(m.getName());
}
}
return source_skipline(true);
}
/**
* Attempts to include the given file.
*
* User code may override this method to implement a virtual
* file system.
*
* @param file The VirtualFile to attempt to include.
* @return true if the file was successfully included, false otherwise.
* @throws IOException if an I/O error occurs.
*/
protected boolean include(@Nonnull VirtualFile file)
throws IOException {
// System.out.println("Try to include " + ((File)file).getAbsolutePath());
if (!file.isFile())
return false;
if (getFeature(Feature.DEBUG))
LOG.debug("pp: including " + file);
includes.add(file);
push_source(file.getSource(), true);
return true;
}
/**
* Attempts to include a file from an include path, by name.
*
* @param path The list of virtual directories to search for the given name.
* @param name The name of the file to attempt to include.
* @return true if the file was successfully included, false otherwise.
* @throws IOException if an I/O error occurs.
*/
protected boolean include(@Nonnull Iterable<String> path, @Nonnull String name)
throws IOException {
for (String dir : path) {
VirtualFile file = getFileSystem().getFile(dir, name);
if (include(file))
return true;
}
return false;
}
/**
* Handles an include directive.
*
* @throws IOException if an I/O error occurs.
* @throws LexerException if the include fails, and the error handler is fatal.
*/
private void include(
@CheckForNull String parent, int line,
@Nonnull String name, boolean quoted, boolean next)
throws IOException,
LexerException {
if (name.startsWith("/")) {
VirtualFile file = filesystem.getFile(name);
if (include(file))
return;
StringBuilder buf = new StringBuilder();
buf.append("File not found: ").append(name);
error(line, 0, buf.toString());
return;
}
VirtualFile pdir = null;
if (quoted) {
if (parent != null) {
VirtualFile pfile = filesystem.getFile(parent);
pdir = pfile.getParentFile();
}
if (pdir != null) {
VirtualFile ifile = pdir.getChildFile(name);
if (include(ifile))
return;
}
if (include(quoteincludepath, name))
return;
} else {
int idx = name.indexOf('/');
if (idx != -1) {
String frameworkName = name.substring(0, idx);
String headerName = name.substring(idx + 1);
String headerPath = frameworkName + ".framework/Headers/" + headerName;
if (include(frameworkspath, headerPath))
return;
}
}
if (include(sysincludepath, name))
return;
StringBuilder buf = new StringBuilder();
buf.append("File not found: ").append(name);
buf.append(" in");
if (quoted) {
buf.append(" .").append('(').append(pdir).append(')');
for (String dir : quoteincludepath)
buf.append(" ").append(dir);
}
for (String dir : sysincludepath)
buf.append(" ").append(dir);
error(line, 0, buf.toString());
}
@Nonnull
private Token include(boolean next)
throws IOException,
LexerException {
LexerSource lexer = (LexerSource) source;
try {
lexer.setInclude(true);
Token tok = token_nonwhite();
String name;
boolean quoted;
if (tok.getType() == STRING) {
/* XXX Use the original text, not the value.
* Backslashes must not be treated as escapes here. */
StringBuilder buf = new StringBuilder((String) tok.getValue());
HEADER:
for (;;) {
tok = token_nonwhite();
switch (tok.getType()) {
case STRING:
buf.append((String) tok.getValue());
break;
case NL:
case EOF:
break HEADER;
default:
warning(tok,
"Unexpected token on #" + "include line");
return source_skipline(false);
}
}
name = buf.toString();
quoted = true;
} else if (tok.getType() == HEADER) {
name = (String) tok.getValue();
quoted = false;
tok = source_skipline(true);
} else {
error(tok,
"Expected string or header, not " + tok.getText());
switch (tok.getType()) {
case NL:
case EOF:
return tok;
default:
/* Only if not a NL or EOF already. */
return source_skipline(false);
}
}
/* Do the inclusion. */
include(source.getPath(), tok.getLine(), name, quoted, next);
/* 'tok' is the 'nl' after the include. We use it after the
* #line directive. */
if (getFeature(Feature.LINEMARKERS))
return line_token(1, source.getName(), " 1");
return tok;
} finally {
lexer.setInclude(false);
}
}
protected void pragma_once(@Nonnull Token name)
throws IOException, LexerException {
Source s = this.source;
if (!onceseenpaths.add(s.getPath())) {
Token mark = pop_source(true);
// FixedTokenSource should never generate a linemarker on exit.
if (mark != null)
push_source(new FixedTokenSource(Arrays.asList(mark)), true);
}
}
protected void pragma(@Nonnull Token name, @Nonnull List<Token> value)
throws IOException,
LexerException {
if (getFeature(Feature.PRAGMA_ONCE)) {
if ("once".equals(name.getText())) {
pragma_once(name);
return;
}
}
warning(name, "Unknown #" + "pragma: " + name.getText());
}
@Nonnull
private Token pragma()
throws IOException,
LexerException {
Token name;
NAME:
for (;;) {
Token tok = source_token();
switch (tok.getType()) {
case EOF:
/* There ought to be a newline before EOF.
* At least, in any skipline context. */
/* XXX Are we sure about this? */
warning(tok,
"End of file in #" + "pragma");
return tok;
case NL:
/* This may contain one or more newlines. */
warning(tok,
"Empty #" + "pragma");
return tok;
case CCOMMENT:
case CPPCOMMENT:
case WHITESPACE:
continue NAME;
case IDENTIFIER:
name = tok;
break NAME;
default:
warning(tok,
"Illegal #" + "pragma " + tok.getText());
return source_skipline(false);
}
}
Token tok;
List<Token> value = new ArrayList<Token>();
VALUE:
for (;;) {
tok = source_token();
switch (tok.getType()) {
case EOF:
/* There ought to be a newline before EOF.
* At least, in any skipline context. */
/* XXX Are we sure about this? */
warning(tok,
"End of file in #" + "pragma");
break VALUE;
case NL:
/* This may contain one or more newlines. */
break VALUE;
case CCOMMENT:
case CPPCOMMENT:
break;
case WHITESPACE:
value.add(tok);
break;
default:
value.add(tok);
break;
}
}
pragma(name, value);
return tok; /* The NL. */
}
/* For #error and #warning. */
private void error(@Nonnull Token pptok, boolean is_error)
throws IOException,
LexerException {
StringBuilder buf = new StringBuilder();
buf.append('#').append(pptok.getText()).append(' ');
/* Peculiar construction to ditch first whitespace. */
Token tok = source_token_nonwhite();
ERROR:
for (;;) {
switch (tok.getType()) {
case NL:
case EOF:
break ERROR;
default:
buf.append(tok.getText());
break;
}
tok = source_token();
}
if (is_error)
error(pptok, buf.toString());
else
warning(pptok, buf.toString());
}
/* This bypasses token() for #elif expressions.
* If we don't do this, then isActive() == false
* causes token() to simply chew the entire input line. */
@Nonnull
private Token expanded_token()
throws IOException,
LexerException {
for (;;) {
Token tok = source_token();
// System.out.println("Source token is " + tok);
if (tok.getType() == IDENTIFIER) {
Macro m = getMacro(tok.getText());
if (m == null)
return tok;
if (source.isExpanding(m))
return tok;
if (macro(m, tok))
continue;
}
return tok;
}
}
@Nonnull
private Token expanded_token_nonwhite()
throws IOException,
LexerException {
Token tok;
do {
tok = expanded_token();
// System.out.println("expanded token is " + tok);
} while (isWhite(tok));
return tok;
}
@CheckForNull
private Token expr_token = null;
@Nonnull
private Token expr_token()
throws IOException,
LexerException {
Token tok = expr_token;
if (tok != null) {
// System.out.println("ungetting");
expr_token = null;
} else {
tok = expanded_token_nonwhite();
// System.out.println("expt is " + tok);
if (tok.getType() == IDENTIFIER
&& tok.getText().equals("defined")) {
Token la = source_token_nonwhite();
boolean paren = false;
if (la.getType() == '(') {
paren = true;
la = source_token_nonwhite();
}
// System.out.println("Core token is " + la);
if (la.getType() != IDENTIFIER) {
error(la,
"defined() needs identifier, not "
+ la.getText());
tok = new Token(NUMBER,
la.getLine(), la.getColumn(),
"0", new NumericValue(10, "0"));
} else if (macros.containsKey(la.getText())) {
// System.out.println("Found macro");
tok = new Token(NUMBER,
la.getLine(), la.getColumn(),
"1", new NumericValue(10, "1"));
} else {
// System.out.println("Not found macro");
tok = new Token(NUMBER,
la.getLine(), la.getColumn(),
"0", new NumericValue(10, "0"));
}
if (paren) {
la = source_token_nonwhite();
if (la.getType() != ')') {
expr_untoken(la);
error(la, "Missing ) in defined(). Got " + la.getText());
}
}
}
}
// System.out.println("expr_token returns " + tok);
return tok;
}
private void expr_untoken(@Nonnull Token tok)
throws LexerException {
if (expr_token != null)
throw new InternalException(
"Cannot unget two expression tokens."
);
expr_token = tok;
}
private int expr_priority(@Nonnull Token op) {
switch (op.getType()) {
case '/':
return 11;
case '%':
return 11;
case '*':
return 11;
case '+':
return 10;
case '-':
return 10;
case LSH:
return 9;
case RSH:
return 9;
case '<':
return 8;
case '>':
return 8;
case LE:
return 8;
case GE:
return 8;
case EQ:
return 7;
case NE:
return 7;
case '&':
return 6;
case '^':
return 5;
case '|':
return 4;
case LAND:
return 3;
case LOR:
return 2;
case '?':
return 1;
default:
// System.out.println("Unrecognised operator " + op);
return 0;
}
}
private long expr(int priority)
throws IOException,
LexerException {
/*
* (new Exception("expr(" + priority + ") called")).printStackTrace();
*/
Token tok = expr_token();
long lhs, rhs;
// System.out.println("Expr lhs token is " + tok);
switch (tok.getType()) {
case '(':
lhs = expr(0);
tok = expr_token();
if (tok.getType() != ')') {
expr_untoken(tok);
error(tok, "Missing ) in expression. Got " + tok.getText());
return 0;
}
break;
case '~':
lhs = ~expr(11);
break;
case '!':
lhs = expr(11) == 0 ? 1 : 0;
break;
case '-':
lhs = -expr(11);
break;
case NUMBER:
NumericValue value = (NumericValue) tok.getValue();
lhs = value.longValue();
break;
case CHARACTER:
lhs = ((Character) tok.getValue()).charValue();
break;
case IDENTIFIER:
if (warnings.contains(Warning.UNDEF))
warning(tok, "Undefined token '" + tok.getText()
+ "' encountered in conditional.");
lhs = 0;
break;
default:
expr_untoken(tok);
error(tok,
"Bad token in expression: " + tok.getText());
return 0;
}
EXPR:
for (;;) {
// System.out.println("expr: lhs is " + lhs + ", pri = " + priority);
Token op = expr_token();
int pri = expr_priority(op); /* 0 if not a binop. */
if (pri == 0 || priority >= pri) {
expr_untoken(op);
break EXPR;
}
rhs = expr(pri);
// System.out.println("rhs token is " + rhs);
switch (op.getType()) {
case '/':
if (rhs == 0) {
error(op, "Division by zero");
lhs = 0;
} else {
lhs = lhs / rhs;
}
break;
case '%':
if (rhs == 0) {
error(op, "Modulus by zero");
lhs = 0;
} else {
lhs = lhs % rhs;
}
break;
case '*':
lhs = lhs * rhs;
break;
case '+':
lhs = lhs + rhs;
break;
case '-':
lhs = lhs - rhs;
break;
case '<':
lhs = lhs < rhs ? 1 : 0;
break;
case '>':
lhs = lhs > rhs ? 1 : 0;
break;
case '&':
lhs = lhs & rhs;
break;
case '^':
lhs = lhs ^ rhs;
break;
case '|':
lhs = lhs | rhs;
break;
case LSH:
lhs = lhs << rhs;
break;
case RSH:
lhs = lhs >> rhs;
break;
case LE:
lhs = lhs <= rhs ? 1 : 0;
break;
case GE:
lhs = lhs >= rhs ? 1 : 0;
break;
case EQ:
lhs = lhs == rhs ? 1 : 0;
break;
case NE:
lhs = lhs != rhs ? 1 : 0;
break;
case LAND:
lhs = (lhs != 0) && (rhs != 0) ? 1 : 0;
break;
case LOR:
lhs = (lhs != 0) || (rhs != 0) ? 1 : 0;
break;
case '?': {
tok = expr_token();
if (tok.getType() != ':') {
expr_untoken(tok);
error(tok, "Missing : in conditional expression. Got " + tok.getText());
return 0;
}
long falseResult = expr(0);
lhs = (lhs != 0) ? rhs : falseResult;
}
break;
default:
error(op,
"Unexpected operator " + op.getText());
return 0;
}
}
/*
* (new Exception("expr returning " + lhs)).printStackTrace();
*/
// System.out.println("expr returning " + lhs);
return lhs;
}
@Nonnull
private Token toWhitespace(@Nonnull Token tok) {
String text = tok.getText();
int len = text.length();
boolean cr = false;
int nls = 0;
for (int i = 0; i < len; i++) {
char c = text.charAt(i);
switch (c) {
case '\r':
cr = true;
nls++;
break;
case '\n':
if (cr) {
cr = false;
break;
}
/* fallthrough */
case '\u2028':
case '\u2029':
case '\u000B':
case '\u000C':
case '\u0085':
cr = false;
nls++;
break;
}
}
char[] cbuf = new char[nls];
Arrays.fill(cbuf, '\n');
return new Token(WHITESPACE,
tok.getLine(), tok.getColumn(),
new String(cbuf));
}
@Nonnull
private Token _token()
throws IOException,
LexerException {
for (;;) {
Token tok;
if (!isActive()) {
Source s = getSource();
if (s == null) {
Token t = next_source();
if (t.getType() == P_LINE && !getFeature(Feature.LINEMARKERS))
continue;
return t;
}
try {
/* XXX Tell lexer to ignore warnings. */
s.setActive(false);
tok = source_token();
} finally {
/* XXX Tell lexer to stop ignoring warnings. */
s.setActive(true);
}
switch (tok.getType()) {
case HASH:
case NL:
case EOF:
/* The preprocessor has to take action here. */
break;
case WHITESPACE:
return tok;
case CCOMMENT:
case CPPCOMMENT:
// Patch up to preserve whitespace.
if (getFeature(Feature.KEEPALLCOMMENTS))
return tok;
if (!isActive())
return toWhitespace(tok);
if (getFeature(Feature.KEEPCOMMENTS))
return tok;
return toWhitespace(tok);
default:
// Return NL to preserve whitespace.
/* XXX This might lose a comment. */
return source_skipline(false);
}
} else {
tok = source_token();
}
LEX:
switch (tok.getType()) {
case EOF:
/* Pop the stacks. */
return tok;
case WHITESPACE:
case NL:
return tok;
case CCOMMENT:
case CPPCOMMENT:
return tok;
case '!':
case '%':
case '&':
case '(':
case ')':
case '*':
case '+':
case ',':
case '-':
case '/':
case ':':
case ';':
case '<':
case '=':
case '>':
case '?':
case '[':
case ']':
case '^':
case '{':
case '|':
case '}':
case '~':
case '.':
/* From Olivier Chafik for Objective C? */
case '@':
/* The one remaining ASCII, might as well. */
case '`':
// case '#':
case AND_EQ:
case ARROW:
case CHARACTER:
case DEC:
case DIV_EQ:
case ELLIPSIS:
case EQ:
case GE:
case HEADER: /* Should only arise from include() */
case INC:
case LAND:
case LE:
case LOR:
case LSH:
case LSH_EQ:
case SUB_EQ:
case MOD_EQ:
case MULT_EQ:
case NE:
case OR_EQ:
case PLUS_EQ:
case RANGE:
case RSH:
case RSH_EQ:
case STRING:
case SQSTRING:
case XOR_EQ:
return tok;
case NUMBER:
return tok;
case IDENTIFIER:
Macro m = getMacro(tok.getText());
if (m == null)
return tok;
if (source.isExpanding(m))
return tok;
if (macro(m, tok))
break;
return tok;
case P_LINE:
if (getFeature(Feature.LINEMARKERS))
return tok;
break;
case INVALID:
if (getFeature(Feature.CSYNTAX))
error(tok, String.valueOf(tok.getValue()));
return tok;
default:
throw new InternalException("Bad token " + tok);
// break;
case HASH:
tok = source_token_nonwhite();
// (new Exception("here")).printStackTrace();
switch (tok.getType()) {
case NL:
break LEX; /* Some code has #\n */
case IDENTIFIER:
break;
default:
error(tok,
"Preprocessor directive not a word "
+ tok.getText());
return source_skipline(false);
}
PreprocessorCommand ppcmd = PreprocessorCommand.forText(tok.getText());
if (ppcmd == null) {
error(tok,
"Unknown preprocessor directive "
+ tok.getText());
return source_skipline(false);
}
PP:
switch (ppcmd) {
case PP_DEFINE:
if (!isActive())
return source_skipline(false);
else
return define();
// break;
case PP_UNDEF:
if (!isActive())
return source_skipline(false);
else
return undef();
// break;
case PP_INCLUDE:
if (!isActive())
return source_skipline(false);
else
return include(false);
// break;
case PP_INCLUDE_NEXT:
if (!isActive())
return source_skipline(false);
if (!getFeature(Feature.INCLUDENEXT)) {
error(tok,
"Directive include_next not enabled"
);
return source_skipline(false);
}
return include(true);
// break;
case PP_WARNING:
case PP_ERROR:
if (!isActive())
return source_skipline(false);
else
error(tok, ppcmd == PP_ERROR);
break;
case PP_IF:
push_state();
if (!isActive()) {
return source_skipline(false);
}
expr_token = null;
states.peek().setActive(expr(0) != 0);
tok = expr_token(); /* unget */
if (tok.getType() == NL)
return tok;
return source_skipline(true);
// break;
case PP_ELIF:
State state = states.peek();
if (false) {
/* Check for 'if' */;
} else if (state.sawElse()) {
error(tok,
"#elif after #" + "else");
return source_skipline(false);
} else if (!state.isParentActive()) {
/* Nested in skipped 'if' */
return source_skipline(false);
} else if (state.isActive()) {
/* The 'if' part got executed. */
state.setParentActive(false);
/* This is like # else # if but with
* only one # end. */
state.setActive(false);
return source_skipline(false);
} else {
expr_token = null;
state.setActive(expr(0) != 0);
tok = expr_token(); /* unget */
if (tok.getType() == NL)
return tok;
return source_skipline(true);
}
// break;
case PP_ELSE:
state = states.peek();
if (false)
/* Check for 'if' */ ; else if (state.sawElse()) {
error(tok,
"#" + "else after #" + "else");
return source_skipline(false);
} else {
state.setSawElse();
state.setActive(!state.isActive());
return source_skipline(warnings.contains(Warning.ENDIF_LABELS));
}
// break;
case PP_IFDEF:
push_state();
if (!isActive()) {
return source_skipline(false);
} else {
tok = source_token_nonwhite();
// System.out.println("ifdef " + tok);
if (tok.getType() != IDENTIFIER) {
error(tok,
"Expected identifier, not "
+ tok.getText());
return source_skipline(false);
} else {
String text = tok.getText();
boolean exists
= macros.containsKey(text);
states.peek().setActive(exists);
return source_skipline(true);
}
}
// break;
case PP_IFNDEF:
push_state();
if (!isActive()) {
return source_skipline(false);
} else {
tok = source_token_nonwhite();
if (tok.getType() != IDENTIFIER) {
error(tok,
"Expected identifier, not "
+ tok.getText());
return source_skipline(false);
} else {
String text = tok.getText();
boolean exists
= macros.containsKey(text);
states.peek().setActive(!exists);
return source_skipline(true);
}
}
// break;
case PP_ENDIF:
pop_state();
return source_skipline(warnings.contains(Warning.ENDIF_LABELS));
// break;
case PP_LINE:
return source_skipline(false);
// break;
case PP_PRAGMA:
if (!isActive())
return source_skipline(false);
return pragma();
// break;
default:
/* Actual unknown directives are
* processed above. If we get here,
* we succeeded the map lookup but
* failed to handle it. Therefore,
* this is (unconditionally?) fatal. */
// if (isActive()) /* XXX Could be warning. */
throw new InternalException(
"Internal error: Unknown directive "
+ tok);
// return source_skipline(false);
}
}
}
}
@Nonnull
private Token token_nonwhite()
throws IOException,
LexerException {
Token tok;
do {
tok = _token();
} while (isWhite(tok));
return tok;
}
/**
* Returns the next preprocessor token.
*
* @see Token
* @return The next fully preprocessed token.
* @throws IOException if an I/O error occurs.
* @throws LexerException if a preprocessing error occurs.
* @throws InternalException if an unexpected error condition arises.
*/
@Nonnull
public Token token()
throws IOException,
LexerException {
Token tok = _token();
if (getFeature(Feature.DEBUG))
LOG.debug("pp: Returning " + tok);
return tok;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
Source s = getSource();
while (s != null) {
buf.append(" -> ").append(String.valueOf(s)).append("\n");
s = s.getParent();
}
Map<String, Macro> macros = new TreeMap<String, Macro>(getMacros());
for (Macro macro : macros.values()) {
buf.append("#").append("macro ").append(macro).append("\n");
}
return buf.toString();
}
@Override
public void close()
throws IOException {
{
Source s = source;
while (s != null) {
s.close();
s = s.getParent();
}
}
for (Source s : inputs) {
s.close();
}
}
}
|