1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
|
//===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Provides the Expression parsing implementation.
///
/// Expressions in C99 basically consist of a bunch of binary operators with
/// unary operators and other random stuff at the leaves.
///
/// In the C99 grammar, these unary operators bind tightest and are represented
/// as the 'cast-expression' production. Everything else is either a binary
/// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
/// handled by ParseCastExpression, the higher level pieces are handled by
/// ParseBinaryExpression.
///
//===----------------------------------------------------------------------===//
#include "clang/Parse/Parser.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Basic/PrettyStackTrace.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/TypoCorrection.h"
#include "llvm/ADT/SmallVector.h"
#include <optional>
using namespace clang;
/// Simple precedence-based parser for binary/ternary operators.
///
/// Note: we diverge from the C99 grammar when parsing the assignment-expression
/// production. C99 specifies that the LHS of an assignment operator should be
/// parsed as a unary-expression, but consistency dictates that it be a
/// conditional-expession. In practice, the important thing here is that the
/// LHS of an assignment has to be an l-value, which productions between
/// unary-expression and conditional-expression don't produce. Because we want
/// consistency, we parse the LHS as a conditional-expression, then check for
/// l-value-ness in semantic analysis stages.
///
/// \verbatim
/// pm-expression: [C++ 5.5]
/// cast-expression
/// pm-expression '.*' cast-expression
/// pm-expression '->*' cast-expression
///
/// multiplicative-expression: [C99 6.5.5]
/// Note: in C++, apply pm-expression instead of cast-expression
/// cast-expression
/// multiplicative-expression '*' cast-expression
/// multiplicative-expression '/' cast-expression
/// multiplicative-expression '%' cast-expression
///
/// additive-expression: [C99 6.5.6]
/// multiplicative-expression
/// additive-expression '+' multiplicative-expression
/// additive-expression '-' multiplicative-expression
///
/// shift-expression: [C99 6.5.7]
/// additive-expression
/// shift-expression '<<' additive-expression
/// shift-expression '>>' additive-expression
///
/// compare-expression: [C++20 expr.spaceship]
/// shift-expression
/// compare-expression '<=>' shift-expression
///
/// relational-expression: [C99 6.5.8]
/// compare-expression
/// relational-expression '<' compare-expression
/// relational-expression '>' compare-expression
/// relational-expression '<=' compare-expression
/// relational-expression '>=' compare-expression
///
/// equality-expression: [C99 6.5.9]
/// relational-expression
/// equality-expression '==' relational-expression
/// equality-expression '!=' relational-expression
///
/// AND-expression: [C99 6.5.10]
/// equality-expression
/// AND-expression '&' equality-expression
///
/// exclusive-OR-expression: [C99 6.5.11]
/// AND-expression
/// exclusive-OR-expression '^' AND-expression
///
/// inclusive-OR-expression: [C99 6.5.12]
/// exclusive-OR-expression
/// inclusive-OR-expression '|' exclusive-OR-expression
///
/// logical-AND-expression: [C99 6.5.13]
/// inclusive-OR-expression
/// logical-AND-expression '&&' inclusive-OR-expression
///
/// logical-OR-expression: [C99 6.5.14]
/// logical-AND-expression
/// logical-OR-expression '||' logical-AND-expression
///
/// conditional-expression: [C99 6.5.15]
/// logical-OR-expression
/// logical-OR-expression '?' expression ':' conditional-expression
/// [GNU] logical-OR-expression '?' ':' conditional-expression
/// [C++] the third operand is an assignment-expression
///
/// assignment-expression: [C99 6.5.16]
/// conditional-expression
/// unary-expression assignment-operator assignment-expression
/// [C++] throw-expression [C++ 15]
///
/// assignment-operator: one of
/// = *= /= %= += -= <<= >>= &= ^= |=
///
/// expression: [C99 6.5.17]
/// assignment-expression ...[opt]
/// expression ',' assignment-expression ...[opt]
/// \endverbatim
ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
ExprResult LHS(ParseAssignmentExpression(isTypeCast));
return ParseRHSOfBinaryExpression(LHS, prec::Comma);
}
/// This routine is called when the '@' is seen and consumed.
/// Current token is an Identifier and is not a 'try'. This
/// routine is necessary to disambiguate \@try-statement from,
/// for example, \@encode-expression.
///
ExprResult
Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
ExprResult LHS(ParseObjCAtExpression(AtLoc));
return ParseRHSOfBinaryExpression(LHS, prec::Comma);
}
/// This routine is called when a leading '__extension__' is seen and
/// consumed. This is necessary because the token gets consumed in the
/// process of disambiguating between an expression and a declaration.
ExprResult
Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
ExprResult LHS(true);
{
// Silence extension warnings in the sub-expression
ExtensionRAIIObject O(Diags);
LHS = ParseCastExpression(AnyCastExpr);
}
if (!LHS.isInvalid())
LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
LHS.get());
return ParseRHSOfBinaryExpression(LHS, prec::Comma);
}
/// Parse an expr that doesn't include (top-level) commas.
ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteExpression(getCurScope(),
PreferredType.get(Tok.getLocation()));
return ExprError();
}
if (Tok.is(tok::kw_throw))
return ParseThrowExpression();
if (Tok.is(tok::kw_co_yield))
return ParseCoyieldExpression();
ExprResult LHS = ParseCastExpression(AnyCastExpr,
/*isAddressOfOperand=*/false,
isTypeCast);
return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
}
/// Parse an assignment expression where part of an Objective-C message
/// send has already been parsed.
///
/// In this case \p LBracLoc indicates the location of the '[' of the message
/// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
/// the receiver of the message.
///
/// Since this handles full assignment-expression's, it handles postfix
/// expressions and other binary operators for these expressions as well.
ExprResult
Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
SourceLocation SuperLoc,
ParsedType ReceiverType,
Expr *ReceiverExpr) {
ExprResult R
= ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
ReceiverType, ReceiverExpr);
R = ParsePostfixExpressionSuffix(R);
return ParseRHSOfBinaryExpression(R, prec::Assignment);
}
ExprResult
Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast) {
assert(Actions.ExprEvalContexts.back().Context ==
Sema::ExpressionEvaluationContext::ConstantEvaluated &&
"Call this function only if your ExpressionEvaluationContext is "
"already ConstantEvaluated");
ExprResult LHS(ParseCastExpression(AnyCastExpr, false, isTypeCast));
ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
return Actions.ActOnConstantExpression(Res);
}
ExprResult Parser::ParseConstantExpression() {
// C++03 [basic.def.odr]p2:
// An expression is potentially evaluated unless it appears where an
// integral constant expression is required (see 5.19) [...].
// C++98 and C++11 have no such rule, but this is only a defect in C++98.
EnterExpressionEvaluationContext ConstantEvaluated(
Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
return ParseConstantExpressionInExprEvalContext(NotTypeCast);
}
ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) {
EnterExpressionEvaluationContext ConstantEvaluated(
Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
return Actions.ActOnCaseExpr(CaseLoc, Res);
}
/// Parse a constraint-expression.
///
/// \verbatim
/// constraint-expression: C++2a[temp.constr.decl]p1
/// logical-or-expression
/// \endverbatim
ExprResult Parser::ParseConstraintExpression() {
EnterExpressionEvaluationContext ConstantEvaluated(
Actions, Sema::ExpressionEvaluationContext::Unevaluated);
ExprResult LHS(ParseCastExpression(AnyCastExpr));
ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
if (Res.isUsable() && !Actions.CheckConstraintExpression(Res.get())) {
Actions.CorrectDelayedTyposInExpr(Res);
return ExprError();
}
return Res;
}
/// \brief Parse a constraint-logical-and-expression.
///
/// \verbatim
/// C++2a[temp.constr.decl]p1
/// constraint-logical-and-expression:
/// primary-expression
/// constraint-logical-and-expression '&&' primary-expression
///
/// \endverbatim
ExprResult
Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause) {
EnterExpressionEvaluationContext ConstantEvaluated(
Actions, Sema::ExpressionEvaluationContext::Unevaluated);
bool NotPrimaryExpression = false;
auto ParsePrimary = [&] () {
ExprResult E = ParseCastExpression(PrimaryExprOnly,
/*isAddressOfOperand=*/false,
/*isTypeCast=*/NotTypeCast,
/*isVectorLiteral=*/false,
&NotPrimaryExpression);
if (E.isInvalid())
return ExprError();
auto RecoverFromNonPrimary = [&] (ExprResult E, bool Note) {
E = ParsePostfixExpressionSuffix(E);
// Use InclusiveOr, the precedence just after '&&' to not parse the
// next arguments to the logical and.
E = ParseRHSOfBinaryExpression(E, prec::InclusiveOr);
if (!E.isInvalid())
Diag(E.get()->getExprLoc(),
Note
? diag::note_unparenthesized_non_primary_expr_in_requires_clause
: diag::err_unparenthesized_non_primary_expr_in_requires_clause)
<< FixItHint::CreateInsertion(E.get()->getBeginLoc(), "(")
<< FixItHint::CreateInsertion(
PP.getLocForEndOfToken(E.get()->getEndLoc()), ")")
<< E.get()->getSourceRange();
return E;
};
if (NotPrimaryExpression ||
// Check if the following tokens must be a part of a non-primary
// expression
getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
/*CPlusPlus11=*/true) > prec::LogicalAnd ||
// Postfix operators other than '(' (which will be checked for in
// CheckConstraintExpression).
Tok.isOneOf(tok::period, tok::plusplus, tok::minusminus) ||
(Tok.is(tok::l_square) && !NextToken().is(tok::l_square))) {
E = RecoverFromNonPrimary(E, /*Note=*/false);
if (E.isInvalid())
return ExprError();
NotPrimaryExpression = false;
}
bool PossibleNonPrimary;
bool IsConstraintExpr =
Actions.CheckConstraintExpression(E.get(), Tok, &PossibleNonPrimary,
IsTrailingRequiresClause);
if (!IsConstraintExpr || PossibleNonPrimary) {
// Atomic constraint might be an unparenthesized non-primary expression
// (such as a binary operator), in which case we might get here (e.g. in
// 'requires 0 + 1 && true' we would now be at '+', and parse and ignore
// the rest of the addition expression). Try to parse the rest of it here.
if (PossibleNonPrimary)
E = RecoverFromNonPrimary(E, /*Note=*/!IsConstraintExpr);
Actions.CorrectDelayedTyposInExpr(E);
return ExprError();
}
return E;
};
ExprResult LHS = ParsePrimary();
if (LHS.isInvalid())
return ExprError();
while (Tok.is(tok::ampamp)) {
SourceLocation LogicalAndLoc = ConsumeToken();
ExprResult RHS = ParsePrimary();
if (RHS.isInvalid()) {
Actions.CorrectDelayedTyposInExpr(LHS);
return ExprError();
}
ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalAndLoc,
tok::ampamp, LHS.get(), RHS.get());
if (!Op.isUsable()) {
Actions.CorrectDelayedTyposInExpr(RHS);
Actions.CorrectDelayedTyposInExpr(LHS);
return ExprError();
}
LHS = Op;
}
return LHS;
}
/// \brief Parse a constraint-logical-or-expression.
///
/// \verbatim
/// C++2a[temp.constr.decl]p1
/// constraint-logical-or-expression:
/// constraint-logical-and-expression
/// constraint-logical-or-expression '||'
/// constraint-logical-and-expression
///
/// \endverbatim
ExprResult
Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause) {
ExprResult LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause));
if (!LHS.isUsable())
return ExprError();
while (Tok.is(tok::pipepipe)) {
SourceLocation LogicalOrLoc = ConsumeToken();
ExprResult RHS =
ParseConstraintLogicalAndExpression(IsTrailingRequiresClause);
if (!RHS.isUsable()) {
Actions.CorrectDelayedTyposInExpr(LHS);
return ExprError();
}
ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalOrLoc,
tok::pipepipe, LHS.get(), RHS.get());
if (!Op.isUsable()) {
Actions.CorrectDelayedTyposInExpr(RHS);
Actions.CorrectDelayedTyposInExpr(LHS);
return ExprError();
}
LHS = Op;
}
return LHS;
}
bool Parser::isNotExpressionStart() {
tok::TokenKind K = Tok.getKind();
if (K == tok::l_brace || K == tok::r_brace ||
K == tok::kw_for || K == tok::kw_while ||
K == tok::kw_if || K == tok::kw_else ||
K == tok::kw_goto || K == tok::kw_try)
return true;
// If this is a decl-specifier, we can't be at the start of an expression.
return isKnownToBeDeclarationSpecifier();
}
bool Parser::isFoldOperator(prec::Level Level) const {
return Level > prec::Unknown && Level != prec::Conditional &&
Level != prec::Spaceship;
}
bool Parser::isFoldOperator(tok::TokenKind Kind) const {
return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
}
/// Parse a binary expression that starts with \p LHS and has a
/// precedence of at least \p MinPrec.
ExprResult
Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
GreaterThanIsOperator,
getLangOpts().CPlusPlus11);
SourceLocation ColonLoc;
auto SavedType = PreferredType;
while (true) {
// Every iteration may rely on a preferred type for the whole expression.
PreferredType = SavedType;
// If this token has a lower precedence than we are allowed to parse (e.g.
// because we are called recursively, or because the token is not a binop),
// then we are done!
if (NextTokPrec < MinPrec)
return LHS;
// Consume the operator, saving the operator token for error reporting.
Token OpToken = Tok;
ConsumeToken();
if (OpToken.is(tok::caretcaret)) {
return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
}
// If we're potentially in a template-id, we may now be able to determine
// whether we're actually in one or not.
if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
tok::greatergreatergreater) &&
checkPotentialAngleBracketDelimiter(OpToken))
return ExprError();
// Bail out when encountering a comma followed by a token which can't
// possibly be the start of an expression. For instance:
// int f() { return 1, }
// We can't do this before consuming the comma, because
// isNotExpressionStart() looks at the token stream.
if (OpToken.is(tok::comma) && isNotExpressionStart()) {
PP.EnterToken(Tok, /*IsReinject*/true);
Tok = OpToken;
return LHS;
}
// If the next token is an ellipsis, then this is a fold-expression. Leave
// it alone so we can handle it in the paren expression.
if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
// FIXME: We can't check this via lookahead before we consume the token
// because that tickles a lexer bug.
PP.EnterToken(Tok, /*IsReinject*/true);
Tok = OpToken;
return LHS;
}
// In Objective-C++, alternative operator tokens can be used as keyword args
// in message expressions. Unconsume the token so that it can reinterpreted
// as an identifier in ParseObjCMessageExpressionBody. i.e., we support:
// [foo meth:0 and:0];
// [foo not_eq];
if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
Tok.isOneOf(tok::colon, tok::r_square) &&
OpToken.getIdentifierInfo() != nullptr) {
PP.EnterToken(Tok, /*IsReinject*/true);
Tok = OpToken;
return LHS;
}
// Special case handling for the ternary operator.
ExprResult TernaryMiddle(true);
if (NextTokPrec == prec::Conditional) {
if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
// Parse a braced-init-list here for error recovery purposes.
SourceLocation BraceLoc = Tok.getLocation();
TernaryMiddle = ParseBraceInitializer();
if (!TernaryMiddle.isInvalid()) {
Diag(BraceLoc, diag::err_init_list_bin_op)
<< /*RHS*/ 1 << PP.getSpelling(OpToken)
<< Actions.getExprRange(TernaryMiddle.get());
TernaryMiddle = ExprError();
}
} else if (Tok.isNot(tok::colon)) {
// Don't parse FOO:BAR as if it were a typo for FOO::BAR.
ColonProtectionRAIIObject X(*this);
// Handle this production specially:
// logical-OR-expression '?' expression ':' conditional-expression
// In particular, the RHS of the '?' is 'expression', not
// 'logical-OR-expression' as we might expect.
TernaryMiddle = ParseExpression();
} else {
// Special case handling of "X ? Y : Z" where Y is empty:
// logical-OR-expression '?' ':' conditional-expression [GNU]
TernaryMiddle = nullptr;
Diag(Tok, diag::ext_gnu_conditional_expr);
}
if (TernaryMiddle.isInvalid()) {
Actions.CorrectDelayedTyposInExpr(LHS);
LHS = ExprError();
TernaryMiddle = nullptr;
}
if (!TryConsumeToken(tok::colon, ColonLoc)) {
// Otherwise, we're missing a ':'. Assume that this was a typo that
// the user forgot. If we're not in a macro expansion, we can suggest
// a fixit hint. If there were two spaces before the current token,
// suggest inserting the colon in between them, otherwise insert ": ".
SourceLocation FILoc = Tok.getLocation();
const char *FIText = ": ";
const SourceManager &SM = PP.getSourceManager();
if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
assert(FILoc.isFileID());
bool IsInvalid = false;
const char *SourcePtr =
SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
if (!IsInvalid && *SourcePtr == ' ') {
SourcePtr =
SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
if (!IsInvalid && *SourcePtr == ' ') {
FILoc = FILoc.getLocWithOffset(-1);
FIText = ":";
}
}
}
Diag(Tok, diag::err_expected)
<< tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
Diag(OpToken, diag::note_matching) << tok::question;
ColonLoc = Tok.getLocation();
}
}
PreferredType.enterBinary(Actions, Tok.getLocation(), LHS.get(),
OpToken.getKind());
// Parse another leaf here for the RHS of the operator.
// ParseCastExpression works here because all RHS expressions in C have it
// as a prefix, at least. However, in C++, an assignment-expression could
// be a throw-expression, which is not a valid cast-expression.
// Therefore we need some special-casing here.
// Also note that the third operand of the conditional operator is
// an assignment-expression in C++, and in C++11, we can have a
// braced-init-list on the RHS of an assignment. For better diagnostics,
// parse as if we were allowed braced-init-lists everywhere, and check that
// they only appear on the RHS of assignments later.
ExprResult RHS;
bool RHSIsInitList = false;
if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
RHS = ParseBraceInitializer();
RHSIsInitList = true;
} else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
RHS = ParseAssignmentExpression();
else
RHS = ParseCastExpression(AnyCastExpr);
if (RHS.isInvalid()) {
// FIXME: Errors generated by the delayed typo correction should be
// printed before errors from parsing the RHS, not after.
Actions.CorrectDelayedTyposInExpr(LHS);
if (TernaryMiddle.isUsable())
TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
LHS = ExprError();
}
// Remember the precedence of this operator and get the precedence of the
// operator immediately to the right of the RHS.
prec::Level ThisPrec = NextTokPrec;
NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
getLangOpts().CPlusPlus11);
// Assignment and conditional expressions are right-associative.
bool isRightAssoc = ThisPrec == prec::Conditional ||
ThisPrec == prec::Assignment;
// Get the precedence of the operator to the right of the RHS. If it binds
// more tightly with RHS than we do, evaluate it completely first.
if (ThisPrec < NextTokPrec ||
(ThisPrec == NextTokPrec && isRightAssoc)) {
if (!RHS.isInvalid() && RHSIsInitList) {
Diag(Tok, diag::err_init_list_bin_op)
<< /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
RHS = ExprError();
}
// If this is left-associative, only parse things on the RHS that bind
// more tightly than the current operator. If it is left-associative, it
// is okay, to bind exactly as tightly. For example, compile A=B=C=D as
// A=(B=(C=D)), where each paren is a level of recursion here.
// The function takes ownership of the RHS.
RHS = ParseRHSOfBinaryExpression(RHS,
static_cast<prec::Level>(ThisPrec + !isRightAssoc));
RHSIsInitList = false;
if (RHS.isInvalid()) {
// FIXME: Errors generated by the delayed typo correction should be
// printed before errors from ParseRHSOfBinaryExpression, not after.
Actions.CorrectDelayedTyposInExpr(LHS);
if (TernaryMiddle.isUsable())
TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
LHS = ExprError();
}
NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
getLangOpts().CPlusPlus11);
}
if (!RHS.isInvalid() && RHSIsInitList) {
if (ThisPrec == prec::Assignment) {
Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
<< Actions.getExprRange(RHS.get());
} else if (ColonLoc.isValid()) {
Diag(ColonLoc, diag::err_init_list_bin_op)
<< /*RHS*/1 << ":"
<< Actions.getExprRange(RHS.get());
LHS = ExprError();
} else {
Diag(OpToken, diag::err_init_list_bin_op)
<< /*RHS*/1 << PP.getSpelling(OpToken)
<< Actions.getExprRange(RHS.get());
LHS = ExprError();
}
}
ExprResult OrigLHS = LHS;
if (!LHS.isInvalid()) {
// Combine the LHS and RHS into the LHS (e.g. build AST).
if (TernaryMiddle.isInvalid()) {
// If we're using '>>' as an operator within a template
// argument list (in C++98), suggest the addition of
// parentheses so that the code remains well-formed in C++0x.
if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
SuggestParentheses(OpToken.getLocation(),
diag::warn_cxx11_right_shift_in_template_arg,
SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
Actions.getExprRange(RHS.get()).getEnd()));
ExprResult BinOp =
Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
OpToken.getKind(), LHS.get(), RHS.get());
if (BinOp.isInvalid())
BinOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
RHS.get()->getEndLoc(),
{LHS.get(), RHS.get()});
LHS = BinOp;
} else {
ExprResult CondOp = Actions.ActOnConditionalOp(
OpToken.getLocation(), ColonLoc, LHS.get(), TernaryMiddle.get(),
RHS.get());
if (CondOp.isInvalid()) {
std::vector<clang::Expr *> Args;
// TernaryMiddle can be null for the GNU conditional expr extension.
if (TernaryMiddle.get())
Args = {LHS.get(), TernaryMiddle.get(), RHS.get()};
else
Args = {LHS.get(), RHS.get()};
CondOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
RHS.get()->getEndLoc(), Args);
}
LHS = CondOp;
}
// In this case, ActOnBinOp or ActOnConditionalOp performed the
// CorrectDelayedTyposInExpr check.
if (!getLangOpts().CPlusPlus)
continue;
}
// Ensure potential typos aren't left undiagnosed.
if (LHS.isInvalid()) {
Actions.CorrectDelayedTyposInExpr(OrigLHS);
Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
Actions.CorrectDelayedTyposInExpr(RHS);
}
}
}
/// Parse a cast-expression, unary-expression or primary-expression, based
/// on \p ExprType.
///
/// \p isAddressOfOperand exists because an id-expression that is the
/// operand of address-of gets special treatment due to member pointers.
///
ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
bool isAddressOfOperand,
TypeCastState isTypeCast,
bool isVectorLiteral,
bool *NotPrimaryExpression) {
bool NotCastExpr;
ExprResult Res = ParseCastExpression(ParseKind,
isAddressOfOperand,
NotCastExpr,
isTypeCast,
isVectorLiteral,
NotPrimaryExpression);
if (NotCastExpr)
Diag(Tok, diag::err_expected_expression);
return Res;
}
namespace {
class CastExpressionIdValidator final : public CorrectionCandidateCallback {
public:
CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
: NextToken(Next), AllowNonTypes(AllowNonTypes) {
WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
}
bool ValidateCandidate(const TypoCorrection &candidate) override {
NamedDecl *ND = candidate.getCorrectionDecl();
if (!ND)
return candidate.isKeyword();
if (isa<TypeDecl>(ND))
return WantTypeSpecifiers;
if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
return false;
if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
return true;
for (auto *C : candidate) {
NamedDecl *ND = C->getUnderlyingDecl();
if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
return true;
}
return false;
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<CastExpressionIdValidator>(*this);
}
private:
Token NextToken;
bool AllowNonTypes;
};
}
/// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
/// a unary-expression.
///
/// \p isAddressOfOperand exists because an id-expression that is the operand
/// of address-of gets special treatment due to member pointers. NotCastExpr
/// is set to true if the token is not the start of a cast-expression, and no
/// diagnostic is emitted in this case and no tokens are consumed.
///
/// \verbatim
/// cast-expression: [C99 6.5.4]
/// unary-expression
/// '(' type-name ')' cast-expression
///
/// unary-expression: [C99 6.5.3]
/// postfix-expression
/// '++' unary-expression
/// '--' unary-expression
/// [Coro] 'co_await' cast-expression
/// unary-operator cast-expression
/// 'sizeof' unary-expression
/// 'sizeof' '(' type-name ')'
/// [C++11] 'sizeof' '...' '(' identifier ')'
/// [GNU] '__alignof' unary-expression
/// [GNU] '__alignof' '(' type-name ')'
/// [C11] '_Alignof' '(' type-name ')'
/// [C++11] 'alignof' '(' type-id ')'
/// [GNU] '&&' identifier
/// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
/// [C++] new-expression
/// [C++] delete-expression
///
/// unary-operator: one of
/// '&' '*' '+' '-' '~' '!'
/// [GNU] '__extension__' '__real' '__imag'
///
/// primary-expression: [C99 6.5.1]
/// [C99] identifier
/// [C++] id-expression
/// constant
/// string-literal
/// [C++] boolean-literal [C++ 2.13.5]
/// [C++11] 'nullptr' [C++11 2.14.7]
/// [C++11] user-defined-literal
/// '(' expression ')'
/// [C11] generic-selection
/// [C++2a] requires-expression
/// '__func__' [C99 6.4.2.2]
/// [GNU] '__FUNCTION__'
/// [MS] '__FUNCDNAME__'
/// [MS] 'L__FUNCTION__'
/// [MS] '__FUNCSIG__'
/// [MS] 'L__FUNCSIG__'
/// [GNU] '__PRETTY_FUNCTION__'
/// [GNU] '(' compound-statement ')'
/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
/// assign-expr ')'
/// [GNU] '__builtin_FILE' '(' ')'
/// [GNU] '__builtin_FUNCTION' '(' ')'
/// [GNU] '__builtin_LINE' '(' ')'
/// [CLANG] '__builtin_COLUMN' '(' ')'
/// [GNU] '__builtin_source_location' '(' ')'
/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
/// [GNU] '__null'
/// [OBJC] '[' objc-message-expr ']'
/// [OBJC] '\@selector' '(' objc-selector-arg ')'
/// [OBJC] '\@protocol' '(' identifier ')'
/// [OBJC] '\@encode' '(' type-name ')'
/// [OBJC] objc-string-literal
/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
/// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
/// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
/// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
/// [C++] 'this' [C++ 9.3.2]
/// [G++] unary-type-trait '(' type-id ')'
/// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
/// [EMBT] array-type-trait '(' type-id ',' integer ')'
/// [clang] '^' block-literal
///
/// constant: [C99 6.4.4]
/// integer-constant
/// floating-constant
/// enumeration-constant -> identifier
/// character-constant
///
/// id-expression: [C++ 5.1]
/// unqualified-id
/// qualified-id
///
/// unqualified-id: [C++ 5.1]
/// identifier
/// operator-function-id
/// conversion-function-id
/// '~' class-name
/// template-id
///
/// new-expression: [C++ 5.3.4]
/// '::'[opt] 'new' new-placement[opt] new-type-id
/// new-initializer[opt]
/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
/// new-initializer[opt]
///
/// delete-expression: [C++ 5.3.5]
/// '::'[opt] 'delete' cast-expression
/// '::'[opt] 'delete' '[' ']' cast-expression
///
/// [GNU/Embarcadero] unary-type-trait:
/// '__is_arithmetic'
/// '__is_floating_point'
/// '__is_integral'
/// '__is_lvalue_expr'
/// '__is_rvalue_expr'
/// '__is_complete_type'
/// '__is_void'
/// '__is_array'
/// '__is_function'
/// '__is_reference'
/// '__is_lvalue_reference'
/// '__is_rvalue_reference'
/// '__is_fundamental'
/// '__is_object'
/// '__is_scalar'
/// '__is_compound'
/// '__is_pointer'
/// '__is_member_object_pointer'
/// '__is_member_function_pointer'
/// '__is_member_pointer'
/// '__is_const'
/// '__is_volatile'
/// '__is_trivial'
/// '__is_standard_layout'
/// '__is_signed'
/// '__is_unsigned'
///
/// [GNU] unary-type-trait:
/// '__has_nothrow_assign'
/// '__has_nothrow_copy'
/// '__has_nothrow_constructor'
/// '__has_trivial_assign' [TODO]
/// '__has_trivial_copy' [TODO]
/// '__has_trivial_constructor'
/// '__has_trivial_destructor'
/// '__has_virtual_destructor'
/// '__is_abstract' [TODO]
/// '__is_class'
/// '__is_empty' [TODO]
/// '__is_enum'
/// '__is_final'
/// '__is_pod'
/// '__is_polymorphic'
/// '__is_sealed' [MS]
/// '__is_trivial'
/// '__is_union'
/// '__has_unique_object_representations'
///
/// [Clang] unary-type-trait:
/// '__is_aggregate'
/// '__trivially_copyable'
///
/// binary-type-trait:
/// [GNU] '__is_base_of'
/// [MS] '__is_convertible_to'
/// '__is_convertible'
/// '__is_same'
///
/// [Embarcadero] array-type-trait:
/// '__array_rank'
/// '__array_extent'
///
/// [Embarcadero] expression-trait:
/// '__is_lvalue_expr'
/// '__is_rvalue_expr'
/// \endverbatim
///
ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
bool isAddressOfOperand,
bool &NotCastExpr,
TypeCastState isTypeCast,
bool isVectorLiteral,
bool *NotPrimaryExpression) {
ExprResult Res;
tok::TokenKind SavedKind = Tok.getKind();
auto SavedType = PreferredType;
NotCastExpr = false;
// Are postfix-expression suffix operators permitted after this
// cast-expression? If not, and we find some, we'll parse them anyway and
// diagnose them.
bool AllowSuffix = true;
// This handles all of cast-expression, unary-expression, postfix-expression,
// and primary-expression. We handle them together like this for efficiency
// and to simplify handling of an expression starting with a '(' token: which
// may be one of a parenthesized expression, cast-expression, compound literal
// expression, or statement expression.
//
// If the parsed tokens consist of a primary-expression, the cases below
// break out of the switch; at the end we call ParsePostfixExpressionSuffix
// to handle the postfix expression suffixes. Cases that cannot be followed
// by postfix exprs should set AllowSuffix to false.
switch (SavedKind) {
case tok::l_paren: {
// If this expression is limited to being a unary-expression, the paren can
// not start a cast expression.
ParenParseOption ParenExprType;
switch (ParseKind) {
case CastParseKind::UnaryExprOnly:
assert(getLangOpts().CPlusPlus && "not possible to get here in C");
[[fallthrough]];
case CastParseKind::AnyCastExpr:
ParenExprType = ParenParseOption::CastExpr;
break;
case CastParseKind::PrimaryExprOnly:
ParenExprType = FoldExpr;
break;
}
ParsedType CastTy;
SourceLocation RParenLoc;
Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
isTypeCast == IsTypeCast, CastTy, RParenLoc);
// FIXME: What should we do if a vector literal is followed by a
// postfix-expression suffix? Usually postfix operators are permitted on
// literals.
if (isVectorLiteral)
return Res;
switch (ParenExprType) {
case SimpleExpr: break; // Nothing else to do.
case CompoundStmt: break; // Nothing else to do.
case CompoundLiteral:
// We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
// postfix-expression exist, parse them now.
break;
case CastExpr:
// We have parsed the cast-expression and no postfix-expr pieces are
// following.
return Res;
case FoldExpr:
// We only parsed a fold-expression. There might be postfix-expr pieces
// afterwards; parse them now.
break;
}
break;
}
// primary-expression
case tok::numeric_constant:
// constant: integer-constant
// constant: floating-constant
Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
ConsumeToken();
break;
case tok::kw_true:
case tok::kw_false:
Res = ParseCXXBoolLiteral();
break;
case tok::kw___objc_yes:
case tok::kw___objc_no:
Res = ParseObjCBoolLiteral();
break;
case tok::kw_nullptr:
if (getLangOpts().CPlusPlus)
Diag(Tok, diag::warn_cxx98_compat_nullptr);
else
Diag(Tok, getLangOpts().C2x ? diag::warn_c17_compat_nullptr
: diag::ext_c_nullptr);
Res = Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
break;
case tok::annot_primary_expr:
case tok::annot_overload_set:
Res = getExprAnnotation(Tok);
if (!Res.isInvalid() && Tok.getKind() == tok::annot_overload_set)
Res = Actions.ActOnNameClassifiedAsOverloadSet(getCurScope(), Res.get());
ConsumeAnnotationToken();
if (!Res.isInvalid() && Tok.is(tok::less))
checkPotentialAngleBracket(Res);
break;
case tok::annot_non_type:
case tok::annot_non_type_dependent:
case tok::annot_non_type_undeclared: {
CXXScopeSpec SS;
Token Replacement;
Res = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
assert(!Res.isUnset() &&
"should not perform typo correction on annotation token");
break;
}
case tok::kw___super:
case tok::kw_decltype:
// Annotate the token and tail recurse.
if (TryAnnotateTypeOrScopeToken())
return ExprError();
assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
isVectorLiteral, NotPrimaryExpression);
case tok::identifier:
ParseIdentifier: { // primary-expression: identifier
// unqualified-id: identifier
// constant: enumeration-constant
// Turn a potentially qualified name into a annot_typename or
// annot_cxxscope if it would be valid. This handles things like x::y, etc.
if (getLangOpts().CPlusPlus) {
// Avoid the unnecessary parse-time lookup in the common case
// where the syntax forbids a type.
const Token &Next = NextToken();
// If this identifier was reverted from a token ID, and the next token
// is a parenthesis, this is likely to be a use of a type trait. Check
// those tokens.
if (Next.is(tok::l_paren) &&
Tok.is(tok::identifier) &&
Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
IdentifierInfo *II = Tok.getIdentifierInfo();
// Build up the mapping of revertible type traits, for future use.
if (RevertibleTypeTraits.empty()) {
#define RTT_JOIN(X,Y) X##Y
#define REVERTIBLE_TYPE_TRAIT(Name) \
RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
= RTT_JOIN(tok::kw_,Name)
REVERTIBLE_TYPE_TRAIT(__is_abstract);
REVERTIBLE_TYPE_TRAIT(__is_aggregate);
REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
REVERTIBLE_TYPE_TRAIT(__is_array);
REVERTIBLE_TYPE_TRAIT(__is_assignable);
REVERTIBLE_TYPE_TRAIT(__is_base_of);
REVERTIBLE_TYPE_TRAIT(__is_bounded_array);
REVERTIBLE_TYPE_TRAIT(__is_class);
REVERTIBLE_TYPE_TRAIT(__is_complete_type);
REVERTIBLE_TYPE_TRAIT(__is_compound);
REVERTIBLE_TYPE_TRAIT(__is_const);
REVERTIBLE_TYPE_TRAIT(__is_constructible);
REVERTIBLE_TYPE_TRAIT(__is_convertible);
REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
REVERTIBLE_TYPE_TRAIT(__is_destructible);
REVERTIBLE_TYPE_TRAIT(__is_empty);
REVERTIBLE_TYPE_TRAIT(__is_enum);
REVERTIBLE_TYPE_TRAIT(__is_floating_point);
REVERTIBLE_TYPE_TRAIT(__is_final);
REVERTIBLE_TYPE_TRAIT(__is_function);
REVERTIBLE_TYPE_TRAIT(__is_fundamental);
REVERTIBLE_TYPE_TRAIT(__is_integral);
REVERTIBLE_TYPE_TRAIT(__is_interface_class);
REVERTIBLE_TYPE_TRAIT(__is_literal);
REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
REVERTIBLE_TYPE_TRAIT(__is_nullptr);
REVERTIBLE_TYPE_TRAIT(__is_object);
REVERTIBLE_TYPE_TRAIT(__is_pod);
REVERTIBLE_TYPE_TRAIT(__is_pointer);
REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
REVERTIBLE_TYPE_TRAIT(__is_reference);
REVERTIBLE_TYPE_TRAIT(__is_referenceable);
REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
REVERTIBLE_TYPE_TRAIT(__is_same);
REVERTIBLE_TYPE_TRAIT(__is_scalar);
REVERTIBLE_TYPE_TRAIT(__is_scoped_enum);
REVERTIBLE_TYPE_TRAIT(__is_sealed);
REVERTIBLE_TYPE_TRAIT(__is_signed);
REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
REVERTIBLE_TYPE_TRAIT(__is_trivial);
REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
REVERTIBLE_TYPE_TRAIT(__is_unbounded_array);
REVERTIBLE_TYPE_TRAIT(__is_union);
REVERTIBLE_TYPE_TRAIT(__is_unsigned);
REVERTIBLE_TYPE_TRAIT(__is_void);
REVERTIBLE_TYPE_TRAIT(__is_volatile);
#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \
REVERTIBLE_TYPE_TRAIT(RTT_JOIN(__, Trait));
#include "clang/Basic/TransformTypeTraits.def"
#undef REVERTIBLE_TYPE_TRAIT
#undef RTT_JOIN
}
// If we find that this is in fact the name of a type trait,
// update the token kind in place and parse again to treat it as
// the appropriate kind of type trait.
llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
= RevertibleTypeTraits.find(II);
if (Known != RevertibleTypeTraits.end()) {
Tok.setKind(Known->second);
return ParseCastExpression(ParseKind, isAddressOfOperand,
NotCastExpr, isTypeCast,
isVectorLiteral, NotPrimaryExpression);
}
}
if ((!ColonIsSacred && Next.is(tok::colon)) ||
Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
tok::l_brace)) {
// If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
if (TryAnnotateTypeOrScopeToken())
return ExprError();
if (!Tok.is(tok::identifier))
return ParseCastExpression(ParseKind, isAddressOfOperand,
NotCastExpr, isTypeCast,
isVectorLiteral,
NotPrimaryExpression);
}
}
// Consume the identifier so that we can see if it is followed by a '(' or
// '.'.
IdentifierInfo &II = *Tok.getIdentifierInfo();
SourceLocation ILoc = ConsumeToken();
// Support 'Class.property' and 'super.property' notation.
if (getLangOpts().ObjC && Tok.is(tok::period) &&
(Actions.getTypeName(II, ILoc, getCurScope()) ||
// Allow the base to be 'super' if in an objc-method.
(&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
ConsumeToken();
if (Tok.is(tok::code_completion) && &II != Ident_super) {
cutOffParsing();
Actions.CodeCompleteObjCClassPropertyRefExpr(
getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
return ExprError();
}
// Allow either an identifier or the keyword 'class' (in C++).
if (Tok.isNot(tok::identifier) &&
!(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
Diag(Tok, diag::err_expected_property_name);
return ExprError();
}
IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
SourceLocation PropertyLoc = ConsumeToken();
Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
ILoc, PropertyLoc);
break;
}
// In an Objective-C method, if we have "super" followed by an identifier,
// the token sequence is ill-formed. However, if there's a ':' or ']' after
// that identifier, this is probably a message send with a missing open
// bracket. Treat it as such.
if (getLangOpts().ObjC && &II == Ident_super && !InMessageExpression &&
getCurScope()->isInObjcMethodScope() &&
((Tok.is(tok::identifier) &&
(NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
Tok.is(tok::code_completion))) {
Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
nullptr);
break;
}
// If we have an Objective-C class name followed by an identifier
// and either ':' or ']', this is an Objective-C class message
// send that's missing the opening '['. Recovery
// appropriately. Also take this path if we're performing code
// completion after an Objective-C class name.
if (getLangOpts().ObjC &&
((Tok.is(tok::identifier) && !InMessageExpression) ||
Tok.is(tok::code_completion))) {
const Token& Next = NextToken();
if (Tok.is(tok::code_completion) ||
Next.is(tok::colon) || Next.is(tok::r_square))
if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
if (Typ.get()->isObjCObjectOrInterfaceType()) {
// Fake up a Declarator to use with ActOnTypeName.
DeclSpec DS(AttrFactory);
DS.SetRangeStart(ILoc);
DS.SetRangeEnd(ILoc);
const char *PrevSpec = nullptr;
unsigned DiagID;
DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
Actions.getASTContext().getPrintingPolicy());
Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
DeclaratorContext::TypeName);
TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
DeclaratorInfo);
if (Ty.isInvalid())
break;
Res = ParseObjCMessageExpressionBody(SourceLocation(),
SourceLocation(),
Ty.get(), nullptr);
break;
}
}
// Make sure to pass down the right value for isAddressOfOperand.
if (isAddressOfOperand && isPostfixExpressionSuffixStart())
isAddressOfOperand = false;
// Function designators are allowed to be undeclared (C99 6.5.1p2), so we
// need to know whether or not this identifier is a function designator or
// not.
UnqualifiedId Name;
CXXScopeSpec ScopeSpec;
SourceLocation TemplateKWLoc;
Token Replacement;
CastExpressionIdValidator Validator(
/*Next=*/Tok,
/*AllowTypes=*/isTypeCast != NotTypeCast,
/*AllowNonTypes=*/isTypeCast != IsTypeCast);
Validator.IsAddressOfOperand = isAddressOfOperand;
if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
Validator.WantExpressionKeywords = false;
Validator.WantRemainingKeywords = false;
} else {
Validator.WantRemainingKeywords = Tok.isNot(tok::r_paren);
}
Name.setIdentifier(&II, ILoc);
Res = Actions.ActOnIdExpression(
getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
isAddressOfOperand, &Validator,
/*IsInlineAsmIdentifier=*/false,
Tok.is(tok::r_paren) ? nullptr : &Replacement);
if (!Res.isInvalid() && Res.isUnset()) {
UnconsumeToken(Replacement);
return ParseCastExpression(ParseKind, isAddressOfOperand,
NotCastExpr, isTypeCast,
/*isVectorLiteral=*/false,
NotPrimaryExpression);
}
if (!Res.isInvalid() && Tok.is(tok::less))
checkPotentialAngleBracket(Res);
break;
}
case tok::char_constant: // constant: character-constant
case tok::wide_char_constant:
case tok::utf8_char_constant:
case tok::utf16_char_constant:
case tok::utf32_char_constant:
Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
ConsumeToken();
break;
case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
case tok::kw_L__FUNCSIG__: // primary-expression: L__FUNCSIG__ [MS]
case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
ConsumeToken();
break;
case tok::string_literal: // primary-expression: string-literal
case tok::wide_string_literal:
case tok::utf8_string_literal:
case tok::utf16_string_literal:
case tok::utf32_string_literal:
Res = ParseStringLiteralExpression(true);
break;
case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
Res = ParseGenericSelectionExpression();
break;
case tok::kw___builtin_available:
Res = ParseAvailabilityCheckExpr(Tok.getLocation());
break;
case tok::kw___builtin_va_arg:
case tok::kw___builtin_offsetof:
case tok::kw___builtin_choose_expr:
case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
case tok::kw___builtin_convertvector:
case tok::kw___builtin_COLUMN:
case tok::kw___builtin_FILE:
case tok::kw___builtin_FUNCTION:
case tok::kw___builtin_LINE:
case tok::kw___builtin_source_location:
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
// This parses the complete suffix; we can return early.
return ParseBuiltinPrimaryExpression();
case tok::kw___null:
Res = Actions.ActOnGNUNullExpr(ConsumeToken());
break;
case tok::plusplus: // unary-expression: '++' unary-expression [C99]
case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
// C++ [expr.unary] has:
// unary-expression:
// ++ cast-expression
// -- cast-expression
Token SavedTok = Tok;
ConsumeToken();
PreferredType.enterUnary(Actions, Tok.getLocation(), SavedTok.getKind(),
SavedTok.getLocation());
// One special case is implicitly handled here: if the preceding tokens are
// an ambiguous cast expression, such as "(T())++", then we recurse to
// determine whether the '++' is prefix or postfix.
Res = ParseCastExpression(getLangOpts().CPlusPlus ?
UnaryExprOnly : AnyCastExpr,
/*isAddressOfOperand*/false, NotCastExpr,
NotTypeCast);
if (NotCastExpr) {
// If we return with NotCastExpr = true, we must not consume any tokens,
// so put the token back where we found it.
assert(Res.isInvalid());
UnconsumeToken(SavedTok);
return ExprError();
}
if (!Res.isInvalid()) {
Expr *Arg = Res.get();
Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
SavedKind, Arg);
if (Res.isInvalid())
Res = Actions.CreateRecoveryExpr(SavedTok.getLocation(),
Arg->getEndLoc(), Arg);
}
return Res;
}
case tok::amp: { // unary-expression: '&' cast-expression
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
// Special treatment because of member pointers
SourceLocation SavedLoc = ConsumeToken();
PreferredType.enterUnary(Actions, Tok.getLocation(), tok::amp, SavedLoc);
Res = ParseCastExpression(AnyCastExpr, /*isAddressOfOperand=*/true);
if (!Res.isInvalid()) {
Expr *Arg = Res.get();
Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
if (Res.isInvalid())
Res = Actions.CreateRecoveryExpr(Tok.getLocation(), Arg->getEndLoc(),
Arg);
}
return Res;
}
case tok::star: // unary-expression: '*' cast-expression
case tok::plus: // unary-expression: '+' cast-expression
case tok::minus: // unary-expression: '-' cast-expression
case tok::tilde: // unary-expression: '~' cast-expression
case tok::exclaim: // unary-expression: '!' cast-expression
case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
SourceLocation SavedLoc = ConsumeToken();
PreferredType.enterUnary(Actions, Tok.getLocation(), SavedKind, SavedLoc);
Res = ParseCastExpression(AnyCastExpr);
if (!Res.isInvalid()) {
Expr *Arg = Res.get();
Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg,
isAddressOfOperand);
if (Res.isInvalid())
Res = Actions.CreateRecoveryExpr(SavedLoc, Arg->getEndLoc(), Arg);
}
return Res;
}
case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
SourceLocation CoawaitLoc = ConsumeToken();
Res = ParseCastExpression(AnyCastExpr);
if (!Res.isInvalid())
Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
return Res;
}
case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
// __extension__ silences extension warnings in the subexpression.
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
ExtensionRAIIObject O(Diags); // Use RAII to do this.
SourceLocation SavedLoc = ConsumeToken();
Res = ParseCastExpression(AnyCastExpr);
if (!Res.isInvalid())
Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
return Res;
}
case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
if (!getLangOpts().C11)
Diag(Tok, diag::ext_c11_feature) << Tok.getName();
[[fallthrough]];
case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
// unary-expression: '__alignof' '(' type-name ')'
case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
// unary-expression: 'sizeof' '(' type-name ')'
case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
// unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
case tok::kw___builtin_omp_required_simd_align:
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
AllowSuffix = false;
Res = ParseUnaryExprOrTypeTraitExpression();
break;
case tok::ampamp: { // unary-expression: '&&' identifier
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
SourceLocation AmpAmpLoc = ConsumeToken();
if (Tok.isNot(tok::identifier))
return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
if (getCurScope()->getFnParent() == nullptr)
return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
Tok.getLocation());
Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
ConsumeToken();
AllowSuffix = false;
break;
}
case tok::kw_const_cast:
case tok::kw_dynamic_cast:
case tok::kw_reinterpret_cast:
case tok::kw_static_cast:
case tok::kw_addrspace_cast:
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseCXXCasts();
break;
case tok::kw___builtin_bit_cast:
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseBuiltinBitCast();
break;
case tok::kw_typeid:
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseCXXTypeid();
break;
case tok::kw___uuidof:
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseCXXUuidof();
break;
case tok::kw_this:
Res = ParseCXXThis();
break;
case tok::kw___builtin_sycl_unique_stable_name:
Res = ParseSYCLUniqueStableNameExpression();
break;
case tok::annot_typename:
if (isStartOfObjCClassMessageMissingOpenBracket()) {
TypeResult Type = getTypeAnnotation(Tok);
// Fake up a Declarator to use with ActOnTypeName.
DeclSpec DS(AttrFactory);
DS.SetRangeStart(Tok.getLocation());
DS.SetRangeEnd(Tok.getLastLoc());
const char *PrevSpec = nullptr;
unsigned DiagID;
DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
PrevSpec, DiagID, Type,
Actions.getASTContext().getPrintingPolicy());
Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
DeclaratorContext::TypeName);
TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
if (Ty.isInvalid())
break;
ConsumeAnnotationToken();
Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
Ty.get(), nullptr);
break;
}
[[fallthrough]];
case tok::annot_decltype:
case tok::kw_char:
case tok::kw_wchar_t:
case tok::kw_char8_t:
case tok::kw_char16_t:
case tok::kw_char32_t:
case tok::kw_bool:
case tok::kw_short:
case tok::kw_int:
case tok::kw_long:
case tok::kw___int64:
case tok::kw___int128:
case tok::kw__ExtInt:
case tok::kw__BitInt:
case tok::kw_signed:
case tok::kw_unsigned:
case tok::kw_half:
case tok::kw_float:
case tok::kw_double:
case tok::kw___bf16:
case tok::kw__Float16:
case tok::kw___float128:
case tok::kw___ibm128:
case tok::kw_void:
case tok::kw_auto:
case tok::kw_typename:
case tok::kw_typeof:
case tok::kw___vector:
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
#include "clang/Basic/OpenCLImageTypes.def"
{
if (!getLangOpts().CPlusPlus) {
Diag(Tok, diag::err_expected_expression);
return ExprError();
}
// Everything henceforth is a postfix-expression.
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
if (SavedKind == tok::kw_typename) {
// postfix-expression: typename-specifier '(' expression-list[opt] ')'
// typename-specifier braced-init-list
if (TryAnnotateTypeOrScopeToken())
return ExprError();
if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
// We are trying to parse a simple-type-specifier but might not get such
// a token after error recovery.
return ExprError();
}
// postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
// simple-type-specifier braced-init-list
//
DeclSpec DS(AttrFactory);
ParseCXXSimpleTypeSpecifier(DS);
if (Tok.isNot(tok::l_paren) &&
(!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
<< DS.getSourceRange());
if (Tok.is(tok::l_brace))
Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Res = ParseCXXTypeConstructExpression(DS);
break;
}
case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
// If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
// (We can end up in this situation after tentative parsing.)
if (TryAnnotateTypeOrScopeToken())
return ExprError();
if (!Tok.is(tok::annot_cxxscope))
return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
isTypeCast, isVectorLiteral,
NotPrimaryExpression);
Token Next = NextToken();
if (Next.is(tok::annot_template_id)) {
TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
if (TemplateId->Kind == TNK_Type_template) {
// We have a qualified template-id that we know refers to a
// type, translate it into a type and continue parsing as a
// cast expression.
CXXScopeSpec SS;
ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
/*ObjectHasErrors=*/false,
/*EnteringContext=*/false);
AnnotateTemplateIdTokenAsType(SS, ImplicitTypenameContext::Yes);
return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
isTypeCast, isVectorLiteral,
NotPrimaryExpression);
}
}
// Parse as an id-expression.
Res = ParseCXXIdExpression(isAddressOfOperand);
break;
}
case tok::annot_template_id: { // [C++] template-id
TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
if (TemplateId->Kind == TNK_Type_template) {
// We have a template-id that we know refers to a type,
// translate it into a type and continue parsing as a cast
// expression.
CXXScopeSpec SS;
AnnotateTemplateIdTokenAsType(SS, ImplicitTypenameContext::Yes);
return ParseCastExpression(ParseKind, isAddressOfOperand,
NotCastExpr, isTypeCast, isVectorLiteral,
NotPrimaryExpression);
}
// Fall through to treat the template-id as an id-expression.
[[fallthrough]];
}
case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
Res = ParseCXXIdExpression(isAddressOfOperand);
break;
case tok::coloncolon: {
// ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
// annotates the token, tail recurse.
if (TryAnnotateTypeOrScopeToken())
return ExprError();
if (!Tok.is(tok::coloncolon))
return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
isVectorLiteral, NotPrimaryExpression);
// ::new -> [C++] new-expression
// ::delete -> [C++] delete-expression
SourceLocation CCLoc = ConsumeToken();
if (Tok.is(tok::kw_new)) {
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseCXXNewExpression(true, CCLoc);
AllowSuffix = false;
break;
}
if (Tok.is(tok::kw_delete)) {
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseCXXDeleteExpression(true, CCLoc);
AllowSuffix = false;
break;
}
// This is not a type name or scope specifier, it is an invalid expression.
Diag(CCLoc, diag::err_expected_expression);
return ExprError();
}
case tok::kw_new: // [C++] new-expression
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseCXXNewExpression(false, Tok.getLocation());
AllowSuffix = false;
break;
case tok::kw_delete: // [C++] delete-expression
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseCXXDeleteExpression(false, Tok.getLocation());
AllowSuffix = false;
break;
case tok::kw_requires: // [C++2a] requires-expression
Res = ParseRequiresExpression();
AllowSuffix = false;
break;
case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
SourceLocation KeyLoc = ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
return ExprError();
// C++11 [expr.unary.noexcept]p1:
// The noexcept operator determines whether the evaluation of its operand,
// which is an unevaluated operand, can throw an exception.
EnterExpressionEvaluationContext Unevaluated(
Actions, Sema::ExpressionEvaluationContext::Unevaluated);
Res = ParseExpression();
T.consumeClose();
if (!Res.isInvalid())
Res = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Res.get(),
T.getCloseLocation());
AllowSuffix = false;
break;
}
#define TYPE_TRAIT(N,Spelling,K) \
case tok::kw_##Spelling:
#include "clang/Basic/TokenKinds.def"
Res = ParseTypeTrait();
break;
case tok::kw___array_rank:
case tok::kw___array_extent:
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseArrayTypeTrait();
break;
case tok::kw___is_lvalue_expr:
case tok::kw___is_rvalue_expr:
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseExpressionTrait();
break;
case tok::at: {
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
SourceLocation AtLoc = ConsumeToken();
return ParseObjCAtExpression(AtLoc);
}
case tok::caret:
Res = ParseBlockLiteralExpression();
break;
case tok::code_completion: {
cutOffParsing();
Actions.CodeCompleteExpression(getCurScope(),
PreferredType.get(Tok.getLocation()));
return ExprError();
}
#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
#include "clang/Basic/TransformTypeTraits.def"
// HACK: libstdc++ uses some of the transform-type-traits as alias
// templates, so we need to work around this.
if (!NextToken().is(tok::l_paren)) {
Tok.setKind(tok::identifier);
Diag(Tok, diag::ext_keyword_as_ident)
<< Tok.getIdentifierInfo()->getName() << 0;
goto ParseIdentifier;
}
goto ExpectedExpression;
case tok::l_square:
if (getLangOpts().CPlusPlus11) {
if (getLangOpts().ObjC) {
// C++11 lambda expressions and Objective-C message sends both start with a
// square bracket. There are three possibilities here:
// we have a valid lambda expression, we have an invalid lambda
// expression, or we have something that doesn't appear to be a lambda.
// If we're in the last case, we fall back to ParseObjCMessageExpression.
Res = TryParseLambdaExpression();
if (!Res.isInvalid() && !Res.get()) {
// We assume Objective-C++ message expressions are not
// primary-expressions.
if (NotPrimaryExpression)
*NotPrimaryExpression = true;
Res = ParseObjCMessageExpression();
}
break;
}
Res = ParseLambdaExpression();
break;
}
if (getLangOpts().ObjC) {
Res = ParseObjCMessageExpression();
break;
}
[[fallthrough]];
default:
ExpectedExpression:
NotCastExpr = true;
return ExprError();
}
// Check to see whether Res is a function designator only. If it is and we
// are compiling for OpenCL, we need to return an error as this implies
// that the address of the function is being taken, which is illegal in CL.
if (ParseKind == PrimaryExprOnly)
// This is strictly a primary-expression - no postfix-expr pieces should be
// parsed.
return Res;
if (!AllowSuffix) {
// FIXME: Don't parse a primary-expression suffix if we encountered a parse
// error already.
if (Res.isInvalid())
return Res;
switch (Tok.getKind()) {
case tok::l_square:
case tok::l_paren:
case tok::plusplus:
case tok::minusminus:
// "expected ';'" or similar is probably the right diagnostic here. Let
// the caller decide what to do.
if (Tok.isAtStartOfLine())
return Res;
[[fallthrough]];
case tok::period:
case tok::arrow:
break;
default:
return Res;
}
// This was a unary-expression for which a postfix-expression suffix is
// not permitted by the grammar (eg, a sizeof expression or
// new-expression or similar). Diagnose but parse the suffix anyway.
Diag(Tok.getLocation(), diag::err_postfix_after_unary_requires_parens)
<< Tok.getKind() << Res.get()->getSourceRange()
<< FixItHint::CreateInsertion(Res.get()->getBeginLoc(), "(")
<< FixItHint::CreateInsertion(PP.getLocForEndOfToken(PrevTokLocation),
")");
}
// These can be followed by postfix-expr pieces.
PreferredType = SavedType;
Res = ParsePostfixExpressionSuffix(Res);
if (getLangOpts().OpenCL &&
!getActions().getOpenCLOptions().isAvailableOption(
"__cl_clang_function_pointers", getLangOpts()))
if (Expr *PostfixExpr = Res.get()) {
QualType Ty = PostfixExpr->getType();
if (!Ty.isNull() && Ty->isFunctionType()) {
Diag(PostfixExpr->getExprLoc(),
diag::err_opencl_taking_function_address_parser);
return ExprError();
}
}
return Res;
}
/// Once the leading part of a postfix-expression is parsed, this
/// method parses any suffixes that apply.
///
/// \verbatim
/// postfix-expression: [C99 6.5.2]
/// primary-expression
/// postfix-expression '[' expression ']'
/// postfix-expression '[' braced-init-list ']'
/// postfix-expression '[' expression-list [opt] ']' [C++2b 12.4.5]
/// postfix-expression '(' argument-expression-list[opt] ')'
/// postfix-expression '.' identifier
/// postfix-expression '->' identifier
/// postfix-expression '++'
/// postfix-expression '--'
/// '(' type-name ')' '{' initializer-list '}'
/// '(' type-name ')' '{' initializer-list ',' '}'
///
/// argument-expression-list: [C99 6.5.2]
/// argument-expression ...[opt]
/// argument-expression-list ',' assignment-expression ...[opt]
/// \endverbatim
ExprResult
Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
// Now that the primary-expression piece of the postfix-expression has been
// parsed, see if there are any postfix-expression pieces here.
SourceLocation Loc;
auto SavedType = PreferredType;
while (true) {
// Each iteration relies on preferred type for the whole expression.
PreferredType = SavedType;
switch (Tok.getKind()) {
case tok::code_completion:
if (InMessageExpression)
return LHS;
cutOffParsing();
Actions.CodeCompletePostfixExpression(
getCurScope(), LHS, PreferredType.get(Tok.getLocation()));
return ExprError();
case tok::identifier:
// If we see identifier: after an expression, and we're not already in a
// message send, then this is probably a message send with a missing
// opening bracket '['.
if (getLangOpts().ObjC && !InMessageExpression &&
(NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
nullptr, LHS.get());
break;
}
// Fall through; this isn't a message send.
[[fallthrough]];
default: // Not a postfix-expression suffix.
return LHS;
case tok::l_square: { // postfix-expression: p-e '[' expression ']'
// If we have a array postfix expression that starts on a new line and
// Objective-C is enabled, it is highly likely that the user forgot a
// semicolon after the base expression and that the array postfix-expr is
// actually another message send. In this case, do some look-ahead to see
// if the contents of the square brackets are obviously not a valid
// expression and recover by pretending there is no suffix.
if (getLangOpts().ObjC && Tok.isAtStartOfLine() &&
isSimpleObjCMessageExpression())
return LHS;
// Reject array indices starting with a lambda-expression. '[[' is
// reserved for attributes.
if (CheckProhibitedCXX11Attribute()) {
(void)Actions.CorrectDelayedTyposInExpr(LHS);
return ExprError();
}
BalancedDelimiterTracker T(*this, tok::l_square);
T.consumeOpen();
Loc = T.getOpenLocation();
ExprResult Length, Stride;
SourceLocation ColonLocFirst, ColonLocSecond;
ExprVector ArgExprs;
bool HasError = false;
PreferredType.enterSubscript(Actions, Tok.getLocation(), LHS.get());
// We try to parse a list of indexes in all language mode first
// and, in we find 0 or one index, we try to parse an OpenMP array
// section. This allow us to support C++2b multi dimensional subscript and
// OpenMp sections in the same language mode.
if (!getLangOpts().OpenMP || Tok.isNot(tok::colon)) {
if (!getLangOpts().CPlusPlus2b) {
ExprResult Idx;
if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Idx = ParseBraceInitializer();
} else {
Idx = ParseExpression(); // May be a comma expression
}
LHS = Actions.CorrectDelayedTyposInExpr(LHS);
Idx = Actions.CorrectDelayedTyposInExpr(Idx);
if (Idx.isInvalid()) {
HasError = true;
} else {
ArgExprs.push_back(Idx.get());
}
} else if (Tok.isNot(tok::r_square)) {
if (ParseExpressionList(ArgExprs)) {
LHS = Actions.CorrectDelayedTyposInExpr(LHS);
HasError = true;
}
}
}
if (ArgExprs.size() <= 1 && getLangOpts().OpenMP) {
ColonProtectionRAIIObject RAII(*this);
if (Tok.is(tok::colon)) {
// Consume ':'
ColonLocFirst = ConsumeToken();
if (Tok.isNot(tok::r_square) &&
(getLangOpts().OpenMP < 50 ||
((Tok.isNot(tok::colon) && getLangOpts().OpenMP >= 50)))) {
Length = ParseExpression();
Length = Actions.CorrectDelayedTyposInExpr(Length);
}
}
if (getLangOpts().OpenMP >= 50 &&
(OMPClauseKind == llvm::omp::Clause::OMPC_to ||
OMPClauseKind == llvm::omp::Clause::OMPC_from) &&
Tok.is(tok::colon)) {
// Consume ':'
ColonLocSecond = ConsumeToken();
if (Tok.isNot(tok::r_square)) {
Stride = ParseExpression();
}
}
}
SourceLocation RLoc = Tok.getLocation();
LHS = Actions.CorrectDelayedTyposInExpr(LHS);
if (!LHS.isInvalid() && !HasError && !Length.isInvalid() &&
!Stride.isInvalid() && Tok.is(tok::r_square)) {
if (ColonLocFirst.isValid() || ColonLocSecond.isValid()) {
LHS = Actions.ActOnOMPArraySectionExpr(
LHS.get(), Loc, ArgExprs.empty() ? nullptr : ArgExprs[0],
ColonLocFirst, ColonLocSecond, Length.get(), Stride.get(), RLoc);
} else {
LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
ArgExprs, RLoc);
}
} else {
LHS = ExprError();
}
// Match the ']'.
T.consumeClose();
break;
}
case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
// '(' argument-expression-list[opt] ')'
tok::TokenKind OpKind = Tok.getKind();
InMessageExpressionRAIIObject InMessage(*this, false);
Expr *ExecConfig = nullptr;
BalancedDelimiterTracker PT(*this, tok::l_paren);
if (OpKind == tok::lesslessless) {
ExprVector ExecConfigExprs;
SourceLocation OpenLoc = ConsumeToken();
if (ParseSimpleExpressionList(ExecConfigExprs)) {
(void)Actions.CorrectDelayedTyposInExpr(LHS);
LHS = ExprError();
}
SourceLocation CloseLoc;
if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
} else if (LHS.isInvalid()) {
SkipUntil(tok::greatergreatergreater, StopAtSemi);
} else {
// There was an error closing the brackets
Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
SkipUntil(tok::greatergreatergreater, StopAtSemi);
LHS = ExprError();
}
if (!LHS.isInvalid()) {
if (ExpectAndConsume(tok::l_paren))
LHS = ExprError();
else
Loc = PrevTokLocation;
}
if (!LHS.isInvalid()) {
ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
OpenLoc,
ExecConfigExprs,
CloseLoc);
if (ECResult.isInvalid())
LHS = ExprError();
else
ExecConfig = ECResult.get();
}
} else {
PT.consumeOpen();
Loc = PT.getOpenLocation();
}
ExprVector ArgExprs;
auto RunSignatureHelp = [&]() -> QualType {
QualType PreferredType = Actions.ProduceCallSignatureHelp(
LHS.get(), ArgExprs, PT.getOpenLocation());
CalledSignatureHelp = true;
return PreferredType;
};
if (OpKind == tok::l_paren || !LHS.isInvalid()) {
if (Tok.isNot(tok::r_paren)) {
if (ParseExpressionList(ArgExprs, [&] {
PreferredType.enterFunctionArgument(Tok.getLocation(),
RunSignatureHelp);
})) {
(void)Actions.CorrectDelayedTyposInExpr(LHS);
// If we got an error when parsing expression list, we don't call
// the CodeCompleteCall handler inside the parser. So call it here
// to make sure we get overload suggestions even when we are in the
// middle of a parameter.
if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
RunSignatureHelp();
LHS = ExprError();
} else if (LHS.isInvalid()) {
for (auto &E : ArgExprs)
Actions.CorrectDelayedTyposInExpr(E);
}
}
}
// Match the ')'.
if (LHS.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
} else if (Tok.isNot(tok::r_paren)) {
bool HadDelayedTypo = false;
if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
HadDelayedTypo = true;
for (auto &E : ArgExprs)
if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
HadDelayedTypo = true;
// If there were delayed typos in the LHS or ArgExprs, call SkipUntil
// instead of PT.consumeClose() to avoid emitting extra diagnostics for
// the unmatched l_paren.
if (HadDelayedTypo)
SkipUntil(tok::r_paren, StopAtSemi);
else
PT.consumeClose();
LHS = ExprError();
} else {
Expr *Fn = LHS.get();
SourceLocation RParLoc = Tok.getLocation();
LHS = Actions.ActOnCallExpr(getCurScope(), Fn, Loc, ArgExprs, RParLoc,
ExecConfig);
if (LHS.isInvalid()) {
ArgExprs.insert(ArgExprs.begin(), Fn);
LHS =
Actions.CreateRecoveryExpr(Fn->getBeginLoc(), RParLoc, ArgExprs);
}
PT.consumeClose();
}
break;
}
case tok::arrow:
case tok::period: {
// postfix-expression: p-e '->' template[opt] id-expression
// postfix-expression: p-e '.' template[opt] id-expression
tok::TokenKind OpKind = Tok.getKind();
SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
CXXScopeSpec SS;
ParsedType ObjectType;
bool MayBePseudoDestructor = false;
Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : nullptr;
PreferredType.enterMemAccess(Actions, Tok.getLocation(), OrigLHS);
if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
Expr *Base = OrigLHS;
const Type* BaseType = Base->getType().getTypePtrOrNull();
if (BaseType && Tok.is(tok::l_paren) &&
(BaseType->isFunctionType() ||
BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
Diag(OpLoc, diag::err_function_is_not_record)
<< OpKind << Base->getSourceRange()
<< FixItHint::CreateRemoval(OpLoc);
return ParsePostfixExpressionSuffix(Base);
}
LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base, OpLoc,
OpKind, ObjectType,
MayBePseudoDestructor);
if (LHS.isInvalid()) {
// Clang will try to perform expression based completion as a
// fallback, which is confusing in case of member references. So we
// stop here without any completions.
if (Tok.is(tok::code_completion)) {
cutOffParsing();
return ExprError();
}
break;
}
ParseOptionalCXXScopeSpecifier(
SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
/*EnteringContext=*/false, &MayBePseudoDestructor);
if (SS.isNotEmpty())
ObjectType = nullptr;
}
if (Tok.is(tok::code_completion)) {
tok::TokenKind CorrectedOpKind =
OpKind == tok::arrow ? tok::period : tok::arrow;
ExprResult CorrectedLHS(/*Invalid=*/true);
if (getLangOpts().CPlusPlus && OrigLHS) {
// FIXME: Creating a TentativeAnalysisScope from outside Sema is a
// hack.
Sema::TentativeAnalysisScope Trap(Actions);
CorrectedLHS = Actions.ActOnStartCXXMemberReference(
getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
MayBePseudoDestructor);
}
Expr *Base = LHS.get();
Expr *CorrectedBase = CorrectedLHS.get();
if (!CorrectedBase && !getLangOpts().CPlusPlus)
CorrectedBase = Base;
// Code completion for a member access expression.
cutOffParsing();
Actions.CodeCompleteMemberReferenceExpr(
getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
Base && ExprStatementTokLoc == Base->getBeginLoc(),
PreferredType.get(Tok.getLocation()));
return ExprError();
}
if (MayBePseudoDestructor && !LHS.isInvalid()) {
LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
ObjectType);
break;
}
// Either the action has told us that this cannot be a
// pseudo-destructor expression (based on the type of base
// expression), or we didn't see a '~' in the right place. We
// can still parse a destructor name here, but in that case it
// names a real destructor.
// Allow explicit constructor calls in Microsoft mode.
// FIXME: Add support for explicit call of template constructor.
SourceLocation TemplateKWLoc;
UnqualifiedId Name;
if (getLangOpts().ObjC && OpKind == tok::period &&
Tok.is(tok::kw_class)) {
// Objective-C++:
// After a '.' in a member access expression, treat the keyword
// 'class' as if it were an identifier.
//
// This hack allows property access to the 'class' method because it is
// such a common method name. For other C++ keywords that are
// Objective-C method names, one must use the message send syntax.
IdentifierInfo *Id = Tok.getIdentifierInfo();
SourceLocation Loc = ConsumeToken();
Name.setIdentifier(Id, Loc);
} else if (ParseUnqualifiedId(
SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
/*EnteringContext=*/false,
/*AllowDestructorName=*/true,
/*AllowConstructorName=*/
getLangOpts().MicrosoftExt && SS.isNotEmpty(),
/*AllowDeductionGuide=*/false, &TemplateKWLoc, Name)) {
(void)Actions.CorrectDelayedTyposInExpr(LHS);
LHS = ExprError();
}
if (!LHS.isInvalid())
LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
OpKind, SS, TemplateKWLoc, Name,
CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
: nullptr);
if (!LHS.isInvalid()) {
if (Tok.is(tok::less))
checkPotentialAngleBracket(LHS);
} else if (OrigLHS && Name.isValid()) {
// Preserve the LHS if the RHS is an invalid member.
LHS = Actions.CreateRecoveryExpr(OrigLHS->getBeginLoc(),
Name.getEndLoc(), {OrigLHS});
}
break;
}
case tok::plusplus: // postfix-expression: postfix-expression '++'
case tok::minusminus: // postfix-expression: postfix-expression '--'
if (!LHS.isInvalid()) {
Expr *Arg = LHS.get();
LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
Tok.getKind(), Arg);
if (LHS.isInvalid())
LHS = Actions.CreateRecoveryExpr(Arg->getBeginLoc(),
Tok.getLocation(), Arg);
}
ConsumeToken();
break;
}
}
}
/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
/// vec_step and we are at the start of an expression or a parenthesized
/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
/// expression (isCastExpr == false) or the type (isCastExpr == true).
///
/// \verbatim
/// unary-expression: [C99 6.5.3]
/// 'sizeof' unary-expression
/// 'sizeof' '(' type-name ')'
/// [GNU] '__alignof' unary-expression
/// [GNU] '__alignof' '(' type-name ')'
/// [C11] '_Alignof' '(' type-name ')'
/// [C++0x] 'alignof' '(' type-id ')'
///
/// [GNU] typeof-specifier:
/// typeof ( expressions )
/// typeof ( type-name )
/// [GNU/C++] typeof unary-expression
/// [C2x] typeof-specifier:
/// typeof '(' typeof-specifier-argument ')'
/// typeof_unqual '(' typeof-specifier-argument ')'
///
/// typeof-specifier-argument:
/// expression
/// type-name
///
/// [OpenCL 1.1 6.11.12] vec_step built-in function:
/// vec_step ( expressions )
/// vec_step ( type-name )
/// \endverbatim
ExprResult
Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
bool &isCastExpr,
ParsedType &CastTy,
SourceRange &CastRange) {
assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual, tok::kw_sizeof,
tok::kw___alignof, tok::kw_alignof, tok::kw__Alignof,
tok::kw_vec_step,
tok::kw___builtin_omp_required_simd_align) &&
"Not a typeof/sizeof/alignof/vec_step expression!");
ExprResult Operand;
// If the operand doesn't start with an '(', it must be an expression.
if (Tok.isNot(tok::l_paren)) {
// If construct allows a form without parenthesis, user may forget to put
// pathenthesis around type name.
if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
tok::kw__Alignof)) {
if (isTypeIdUnambiguously()) {
DeclSpec DS(AttrFactory);
ParseSpecifierQualifierList(DS);
Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
DeclaratorContext::TypeName);
ParseDeclarator(DeclaratorInfo);
SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
if (LParenLoc.isInvalid() || RParenLoc.isInvalid()) {
Diag(OpTok.getLocation(),
diag::err_expected_parentheses_around_typename)
<< OpTok.getName();
} else {
Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
<< OpTok.getName() << FixItHint::CreateInsertion(LParenLoc, "(")
<< FixItHint::CreateInsertion(RParenLoc, ")");
}
isCastExpr = true;
return ExprEmpty();
}
}
isCastExpr = false;
if (OpTok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
!getLangOpts().CPlusPlus) {
Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
<< tok::l_paren;
return ExprError();
}
Operand = ParseCastExpression(UnaryExprOnly);
} else {
// If it starts with a '(', we know that it is either a parenthesized
// type-name, or it is a unary-expression that starts with a compound
// literal, or starts with a primary-expression that is a parenthesized
// expression.
ParenParseOption ExprType = CastExpr;
SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
false, CastTy, RParenLoc);
CastRange = SourceRange(LParenLoc, RParenLoc);
// If ParseParenExpression parsed a '(typename)' sequence only, then this is
// a type.
if (ExprType == CastExpr) {
isCastExpr = true;
return ExprEmpty();
}
if (getLangOpts().CPlusPlus ||
!OpTok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual)) {
// GNU typeof in C requires the expression to be parenthesized. Not so for
// sizeof/alignof or in C++. Therefore, the parenthesized expression is
// the start of a unary-expression, but doesn't include any postfix
// pieces. Parse these now if present.
if (!Operand.isInvalid())
Operand = ParsePostfixExpressionSuffix(Operand.get());
}
}
// If we get here, the operand to the typeof/sizeof/alignof was an expression.
isCastExpr = false;
return Operand;
}
/// Parse a __builtin_sycl_unique_stable_name expression. Accepts a type-id as
/// a parameter.
ExprResult Parser::ParseSYCLUniqueStableNameExpression() {
assert(Tok.is(tok::kw___builtin_sycl_unique_stable_name) &&
"Not __builtin_sycl_unique_stable_name");
SourceLocation OpLoc = ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
// __builtin_sycl_unique_stable_name expressions are always parenthesized.
if (T.expectAndConsume(diag::err_expected_lparen_after,
"__builtin_sycl_unique_stable_name"))
return ExprError();
TypeResult Ty = ParseTypeName();
if (Ty.isInvalid()) {
T.skipToEnd();
return ExprError();
}
if (T.consumeClose())
return ExprError();
return Actions.ActOnSYCLUniqueStableNameExpr(OpLoc, T.getOpenLocation(),
T.getCloseLocation(), Ty.get());
}
/// Parse a sizeof or alignof expression.
///
/// \verbatim
/// unary-expression: [C99 6.5.3]
/// 'sizeof' unary-expression
/// 'sizeof' '(' type-name ')'
/// [C++11] 'sizeof' '...' '(' identifier ')'
/// [GNU] '__alignof' unary-expression
/// [GNU] '__alignof' '(' type-name ')'
/// [C11] '_Alignof' '(' type-name ')'
/// [C++11] 'alignof' '(' type-id ')'
/// \endverbatim
ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
tok::kw__Alignof, tok::kw_vec_step,
tok::kw___builtin_omp_required_simd_align) &&
"Not a sizeof/alignof/vec_step expression!");
Token OpTok = Tok;
ConsumeToken();
// [C++11] 'sizeof' '...' '(' identifier ')'
if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
SourceLocation EllipsisLoc = ConsumeToken();
SourceLocation LParenLoc, RParenLoc;
IdentifierInfo *Name = nullptr;
SourceLocation NameLoc;
if (Tok.is(tok::l_paren)) {
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
LParenLoc = T.getOpenLocation();
if (Tok.is(tok::identifier)) {
Name = Tok.getIdentifierInfo();
NameLoc = ConsumeToken();
T.consumeClose();
RParenLoc = T.getCloseLocation();
if (RParenLoc.isInvalid())
RParenLoc = PP.getLocForEndOfToken(NameLoc);
} else {
Diag(Tok, diag::err_expected_parameter_pack);
SkipUntil(tok::r_paren, StopAtSemi);
}
} else if (Tok.is(tok::identifier)) {
Name = Tok.getIdentifierInfo();
NameLoc = ConsumeToken();
LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
RParenLoc = PP.getLocForEndOfToken(NameLoc);
Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
<< Name
<< FixItHint::CreateInsertion(LParenLoc, "(")
<< FixItHint::CreateInsertion(RParenLoc, ")");
} else {
Diag(Tok, diag::err_sizeof_parameter_pack);
}
if (!Name)
return ExprError();
EnterExpressionEvaluationContext Unevaluated(
Actions, Sema::ExpressionEvaluationContext::Unevaluated,
Sema::ReuseLambdaContextDecl);
return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
OpTok.getLocation(),
*Name, NameLoc,
RParenLoc);
}
if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
Diag(OpTok, diag::warn_cxx98_compat_alignof);
EnterExpressionEvaluationContext Unevaluated(
Actions, Sema::ExpressionEvaluationContext::Unevaluated,
Sema::ReuseLambdaContextDecl);
bool isCastExpr;
ParsedType CastTy;
SourceRange CastRange;
ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
isCastExpr,
CastTy,
CastRange);
UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
ExprKind = UETT_AlignOf;
else if (OpTok.is(tok::kw___alignof))
ExprKind = UETT_PreferredAlignOf;
else if (OpTok.is(tok::kw_vec_step))
ExprKind = UETT_VecStep;
else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
ExprKind = UETT_OpenMPRequiredSimdAlign;
if (isCastExpr)
return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
ExprKind,
/*IsType=*/true,
CastTy.getAsOpaquePtr(),
CastRange);
if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
// If we get here, the operand to the sizeof/alignof was an expression.
if (!Operand.isInvalid())
Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
ExprKind,
/*IsType=*/false,
Operand.get(),
CastRange);
return Operand;
}
/// ParseBuiltinPrimaryExpression
///
/// \verbatim
/// primary-expression: [C99 6.5.1]
/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
/// assign-expr ')'
/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
/// [GNU] '__builtin_FILE' '(' ')'
/// [GNU] '__builtin_FUNCTION' '(' ')'
/// [GNU] '__builtin_LINE' '(' ')'
/// [CLANG] '__builtin_COLUMN' '(' ')'
/// [GNU] '__builtin_source_location' '(' ')'
/// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
///
/// [GNU] offsetof-member-designator:
/// [GNU] identifier
/// [GNU] offsetof-member-designator '.' identifier
/// [GNU] offsetof-member-designator '[' expression ']'
/// \endverbatim
ExprResult Parser::ParseBuiltinPrimaryExpression() {
ExprResult Res;
const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
tok::TokenKind T = Tok.getKind();
SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
// All of these start with an open paren.
if (Tok.isNot(tok::l_paren))
return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
<< tok::l_paren);
BalancedDelimiterTracker PT(*this, tok::l_paren);
PT.consumeOpen();
// TODO: Build AST.
switch (T) {
default: llvm_unreachable("Not a builtin primary expression!");
case tok::kw___builtin_va_arg: {
ExprResult Expr(ParseAssignmentExpression());
if (ExpectAndConsume(tok::comma)) {
SkipUntil(tok::r_paren, StopAtSemi);
Expr = ExprError();
}
TypeResult Ty = ParseTypeName();
if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::err_expected) << tok::r_paren;
Expr = ExprError();
}
if (Expr.isInvalid() || Ty.isInvalid())
Res = ExprError();
else
Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
break;
}
case tok::kw___builtin_offsetof: {
SourceLocation TypeLoc = Tok.getLocation();
auto OOK = Sema::OffsetOfKind::OOK_Builtin;
if (Tok.getLocation().isMacroID()) {
StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
Tok.getLocation(), PP.getSourceManager(), getLangOpts());
if (MacroName == "offsetof")
OOK = Sema::OffsetOfKind::OOK_Macro;
}
TypeResult Ty;
{
OffsetOfStateRAIIObject InOffsetof(*this, OOK);
Ty = ParseTypeName();
if (Ty.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
}
if (ExpectAndConsume(tok::comma)) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
// We must have at least one identifier here.
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
// Keep track of the various subcomponents we see.
SmallVector<Sema::OffsetOfComponent, 4> Comps;
Comps.push_back(Sema::OffsetOfComponent());
Comps.back().isBrackets = false;
Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
// FIXME: This loop leaks the index expressions on error.
while (true) {
if (Tok.is(tok::period)) {
// offsetof-member-designator: offsetof-member-designator '.' identifier
Comps.push_back(Sema::OffsetOfComponent());
Comps.back().isBrackets = false;
Comps.back().LocStart = ConsumeToken();
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
Comps.back().LocEnd = ConsumeToken();
} else if (Tok.is(tok::l_square)) {
if (CheckProhibitedCXX11Attribute())
return ExprError();
// offsetof-member-designator: offsetof-member-design '[' expression ']'
Comps.push_back(Sema::OffsetOfComponent());
Comps.back().isBrackets = true;
BalancedDelimiterTracker ST(*this, tok::l_square);
ST.consumeOpen();
Comps.back().LocStart = ST.getOpenLocation();
Res = ParseExpression();
if (Res.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return Res;
}
Comps.back().U.E = Res.get();
ST.consumeClose();
Comps.back().LocEnd = ST.getCloseLocation();
} else {
if (Tok.isNot(tok::r_paren)) {
PT.consumeClose();
Res = ExprError();
} else if (Ty.isInvalid()) {
Res = ExprError();
} else {
PT.consumeClose();
Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
Ty.get(), Comps,
PT.getCloseLocation());
}
break;
}
}
break;
}
case tok::kw___builtin_choose_expr: {
ExprResult Cond(ParseAssignmentExpression());
if (Cond.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return Cond;
}
if (ExpectAndConsume(tok::comma)) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
ExprResult Expr1(ParseAssignmentExpression());
if (Expr1.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return Expr1;
}
if (ExpectAndConsume(tok::comma)) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
ExprResult Expr2(ParseAssignmentExpression());
if (Expr2.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return Expr2;
}
if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::err_expected) << tok::r_paren;
return ExprError();
}
Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
Expr2.get(), ConsumeParen());
break;
}
case tok::kw___builtin_astype: {
// The first argument is an expression to be converted, followed by a comma.
ExprResult Expr(ParseAssignmentExpression());
if (Expr.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
if (ExpectAndConsume(tok::comma)) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
// Second argument is the type to bitcast to.
TypeResult DestTy = ParseTypeName();
if (DestTy.isInvalid())
return ExprError();
// Attempt to consume the r-paren.
if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::err_expected) << tok::r_paren;
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
ConsumeParen());
break;
}
case tok::kw___builtin_convertvector: {
// The first argument is an expression to be converted, followed by a comma.
ExprResult Expr(ParseAssignmentExpression());
if (Expr.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
if (ExpectAndConsume(tok::comma)) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
// Second argument is the type to bitcast to.
TypeResult DestTy = ParseTypeName();
if (DestTy.isInvalid())
return ExprError();
// Attempt to consume the r-paren.
if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::err_expected) << tok::r_paren;
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
ConsumeParen());
break;
}
case tok::kw___builtin_COLUMN:
case tok::kw___builtin_FILE:
case tok::kw___builtin_FUNCTION:
case tok::kw___builtin_LINE:
case tok::kw___builtin_source_location: {
// Attempt to consume the r-paren.
if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::err_expected) << tok::r_paren;
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
SourceLocExpr::IdentKind Kind = [&] {
switch (T) {
case tok::kw___builtin_FILE:
return SourceLocExpr::File;
case tok::kw___builtin_FUNCTION:
return SourceLocExpr::Function;
case tok::kw___builtin_LINE:
return SourceLocExpr::Line;
case tok::kw___builtin_COLUMN:
return SourceLocExpr::Column;
case tok::kw___builtin_source_location:
return SourceLocExpr::SourceLocStruct;
default:
llvm_unreachable("invalid keyword");
}
}();
Res = Actions.ActOnSourceLocExpr(Kind, StartLoc, ConsumeParen());
break;
}
}
if (Res.isInvalid())
return ExprError();
// These can be followed by postfix-expr pieces because they are
// primary-expressions.
return ParsePostfixExpressionSuffix(Res.get());
}
bool Parser::tryParseOpenMPArrayShapingCastPart() {
assert(Tok.is(tok::l_square) && "Expected open bracket");
bool ErrorFound = true;
TentativeParsingAction TPA(*this);
do {
if (Tok.isNot(tok::l_square))
break;
// Consume '['
ConsumeBracket();
// Skip inner expression.
while (!SkipUntil(tok::r_square, tok::annot_pragma_openmp_end,
StopAtSemi | StopBeforeMatch))
;
if (Tok.isNot(tok::r_square))
break;
// Consume ']'
ConsumeBracket();
// Found ')' - done.
if (Tok.is(tok::r_paren)) {
ErrorFound = false;
break;
}
} while (Tok.isNot(tok::annot_pragma_openmp_end));
TPA.Revert();
return !ErrorFound;
}
/// ParseParenExpression - This parses the unit that starts with a '(' token,
/// based on what is allowed by ExprType. The actual thing parsed is returned
/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
/// not the parsed cast-expression.
///
/// \verbatim
/// primary-expression: [C99 6.5.1]
/// '(' expression ')'
/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
/// postfix-expression: [C99 6.5.2]
/// '(' type-name ')' '{' initializer-list '}'
/// '(' type-name ')' '{' initializer-list ',' '}'
/// cast-expression: [C99 6.5.4]
/// '(' type-name ')' cast-expression
/// [ARC] bridged-cast-expression
/// [ARC] bridged-cast-expression:
/// (__bridge type-name) cast-expression
/// (__bridge_transfer type-name) cast-expression
/// (__bridge_retained type-name) cast-expression
/// fold-expression: [C++1z]
/// '(' cast-expression fold-operator '...' ')'
/// '(' '...' fold-operator cast-expression ')'
/// '(' cast-expression fold-operator '...'
/// fold-operator cast-expression ')'
/// [OPENMP] Array shaping operation
/// '(' '[' expression ']' { '[' expression ']' } cast-expression
/// \endverbatim
ExprResult
Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
bool isTypeCast, ParsedType &CastTy,
SourceLocation &RParenLoc) {
assert(Tok.is(tok::l_paren) && "Not a paren expr!");
ColonProtectionRAIIObject ColonProtection(*this, false);
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.consumeOpen())
return ExprError();
SourceLocation OpenLoc = T.getOpenLocation();
PreferredType.enterParenExpr(Tok.getLocation(), OpenLoc);
ExprResult Result(true);
bool isAmbiguousTypeId;
CastTy = nullptr;
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteExpression(
getCurScope(), PreferredType.get(Tok.getLocation()),
/*IsParenthesized=*/ExprType >= CompoundLiteral);
return ExprError();
}
// Diagnose use of bridge casts in non-arc mode.
bool BridgeCast = (getLangOpts().ObjC &&
Tok.isOneOf(tok::kw___bridge,
tok::kw___bridge_transfer,
tok::kw___bridge_retained,
tok::kw___bridge_retain));
if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
if (!TryConsumeToken(tok::kw___bridge)) {
StringRef BridgeCastName = Tok.getName();
SourceLocation BridgeKeywordLoc = ConsumeToken();
if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
<< BridgeCastName
<< FixItHint::CreateReplacement(BridgeKeywordLoc, "");
}
BridgeCast = false;
}
// None of these cases should fall through with an invalid Result
// unless they've already reported an error.
if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
Diag(Tok, OpenLoc.isMacroID() ? diag::ext_gnu_statement_expr_macro
: diag::ext_gnu_statement_expr);
checkCompoundToken(OpenLoc, tok::l_paren, CompoundToken::StmtExprBegin);
if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
} else {
// Find the nearest non-record decl context. Variables declared in a
// statement expression behave as if they were declared in the enclosing
// function, block, or other code construct.
DeclContext *CodeDC = Actions.CurContext;
while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
CodeDC = CodeDC->getParent();
assert(CodeDC && !CodeDC->isFileContext() &&
"statement expr not in code context");
}
Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
Actions.ActOnStartStmtExpr();
StmtResult Stmt(ParseCompoundStatement(true));
ExprType = CompoundStmt;
// If the substmt parsed correctly, build the AST node.
if (!Stmt.isInvalid()) {
Result = Actions.ActOnStmtExpr(getCurScope(), OpenLoc, Stmt.get(),
Tok.getLocation());
} else {
Actions.ActOnStmtExprError();
}
}
} else if (ExprType >= CompoundLiteral && BridgeCast) {
tok::TokenKind tokenKind = Tok.getKind();
SourceLocation BridgeKeywordLoc = ConsumeToken();
// Parse an Objective-C ARC ownership cast expression.
ObjCBridgeCastKind Kind;
if (tokenKind == tok::kw___bridge)
Kind = OBC_Bridge;
else if (tokenKind == tok::kw___bridge_transfer)
Kind = OBC_BridgeTransfer;
else if (tokenKind == tok::kw___bridge_retained)
Kind = OBC_BridgeRetained;
else {
// As a hopefully temporary workaround, allow __bridge_retain as
// a synonym for __bridge_retained, but only in system headers.
assert(tokenKind == tok::kw___bridge_retain);
Kind = OBC_BridgeRetained;
if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
<< FixItHint::CreateReplacement(BridgeKeywordLoc,
"__bridge_retained");
}
TypeResult Ty = ParseTypeName();
T.consumeClose();
ColonProtection.restore();
RParenLoc = T.getCloseLocation();
PreferredType.enterTypeCast(Tok.getLocation(), Ty.get().get());
ExprResult SubExpr = ParseCastExpression(AnyCastExpr);
if (Ty.isInvalid() || SubExpr.isInvalid())
return ExprError();
return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
BridgeKeywordLoc, Ty.get(),
RParenLoc, SubExpr.get());
} else if (ExprType >= CompoundLiteral &&
isTypeIdInParens(isAmbiguousTypeId)) {
// Otherwise, this is a compound literal expression or cast expression.
// In C++, if the type-id is ambiguous we disambiguate based on context.
// If stopIfCastExpr is true the context is a typeof/sizeof/alignof
// in which case we should treat it as type-id.
// if stopIfCastExpr is false, we need to determine the context past the
// parens, so we defer to ParseCXXAmbiguousParenExpression for that.
if (isAmbiguousTypeId && !stopIfCastExpr) {
ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
ColonProtection);
RParenLoc = T.getCloseLocation();
return res;
}
// Parse the type declarator.
DeclSpec DS(AttrFactory);
ParseSpecifierQualifierList(DS);
Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
DeclaratorContext::TypeName);
ParseDeclarator(DeclaratorInfo);
// If our type is followed by an identifier and either ':' or ']', then
// this is probably an Objective-C message send where the leading '[' is
// missing. Recover as if that were the case.
if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
!InMessageExpression && getLangOpts().ObjC &&
(NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
TypeResult Ty;
{
InMessageExpressionRAIIObject InMessage(*this, false);
Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
}
Result = ParseObjCMessageExpressionBody(SourceLocation(),
SourceLocation(),
Ty.get(), nullptr);
} else {
// Match the ')'.
T.consumeClose();
ColonProtection.restore();
RParenLoc = T.getCloseLocation();
if (Tok.is(tok::l_brace)) {
ExprType = CompoundLiteral;
TypeResult Ty;
{
InMessageExpressionRAIIObject InMessage(*this, false);
Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
}
return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
}
if (Tok.is(tok::l_paren)) {
// This could be OpenCL vector Literals
if (getLangOpts().OpenCL)
{
TypeResult Ty;
{
InMessageExpressionRAIIObject InMessage(*this, false);
Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
}
if(Ty.isInvalid())
{
return ExprError();
}
QualType QT = Ty.get().get().getCanonicalType();
if (QT->isVectorType())
{
// We parsed '(' vector-type-name ')' followed by '('
// Parse the cast-expression that follows it next.
// isVectorLiteral = true will make sure we don't parse any
// Postfix expression yet
Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
/*isAddressOfOperand=*/false,
/*isTypeCast=*/IsTypeCast,
/*isVectorLiteral=*/true);
if (!Result.isInvalid()) {
Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
DeclaratorInfo, CastTy,
RParenLoc, Result.get());
}
// After we performed the cast we can check for postfix-expr pieces.
if (!Result.isInvalid()) {
Result = ParsePostfixExpressionSuffix(Result);
}
return Result;
}
}
}
if (ExprType == CastExpr) {
// We parsed '(' type-name ')' and the thing after it wasn't a '{'.
if (DeclaratorInfo.isInvalidType())
return ExprError();
// Note that this doesn't parse the subsequent cast-expression, it just
// returns the parsed type to the callee.
if (stopIfCastExpr) {
TypeResult Ty;
{
InMessageExpressionRAIIObject InMessage(*this, false);
Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
}
CastTy = Ty.get();
return ExprResult();
}
// Reject the cast of super idiom in ObjC.
if (Tok.is(tok::identifier) && getLangOpts().ObjC &&
Tok.getIdentifierInfo() == Ident_super &&
getCurScope()->isInObjcMethodScope() &&
GetLookAheadToken(1).isNot(tok::period)) {
Diag(Tok.getLocation(), diag::err_illegal_super_cast)
<< SourceRange(OpenLoc, RParenLoc);
return ExprError();
}
PreferredType.enterTypeCast(Tok.getLocation(), CastTy.get());
// Parse the cast-expression that follows it next.
// TODO: For cast expression with CastTy.
Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
/*isAddressOfOperand=*/false,
/*isTypeCast=*/IsTypeCast);
if (!Result.isInvalid()) {
Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
DeclaratorInfo, CastTy,
RParenLoc, Result.get());
}
return Result;
}
Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
return ExprError();
}
} else if (ExprType >= FoldExpr && Tok.is(tok::ellipsis) &&
isFoldOperator(NextToken().getKind())) {
ExprType = FoldExpr;
return ParseFoldExpression(ExprResult(), T);
} else if (isTypeCast) {
// Parse the expression-list.
InMessageExpressionRAIIObject InMessage(*this, false);
ExprVector ArgExprs;
if (!ParseSimpleExpressionList(ArgExprs)) {
// FIXME: If we ever support comma expressions as operands to
// fold-expressions, we'll need to allow multiple ArgExprs here.
if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) {
ExprType = FoldExpr;
return ParseFoldExpression(ArgExprs[0], T);
}
ExprType = SimpleExpr;
Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
ArgExprs);
}
} else if (getLangOpts().OpenMP >= 50 && OpenMPDirectiveParsing &&
ExprType == CastExpr && Tok.is(tok::l_square) &&
tryParseOpenMPArrayShapingCastPart()) {
bool ErrorFound = false;
SmallVector<Expr *, 4> OMPDimensions;
SmallVector<SourceRange, 4> OMPBracketsRanges;
do {
BalancedDelimiterTracker TS(*this, tok::l_square);
TS.consumeOpen();
ExprResult NumElements =
Actions.CorrectDelayedTyposInExpr(ParseExpression());
if (!NumElements.isUsable()) {
ErrorFound = true;
while (!SkipUntil(tok::r_square, tok::r_paren,
StopAtSemi | StopBeforeMatch))
;
}
TS.consumeClose();
OMPDimensions.push_back(NumElements.get());
OMPBracketsRanges.push_back(TS.getRange());
} while (Tok.isNot(tok::r_paren));
// Match the ')'.
T.consumeClose();
RParenLoc = T.getCloseLocation();
Result = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
if (ErrorFound) {
Result = ExprError();
} else if (!Result.isInvalid()) {
Result = Actions.ActOnOMPArrayShapingExpr(
Result.get(), OpenLoc, RParenLoc, OMPDimensions, OMPBracketsRanges);
}
return Result;
} else {
InMessageExpressionRAIIObject InMessage(*this, false);
Result = ParseExpression(MaybeTypeCast);
if (!getLangOpts().CPlusPlus && Result.isUsable()) {
// Correct typos in non-C++ code earlier so that implicit-cast-like
// expressions are parsed correctly.
Result = Actions.CorrectDelayedTyposInExpr(Result);
}
if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
NextToken().is(tok::ellipsis)) {
ExprType = FoldExpr;
return ParseFoldExpression(Result, T);
}
ExprType = SimpleExpr;
// Don't build a paren expression unless we actually match a ')'.
if (!Result.isInvalid() && Tok.is(tok::r_paren))
Result =
Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
}
// Match the ')'.
if (Result.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
T.consumeClose();
RParenLoc = T.getCloseLocation();
return Result;
}
/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
/// and we are at the left brace.
///
/// \verbatim
/// postfix-expression: [C99 6.5.2]
/// '(' type-name ')' '{' initializer-list '}'
/// '(' type-name ')' '{' initializer-list ',' '}'
/// \endverbatim
ExprResult
Parser::ParseCompoundLiteralExpression(ParsedType Ty,
SourceLocation LParenLoc,
SourceLocation RParenLoc) {
assert(Tok.is(tok::l_brace) && "Not a compound literal!");
if (!getLangOpts().C99) // Compound literals don't exist in C90.
Diag(LParenLoc, diag::ext_c99_compound_literal);
PreferredType.enterTypeCast(Tok.getLocation(), Ty.get());
ExprResult Result = ParseInitializer();
if (!Result.isInvalid() && Ty)
return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
return Result;
}
/// ParseStringLiteralExpression - This handles the various token types that
/// form string literals, and also handles string concatenation [C99 5.1.1.2,
/// translation phase #6].
///
/// \verbatim
/// primary-expression: [C99 6.5.1]
/// string-literal
/// \verbatim
ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
assert(isTokenStringLiteral() && "Not a string literal!");
// String concat. Note that keywords like __func__ and __FUNCTION__ are not
// considered to be strings for concatenation purposes.
SmallVector<Token, 4> StringToks;
do {
StringToks.push_back(Tok);
ConsumeStringToken();
} while (isTokenStringLiteral());
// Pass the set of string tokens, ready for concatenation, to the actions.
return Actions.ActOnStringLiteral(StringToks,
AllowUserDefinedLiteral ? getCurScope()
: nullptr);
}
/// ParseGenericSelectionExpression - Parse a C11 generic-selection
/// [C11 6.5.1.1].
///
/// \verbatim
/// generic-selection:
/// _Generic ( assignment-expression , generic-assoc-list )
/// generic-assoc-list:
/// generic-association
/// generic-assoc-list , generic-association
/// generic-association:
/// type-name : assignment-expression
/// default : assignment-expression
/// \endverbatim
ExprResult Parser::ParseGenericSelectionExpression() {
assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
if (!getLangOpts().C11)
Diag(Tok, diag::ext_c11_feature) << Tok.getName();
SourceLocation KeyLoc = ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.expectAndConsume())
return ExprError();
ExprResult ControllingExpr;
{
// C11 6.5.1.1p3 "The controlling expression of a generic selection is
// not evaluated."
EnterExpressionEvaluationContext Unevaluated(
Actions, Sema::ExpressionEvaluationContext::Unevaluated);
ControllingExpr =
Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
if (ControllingExpr.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
}
if (ExpectAndConsume(tok::comma)) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
SourceLocation DefaultLoc;
SmallVector<ParsedType, 12> Types;
ExprVector Exprs;
do {
ParsedType Ty;
if (Tok.is(tok::kw_default)) {
// C11 6.5.1.1p2 "A generic selection shall have no more than one default
// generic association."
if (!DefaultLoc.isInvalid()) {
Diag(Tok, diag::err_duplicate_default_assoc);
Diag(DefaultLoc, diag::note_previous_default_assoc);
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
DefaultLoc = ConsumeToken();
Ty = nullptr;
} else {
ColonProtectionRAIIObject X(*this);
TypeResult TR = ParseTypeName(nullptr, DeclaratorContext::Association);
if (TR.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
Ty = TR.get();
}
Types.push_back(Ty);
if (ExpectAndConsume(tok::colon)) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
// FIXME: These expressions should be parsed in a potentially potentially
// evaluated context.
ExprResult ER(
Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
if (ER.isInvalid()) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
Exprs.push_back(ER.get());
} while (TryConsumeToken(tok::comma));
T.consumeClose();
if (T.getCloseLocation().isInvalid())
return ExprError();
return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
T.getCloseLocation(),
ControllingExpr.get(),
Types, Exprs);
}
/// Parse A C++1z fold-expression after the opening paren and optional
/// left-hand-side expression.
///
/// \verbatim
/// fold-expression:
/// ( cast-expression fold-operator ... )
/// ( ... fold-operator cast-expression )
/// ( cast-expression fold-operator ... fold-operator cast-expression )
ExprResult Parser::ParseFoldExpression(ExprResult LHS,
BalancedDelimiterTracker &T) {
if (LHS.isInvalid()) {
T.skipToEnd();
return true;
}
tok::TokenKind Kind = tok::unknown;
SourceLocation FirstOpLoc;
if (LHS.isUsable()) {
Kind = Tok.getKind();
assert(isFoldOperator(Kind) && "missing fold-operator");
FirstOpLoc = ConsumeToken();
}
assert(Tok.is(tok::ellipsis) && "not a fold-expression");
SourceLocation EllipsisLoc = ConsumeToken();
ExprResult RHS;
if (Tok.isNot(tok::r_paren)) {
if (!isFoldOperator(Tok.getKind()))
return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
if (Kind != tok::unknown && Tok.getKind() != Kind)
Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
<< SourceRange(FirstOpLoc);
Kind = Tok.getKind();
ConsumeToken();
RHS = ParseExpression();
if (RHS.isInvalid()) {
T.skipToEnd();
return true;
}
}
Diag(EllipsisLoc, getLangOpts().CPlusPlus17
? diag::warn_cxx14_compat_fold_expression
: diag::ext_fold_expression);
T.consumeClose();
return Actions.ActOnCXXFoldExpr(getCurScope(), T.getOpenLocation(), LHS.get(),
Kind, EllipsisLoc, RHS.get(),
T.getCloseLocation());
}
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
///
/// \verbatim
/// argument-expression-list:
/// assignment-expression
/// argument-expression-list , assignment-expression
///
/// [C++] expression-list:
/// [C++] assignment-expression
/// [C++] expression-list , assignment-expression
///
/// [C++0x] expression-list:
/// [C++0x] initializer-list
///
/// [C++0x] initializer-list
/// [C++0x] initializer-clause ...[opt]
/// [C++0x] initializer-list , initializer-clause ...[opt]
///
/// [C++0x] initializer-clause:
/// [C++0x] assignment-expression
/// [C++0x] braced-init-list
/// \endverbatim
bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
llvm::function_ref<void()> ExpressionStarts,
bool FailImmediatelyOnInvalidExpr,
bool EarlyTypoCorrection) {
bool SawError = false;
while (true) {
if (ExpressionStarts)
ExpressionStarts();
ExprResult Expr;
if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
Expr = ParseBraceInitializer();
} else
Expr = ParseAssignmentExpression();
if (EarlyTypoCorrection)
Expr = Actions.CorrectDelayedTyposInExpr(Expr);
if (Tok.is(tok::ellipsis))
Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
else if (Tok.is(tok::code_completion)) {
// There's nothing to suggest in here as we parsed a full expression.
// Instead fail and propogate the error since caller might have something
// the suggest, e.g. signature help in function call. Note that this is
// performed before pushing the \p Expr, so that signature help can report
// current argument correctly.
SawError = true;
cutOffParsing();
break;
}
if (Expr.isInvalid()) {
SawError = true;
if (FailImmediatelyOnInvalidExpr)
break;
SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
} else {
Exprs.push_back(Expr.get());
}
if (Tok.isNot(tok::comma))
break;
// Move to the next argument, remember where the comma was.
Token Comma = Tok;
ConsumeToken();
checkPotentialAngleBracketDelimiter(Comma);
}
if (SawError) {
// Ensure typos get diagnosed when errors were encountered while parsing the
// expression list.
for (auto &E : Exprs) {
ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
if (Expr.isUsable()) E = Expr.get();
}
}
return SawError;
}
/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
/// used for misc language extensions.
///
/// \verbatim
/// simple-expression-list:
/// assignment-expression
/// simple-expression-list , assignment-expression
/// \endverbatim
bool Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs) {
while (true) {
ExprResult Expr = ParseAssignmentExpression();
if (Expr.isInvalid())
return true;
Exprs.push_back(Expr.get());
// We might be parsing the LHS of a fold-expression. If we reached the fold
// operator, stop.
if (Tok.isNot(tok::comma) || NextToken().is(tok::ellipsis))
return false;
// Move to the next argument, remember where the comma was.
Token Comma = Tok;
ConsumeToken();
checkPotentialAngleBracketDelimiter(Comma);
}
}
/// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
///
/// \verbatim
/// [clang] block-id:
/// [clang] specifier-qualifier-list block-declarator
/// \endverbatim
void Parser::ParseBlockId(SourceLocation CaretLoc) {
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
return;
}
// Parse the specifier-qualifier-list piece.
DeclSpec DS(AttrFactory);
ParseSpecifierQualifierList(DS);
// Parse the block-declarator.
Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
DeclaratorContext::BlockLiteral);
DeclaratorInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
ParseDeclarator(DeclaratorInfo);
MaybeParseGNUAttributes(DeclaratorInfo);
// Inform sema that we are starting a block.
Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
}
/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
/// like ^(int x){ return x+1; }
///
/// \verbatim
/// block-literal:
/// [clang] '^' block-args[opt] compound-statement
/// [clang] '^' block-id compound-statement
/// [clang] block-args:
/// [clang] '(' parameter-list ')'
/// \endverbatim
ExprResult Parser::ParseBlockLiteralExpression() {
assert(Tok.is(tok::caret) && "block literal starts with ^");
SourceLocation CaretLoc = ConsumeToken();
PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
"block literal parsing");
// Enter a scope to hold everything within the block. This includes the
// argument decls, decls within the compound expression, etc. This also
// allows determining whether a variable reference inside the block is
// within or outside of the block.
ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
Scope::CompoundStmtScope | Scope::DeclScope);
// Inform sema that we are starting a block.
Actions.ActOnBlockStart(CaretLoc, getCurScope());
// Parse the return type if present.
DeclSpec DS(AttrFactory);
Declarator ParamInfo(DS, ParsedAttributesView::none(),
DeclaratorContext::BlockLiteral);
ParamInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
// FIXME: Since the return type isn't actually parsed, it can't be used to
// fill ParamInfo with an initial valid range, so do it manually.
ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
// If this block has arguments, parse them. There is no ambiguity here with
// the expression case, because the expression case requires a parameter list.
if (Tok.is(tok::l_paren)) {
ParseParenDeclarator(ParamInfo);
// Parse the pieces after the identifier as if we had "int(...)".
// SetIdentifier sets the source range end, but in this case we're past
// that location.
SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
ParamInfo.SetIdentifier(nullptr, CaretLoc);
ParamInfo.SetRangeEnd(Tmp);
if (ParamInfo.isInvalidType()) {
// If there was an error parsing the arguments, they may have
// tried to use ^(x+y) which requires an argument list. Just
// skip the whole block literal.
Actions.ActOnBlockError(CaretLoc, getCurScope());
return ExprError();
}
MaybeParseGNUAttributes(ParamInfo);
// Inform sema that we are starting a block.
Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
} else if (!Tok.is(tok::l_brace)) {
ParseBlockId(CaretLoc);
} else {
// Otherwise, pretend we saw (void).
SourceLocation NoLoc;
ParamInfo.AddTypeInfo(
DeclaratorChunk::getFunction(/*HasProto=*/true,
/*IsAmbiguous=*/false,
/*RParenLoc=*/NoLoc,
/*ArgInfo=*/nullptr,
/*NumParams=*/0,
/*EllipsisLoc=*/NoLoc,
/*RParenLoc=*/NoLoc,
/*RefQualifierIsLvalueRef=*/true,
/*RefQualifierLoc=*/NoLoc,
/*MutableLoc=*/NoLoc, EST_None,
/*ESpecRange=*/SourceRange(),
/*Exceptions=*/nullptr,
/*ExceptionRanges=*/nullptr,
/*NumExceptions=*/0,
/*NoexceptExpr=*/nullptr,
/*ExceptionSpecTokens=*/nullptr,
/*DeclsInPrototype=*/std::nullopt,
CaretLoc, CaretLoc, ParamInfo),
CaretLoc);
MaybeParseGNUAttributes(ParamInfo);
// Inform sema that we are starting a block.
Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
}
ExprResult Result(true);
if (!Tok.is(tok::l_brace)) {
// Saw something like: ^expr
Diag(Tok, diag::err_expected_expression);
Actions.ActOnBlockError(CaretLoc, getCurScope());
return ExprError();
}
StmtResult Stmt(ParseCompoundStatementBody());
BlockScope.Exit();
if (!Stmt.isInvalid())
Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
else
Actions.ActOnBlockError(CaretLoc, getCurScope());
return Result;
}
/// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
///
/// '__objc_yes'
/// '__objc_no'
ExprResult Parser::ParseObjCBoolLiteral() {
tok::TokenKind Kind = Tok.getKind();
return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
}
/// Validate availability spec list, emitting diagnostics if necessary. Returns
/// true if invalid.
static bool CheckAvailabilitySpecList(Parser &P,
ArrayRef<AvailabilitySpec> AvailSpecs) {
llvm::SmallSet<StringRef, 4> Platforms;
bool HasOtherPlatformSpec = false;
bool Valid = true;
for (const auto &Spec : AvailSpecs) {
if (Spec.isOtherPlatformSpec()) {
if (HasOtherPlatformSpec) {
P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
Valid = false;
}
HasOtherPlatformSpec = true;
continue;
}
bool Inserted = Platforms.insert(Spec.getPlatform()).second;
if (!Inserted) {
// Rule out multiple version specs referring to the same platform.
// For example, we emit an error for:
// @available(macos 10.10, macos 10.11, *)
StringRef Platform = Spec.getPlatform();
P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
<< Spec.getEndLoc() << Platform;
Valid = false;
}
}
if (!HasOtherPlatformSpec) {
SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
<< FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
return true;
}
return !Valid;
}
/// Parse availability query specification.
///
/// availability-spec:
/// '*'
/// identifier version-tuple
std::optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
if (Tok.is(tok::star)) {
return AvailabilitySpec(ConsumeToken());
} else {
// Parse the platform name.
if (Tok.is(tok::code_completion)) {
cutOffParsing();
Actions.CodeCompleteAvailabilityPlatformName();
return std::nullopt;
}
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_avail_query_expected_platform_name);
return std::nullopt;
}
IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
SourceRange VersionRange;
VersionTuple Version = ParseVersionTuple(VersionRange);
if (Version.empty())
return std::nullopt;
StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
StringRef Platform =
AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
Diag(PlatformIdentifier->Loc,
diag::err_avail_query_unrecognized_platform_name)
<< GivenPlatform;
return std::nullopt;
}
return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
VersionRange.getEnd());
}
}
ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
assert(Tok.is(tok::kw___builtin_available) ||
Tok.isObjCAtKeyword(tok::objc_available));
// Eat the available or __builtin_available.
ConsumeToken();
BalancedDelimiterTracker Parens(*this, tok::l_paren);
if (Parens.expectAndConsume())
return ExprError();
SmallVector<AvailabilitySpec, 4> AvailSpecs;
bool HasError = false;
while (true) {
std::optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
if (!Spec)
HasError = true;
else
AvailSpecs.push_back(*Spec);
if (!TryConsumeToken(tok::comma))
break;
}
if (HasError) {
SkipUntil(tok::r_paren, StopAtSemi);
return ExprError();
}
CheckAvailabilitySpecList(*this, AvailSpecs);
if (Parens.consumeClose())
return ExprError();
return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
Parens.getCloseLocation());
}
|