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
|
/*
* Copyright (c) 2021-2025 Symas Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of the Symas Corporation nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This file supports parsing without requiring access to the symbol
* table definition. Unlike the Bison input, this file brings in gcc
* header files.
*/
#include "cobol-system.h"
#include <langinfo.h>
#include "coretypes.h"
#include "version.h"
#include "demangle.h"
#include "intl.h"
#include "backtrace.h"
#include "diagnostic.h"
#include "diagnostic-color.h"
#include "diagnostic-url.h"
#include "diagnostic-metadata.h"
#include "diagnostic-path.h"
#include "edit-context.h"
#include "selftest.h"
#include "selftest-diagnostic.h"
#include "opts.h"
#include "util.h"
#include "cbldiag.h"
#include "lexio.h"
#define HOWEVER_GCC_DEFINES_TREE
#include "../../libgcobol/ec.h"
#include "../../libgcobol/common-defs.h"
#include "symbols.h"
#include "inspect.h"
#include "../../libgcobol/io.h"
#include "genapi.h"
#pragma GCC diagnostic ignored "-Wunused-result"
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
// External declarations.
extern FILE * yyin;
extern int yyparse(void);
extern int demonstration_administrator(int N);
#if !defined (HAVE_GET_CURRENT_DIR_NAME)
/* Posix platforms might not have get_current_dir_name but should have
getcwd() and PATH_MAX. */
#if __has_include (<limits.h>)
# include <limits.h>
#endif
/* The Hurd doesn't define PATH_MAX. */
#if !defined (PATH_MAX) && defined(__GNU__)
# define PATH_MAX 4096
#endif
static inline char *
get_current_dir_name ()
{
/* Use libiberty's allocator here. */
char *buf = (char *) xmalloc (PATH_MAX);
return getcwd (buf, PATH_MAX);
}
#endif
const char *
symbol_type_str( enum symbol_type_t type )
{
switch(type) {
case SymFilename:
return "SymFilename";
case SymFunction:
return "SymFunction";
case SymField:
return "SymField";
case SymLabel:
return "SymLabel";
case SymSpecial:
return "SymSpecial";
case SymAlphabet:
return "SymAlphabet";
case SymFile:
return "SymFile";
case SymDataSection:
return "SymDataSection";
}
dbgmsg("%s:%d: invalid symbol_type_t %d", __func__, __LINE__, type);
return "???";
}
const char *
cbl_field_type_str( enum cbl_field_type_t type )
{
switch(type) {
case FldDisplay:
return "FldDisplay";
case FldInvalid:
return "Fld"; // Invalid";
case FldGroup:
return "FldGroup";
case FldAlphanumeric:
return "FldAlphanumeric";
case FldNumericBinary:
return "FldNumericBinary";
case FldFloat:
return "FldFloat";
case FldNumericBin5:
return "FldNumericBin5";
case FldPacked:
return "FldPacked";
case FldNumericDisplay:
return "FldNumericDisplay";
case FldNumericEdited:
return "FldNumericEdited";
case FldAlphaEdited:
return "FldAlphaEdited";
case FldLiteralA:
return "FldLiteralA";
case FldLiteralN:
return "FldLiteralN";
case FldClass:
return "FldClass";
case FldConditional:
return "FldConditional";
case FldForward:
return "FldForward";
case FldIndex:
return "FldIndex";
case FldSwitch:
return "FldSwitch";
case FldPointer:
return "FldPointer";
case FldBlob:
return "FldBlob";
}
dbgmsg("%s:%d: invalid symbol_type_t %d", __func__, __LINE__, type);
return "???";
}
const char *
cbl_logop_str( enum logop_t op )
{
switch(op) {
case not_op:
return "not_op";
case and_op:
return "and_op";
case or_op:
return "or_op";
case xor_op:
return "xor_op";
case xnor_op:
return "xnor_op";
case true_op:
return "true_op";
case false_op:
return "false_op";
}
dbgmsg("%s:%d: invalid logop_t %d", __func__, __LINE__, op);
return "???";
}
cbl_field_t
determine_intermediate_type( const cbl_refer_t& aref,
int op __attribute__ ((unused)),
const cbl_refer_t& bref )
{
cbl_field_t output = {};
if( aref.field->type == FldFloat || bref.field->type == FldFloat )
{
output.type = FldFloat;
output.data.capacity = 16;
output.attr = (intermediate_e );
}
else if( op == '*'
&& aref.field->data.digits + bref.field->data.digits
> MAX_FIXED_POINT_DIGITS)
{
output.type = FldFloat;
output.data.capacity = 16;
output.attr = (intermediate_e );
}
else
{
output.type = FldNumericBin5;
output.data.capacity = 16;
output.data.digits = MAX_FIXED_POINT_DIGITS;
output.attr = (intermediate_e | signable_e );
}
return output;
}
static char regexmsg[80];
/*
* Scan part of the picture, parsing any repetition count.
*/
int
repeat_count( const char picture[] )
{
char ch;
int n, count = -1;
n = sscanf( picture, "%c(%d)", &ch, &count );
if( count <= 0 && 4 < n ) { // parsed count is negative
count = 0; // zero is invalid; -1 means no repetition
}
return count;
}
const char *numed_message;
extern int yydebug, yy_flex_debug;
bool
is_alpha_edited( const char picture[] ) {
static const char valid[] = "abxABX90/(),.";
assert(picture);
for( const char *p = picture; *p != '\0'; p++ ) {
if( strchr(valid, *p) ) continue;
if( ISDIGIT(*p) ) continue;
if( symbol_decimal_point() == *p ) continue;
if( symbol_currency(*p) ) continue;
if( yydebug ) {
dbgmsg( "%s: bad character '%c' at %.*s<-- in '%s'",
__func__, *p, int(p - picture) + 1, picture, picture );
}
return false;
}
return true;
}
bool
is_numeric_edited( const char picture[] ) {
static const char valid[] = "BbPpVvZz90/(),.+-*"; // and CR DB
const char *p;
assert(picture);
if( strstr(picture, "(0)") ) {
numed_message = "'(0)' invalid in PICTURE (ISO 2023 13.18.40.3)";
return false;
}
// check for correct parenthetical constructs
for( p=picture; (p = strchr(p, '(')) != NULL; p++ ) {
int v, n, pos;
n = sscanf(++p, "%d%n", &v, &pos);
numed_message = NULL;
if( n == -1 ) {
numed_message = "invalid repeat-count in PICTURE";
} else if( n == 0 ) {
numed_message = "invalid repeat-count in PICTURE";
} else if( p[pos] != ')' ) {
numed_message = "unbalanced parentheses in PICTURE";
}
if( numed_message ) return false;
}
// check for dangling right parenthesis
for( p=picture; (p = strchr(p, ')')) != NULL; p++ ) {
auto prior = p;
while( picture < prior-- ) {
if( ISDIGIT(*prior) ) continue;
if( *prior == '(' ) break;
numed_message = "unbalanced parentheses in PICTURE";
return false;
}
}
if( (strchr(picture, 'Z') || strchr(picture, 'z')) && strchr(picture, '*') ) {
numed_message = "Z and * are mutually exclusive";
return false;
}
for( p = picture; *p != '\0'; p++ ) {
if( strchr(valid, *p) ) continue;
if( ISDIGIT(*p) ) continue;
if( symbol_decimal_point() == *p ) continue;
if( symbol_currency(*p) ) continue;
switch(*p) { // test for CR or DB
case 'C': case 'c':
if( TOUPPER(*++p) == 'R' ) continue;
numed_message = "expected CR in PICTURE";
break;
case 'D': case 'd':
if( TOUPPER(*++p) == 'B' ) continue;
numed_message = "expected DB in PICTURE";
break;
default:
numed_message = xasprintf("invalid PICTURE character "
"'%c' at offset %zu in '%s'",
*p, p - picture, picture);
break;
}
dbgmsg( "%s: no, because '%c' at %.*s<-- in '%s'",
__func__, *p, int(p - picture) + 1, picture, picture );
return false;
}
return true;
}
char *
normalize_picture( char picture[] )
{
int erc;
char *p;
regex_t *preg = NULL;
const char regex[] = "([AX9])[(]([[:digit:]]+)[)]";
int cflags = REG_EXTENDED | REG_ICASE;
regmatch_t pmatch[4];
if( (erc = regcomp(preg, regex, cflags)) != 0 ) {
regerror(erc, preg, regexmsg, sizeof(regexmsg));
dbgmsg( "%s:%d: could not compile regex: %s", __func__, __LINE__, regexmsg );
return picture;
}
while( (erc = regexec(preg, picture, COUNT_OF(pmatch), pmatch, 0)) == 0 ) {
assert(pmatch[1].rm_so != -1 && pmatch[1].rm_so < pmatch[1].rm_eo);
size_t len = pmatch[1].rm_eo - pmatch[1].rm_so;
assert(len == 1);
const char *start = picture + pmatch[1].rm_so;
assert(pmatch[2].rm_so != -2 && pmatch[2].rm_so < pmatch[2].rm_eo);
len = pmatch[2].rm_eo - pmatch[2].rm_so;
assert(len > 0);
/*
* Overwrite e.g. A(4) with AAAA.
*/
assert(pmatch[2].rm_so == pmatch[1].rm_eo + 1); // character paren number
p = picture + pmatch[2].rm_so;
len = 0;
if( 1 != sscanf(p, "%zu", &len) ) {
dbgmsg("%s:%d: no number found in '%s'", __func__, __LINE__, p);
goto irregular;
}
if( len == 0 ) {
dbgmsg("%s:%d: ZERO length found in '%s'", __func__, __LINE__, p);
goto irregular;
}
std::vector <char> pic(len + 1, '\0');
memset(pic.data(), *start, len);
const char *finish = picture + pmatch[2].rm_eo,
*eopicture = picture + strlen(picture);
p = xasprintf( "%*s%s%*s",
(int)(start - picture), picture,
pic.data(),
(int)(eopicture - finish), finish );
free(picture);
picture = p;
continue;
}
assert(erc == REG_NOMATCH);
irregular:
regfree(preg);
return picture;
}
static bool
memall( const char picture[], char ch )
{
for( const char *p=picture; *p != '\0'; p++ ) {
if( *p != ch ) {
return false;
}
}
return true;
}
static const char *
match( const char picture[], const char pattern[] )
{
int erc;
regex_t *preg = NULL;
int cflags = REG_EXTENDED;
regmatch_t pmatch[1];
if( (erc = regcomp(preg, pattern, cflags)) != 0 ) {
regerror(erc, preg, regexmsg, sizeof(regexmsg));
dbgmsg( "%s:%d: could not compile regex: %s", __func__, __LINE__, regexmsg );
return picture;
}
if( (erc = regexec(preg, picture, COUNT_OF(pmatch), pmatch, 0)) != 0 ) {
assert(erc == REG_NOMATCH);
return NULL;
}
assert(pmatch[0].rm_so != -1);
return picture + pmatch[0].rm_so;
}
bool
is_elementary( enum cbl_field_type_t type )
{
switch(type) {
case FldDisplay:
case FldInvalid:
case FldGroup:
case FldLiteralA:
case FldLiteralN:
case FldClass:
case FldConditional:
case FldForward:
case FldIndex:
case FldSwitch:
case FldBlob:
return false;
case FldPointer:
case FldAlphanumeric:
case FldPacked:
case FldNumericDisplay:
case FldNumericEdited:
case FldAlphaEdited:
case FldNumericBinary:
case FldNumericBin5:
case FldFloat:
return true; // takes up space
}
dbgmsg("%s:%d: invalid symbol_type_t %d", __func__, __LINE__, type);
return false;
}
static bool
is_numericish( cbl_field_type_t type ) {
return
type == FldNumericDisplay ||
type == FldNumericEdited || is_numeric(type);
}
static inline bool
is_numericish( const struct cbl_field_t *field ) {
return is_numericish(field->type);
}
static bool
integer_move_ok( const cbl_field_t *src, const cbl_field_t *tgt ) {
if( is_numericish(src) &&
! (tgt->type == FldInvalid || is_literal(tgt)) ) {
if( src->data.rdigits > 0 ) {
dbgmsg("%s has %d rdigits", src->name, src->data.rdigits);
}
return src->data.rdigits == 0;
}
return integer_move_ok( tgt, src );
}
static bool
is_alphanumeric( const cbl_field_t *field ) {
assert(field);
if( is_elementary(field->type) ) {
switch(field->type) {
case FldAlphanumeric:
case FldPacked:
case FldNumericDisplay:
case FldNumericEdited:
case FldAlphaEdited:
case FldNumericBinary:
return true;
case FldNumericBin5:
case FldFloat:
return false;
default:
break;
}
return false;
}
if( field->type != FldGroup ) return false;
const struct symbol_elem_t *e = symbol_elem_of(field);
for( ++e; e < symbols_end(); e++ ) {
if( e->type != SymField ) {
// Ignore non-fields:
continue;
}
const uint32_t level = cbl_field_of(e)->level;
if( level == 88 ) continue;
if( level <= field->level || level == LEVEL77 ) {
break; // stop if next field is higher in the hierarchy
}
if( ! is_alphanumeric(cbl_field_of(e)) ) {
return false;
}
}
return true;
}
/*
* When setting a field's type, there is a 3-way test involving:
* 1. The current value of cbl_field_t::type
* 2. The value of cbl_field_t::usage, from USAGE or parent's USAGE
* 3. The candidate (proposed new type)
*
* cbl_field_t::usage == FldInvalid indicates no prescribed
* type. Type-setting succeeds unless the candidate cannot override
* the current type.
*
* A candidate of FldDisplay updates cbl_field_t::usage only, and only
* if it is FldInvalid, provided the cbl_field_t::type is either
* FldInvalid or displayable. FldDisplay isn't really a type, but a
* kind of type: it constrains what the type may be set to.
*
* When cbl_field_t::usage == FldDisplay, the candidate type must be
* displayable, else the update is rejected.
*
* If the candidate passes the usage test, we consider the current type.
*
* cbl_field_t::type == FldInvalid indicates no defined type
* (yet). The candidate type becomes the type. Otherwise, the
* candidate must match the type, or can override it.
*/
static bool
is_displayable( cbl_field_type_t type ) {
switch(type) {
case FldDisplay:
case FldAlphaEdited:
case FldAlphanumeric:
case FldNumericDisplay:
case FldNumericEdited:
return true;
default: break;
}
return false;
}
// disallow implausible combinations
static bool
plausible_usage( cbl_field_type_t usage, cbl_field_type_t candidate ) {
switch(usage) {
case FldInvalid:
return true;
case FldDisplay:
return is_displayable(candidate);
case FldGroup:
gcc_unreachable();
default:
if( candidate == FldDisplay ) return false; // because overrides FldInvalid only
break;
}
assert(is_elementary(usage));
assert(is_elementary(candidate));
return usage == candidate || (is_numericish(usage) && is_numericish(candidate));
}
cbl_field_t *
symbol_field_index_set( cbl_field_t *field ) {
static const cbl_field_data_t data { 0, 8 };
field->data = data;
field->type = FldIndex;
field->attr &= ~size_t(signable_e);
return field;
}
bool
symbol_field_type_update( cbl_field_t *field,
cbl_field_type_t candidate, bool is_usage ) {
if( is_usage && (candidate == FldIndex || candidate == FldPointer) ) {
field->usage = candidate;
switch(field->type) {
case FldInvalid:
case FldIndex:
case FldPointer:
// set the type
field->type = candidate;
if( field->data.capacity == 0 ) {
static const cbl_field_data_t data = {0, 8, 0, 0, NULL};
field->data = data;
field->attr &= ~size_t(signable_e);
}
return true;
default:
break;
}
return false; // type unchanged
}
assert(candidate == FldDisplay || is_elementary(candidate));
assert(field->type != FldDisplay); // can never be
assert(field->usage == FldInvalid ||
field->usage == FldDisplay || is_elementary(field->usage));
if( ! (field->type == FldInvalid ||
field->type == FldGroup || is_elementary(field->type)) ) {
return false; // semantic user error
}
// type matches itself
if( field->type == candidate ) {
if( is_usage ) field->usage = candidate;
return true;
}
if( is_usage && field->usage == candidate ) return true;
if( ! plausible_usage(field->usage, candidate) ) return false;
/*
* FldDisplay candidate
*/
if( candidate == FldDisplay ) { // update usage at most
if( field->type == FldInvalid ||
field->type == FldGroup ||
is_displayable(field->type) ) {
field->usage = candidate;
return true;
}
return false;
}
assert(field->type != candidate && is_elementary(candidate));
/*
* Concrete usage candidate. Update usage first (if USAGE clause), then type.
*/
if( is_usage ) {
switch(field->type) {
case FldBlob:
case FldDisplay:
gcc_unreachable(); // type is never just "display"
break;
case FldAlphaEdited:
break;
case FldNumericEdited:
case FldPointer:
if( is_numeric(candidate) ) {
return false;
}
__attribute__((fallthrough));
case FldInvalid:
case FldGroup:
case FldNumericDisplay:
field->usage = candidate;
break;
case FldLiteralA:
case FldLiteralN:
case FldClass:
case FldConditional:
case FldForward:
case FldIndex:
case FldSwitch:
gcc_unreachable();
case FldAlphanumeric:
// MF allows PIC X(n) to have USAGE COMP-[5x]
if( candidate != FldNumericBin5 ) return false;
if( ! (dialect_mf() && field->has_attr(all_x_e)) ) {
return false;
}
__attribute__((fallthrough));
case FldFloat:
case FldNumericBin5:
case FldNumericBinary:
case FldPacked:
assert(field->type != candidate); // ensured by test at start of function
field->usage = candidate;
}
}
// Now, apply (possibly new) usage to type
assert( !is_usage || field->usage == candidate );
/*
* Concrete type candidate
*/
switch(field->usage) {
case FldInvalid:
field->type = candidate;
field->attr |= numeric_group_attrs(field);
return true;
case FldDisplay:
if( is_displayable(candidate) ) {
field->type = candidate;
field->attr |= numeric_group_attrs(field);
return true;
}
break;
case FldAlphaEdited:
case FldAlphanumeric:
assert( dialect_mf() && field->has_attr(all_x_e) );
// convert all X's alphanumeric to numeric
field->clear_attr(all_x_e);
field->type = field->usage;
field->attr |= numeric_group_attrs(field);
return true;
case FldNumericDisplay:
case FldNumericEdited:
case FldGroup:
case FldLiteralA:
case FldLiteralN:
case FldClass:
case FldConditional:
case FldForward:
case FldSwitch:
case FldPointer:
case FldBlob:
// invalid usage value
gcc_unreachable();
break;
case FldIndex:
if( field->usage == candidate ) {
field->type = candidate;
return true;
}
break;
case FldFloat:
case FldNumericBin5:
case FldNumericBinary:
case FldPacked:
if( field->usage == candidate ) {
field->type = candidate;
return true;
}
if( candidate == FldNumericDisplay ) {
field->type = field->usage;
field->attr |= numeric_group_attrs(field);
return true;
}
break;
}
return false;
}
bool
redefine_field( cbl_field_t *field ) {
cbl_field_t *primary = symbol_redefines(field);
bool fOK = true;
if( !primary ) return false;
if( field->type == FldInvalid ) { // no PICTURE
field->type = primary->type;
field->data = primary->data;
field->data.initial = NULL;
}
if( field->data.capacity == 0 ) field->data = primary->data;
if( is_numeric(field->type) && field->usage == FldDisplay ) {
fOK = symbol_field_type_update(field, FldNumericDisplay, false);
}
return fOK;
}
void
cbl_field_t::report_invalid_initial_value(const YYLTYPE& loc) const {
if( ! data.initial ) return;
auto fig = cbl_figconst_of(data.initial);
// numeric initial value
if( is_numeric(type) ) {
if( has_attr(quoted_e) ) {
error_msg(loc, "numeric type %s VALUE '%s' requires numeric VALUE",
name, data.initial);
return;
}
if( ! (fig == normal_value_e || fig == zero_value_e) ) {
error_msg(loc, "numeric type %s VALUE '%s' requires numeric VALUE",
name, cbl_figconst_str(fig));
return;
}
switch( type ) {
case FldIndex:
case FldNumericBin5:
if( data.digits == 0 ) {
// We are dealing with a pure binary type. If the capacity is
// 8 or more, we need do no further testing because we assume
// everything fits.
if( data.capacity < 8 ) {
auto p = strchr(data.initial, symbol_decimal_point());
if( p && atoll(p+1) != 0 ) {
error_msg(loc, "integer type %s VALUE '%s' "
"requires integer VALUE",
name, data.initial);
} else {
// Calculate the maximum possible value that a binary with this
// many bytes can hold
size_t max_possible_value;
max_possible_value = 1;
max_possible_value <<= data.capacity*8;
max_possible_value -= 1;
if( attr & signable_e )
{
// Because it is signable, we divide by two to account for the
// sign bit:
max_possible_value >>= 1;
}
// Pick up the given VALUE
size_t candidate;
if( *data.initial == '-' ) {
// We care about the magnitude, not the sign
if( !(attr & signable_e) ){
error_msg(loc, "integer type %s VALUE '%s' "
"requires a non-negative integer",
name, data.initial);
}
candidate = atoll(data.initial+1);
}
else {
candidate = (size_t)atoll(data.initial);
}
if( candidate > max_possible_value ) {
error_msg(loc, "integer type %s VALUE '%s' "
"requires an integer of magnitude no greater than %zu",
name, data.initial, max_possible_value);
}
}
}
}
break;
case FldFloat:
break;
default:
if( ! has_attr(scaled_e) ) {
/*
* Check fraction for excess precision
*/
const char *p = strchr(data.initial, symbol_decimal_point());
if( p ) {
auto pend = std::find(p, p + strlen(p), 0x20);
int n = std::count_if( ++p, pend, isdigit );
if( data.precision() < n) {
if( 0 == data.rdigits ) {
error_msg(loc, "integer type %s VALUE '%s' requires integer VALUE",
name, data.initial);
} else {
auto has_exponent = std::any_of( p, pend,
[]( char ch ) {
return TOUPPER(ch) == 'E';
} );
if( !has_exponent && data.precision() < pend - p ) {
error_msg(loc, "%s cannot represent VALUE '%s' exactly (max .%zu)",
name, data.initial, pend - p);
}
}
}
} else {
p = data.initial + strlen(data.initial);
}
/*
* Check magnitude, whether or not there's a decimal point.
*/
// skip leading zeros
auto first_digit = std::find_if( data.initial, p,
[]( char ch ) {
return ch != '0'; } );
// count remaining digits, up to the decimal point
auto n = std::count_if( first_digit, p, isdigit );
if( data.ldigits() < n ) {
error_msg(loc, "numeric %s VALUE '%s' holds only %u digits",
name, data.initial,
data.digits);
}
}
break;
} // end type switch for normal string initial value
return;
} // end numeric
assert( ! is_numeric(type) );
// consider all-alphabetic
if( has_attr(all_alpha_e) ) {
bool alpha_value = fig != zero_value_e;
if( fig == normal_value_e ) {
alpha_value = std::all_of( data.initial,
data.initial +
strlen(data.initial),
[]( char ch ) {
return ISSPACE(ch) ||
ISPUNCT(ch) ||
ISALPHA(ch); } );
}
if( ! alpha_value ) {
error_msg(loc, "alpha-only %s VALUE '%s' contains non-alphabetic data",
name, fig == zero_value_e? cbl_figconst_str(fig) : data.initial);
}
}
return;
}
// Return the field representing the subscript whose literal value
// exceeds the OCCURS clause for that dimension, else NULL if all
// literals are in bounds.
const cbl_field_t *
literal_subscript_oob( const cbl_refer_t& r, size_t& isub /* output */) {
// Verify literal subscripts if dimensions are correct.
size_t ndim(dimensions(r.field));
if( ndim == 0 || ndim != r.nsubscript ) return NULL;
cbl_refer_t *esub = r.subscripts + r.nsubscript;
std::vector<cbl_field_t *> dims( ndim, NULL );
auto pdim = dims.end();
for( auto f = r.field; f; f = parent_of(f) ) {
if( f->occurs.ntimes() ) {
--pdim;
*pdim = f;
}
}
assert(dims[0] != NULL);
assert(pdim == dims.begin());
/*
* For each subscript, if it is a literal, verify it is in bounds
* for the corresponding dimension. Return the first subscript not
* meeting those criteria, if any.
*/
auto p = std::find_if( r.subscripts, esub,
[&pdim]( const cbl_refer_t& r ) {
const auto& occurs((*pdim)->occurs);
pdim++;
return ! occurs.subscript_ok(r.field);
} );
isub = p - r.subscripts;
return p == esub? NULL : dims[isub];
}
size_t
cbl_refer_t::subscripts_set( const std::list<cbl_refer_t>& subs ) {
nsubscript = subs.size();
subscripts = new cbl_refer_t[nsubscript];
std::copy( subs.begin(), subs.end(), subscripts );
return dimensions(field);
}
const char *
cbl_refer_t::str() const {
static char subscripts[64];
sprintf(subscripts, "(%u of %zu dimensions)", nsubscript, dimensions(field));
char *output = xasprintf("%s %s %s",
field? field_str(field) : "(none)",
0 < dimensions(field)? subscripts : "",
is_refmod_reference()? "(refmod)" : "" );
return output;
}
const char *
cbl_refer_t::name() const {
if( prog_func ) return prog_func->name;
char *output = xasprintf("%s", field? field->name : "(none)" );
return output;
}
const char *
cbl_refer_t::deref_str() const {
std::vector<char> dimstr(nsubscript * 16, '\0');
dimstr.at(0) = '(';
auto p = dimstr.begin() + 1;
if( !field ) return name();
for( auto sub = subscripts; sub < subscripts + nsubscript; sub++ ) {
auto initial = sub->field->data.initial ? sub->field->data.initial : "?";
size_t len = dimstr.end() - p;
p += snprintf( &*p, len, "%s ", initial );
}
if( 0 < nsubscript ) {
*--p = ')';
}
char *output = xasprintf("%s%s", field->name, dimstr.data());
return output;
}
struct move_corresponding_field {
cbl_refer_t tgt, src;
move_corresponding_field( const cbl_refer_t& tgt, const cbl_refer_t& src )
: tgt(tgt), src(src) {}
void operator()( corresponding_fields_t::const_reference elem ) {
if( elem.second == 0 ) return;
src.field = cbl_field_of(symbol_at(elem.first));
tgt.field = cbl_field_of(symbol_at(elem.second));
if( yydebug ) {
dbgmsg("move_corresponding:%d: SRC: %3zu %s", __LINE__,
elem.first, src.str());
dbgmsg("move_corresponding:%d: to %3zu %s", __LINE__,
elem.second, tgt.str());
}
parser_move(tgt, src);
}
};
bool
move_corresponding( cbl_refer_t& tgt, cbl_refer_t& src )
{
assert(tgt.field && src.field);
assert(tgt.field->type == FldGroup);
assert(src.field->type == FldGroup);
corresponding_fields_t pairs = corresponding_move_fields( src.field,
tgt.field );
if( pairs.empty() ) return false;
std::for_each( pairs.begin(), pairs.end(),
move_corresponding_field(tgt, src) );
return true;
}
bool
valid_move( const struct cbl_field_t *tgt, const struct cbl_field_t *src )
{
// This is the base matrix of allowable moves. Moves from Alphanumeric are
// modified based on the attribute bit all_alpha_e, and moves from Numeric
// types to Alphanumeric and AlphanumericEdited are allowable when the
// Numeric type is integer, and not allowed when the type has digits to the
// right of the decimal point.
// Note that the ordering of elements in this matrix has to match the
// ordering of the symbols.h elements in enum cbl_field_type_t.
static const unsigned char matrix[FldLiteralN+1][FldLiteralN+1] = {
// src down, tgt across
//I G A B F P 5 ND NE AE LA LN
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, // FldInvalid
{ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, }, // FldGroup
{ 0, 1, 1, 8, 8, 8, 8, 8, 8, 1, 0, 0, }, // FldAlphanumeric
{ 0, 1, 6, 1, 1, 1, 1, 1, 1, 2, 0, 0, }, // FldNumericBinary (numeric)
{ 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, }, // FldFloat
{ 0, 1, 6, 1, 1, 1, 1, 1, 1, 2, 0, 0, }, // FldPacked (numeric)
{ 0, 1, 6, 1, 1, 1, 1, 1, 1, 2, 0, 0, }, // FldNumericBin5 (numeric)
{ 0, 1, 6, 1, 1, 1, 1, 1, 1, 2, 0, 0, }, // FldNumericDisplay (numeric)
{ 0, 1, 4, 1, 1, 1, 1, 1, 1, 1, 0, 0, }, // FldNumericEdited
{ 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, }, // FldAlphaEdited
{ 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, }, // FldLiteralA
{ 0, 1, 6, 1, 1, 1, 1, 1, 1, 2, 0, 0, }, // FldLiteralN (numeric)
};
/* Needs C++11 */
static_assert(sizeof(matrix[0]) == COUNT_OF(matrix[0]),
"matrix should be square");
for( const cbl_field_t *args[] = {tgt, src}, **p=args;
p < args + COUNT_OF(args); p++ ) {
auto& f(**p);
switch(f.type) {
case FldClass:
case FldConditional:
case FldIndex:
case FldSwitch:
case FldDisplay:
case FldPointer:
return false;
// parser should not allow the following types here
case FldForward:
case FldBlob:
default:
if( sizeof(matrix[0]) < f.type ) {
cbl_internal_error("logic error: MOVE %s %s invalid type:",
cbl_field_type_str(f.type), f.name);
}
break;
}
}
assert(tgt->type < sizeof(matrix[0]));
assert(src->type < sizeof(matrix[0]));
// A value of zero means the move is prohibited.
// The 1 bit means the move is allowed
// The 2 bit means the move is allowed if the source has zero rdigits,
// or is P-scaled
// The 4 bit means the move is allowed if dest all_alpha_e is off.
// The 8 bit means the move is allowed if source all_alpha_e is off.
bool retval = false;
bool nofraction = src->data.rdigits == 0 || src->has_attr(scaled_e);
bool alphabetic = tgt->has_attr(all_alpha_e);
bool src_alpha = src->has_attr(all_alpha_e);
switch( matrix[src->type][tgt->type] )
{
case 0:
if( src->type == FldLiteralA && is_numericish(tgt) && !is_literal(tgt) ) {
// Allow if input string is an integer.
const char *p = src->data.initial, *pend = p + src->data.capacity;
if( p[0] == '+' || p[0] == '-' ) p++;
retval = std::all_of( p, pend, isdigit );
if( yydebug && ! retval ) {
auto bad = std::find_if( p, pend,
[]( char ch ) { return ! ISDIGIT(ch); } );
dbgmsg("%s:%d: offending character '%c' at position %zu",
__func__, __LINE__, *bad, bad - p);
}
}
break;
case 1:
retval = true;
break;
case 2:
retval = nofraction;
break;
case 4:
retval = !alphabetic;
break;
case 6:
retval = nofraction && !alphabetic;
break;
case 8:
retval = !src_alpha;
break;
default:
dbgmsg("%s:%d: matrix at %s, %s is %d", __func__, __LINE__,
cbl_field_type_str(src->type), cbl_field_type_str(tgt->type),
matrix[src->type][tgt->type]);
gcc_unreachable();
}
if( retval && src->has_attr(embiggened_e) ) {
if( is_numeric(tgt) && tgt->data.capacity < src->data.capacity ) {
dbgmsg("error: source no longer fits in target");
return false;
}
}
if( yydebug && getenv(__func__) ) {
dbgmsg("%s:%d: ok to move %s to %s (0x%02x)", __func__, __LINE__,
cbl_field_type_str(src->type), cbl_field_type_str(tgt->type),
retval);
}
return retval;
}
bool
valid_picture( enum cbl_field_type_t type, const char picture[] )
{
switch(type) {
case FldBlob:
gcc_unreachable(); // can't get here via the parser
case FldInvalid:
case FldGroup:
case FldLiteralA:
case FldLiteralN:
case FldClass:
case FldConditional:
case FldForward:
case FldIndex:
case FldSwitch:
case FldDisplay:
case FldPointer:
// These types don't take pictures; the grammar shouldn't call the function.
dbgmsg("%s:%d: no polaroid: %s", __func__, __LINE__, cbl_field_type_str(type));
return false;
case FldNumericBinary:
case FldFloat:
case FldNumericBin5:
case FldPacked:
// Validated in scan.l.
return true;
case FldAlphanumeric:
// Cannot be all As or all 9s.
return !( memall(picture, 'A') || memall(picture, '9') );
case FldNumericDisplay:
// Must have A or X and B, 0, or /.
return match(picture, "[AX]") && match(picture, "[B0/]");
case FldNumericEdited:
case FldAlphaEdited:
break;
}
assert(type == FldNumericEdited );
// Must contain at least one 0, B, /, Z, *, +, (comma), ., –, CR, DB, or cs.
if( ! match( picture, "[$0B/Z*+.,+–]|DB$|CR$" ) ) {
return false;
}
return true;
}
uint32_t
type_capacity( enum cbl_field_type_t type, uint32_t digits )
{
switch(type) {
case FldBlob: gcc_unreachable();
case FldInvalid:
case FldGroup:
case FldAlphanumeric:
case FldNumericDisplay:
case FldNumericEdited:
case FldAlphaEdited:
case FldClass:
case FldConditional:
case FldForward:
case FldIndex:
case FldSwitch:
case FldDisplay:
case FldPointer:
return digits;
case FldFloat:
case FldNumericBinary:
case FldNumericBin5:
case FldLiteralA:
case FldLiteralN:
break;
case FldPacked:
return (digits+2)/2; // one nybble per digit + a sign nybble
}
static const struct sizes_t {
std::pair<uint32_t, uint32_t> bounds;
size_t size;
sizes_t( uint32_t first, uint32_t last, uint32_t size )
: bounds(first, last), size(size)
{}
} sizes[] = {
{ 1, 4, 2 },
{ 5, 9, 4 },
{10, 18, 8 },
{19, 38, 16 },
}, *esizes = sizes + COUNT_OF(sizes);
auto psize = std::find_if( sizes, esizes,
[digits]( sizes_t sizes ) {
return sizes.bounds.first <= digits && digits <= sizes.bounds.second;
} );
if( psize != esizes ) return psize->size;
dbgmsg( "%s:%d: invalid size %u for type %s", __func__, __LINE__,
digits, cbl_field_type_str(type) );
return digits;
}
typedef char hex_pair_t[2];
class scan_hex {
public:
unsigned char operator()( const hex_pair_t input ) {
static char buffer[ sizeof(hex_pair_t) + 1 ] = "";
memcpy( buffer, input, sizeof(buffer) - 1 );
unsigned int x;
sscanf( buffer, "%x", &x );
return x;
}
};
/*
* Convert hexadecimal string to ASCII, e.g. X'434154' to "CAT".
*/
char *
hex_decode( const char input[] ) {
const size_t len = strlen(input);
assert( 0 == len % 2 );
auto output = static_cast<char *>(xcalloc( 1, 1 + len / 2 ));
auto beg = reinterpret_cast<const hex_pair_t*>(input + 0),
end = reinterpret_cast<const hex_pair_t*>(input + len);
std::transform( beg, end, output, scan_hex() );
return output;
}
/*
* Verify unique procedure reference.
*
* Section and paragraph names need not be unique unless they are
* referenced, for example by PERFORM.
*
* When a program contains sections, a paragraph can be referenced
* without qualification if it's unique within the current section or
* globally. Else <para> OF <sect> is required. That means the
* validity of a reference depends on location of reference, which is
* why order matters. (We can't use line number because the Cobol text
* could be all on one line.)
*
* We maintain a map of referenceable {section,paragraph} pairs, with
* a count. A count of 1 means it's globally unique.
*
* For local calls, we maintain a multimap of sections (whose names might
* not be unique) in order of appearance. For each section, we have a
* set of paragraph names defined by the section, and a count, plus a
* list of references: {section,paragraph} names used by PERFORM or
* similar.
*
* To determine if a call is valid:
* For each key {section}:
* for each reference:
* Local: if section is empty or matches the key, the call is valid if
* if the paragraph name is unique within section:
* valid if count == 1
* Global: valid if {section,paragraph} is unique in the global map
*
* Line numbers are just decoration.
*/
bool
procref_base_t::operator<( const procref_base_t& that ) const {
int result = strcasecmp(section(), that.section());
if( result == 0 ) {
return strcasecmp(paragraph(), that.paragraph()) < 0;
}
return result < 0;
}
bool
procref_base_t::operator==( const procref_base_t& that ) const {
return
0 == strcasecmp(section(), that.section()) &&
0 == strcasecmp(paragraph(), that.paragraph());
}
class procdef_t : public procref_base_t {
size_t isym;
public:
procdef_t( const char *section, const char *paragraph, size_t isym )
: procref_base_t(section, paragraph)
, isym(isym)
{
assert(isym);
}
procdef_t( const procref_base_t& ref )
: procref_base_t(ref)
, isym(0)
{}
bool operator<( const procdef_t& that ) const {
return procref_base_t(*this) < procref_base_t(that);
}
bool operator<( const procref_base_t& that ) const {
if( that.has_section() ) {
return procref_base_t(*this) < that;
}
return strcasecmp(paragraph(), that.paragraph()) < 0;
}
cbl_label_t * label_of() const {
return isym == 0? NULL : cbl_label_of(symbol_at(isym));
}
};
/*
* Every reference occurs in a {program,section,paragraph} context,
* even if they're implicit.
*/
typedef std::multimap<procdef_t, std::list<procref_t>> procedures_t;
static std::map<size_t, procedures_t> programs;
static procedures_t::iterator current_procedure = programs.end()->second.end();
/*
* If a procedure reference uses only one name, it could refer to a
* section or paragraph. The "paragraph" name in the reference, if not
* paired with a section name, might refer to a section.
*
* For a 1-name reference:
* a global match means the name is defined exactly once
* a local match matches a unique paragraph name in the
* section in which the reference occurs, or the section name itself
*
* No paragraph can have the same name as a section.
*/
class procedure_match {
const procref_base_t& ref;
public:
procedure_match( const procref_base_t& ref ) : ref(ref) {}
// Match a 2-name reference to section & paragraph, else to one or the other.
bool operator()( procedures_t::const_reference elem ) {
const procdef_t& key = elem.first;
if( ref.has_section() ) return ref == key;
bool hit =
(!key.has_paragraph() && 0 == strcasecmp(key.section(), ref.paragraph()))
|| 0 == strcasecmp(key.paragraph(), ref.paragraph());
return hit;
}
};
static bool
globally_unique( size_t program, const procref_t& ref ) {
const procedures_t& procedures = programs[program];
assert(!procedures.empty());
return 1 == count_if(procedures.begin(), procedures.end(), procedure_match(ref));
}
static bool
locally_unique( size_t program, const procdef_t& key, const procref_t& ref ) {
const procedures_t& procedures = programs[program];
assert(!procedures.empty());
const char *section_name = ref.has_section()? ref.section() : key.section();
procref_base_t full_ref(section_name, ref.paragraph());
if( getenv(__func__) ) {
dbgmsg("%s: %zu for ref %s of '%s' (line %d) "
"in %s of '%s' (as %s of '%s')", __func__,
procedures.count(full_ref),
ref.paragraph(), ref.section(), ref.line_number(),
key.paragraph(), key.section(),
full_ref.paragraph(), full_ref.section() );
}
return 1 == procedures.count(full_ref);
}
// Add each section and paragraph to the map as it occurs in the Cobol text.
void
procedure_definition_add( size_t program, const cbl_label_t *procedure ) {
const char *section_name = NULL, *paragraph_name = NULL;
size_t isym = symbol_index(symbol_elem_of(procedure));
if( procedure->type == LblParagraph ) {
if( procedure->parent > 0) {
section_name = cbl_label_of(symbol_at(procedure->parent))->name;
}
paragraph_name = procedure->name;
} else {
assert( procedure->type == LblSection );
section_name = procedure->name;
}
procdef_t key( section_name, paragraph_name, isym );
if( getenv(__func__) ) {
dbgmsg("%s: #%3zu %s of %s", __func__, isym, paragraph_name, section_name);
}
current_procedure =
programs[program].insert( make_pair(key, procedures_t::mapped_type()) );
}
// Add each procedure reference as it occurs in the Cobol text, in context.
void
procedure_reference_add( const char *section, const char *paragraph,
int line, size_t context )
{
if( getenv(__func__) ) {
dbgmsg("%s: line %3d %s of %s", __func__, line, paragraph, section);
}
current_procedure->second.push_back( procref_t(section, paragraph,
line, context) );
}
// Verify each reference in a map element is locally or globally unique
class is_unique {
size_t program;
procedures_t::key_type key;
public:
is_unique( size_t program, const procedures_t::key_type& key )
: program(program)
, key(key)
{}
bool operator()( procedures_t::mapped_type::const_reference ref ) {
return
locally_unique( program, key, ref ) ||
globally_unique( program, ref);
}
};
procref_t *
ambiguous_reference( size_t program ) {
procedures_t& procedures = programs[program];
for( const auto& proc : procedures ) {
procedures_t::mapped_type::const_iterator
ambiguous = find_if_not( proc.second.begin(), proc.second.end(),
is_unique(program, proc.first) );
if( proc.second.end() != ambiguous ) {
if( yydebug || getenv("symbol_label_add")) {
dbgmsg("%s: %s of '%s' has %zu potential matches", __func__,
ambiguous->paragraph(), ambiguous->section(),
procedures.count(*ambiguous));
}
return new procref_t(*ambiguous);
}
}
return NULL;
}
/*
* See declaratives nonterminal in parse.y
*/
// Todo: unused
cbl_label_t *
intradeclarative_reference() {
const procedures_t& procedures = programs[current_program_index()];
for( auto elem : procedures ) {
procdef_t key( elem.first );
auto L = key.label_of();
if( L->type != LblNone ) return L;
}
return NULL;
}
class next_group {
size_t isym;
public:
next_group( symbol_elem_t *group ) : isym(symbol_index(group)) {}
// return true if elem is not a member of the group
bool operator()( const symbol_elem_t& elem ) {
if( elem.type != SymField ) return false;
if( symbol_index(&elem) == isym ) return false;
return cbl_field_of(&elem)->parent < isym;
}
};
static void
parent_names( const symbol_elem_t *elem,
const symbol_elem_t *group, std::list<const char *>& names ) {
if( is_filler(cbl_field_of(elem)) ) return;
// dbgmsg("%s: asked about %s of %s (%zu away)", __func__,
// cbl_field_of(elem)->name,
// cbl_field_of(group)->name, elem - group);
for( const symbol_elem_t *e=elem; e && group < e; e = symbol_parent(e) ) {
names.push_front( cbl_field_of(e)->name );
}
}
extern int yylineno;
class find_corresponding {
public:
enum type_t { arith_op, move_op };
private:
symbol_elem_t *lgroup, *rgroup;
type_t type;
public:
find_corresponding( symbol_elem_t *lgroup,
symbol_elem_t *rgroup, type_t type )
: lgroup(lgroup), rgroup(rgroup), type(type)
{
dbgmsg( "%s:%d: for #%zu %s and #%zu %s on line %d", __func__, __LINE__,
symbol_index(lgroup), cbl_field_of(lgroup)->name,
symbol_index(rgroup), cbl_field_of(rgroup)->name, yylineno );
}
static bool
any_redefines( const cbl_field_t& field, const symbol_elem_t *group ) {
for( const cbl_field_t *f = &field; f && f->parent > 0; f = parent_of(f) ) {
symbol_elem_t *e = symbol_at(f->parent);
if( e == group || e->type != SymField ) break;
if( symbol_redefines(f) ) return true;
}
return false;
}
corresponding_fields_t::value_type
operator()( const symbol_elem_t& that ) {
if( &that == lgroup ) return std::make_pair(0,0);
if( that.type != SymField ) return std::make_pair(0,0);
const cbl_field_t& lfield( *cbl_field_of(&that) );
switch(lfield.level) {
case 66: case 77: case 88:
return std::make_pair(0,0);
default:
if( any_redefines(lfield, lgroup) ) return std::make_pair(0,0);
if( is_filler(&lfield) ) return std::make_pair(0,0);
if( is_table(&lfield) ) return std::make_pair(0,0);
break;
}
std::list<const char *> names;
parent_names( &that, lgroup, names );
names.push_front(cbl_field_of(rgroup)->name);
symbol_elem_t *e = symbol_find_of( that.program, names, symbol_index(rgroup) );
if( !e ) return std::make_pair(0,0);
const cbl_field_t& rfield( *cbl_field_of(e) );
switch(rfield.level) {
case 66: case 77: case 88:
return std::make_pair(0,0);
default:
if( any_redefines(rfield, rgroup) ) return std::make_pair(0,0);
if( is_table(&rfield) ) return std::make_pair(0,0);
break;
}
switch(type) {
case arith_op:
if( !(is_numeric(lfield.type) && is_numeric(rfield.type)) ) {
return std::make_pair(0,0);
}
break;
case move_op:
if( !(is_elementary(lfield.type) || is_elementary(rfield.type)) ) {
return std::make_pair(0,0);
}
break;
}
return std::make_pair( symbol_index(&that), symbol_index(e));
}
};
static corresponding_fields_t
corresponding_fields( cbl_field_t *lhs, cbl_field_t *rhs,
find_corresponding::type_t type ) {
corresponding_fields_t output;
assert(lhs); assert(rhs);
assert(lhs->type == FldGroup && rhs->type == FldGroup);
struct { symbol_elem_t *a, *z; } lhsg;
lhsg.a = symbols_begin(field_index(lhs));
lhsg.z = std::find_if( lhsg.a, symbols_end(), next_group(lhsg.a) );
dbgmsg("%s:%d: examining %zu symbols after %s", __func__, __LINE__,
lhsg.z - lhsg.a, lhs->name);
find_corresponding finder( symbol_at(field_index(lhs)),
symbol_at(field_index(rhs)), type );
std::transform( lhsg.a, lhsg.z, std::inserter(output, output.begin()), finder );
output.erase(0);
dbgmsg( "%s:%d: %s and %s have %zu corresponding fields",
__func__, __LINE__, lhs->name, rhs->name, output.size() );
return output;
}
corresponding_fields_t
corresponding_move_fields( cbl_field_t *lhs, cbl_field_t *rhs ) {
return corresponding_fields( lhs, rhs, find_corresponding::move_op );
}
corresponding_fields_t
corresponding_arith_fields( cbl_field_t *lhs, cbl_field_t *rhs ) {
return corresponding_fields( lhs, rhs, find_corresponding::arith_op );
}
char
date_time_fmt( const char input[] ) {
if( ! input ) return 0;
#define DATE_FMT_B "(YYYYMMDD|YYYYDDD|YYYYWwwD)"
#define DATE_FMT_E "(YYYY-MM-DD|YYYY-DDD|YYYY-Www-D)"
#define TIME_FMT1 "hhmmss([.,]s+)?"
#define TIME_FMT3 "hhmmss([.,]s+)?Z"
#define TIME_FMT5 "hhmmss([.,]s+)?[+]hhmm"
#define TIME_FMT2 "hh:mm:ss([.,]s+)?"
#define TIME_FMT4 "hh:mm:ss([.,]s+)?Z"
#define TIME_FMT6 "hh:mm:ss([.,]s+)?[+]hh:mm"
#define TIME_FMT_B "(" TIME_FMT1 "|" TIME_FMT3 "|" TIME_FMT5 ")"
#define TIME_FMT_E "(" TIME_FMT2 "|" TIME_FMT4 "|" TIME_FMT6 ")"
static bool compiled = false;
static struct fmts_t {
regex_t reg; char type; char pattern[256];
} fmts[] = {
{ regex_t(), 'D', "^((" DATE_FMT_B "T" TIME_FMT_B ")|("
DATE_FMT_E "T" TIME_FMT_E "))$" },
{ regex_t(), 'd', "^(" DATE_FMT_B "|" DATE_FMT_E ")$" },
{ regex_t(), 't', "^(" TIME_FMT_B "|" TIME_FMT_E ")$" },
};
int erc, cflags = REG_EXTENDED | REG_ICASE, eflags=0;
regmatch_t m[5];
char result = 0;
if( ! compiled ) {
for( auto& fmt : fmts ) {
if( (erc = regcomp(&fmt.reg, fmt.pattern, cflags)) != 0 ) {
char msg[80];
regerror(erc, &fmt.reg, msg, sizeof(msg));
cbl_errx( "%s: regcomp: %s", __func__, msg );
}
}
compiled = true;
}
for( auto& fmt : fmts ) {
if( 0 == regexec(&fmt.reg, input, COUNT_OF(m), m, eflags) ) {
result = fmt.type;
break;
}
}
return result;
}
/*
* Development suppport
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
struct input_file_t {
ino_t inode;
int lineno;
const char *name;
const line_map *lines;
input_file_t( const char *name, ino_t inode,
int lineno=1, const line_map *lines = NULL )
: inode(inode), lineno(lineno), name(name), lines(lines)
{
if( inode == 0 ) inode_set();
}
bool operator==( const input_file_t& that ) const {
return inode == that.inode;
}
protected:
void inode_set() {
struct stat sb;
if( -1 == stat(name, &sb) ) {
cbl_err( "could not stat '%s'", name);
}
inode = sb.st_ino;
}
};
class unique_stack : public std::stack<input_file_t>
{
public:
bool push( const value_type& value ) {
auto ok = std::none_of( c.cbegin(), c.cend(),
[value]( auto& that ) {
return value == that;
} );
if( ok ) {
std::stack<input_file_t>::push(value);
return true;
}
size_t n = c.size();
if( n > 1 ) {
char *wd = get_current_dir_name();
if( wd ) {
dbgmsg( "depth line copybook filename\n"
"----- ---- --------"
"----------------------------------------");
for( const auto& v : c ) {
dbgmsg( " %4zu %4d %s", c.size() - --n, v.lineno, no_wd(wd, v.name) );
}
} else {
dbgmsg("unable to get current working directory: %m");
}
free(wd);
}
return false;
}
const char *
no_wd( const char *wd, const char *name ) {
int i;
for( i=0; wd[i] == name[i]; i++ ) i++;
if( wd[i] == '\0' && name[i] == '/' ) i++;
return yydebug? name : name + i;
}
};
static const char *input_filename_vestige;
static unique_stack input_filenames;
static std::map<std::string, ino_t> old_filenames;
static const unsigned int sysp = 0; // not a C header file, cf. line-map.h
/*
* Maintain a stack of input filenames. Ensure the files are unique (by
* inode), to prevent copybook cycles. Before pushing a new name, Record the
* line number that was is current for the current name, so that it can be
* restored when the usurper is popped.
*
* Both the file-reader (lexio) and the scanner use this stack. Lexio uses it
* to enforce uniqueness, and the scanner to maintain line numbers.
*/
bool cobol_filename( const char *name, ino_t inode ) {
line_map *lines = NULL;
if( inode == 0 ) {
auto p = old_filenames.find(name);
if( p == old_filenames.end() ) {
for( auto& elem : old_filenames ) {
dbgmsg("%6zu %-30s", elem.second, elem.first.c_str());
}
cbl_errx( "logic error: missing inode for %s", name);
}
inode = p->second;
assert(inode != 0);
}
linemap_add(line_table, LC_ENTER, sysp, name, 1);
input_filename_vestige = name;
bool pushed = input_filenames.push( input_file_t(name, inode, 1, lines) );
input_filenames.top().lineno = yylineno = 1;
if( getenv(__func__) ) {
dbgmsg(" saving %s with lineno as %d",
input_filenames.top().name, input_filenames.top().lineno);
}
return pushed;
}
const char *
cobol_lineno_save() {
if( input_filenames.empty() ) return NULL;
auto& input( input_filenames.top() );
input.lineno = yylineno;
if( getenv(__func__) ) {
dbgmsg(" setting %s with lineno as %d", input.name, input.lineno);
}
return input.name;
}
const char *
cobol_filename() {
return input_filenames.empty()? input_filename_vestige : input_filenames.top().name;
}
const char *
cobol_filename_restore() {
assert(!input_filenames.empty());
const input_file_t& top( input_filenames.top() );
old_filenames[top.name] = top.inode;
input_filename_vestige = top.name;
input_filenames.pop();
if( input_filenames.empty() ) return NULL;
auto& input = input_filenames.top();
input.lines = linemap_add(line_table, LC_LEAVE, sysp, NULL, 0);
yylineno = input.lineno;
if( getenv("cobol_filename") ) {
dbgmsg("restoring %s with lineno to %d", input.name, input.lineno);
}
return input.name;
}
static location_t token_location;
template <typename LOC>
static void
gcc_location_set_impl( const LOC& loc ) {
token_location = linemap_line_start( line_table, loc.last_line, 80 );
token_location = linemap_position_for_column( line_table, loc.first_column);
location_dump(__func__, __LINE__, "parser", loc);
}
void gcc_location_set( const YYLTYPE& loc ) {
gcc_location_set_impl(loc);
}
void gcc_location_set( const YDFLTYPE& loc ) {
gcc_location_set_impl(loc);
}
#ifdef NDEBUG
# define verify_format(M)
#else
#include <regex.h>
static void
verify_format( const char gmsgid[] ) {
static const char pattern[] = "%[[:digit:]][[:digit:].]*[^s]";
static regex_t re;
static int cflags = REG_EXTENDED;
static int status = regcomp( &re, pattern, cflags );
static char errbuf[80];
if( status != 0 ) {
int n = regerror(status, &re, errbuf, sizeof(errbuf));
gcc_assert(size_t(n) < sizeof(errbuf));
fprintf(stderr, "%s:%d: %s", __func__, __LINE__, errbuf);
return;
}
gcc_assert(status == 0);
regmatch_t rm[30];
if( REG_NOMATCH != regexec(&re, gmsgid, COUNT_OF(rm), rm, 0) ){
fprintf(stderr, "bad diagnositic format: '%s'\n", gmsgid);
}
}
#endif
static const diagnostic_option_id option_zero;
size_t parse_error_inc();
void
ydferror( const char gmsgid[], ... ) {
verify_format(gmsgid);
parse_error_inc();
auto_diagnostic_group d;
va_list ap;
va_start (ap, gmsgid);
rich_location richloc (line_table, token_location);
bool ret = global_dc->diagnostic_impl (&richloc, nullptr, option_zero,
gmsgid, &ap, DK_ERROR);
va_end (ap);
}
extern int yychar;
extern YYLTYPE yylloc;
/*
* temp_loc_t is a hack in lieu of "%define parse.error custom". When
* instantiated, if there is a lookahead token (or one is provided), it sets
* the global token_location, which is passed to the diagnostic framework. The
* original value is restored when the instantiated variable goes out of scope.
*/
class temp_loc_t : protected YYLTYPE {
location_t orig;
public:
temp_loc_t() : orig(token_location) {
if( yychar < 3 ) return;
gcc_location_set(yylloc); // use lookahead location
}
temp_loc_t( const YYLTYPE& loc) : orig(token_location) {
gcc_location_set(loc);
}
temp_loc_t( const YDFLTYPE& loc) : orig(token_location) {
YYLTYPE lloc = {
loc.first_line, loc.first_column,
loc.last_line, loc.last_column };
gcc_location_set(lloc);
}
~temp_loc_t() {
if( orig != token_location ) {
token_location = orig;
}
}
};
/*
* Both CDF and parser need to call error_msg, each with their own distinct
* location type, not because they *need* to be different, but because they
* are, as an artifact of using different prefixes. Possibly a better plan
* would be to convert cdf.y to a pure parser, using no global variables. But
* this is where we are.
*
* Because we can't reliably instantiate it as a forward-declared template
* function, and because the paramters are variadic, we can't use a template
* function or call one. So, a macro.
*/
#define ERROR_MSG_BODY \
temp_loc_t looker(loc); \
verify_format(gmsgid); \
parse_error_inc(); \
global_dc->begin_group(); \
va_list ap; \
va_start (ap, gmsgid); \
rich_location richloc (line_table, token_location); \
bool ret = global_dc->diagnostic_impl (&richloc, nullptr, option_zero, \
gmsgid, &ap, DK_ERROR); \
va_end (ap); \
global_dc->end_group();
void error_msg( const YYLTYPE& loc, const char gmsgid[], ... ) {
ERROR_MSG_BODY
}
void error_msg( const YDFLTYPE& loc, const char gmsgid[], ... ) {
ERROR_MSG_BODY
}
void
cdf_location_set(YYLTYPE loc) {
extern YDFLTYPE ydflloc;
ydflloc.first_line = loc.first_line;
ydflloc.first_column = loc.first_column;
ydflloc.last_line = loc.last_line;
ydflloc.last_column = loc.last_column;
}
void
yyerror( const char gmsgid[], ... ) {
temp_loc_t looker;
verify_format(gmsgid);
parse_error_inc();
global_dc->begin_group();
va_list ap;
va_start (ap, gmsgid);
rich_location richloc (line_table, token_location);
bool ret = global_dc->diagnostic_impl (&richloc, nullptr, option_zero,
gmsgid, &ap, DK_ERROR);
va_end (ap);
global_dc->end_group();
}
bool
yywarn( const char gmsgid[], ... ) {
verify_format(gmsgid);
auto_diagnostic_group d;
va_list ap;
va_start (ap, gmsgid);
auto ret = emit_diagnostic_valist( DK_WARNING, token_location,
option_zero, gmsgid, &ap );
va_end (ap);
return ret;
}
/*
* Sometimes during parsing an error is noticed late. This message refers back
* to an arbitrary file and line number.
*/
void
yyerrorvl( int line, const char *filename, const char fmt[], ... ) {
verify_format(fmt);
parse_error_inc();
auto_diagnostic_group d; // not needed unless we can use global_dc
char *msg;
va_list ap;
va_start(ap, fmt);
msg = xvasprintf(fmt, ap);
if( !filename ) filename = cobol_filename();
fprintf( stderr, "%s:%d: %s\n", filename, line, msg);
free(msg);
va_end(ap);
}
static inline size_t
matched_length( const regmatch_t& rm ) { return rm.rm_eo - rm.rm_so; }
const char *
cobol_fileline_set( const char line[] ) {
static const char pattern[] = "#line +([[:alnum:]]+) +[\"']([^\"']+). *\n";
static const int cflags = REG_EXTENDED | REG_ICASE;
static regex_t re, *preg = NULL;
int erc;
regmatch_t pmatch[4];
if( !preg ) {
if( (erc = regcomp(&re, pattern, cflags)) != 0 ) {
regerror(erc, &re, regexmsg, sizeof(regexmsg));
dbgmsg( "%s:%d: could not compile regex: %s", __func__, __LINE__, regexmsg );
return line;
}
preg = &re;
}
if( (erc = regexec(preg, line, COUNT_OF(pmatch), pmatch, 0)) != 0 ) {
if( erc != REG_NOMATCH ) {
regerror(erc, preg, regexmsg, sizeof(regexmsg));
dbgmsg( "%s:%d: could not compile regex: %s", __func__, __LINE__, regexmsg );
return line;
}
error_msg(yylloc, "invalid #line directive: %s", line );
return line;
}
const char
*line_str = xstrndup(line + pmatch[1].rm_so, matched_length(pmatch[1])),
*filename = xstrndup(line + pmatch[2].rm_so, matched_length(pmatch[2]));
int fileline;
if( 1 != sscanf(line_str, "%d", &fileline) )
yywarn("could not parse line number %s from #line directive", line_str);
input_file_t input_file( filename, ino_t(0), fileline ); // constructor sets inode
if( getenv(__func__) ) return filename; // ignore #line directive
if( input_filenames.empty() ) {
input_file.lines = linemap_add(line_table, LC_ENTER, sysp, filename, 1);
input_filenames.push(input_file);
}
input_file_t& file = input_filenames.top();
file = input_file;
yylineno = file.lineno;
return file.name;
}
class timespec_t {
struct timespec now;
public:
timespec_t() {
clock_gettime(CLOCK_MONOTONIC, &now);
}
double ns() const {
return now.tv_sec * 1000000000 + now.tv_nsec;
}
friend double operator-( const timespec_t& now, const timespec_t& then );
};
double
operator-( const timespec_t& then, const timespec_t& now ) {
return (now.ns() - then.ns()) / 1000000000;
}
static int
parse_file( const char filename[] )
{
if( (yyin = cdftext::lex_open(filename)) == NULL) {
cbl_err("cannot open %s", filename);
}
parser_enter_file(filename);
timespec_t start;
int erc = yyparse();
timespec_t finish;
double dt = finish - start;
parser_leave_file();
//printf("Overall parse & generate time is %.6f seconds\n", dt);
fclose (yyin);
if( erc ) {
error_at (UNKNOWN_LOCATION, "failed compiling %s", filename);
}
return erc;
}
#pragma GCC diagnostic pop
extern int yy_flex_debug, yydebug, ydfdebug;
extern int f_trace_debug;
void cobol_set_indicator_column( int column );
void
cobol_set_debugging( bool flex, bool yacc, bool parser )
{
yy_flex_debug = flex? 1 : 0;
ydfdebug = yydebug = yacc? 1 : 0;
f_trace_debug = parser? 1 : 0;
char *ind = getenv("INDICATOR_COLUMN");
if( ind ) {
int col;
if( 1 != sscanf(ind, "%d", &col) ) {
yywarn("ignored non-integer value for INDICATOR_COLUMN=%s", ind);
}
cobol_set_indicator_column(col);
}
}
os_locale_t os_locale = { "UTF-8", xstrdup("C.UTF-8") };
void
cobol_parse_files (int nfile, const char **files)
{
char * opaque = setlocale(LC_CTYPE, "");
if( ! opaque ) {
yywarn("setlocale: unable to initialize LOCALE");
} else {
char *codeset = nl_langinfo(CODESET);
if( ! codeset ) {
yywarn("nl_langinfo failed after setlocale succeeded");
} else {
os_locale.codeset = codeset;
}
}
assert(os_locale.codeset);
for (int i = 0; i < nfile; i++) {
parse_file (files[i]);
}
}
/* Outputs the formatted string onto the file descriptor */
void
cbl_message(int fd, const char *format_string, ...)
{
va_list ap;
va_start(ap, format_string);
char *ostring = xvasprintf(format_string, ap);
va_end(ap);
write(fd, ostring, strlen(ostring));
free(ostring);
}
/* Uses the GCC internal_error () to output the formatted string. Processing
ends with a stack trace */
void
cbl_internal_error(const char *gmsgid, ...) {
verify_format(gmsgid);
auto_diagnostic_group d;
va_list ap;
va_start(ap, gmsgid);
emit_diagnostic_valist( DK_ICE, token_location, option_zero, gmsgid, &ap );
va_end(ap);
}
void
cbl_unimplementedw(const char *gmsgid, ...) {
verify_format(gmsgid);
auto_diagnostic_group d;
va_list ap;
va_start(ap, gmsgid);
emit_diagnostic_valist( DK_SORRY, token_location, option_zero, gmsgid, &ap );
va_end(ap);
}
void
cbl_unimplemented(const char *gmsgid, ...) {
verify_format(gmsgid);
auto_diagnostic_group d;
va_list ap;
va_start(ap, gmsgid);
emit_diagnostic_valist( DK_SORRY, token_location, option_zero, gmsgid, &ap );
va_end(ap);
}
void
cbl_unimplemented_at( const YYLTYPE& loc, const char *gmsgid, ... ) {
temp_loc_t looker(loc);
verify_format(gmsgid);
auto_diagnostic_group d;
va_list ap;
va_start(ap, gmsgid);
emit_diagnostic_valist( DK_SORRY, token_location, option_zero, gmsgid, &ap );
va_end(ap);
}
/*
* analogs to err(3) and errx(3).
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat"
void
cbl_err(const char *fmt, ...) {
auto_diagnostic_group d;
char *gmsgid = xasprintf("%m: %s", fmt);
verify_format(gmsgid);
va_list ap;
va_start(ap, fmt);
emit_diagnostic_valist( DK_FATAL, token_location, option_zero, gmsgid, &ap );
va_end(ap);
}
#pragma GCC diagnostic pop
void
cbl_errx(const char *gmsgid, ...) {
verify_format(gmsgid);
auto_diagnostic_group d;
va_list ap;
va_start(ap, gmsgid);
emit_diagnostic_valist( DK_FATAL, token_location, option_zero, gmsgid, &ap );
va_end(ap);
}
void
dbgmsg(const char *msg, ...) {
if( yy_flex_debug || yydebug ) {
fflush(stdout);
va_list ap;
va_start(ap, msg);
vfprintf(stderr, msg, ap);
fprintf(stderr, "\n");
va_end(ap);
}
}
void
dialect_error( const YYLTYPE& loc, const char term[], const char dialect[] ) {
error_msg(loc, "%s is not ISO syntax, requires -dialect %s",
term, dialect);
}
bool fisdigit(int c)
{
return ISDIGIT(c);
}
bool fisspace(int c)
{
return ISSPACE(c);
};
int ftolower(int c)
{
return TOLOWER(c);
}
bool fisprint(int c)
{
return ISPRINT(c);
};
|