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
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
|
/**
* Copyright (C) 2019-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kQuery
#include "mongo/platform/basic.h"
#include "mongo/db/exec/sbe/expressions/expression.h"
#include "mongo/db/exec/sbe/vm/vm.h"
#include <boost/algorithm/string.hpp>
#include <pcre.h>
#include "mongo/bson/oid.h"
#include "mongo/db/client.h"
#include "mongo/db/exec/js_function.h"
#include "mongo/db/exec/sbe/values/bson.h"
#include "mongo/db/exec/sbe/values/sbe_pattern_value_cmp.h"
#include "mongo/db/exec/sbe/values/sort_spec.h"
#include "mongo/db/exec/sbe/values/value.h"
#include "mongo/db/exec/sbe/vm/datetime.h"
#include "mongo/db/hasher.h"
#include "mongo/db/index/btree_key_generator.h"
#include "mongo/db/query/collation/collation_index_key.h"
#include "mongo/db/query/datetime/date_time_support.h"
#include "mongo/db/query/query_knobs_gen.h"
#include "mongo/db/storage/key_string.h"
#include "mongo/logv2/log.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/str.h"
#include "mongo/util/summation.h"
MONGO_FAIL_POINT_DEFINE(failOnPoisonedFieldLookup);
namespace mongo {
namespace sbe {
namespace vm {
/*
* This table must be kept in sync with Instruction::Tags. It encodes how the instruction affects
* the stack; i.e. push(+1), pop(-1), or no effect.
*/
int Instruction::stackOffset[Instruction::Tags::lastInstruction] = {
1, // pushConstVal
1, // pushAccessVal
1, // pushMoveVal
1, // pushLocalVal
1, // pushMoveLocalVal
1, // pushLocalLambda
-1, // pop
0, // swap
-1, // add
-1, // sub
-1, // mul
-1, // div
-1, // idiv
-1, // mod
0, // negate
0, // numConvert
0, // logicNot
-1, // less
-1, // lessEq
-1, // greater
-1, // greaterEq
-1, // eq
-1, // neq
-1, // cmp3w
-2, // collLess
-2, // collLessEq
-2, // collGreater
-2, // collGreaterEq
-2, // collEq
-2, // collNeq
-2, // collCmp3w
-1, // fillEmpty
-1, // getField
-1, // getElement
-1, // collComparisonKey
-1, // getFieldOrElement
-1, // traverseP
-2, // traverseF
-2, // setField
0, // getArraySize
-1, // aggSum
-1, // aggMin
-1, // aggMax
-1, // aggFirst
-1, // aggLast
-1, // aggCollMin
-1, // aggCollMax
0, // exists
0, // isNull
0, // isObject
0, // isArray
0, // isString
0, // isNumber
0, // isBinData
0, // isDate
0, // isNaN
0, // isInfinity
0, // isRecordId
0, // isMinKey
0, // isMaxKey
0, // isTimestamp
0, // typeMatch
0, // function is special, the stack offset is encoded in the instruction itself
0, // functionSmall is special, the stack offset is encoded in the instruction itself
0, // jmp
-1, // jmpTrue
0, // jmpNothing
0, // ret
-1, // fail
};
namespace {
template <typename T>
T readFromMemory(const uint8_t* ptr) noexcept {
static_assert(!IsEndian<T>::value);
T val;
memcpy(&val, ptr, sizeof(T));
return val;
}
template <typename T>
size_t writeToMemory(uint8_t* ptr, const T val) noexcept {
static_assert(!IsEndian<T>::value);
memcpy(ptr, &val, sizeof(T));
return sizeof(T);
}
} // namespace
void CodeFragment::adjustStackSimple(const Instruction& i) {
_stackSize += Instruction::stackOffset[i.tag];
}
void CodeFragment::fixup(int offset) {
for (auto fixUp : _fixUps) {
auto ptr = instrs().data() + fixUp.offset;
int newOffset = readFromMemory<int>(ptr) + offset;
writeToMemory(ptr, newOffset);
}
}
void CodeFragment::removeFixup(FrameId frameId) {
_fixUps.erase(std::remove_if(_fixUps.begin(),
_fixUps.end(),
[frameId](const auto& f) { return f.frameId == frameId; }),
_fixUps.end());
}
void CodeFragment::copyCodeAndFixup(CodeFragment&& from) {
for (auto fixUp : from._fixUps) {
fixUp.offset += _instrs.size();
_fixUps.push_back(fixUp);
}
if (_instrs.empty()) {
_instrs = std::move(from._instrs);
} else {
_instrs.insert(_instrs.end(), from._instrs.begin(), from._instrs.end());
}
}
void CodeFragment::append(CodeFragment&& code) {
// Fixup before copying.
code.fixup(_stackSize);
_stackSize += code._stackSize;
copyCodeAndFixup(std::move(code));
}
void CodeFragment::appendNoStack(CodeFragment&& code) {
invariant(code._fixUps.empty());
copyCodeAndFixup(std::move(code));
}
void CodeFragment::append(CodeFragment&& lhs, CodeFragment&& rhs) {
invariant(lhs.stackSize() == rhs.stackSize());
// Fixup before copying.
lhs.fixup(_stackSize);
rhs.fixup(_stackSize);
_stackSize += lhs._stackSize;
copyCodeAndFixup(std::move(lhs));
copyCodeAndFixup(std::move(rhs));
}
void CodeFragment::appendConstVal(value::TypeTags tag, value::Value val) {
Instruction i;
i.tag = Instruction::pushConstVal;
adjustStackSimple(i);
auto offset = allocateSpace(sizeof(Instruction) + sizeof(tag) + sizeof(val));
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, tag);
offset += writeToMemory(offset, val);
}
void CodeFragment::appendAccessVal(value::SlotAccessor* accessor) {
Instruction i;
i.tag = Instruction::pushAccessVal;
adjustStackSimple(i);
auto offset = allocateSpace(sizeof(Instruction) + sizeof(accessor));
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, accessor);
}
void CodeFragment::appendMoveVal(value::SlotAccessor* accessor) {
Instruction i;
i.tag = Instruction::pushMoveVal;
adjustStackSimple(i);
auto offset = allocateSpace(sizeof(Instruction) + sizeof(accessor));
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, accessor);
}
void CodeFragment::appendLocalVal(FrameId frameId, int stackOffset, bool moveFrom) {
Instruction i;
i.tag = moveFrom ? Instruction::pushMoveLocalVal : Instruction::pushLocalVal;
adjustStackSimple(i);
auto fixUpOffset = _instrs.size() + sizeof(Instruction);
_fixUps.push_back(FixUp{frameId, fixUpOffset});
auto offset = allocateSpace(sizeof(Instruction) + sizeof(stackOffset));
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, stackOffset);
}
void CodeFragment::appendLocalLambda(int codePosition) {
Instruction i;
i.tag = Instruction::pushLocalLambda;
adjustStackSimple(i);
auto size = sizeof(Instruction) + sizeof(codePosition);
auto offset = allocateSpace(size);
int codeOffset = codePosition - _instrs.size();
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, codeOffset);
}
void CodeFragment::appendAdd() {
appendSimpleInstruction(Instruction::add);
}
void CodeFragment::appendNumericConvert(value::TypeTags targetTag) {
Instruction i;
i.tag = Instruction::numConvert;
adjustStackSimple(i);
auto offset = allocateSpace(sizeof(Instruction) + sizeof(targetTag));
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, targetTag);
}
void CodeFragment::appendSub() {
appendSimpleInstruction(Instruction::sub);
}
void CodeFragment::appendMul() {
appendSimpleInstruction(Instruction::mul);
}
void CodeFragment::appendDiv() {
appendSimpleInstruction(Instruction::div);
}
void CodeFragment::appendIDiv() {
appendSimpleInstruction(Instruction::idiv);
}
void CodeFragment::appendMod() {
appendSimpleInstruction(Instruction::mod);
}
void CodeFragment::appendNegate() {
appendSimpleInstruction(Instruction::negate);
}
void CodeFragment::appendNot() {
appendSimpleInstruction(Instruction::logicNot);
}
void CodeFragment::appendSimpleInstruction(Instruction::Tags tag) {
Instruction i;
i.tag = tag;
adjustStackSimple(i);
auto offset = allocateSpace(sizeof(Instruction));
offset += writeToMemory(offset, i);
}
void CodeFragment::appendGetField() {
appendSimpleInstruction(Instruction::getField);
}
void CodeFragment::appendGetElement() {
appendSimpleInstruction(Instruction::getElement);
}
void CodeFragment::appendCollComparisonKey() {
appendSimpleInstruction(Instruction::collComparisonKey);
}
void CodeFragment::appendGetFieldOrElement() {
appendSimpleInstruction(Instruction::getFieldOrElement);
}
void CodeFragment::appendGetArraySize() {
appendSimpleInstruction(Instruction::getArraySize);
}
void CodeFragment::appendSum() {
appendSimpleInstruction(Instruction::aggSum);
}
void CodeFragment::appendMin() {
appendSimpleInstruction(Instruction::aggMin);
}
void CodeFragment::appendMax() {
appendSimpleInstruction(Instruction::aggMax);
}
void CodeFragment::appendFirst() {
appendSimpleInstruction(Instruction::aggFirst);
}
void CodeFragment::appendLast() {
appendSimpleInstruction(Instruction::aggLast);
}
void CodeFragment::appendCollMin() {
appendSimpleInstruction(Instruction::aggCollMin);
}
void CodeFragment::appendCollMax() {
appendSimpleInstruction(Instruction::aggCollMax);
}
void CodeFragment::appendExists() {
appendSimpleInstruction(Instruction::exists);
}
void CodeFragment::appendIsNull() {
appendSimpleInstruction(Instruction::isNull);
}
void CodeFragment::appendIsObject() {
appendSimpleInstruction(Instruction::isObject);
}
void CodeFragment::appendIsArray() {
appendSimpleInstruction(Instruction::isArray);
}
void CodeFragment::appendIsString() {
appendSimpleInstruction(Instruction::isString);
}
void CodeFragment::appendIsNumber() {
appendSimpleInstruction(Instruction::isNumber);
}
void CodeFragment::appendIsBinData() {
appendSimpleInstruction(Instruction::isBinData);
}
void CodeFragment::appendIsDate() {
appendSimpleInstruction(Instruction::isDate);
}
void CodeFragment::appendIsNaN() {
appendSimpleInstruction(Instruction::isNaN);
}
void CodeFragment::appendIsInfinity() {
appendSimpleInstruction(Instruction::isInfinity);
}
void CodeFragment::appendIsRecordId() {
appendSimpleInstruction(Instruction::isRecordId);
}
void CodeFragment::appendTypeMatch(uint32_t typeMask) {
Instruction i;
i.tag = Instruction::typeMatch;
adjustStackSimple(i);
auto offset = allocateSpace(sizeof(Instruction) + sizeof(typeMask));
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, typeMask);
}
void CodeFragment::appendFunction(Builtin f, ArityType arity) {
Instruction i;
const bool isSmallArity = (arity <= std::numeric_limits<SmallArityType>::max());
i.tag = isSmallArity ? Instruction::functionSmall : Instruction::function;
// Account for consumed arguments
_stackSize -= arity;
// and the return value.
_stackSize += 1;
auto offset = allocateSpace(sizeof(Instruction) + sizeof(f) +
(isSmallArity ? sizeof(SmallArityType) : sizeof(ArityType)));
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, f);
offset += isSmallArity ? writeToMemory(offset, static_cast<SmallArityType>(arity))
: writeToMemory(offset, arity);
}
void CodeFragment::appendJump(int jumpOffset) {
Instruction i;
i.tag = Instruction::jmp;
adjustStackSimple(i);
auto offset = allocateSpace(sizeof(Instruction) + sizeof(jumpOffset));
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, jumpOffset);
}
void CodeFragment::appendJumpTrue(int jumpOffset) {
Instruction i;
i.tag = Instruction::jmpTrue;
adjustStackSimple(i);
auto offset = allocateSpace(sizeof(Instruction) + sizeof(jumpOffset));
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, jumpOffset);
}
void CodeFragment::appendJumpNothing(int jumpOffset) {
Instruction i;
i.tag = Instruction::jmpNothing;
adjustStackSimple(i);
auto offset = allocateSpace(sizeof(Instruction) + sizeof(jumpOffset));
offset += writeToMemory(offset, i);
offset += writeToMemory(offset, jumpOffset);
}
void ByteCode::Stack::growAndResize(size_t newSize) {
auto currentCapacity = capacity();
if (newSize <= currentCapacity) {
_size = newSize;
return;
}
auto newCapacity = newSize;
if (newCapacity > kMaxCapacity) {
uasserted(6040901,
str::stream() << "Requested capacity of " << newCapacity
<< " elements exceeds the maximum capacity of " << kMaxCapacity);
return;
}
if (currentCapacity >= kMaxCapacity / 2) {
newCapacity = kMaxCapacity;
} else if (2 * currentCapacity > newCapacity) {
newCapacity = 2 * currentCapacity;
}
try {
auto numSegments = (_size + ElementsPerSegment - 1) / ElementsPerSegment;
auto numNewSegments = (newCapacity + ElementsPerSegment - 1) / ElementsPerSegment;
newCapacity = numNewSegments * ElementsPerSegment;
auto newSegments = std::make_unique<StackSegment[]>(numNewSegments);
if (_segments.get() != nullptr && numSegments > 0) {
memcpy(newSegments.get(), _segments.get(), numSegments * sizeof(StackSegment));
}
_segments = std::move(newSegments);
_capacity = newCapacity;
_size = newSize;
} catch (std::bad_alloc&) {
uasserted(6040902,
str::stream() << "Unable to allocate requested capacity of " << newCapacity
<< " elements");
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::getField(value::TypeTags objTag,
value::Value objValue,
value::TypeTags fieldTag,
value::Value fieldValue) {
if (!value::isString(fieldTag)) {
return {false, value::TypeTags::Nothing, 0};
}
auto fieldStr = value::getStringView(fieldTag, fieldValue);
if (MONGO_unlikely(failOnPoisonedFieldLookup.shouldFail())) {
uassert(4623399, "Lookup of $POISON", fieldStr != "POISON");
}
if (objTag == value::TypeTags::Object) {
auto [tag, val] = value::getObjectView(objValue)->getField(fieldStr);
return {false, tag, val};
} else if (objTag == value::TypeTags::bsonObject) {
auto be = value::bitcastTo<const char*>(objValue);
auto end = be + ConstDataView(be).read<LittleEndian<uint32_t>>();
// Skip document length.
be += 4;
while (*be != 0) {
auto sv = bson::fieldNameView(be);
if (sv == fieldStr) {
auto [tag, val] = bson::convertFrom<true>(be, end, sv.size());
return {false, tag, val};
}
be = bson::advance(be, sv.size());
}
}
return {false, value::TypeTags::Nothing, 0};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::getElement(value::TypeTags arrTag,
value::Value arrValue,
value::TypeTags idxTag,
value::Value idxValue) {
// We need to ensure that 'size_t' is wide enough to store 32-bit index.
static_assert(sizeof(size_t) >= sizeof(int32_t), "size_t must be at least 32-bits");
if (!value::isArray(arrTag)) {
return {false, value::TypeTags::Nothing, 0};
}
if (idxTag != value::TypeTags::NumberInt32) {
return {false, value::TypeTags::Nothing, 0};
}
const auto idxInt32 = value::bitcastTo<int32_t>(idxValue);
const bool isNegative = idxInt32 < 0;
size_t idx = 0;
if (isNegative) {
// Upcast 'idxInt32' to 'int64_t' prevent overflow during the sign change.
idx = static_cast<size_t>(-static_cast<int64_t>(idxInt32));
} else {
idx = static_cast<size_t>(idxInt32);
}
if (arrTag == value::TypeTags::Array) {
// If 'arr' is an SBE array, use Array::getAt() to retrieve the element at index 'idx'.
auto arrayView = value::getArrayView(arrValue);
size_t convertedIdx = idx;
if (isNegative) {
if (idx > arrayView->size()) {
return {false, value::TypeTags::Nothing, 0};
}
convertedIdx = arrayView->size() - idx;
}
auto [tag, val] = value::getArrayView(arrValue)->getAt(convertedIdx);
return {false, tag, val};
} else if (arrTag == value::TypeTags::bsonArray || arrTag == value::TypeTags::ArraySet) {
value::ArrayEnumerator enumerator(arrTag, arrValue);
if (!isNegative) {
// Loop through array until we meet element at position 'idx'.
size_t i = 0;
while (i < idx && !enumerator.atEnd()) {
i++;
enumerator.advance();
}
// If the array didn't have an element at index 'idx', return Nothing.
if (enumerator.atEnd()) {
return {false, value::TypeTags::Nothing, 0};
}
auto [tag, val] = enumerator.getViewOfValue();
return {false, tag, val};
}
// For negative indexes we use two pointers approach. We start two array enumerators at the
// distance of 'idx' and move them at the same time. Once one of the enumerators reaches the
// end of the array, the second one points to the element at position '-idx'.
//
// First, move one of the enumerators 'idx' elements forward.
size_t i = 0;
while (i < idx && !enumerator.atEnd()) {
enumerator.advance();
i++;
}
if (i != idx) {
// Array is too small to have an element at the requested index.
return {false, value::TypeTags::Nothing, 0};
}
// Initiate second enumerator at the start of the array. Now the distance between
// 'enumerator' and 'windowEndEnumerator' is exactly 'idx' elements. Move both enumerators
// until the first one reaches the end of the array.
value::ArrayEnumerator windowEndEnumerator(arrTag, arrValue);
while (!enumerator.atEnd() && !windowEndEnumerator.atEnd()) {
enumerator.advance();
windowEndEnumerator.advance();
}
invariant(enumerator.atEnd());
invariant(!windowEndEnumerator.atEnd());
auto [tag, val] = windowEndEnumerator.getViewOfValue();
return {false, tag, val};
} else {
// Earlier in this function we bailed out if the 'arrTag' wasn't Array, ArraySet or
// bsonArray, so it should be impossible to reach this point.
MONGO_UNREACHABLE
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::getFieldOrElement(
value::TypeTags objTag,
value::Value objValue,
value::TypeTags fieldTag,
value::Value fieldValue) {
// If this is an array and we can convert the "field name" to a reasonable number then treat
// this as getElement call.
if (value::isArray(objTag) && value::isString(fieldTag)) {
int idx;
auto status = NumberParser{}(value::getStringView(fieldTag, fieldValue), &idx);
if (!status.isOK()) {
return {false, value::TypeTags::Nothing, 0};
}
return getElement(
objTag, objValue, value::TypeTags::NumberInt32, value::bitcastFrom<int>(idx));
} else {
return getField(objTag, objValue, fieldTag, fieldValue);
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::traverseP(const CodeFragment* code) {
// Traverse a projection path - evaluate the input lambda on every element of the input array.
// The traversal is recursive; i.e. we visit nested arrays if any.
auto [lamOwn, lamTag, lamVal] = getFromStack(0);
auto [own, tag, val] = getFromStack(1);
if (lamTag != value::TypeTags::LocalLambda) {
return {false, value::TypeTags::Nothing, 0};
}
int64_t lamPos = value::bitcastTo<int64_t>(lamVal);
if (value::isArray(tag)) {
return traverseP_nested(code, lamPos, tag, val);
} else {
// Transfer the ownership to the lambda
setStack(1, false, value::TypeTags::Nothing, 0);
pushStack(own, tag, val);
return runLambdaInternal(code, lamPos);
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::traverseP_nested(const CodeFragment* code,
int64_t position,
value::TypeTags tagInput,
value::Value valInput) {
if (value::isArray(tagInput)) {
auto [tagArrOutput, valArrOutput] = value::makeNewArray();
auto arrOutput = value::getArrayView(valArrOutput);
value::ValueGuard guard{tagInput, valArrOutput};
for (value::ArrayEnumerator enumerator(tagInput, valInput); !enumerator.atEnd();
enumerator.advance()) {
auto [elemTag, elemVal] = enumerator.getViewOfValue();
auto [retOwn, retTag, retVal] = traverseP_nested(code, position, elemTag, elemVal);
if (!retOwn) {
auto [copyTag, copyVal] = value::copyValue(retTag, retVal);
retTag = copyTag;
retVal = copyVal;
}
arrOutput->push_back(retTag, retVal);
}
guard.reset();
return {true, tagArrOutput, valArrOutput};
} else {
pushStack(false, tagInput, valInput);
return runLambdaInternal(code, position);
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::traverseF(const CodeFragment* code) {
// Traverse a filter path - evaluate the input lambda (predicate) on every element of the input
// array without resursion.
auto [lamOwn, lamTag, lamVal] = getFromStack(1);
auto [ownInput, tagInput, valInput] = getFromStack(2);
auto [numberOwn, numberTag, numberVal] = getFromStack(0);
if (lamTag != value::TypeTags::LocalLambda) {
return {false, value::TypeTags::Nothing, 0};
}
int64_t lamPos = value::bitcastTo<int64_t>(lamVal);
if (value::isArray(tagInput)) {
// Return true if any of the array elements is true.
for (value::ArrayEnumerator enumerator(tagInput, valInput); !enumerator.atEnd();
enumerator.advance()) {
auto [elemTag, elemVal] = enumerator.getViewOfValue();
pushStack(false, elemTag, elemVal);
auto [retOwn, retTag, retVal] = runLambdaInternal(code, lamPos);
bool isTrue = (retTag == value::TypeTags::Boolean) && value::bitcastTo<bool>(retVal);
if (retOwn) {
value::releaseValue(retTag, retVal);
}
if (isTrue) {
return {false, value::TypeTags::Boolean, value::bitcastFrom<bool>(true)};
}
}
// If this is a filter over a number path then run over the whole array. More details in
// SERVER-27442.
if (numberTag == value::TypeTags::Boolean && value::bitcastTo<bool>(numberVal)) {
// Transfer the ownership to the lambda
setStack(2, false, value::TypeTags::Nothing, 0);
pushStack(ownInput, tagInput, valInput);
return runLambdaInternal(code, lamPos);
}
return {false, value::TypeTags::Boolean, value::bitcastFrom<bool>(false)};
} else {
// Transfer the ownership to the lambda
setStack(2, false, value::TypeTags::Nothing, 0);
pushStack(ownInput, tagInput, valInput);
return runLambdaInternal(code, lamPos);
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::setField() {
auto [newOwn, newTag, newVal] = moveFromStack(0);
auto [fieldOwn, fieldTag, fieldVal] = getFromStack(1);
// Consider using a moveFromStack optimization.
auto [objOwn, objTag, objVal] = getFromStack(2);
if (!value::isString(fieldTag)) {
return {false, value::TypeTags::Nothing, 0};
}
auto fieldName = value::getStringView(fieldTag, fieldVal);
if (newTag == value::TypeTags::Nothing) {
// Setting a field value to nothing means removing the field.
if (value::isObject(objTag)) {
auto [tagOutput, valOutput] = value::makeNewObject();
auto objOutput = value::getObjectView(valOutput);
value::ValueGuard guard{tagOutput, valOutput};
if (objTag == value::TypeTags::bsonObject) {
auto be = value::bitcastTo<const char*>(objVal);
auto end = be + ConstDataView(be).read<LittleEndian<uint32_t>>();
// Skip document length.
be += 4;
while (*be != 0) {
auto sv = bson::fieldNameView(be);
if (sv != fieldName) {
auto [tag, val] = bson::convertFrom<false>(be, end, sv.size());
objOutput->push_back(sv, tag, val);
}
be = bson::advance(be, sv.size());
}
} else {
auto objRoot = value::getObjectView(objVal);
for (size_t idx = 0; idx < objRoot->size(); ++idx) {
StringData sv(objRoot->field(idx));
if (sv != fieldName) {
auto [tag, val] = objRoot->getAt(idx);
auto [copyTag, copyVal] = value::copyValue(tag, val);
objOutput->push_back(sv, copyTag, copyVal);
}
}
}
guard.reset();
return {true, tagOutput, valOutput};
} else {
// Removing field from non-object value hardly makes any sense.
return {false, value::TypeTags::Nothing, 0};
}
} else {
// New value is not Nothing. We will be returning a new Object no matter what.
auto [tagOutput, valOutput] = value::makeNewObject();
auto objOutput = value::getObjectView(valOutput);
value::ValueGuard guard{tagOutput, valOutput};
if (objTag == value::TypeTags::bsonObject) {
auto be = value::bitcastTo<const char*>(objVal);
auto end = be + ConstDataView(be).read<LittleEndian<uint32_t>>();
// Skip document length.
be += 4;
while (*be != 0) {
auto sv = bson::fieldNameView(be);
if (sv != fieldName) {
auto [tag, val] = bson::convertFrom<false>(be, end, sv.size());
objOutput->push_back(sv, tag, val);
}
be = bson::advance(be, sv.size());
}
} else if (objTag == value::TypeTags::Object) {
auto objRoot = value::getObjectView(objVal);
for (size_t idx = 0; idx < objRoot->size(); ++idx) {
StringData sv(objRoot->field(idx));
if (sv != fieldName) {
auto [tag, val] = objRoot->getAt(idx);
auto [copyTag, copyVal] = value::copyValue(tag, val);
objOutput->push_back(sv, copyTag, copyVal);
}
}
}
if (!newOwn) {
auto [copyTag, copyVal] = value::copyValue(newTag, newVal);
newTag = copyTag;
newVal = copyVal;
}
objOutput->push_back(fieldName, newTag, newVal);
guard.reset();
return {true, tagOutput, valOutput};
}
return {false, value::TypeTags::Nothing, 0};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::getArraySize(value::TypeTags tag,
value::Value val) {
size_t result = 0;
switch (tag) {
case value::TypeTags::Array: {
result = value::getArrayView(val)->size();
break;
}
case value::TypeTags::ArraySet: {
result = value::getArraySetView(val)->size();
break;
}
case value::TypeTags::bsonArray: {
auto enumerator = value::ArrayEnumerator{tag, val};
for (result = 0; !enumerator.atEnd(); result++, enumerator.advance()) {
}
break;
}
default: { return {false, value::TypeTags::Nothing, 0}; }
}
return {false, value::TypeTags::NumberInt64, value::bitcastFrom<int64_t>(result)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::aggSum(value::TypeTags accTag,
value::Value accValue,
value::TypeTags fieldTag,
value::Value fieldValue) {
// Skip aggregation step if we don't have the input.
if (fieldTag == value::TypeTags::Nothing) {
auto [tag, val] = value::copyValue(accTag, accValue);
return {true, tag, val};
}
// Initialize the accumulator.
if (accTag == value::TypeTags::Nothing) {
accTag = value::TypeTags::NumberInt64;
accValue = value::bitcastFrom<int64_t>(0);
}
return genericAdd(accTag, accValue, fieldTag, fieldValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAggDoubleDoubleSum(
ArityType arity) {
auto [_, fieldTag, fieldValue] = getFromStack(1);
// Move the incoming accumulator state from the stack. Given that we are now the owner of the
// state we are free to do any in-place update as we see fit.
auto [accTag, accValue] = moveOwnedFromStack(0);
value::ValueGuard guard{accTag, accValue};
// Initialize the accumulator.
if (accTag == value::TypeTags::Nothing) {
std::tie(accTag, accValue) = value::makeNewArray();
value::ValueGuard guard{accTag, accValue};
auto arr = value::getArrayView(accValue);
arr->reserve(AggSumValueElems::kMaxSizeOfArray);
// The order of the following three elements should match to 'AggSumValueElems'.
arr->push_back(value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(0));
arr->push_back(value::TypeTags::NumberDouble, value::bitcastFrom<double>(0.0));
arr->push_back(value::TypeTags::NumberDouble, value::bitcastFrom<double>(0.0));
// The absent 'kDecimalTotal' element means that we've not seen any decimal value. So, we're
// not adding 'kDecimalTotal' element yet.
aggDoubleDoubleSumImpl(arr, fieldTag, fieldValue);
guard.reset();
return {true, accTag, accValue};
}
tassert(5755317, "The result slot must be Array-typed", accTag == value::TypeTags::Array);
aggDoubleDoubleSumImpl(value::getArrayView(accValue), fieldTag, fieldValue);
guard.reset();
return {true, accTag, accValue};
}
// This function is necessary because 'aggDoubleDoubleSum()' result is 'Array' type but we need
// to produce a scalar value out of it.
//
// 'keepIntegerPrecision' should be set to true when we want to keep precision for integral values.
template <bool keepIntegerPrecision>
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDoubleDoubleSumFinalize(
ArityType arity) {
auto [_, fieldTag, fieldValue] = getFromStack(0);
auto arr = value::getArrayView(fieldValue);
tassert(5755321,
str::stream() << "The result slot must have at least "
<< AggSumValueElems::kMaxSizeOfArray - 1
<< " elements but got: " << arr->size(),
arr->size() >= AggSumValueElems::kMaxSizeOfArray - 1);
auto nonDecimalTotalTag = arr->getAt(AggSumValueElems::kNonDecimalTotalTag).first;
tassert(5755322,
"The nonDecimalTag can't be NumberDecimal",
nonDecimalTotalTag != value::TypeTags::NumberDecimal);
auto [sumTag, sum] = arr->getAt(AggSumValueElems::kNonDecimalTotalSum);
auto [addendTag, addend] = arr->getAt(AggSumValueElems::kNonDecimalTotalAddend);
tassert(5755323,
"The sum and addend must be NumberDouble",
sumTag == addendTag && sumTag == value::TypeTags::NumberDouble);
// We're guaranteed to always have a valid nonDecimalTotal value.
auto nonDecimalTotal = DoubleDoubleSummation::create(value::bitcastTo<double>(sum),
value::bitcastTo<double>(addend));
if (auto nElems = arr->size(); nElems < AggSumValueElems::kMaxSizeOfArray) {
// We've not seen any decimal value.
switch (nonDecimalTotalTag) {
case value::TypeTags::NumberInt32:
case value::TypeTags::NumberInt64:
if (nonDecimalTotal.fitsLong()) {
auto longVal = nonDecimalTotal.getLong();
if (int intVal = longVal;
nonDecimalTotalTag == value::TypeTags::NumberInt32 && intVal == longVal) {
return {true,
value::TypeTags::NumberInt32,
value::bitcastFrom<int32_t>(intVal)};
} else {
return {true,
value::TypeTags::NumberInt64,
value::bitcastFrom<int64_t>(longVal)};
}
}
if constexpr (keepIntegerPrecision) {
// The value was too large for a NumberInt64, so output an array with two
// values adding up to the desired total. The mongos computes the final sum,
// considering errors.
auto [total, error] = nonDecimalTotal.getDoubleDouble();
auto llerror = static_cast<int64_t>(error);
auto [tag, val] = value::makeNewArray();
value::ValueGuard guard(tag, val);
auto arr = value::getArrayView(val);
arr->reserve(static_cast<size_t>(AggPartialSumElems::kSizeOfArray));
arr->push_back(value::TypeTags::NumberDouble,
value::bitcastFrom<double>(total));
arr->push_back(value::TypeTags::NumberInt64,
value::bitcastFrom<int64_t>(llerror));
guard.reset();
return {true, tag, val};
}
// Sum doesn't fit a NumberLong, so return a NumberDouble instead.
[[fallthrough]];
case value::TypeTags::NumberDouble:
return {true,
value::TypeTags::NumberDouble,
value::bitcastFrom<double>(nonDecimalTotal.getDouble())};
default:
MONGO_UNREACHABLE_TASSERT(5755324);
}
} else {
// We've seen a decimal value.
tassert(5755325,
str::stream() << "The result slot must have at most "
<< AggSumValueElems::kMaxSizeOfArray
<< " elements but got: " << arr->size(),
nElems == AggSumValueElems::kMaxSizeOfArray);
auto [decimalTotalTag, decimalTotalVal] = arr->getAt(AggSumValueElems::kDecimalTotal);
tassert(5755326,
"The decimalTotal must be NumberDecimal",
decimalTotalTag == value::TypeTags::NumberDecimal);
auto decimalTotal = value::bitcastTo<Decimal128>(decimalTotalVal);
auto [tag, val] = value::makeCopyDecimal(decimalTotal.add(nonDecimalTotal.getDecimal()));
return {true, tag, val};
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAggStdDev(ArityType arity) {
auto [_, fieldTag, fieldValue] = getFromStack(1);
// Move the incoming accumulator state from the stack. Given that we are now the owner of the
// state we are free to do any in-place update as we see fit.
auto [accTag, accValue] = moveOwnedFromStack(0);
value::ValueGuard guard{accTag, accValue};
// Initialize the accumulator.
if (accTag == value::TypeTags::Nothing) {
auto [newAccTag, newAccValue] = value::makeNewArray();
value::ValueGuard newGuard{newAccTag, newAccValue};
auto arr = value::getArrayView(newAccValue);
arr->reserve(AggStdDevValueElems::kSizeOfArray);
// The order of the following three elements should match to 'AggStdDevValueElems'.
arr->push_back(value::TypeTags::NumberInt64, value::bitcastFrom<int64_t>(0));
arr->push_back(value::TypeTags::NumberDouble, value::bitcastFrom<double>(0.0));
arr->push_back(value::TypeTags::NumberDouble, value::bitcastFrom<double>(0.0));
aggStdDevImpl(arr, fieldTag, fieldValue);
newGuard.reset();
return {true, newAccTag, newAccValue};
}
tassert(5755210, "The result slot must be Array-typed", accTag == value::TypeTags::Array);
aggStdDevImpl(value::getArrayView(accValue), fieldTag, fieldValue);
guard.reset();
return {true, accTag, accValue};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinStdDevPopFinalize(
ArityType arity) {
auto [_, fieldTag, fieldValue] = getFromStack(0);
return aggStdDevFinalizeImpl(fieldValue, false /* isSamp */);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinStdDevSampFinalize(
ArityType arity) {
auto [_, fieldTag, fieldValue] = getFromStack(0);
return aggStdDevFinalizeImpl(fieldValue, true /* isSamp */);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::aggMin(value::TypeTags accTag,
value::Value accValue,
value::TypeTags fieldTag,
value::Value fieldValue,
CollatorInterface* collator) {
// Skip aggregation step if we don't have the input.
if (fieldTag == value::TypeTags::Nothing) {
auto [tag, val] = value::copyValue(accTag, accValue);
return {true, tag, val};
}
// Initialize the accumulator.
if (accTag == value::TypeTags::Nothing) {
auto [tag, val] = value::copyValue(fieldTag, fieldValue);
return {true, tag, val};
}
auto [tag, val] = compare3way(accTag, accValue, fieldTag, fieldValue, collator);
if (tag == value::TypeTags::NumberInt32 && value::bitcastTo<int>(val) < 0) {
auto [tag, val] = value::copyValue(accTag, accValue);
return {true, tag, val};
} else {
auto [tag, val] = value::copyValue(fieldTag, fieldValue);
return {true, tag, val};
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::aggMax(value::TypeTags accTag,
value::Value accValue,
value::TypeTags fieldTag,
value::Value fieldValue,
CollatorInterface* collator) {
// Skip aggregation step if we don't have the input.
if (fieldTag == value::TypeTags::Nothing) {
auto [tag, val] = value::copyValue(accTag, accValue);
return {true, tag, val};
}
// Initialize the accumulator.
if (accTag == value::TypeTags::Nothing) {
auto [tag, val] = value::copyValue(fieldTag, fieldValue);
return {true, tag, val};
}
auto [tag, val] = compare3way(accTag, accValue, fieldTag, fieldValue, collator);
if (tag == value::TypeTags::NumberInt32 && value::bitcastTo<int>(val) > 0) {
auto [tag, val] = value::copyValue(accTag, accValue);
return {true, tag, val};
} else {
auto [tag, val] = value::copyValue(fieldTag, fieldValue);
return {true, tag, val};
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::aggFirst(value::TypeTags accTag,
value::Value accValue,
value::TypeTags fieldTag,
value::Value fieldValue) {
// Skip aggregation step if we don't have the input.
if (fieldTag == value::TypeTags::Nothing) {
auto [tag, val] = value::copyValue(accTag, accValue);
return {true, tag, val};
}
// Initialize the accumulator.
if (accTag == value::TypeTags::Nothing) {
auto [tag, val] = value::copyValue(fieldTag, fieldValue);
return {true, tag, val};
}
// Disregard the next value, always return the first one.
auto [tag, val] = value::copyValue(accTag, accValue);
return {true, tag, val};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::aggLast(value::TypeTags accTag,
value::Value accValue,
value::TypeTags fieldTag,
value::Value fieldValue) {
// Skip aggregation step if we don't have the input.
if (fieldTag == value::TypeTags::Nothing) {
auto [tag, val] = value::copyValue(accTag, accValue);
return {true, tag, val};
}
// Initialize the accumulator.
if (accTag == value::TypeTags::Nothing) {
auto [tag, val] = value::copyValue(fieldTag, fieldValue);
return {true, tag, val};
}
// Disregard the accumulator, always return the next value.
auto [tag, val] = value::copyValue(fieldTag, fieldValue);
return {true, tag, val};
}
bool hasSeparatorAt(size_t idx, StringData input, StringData separator) {
return (idx + separator.size() <= input.size()) &&
input.substr(idx, separator.size()) == separator;
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinSplit(ArityType arity) {
auto [ownedSeparator, tagSeparator, valSeparator] = getFromStack(1);
auto [ownedInput, tagInput, valInput] = getFromStack(0);
if (!value::isString(tagSeparator) || !value::isString(tagInput)) {
return {false, value::TypeTags::Nothing, 0};
}
auto input = value::getStringView(tagInput, valInput);
auto separator = value::getStringView(tagSeparator, valSeparator);
auto [tag, val] = value::makeNewArray();
auto arr = value::getArrayView(val);
value::ValueGuard guard{tag, val};
size_t splitPos;
while ((splitPos = input.find(separator)) != std::string::npos) {
auto [tag, val] = value::makeNewString(input.substr(0, splitPos));
arr->push_back(tag, val);
splitPos += separator.size();
input = input.substr(splitPos);
}
// This is the last string.
{
auto [tag, val] = value::makeNewString(input);
arr->push_back(tag, val);
}
guard.reset();
return {true, tag, val};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDropFields(ArityType arity) {
auto [ownedSeparator, tagInObj, valInObj] = getFromStack(0);
// We operate only on objects.
if (!value::isObject(tagInObj)) {
return {false, value::TypeTags::Nothing, 0};
}
// Build the set of fields to drop.
StringDataSet restrictFieldsSet;
for (ArityType idx = 1; idx < arity; ++idx) {
auto [owned, tag, val] = getFromStack(idx);
if (!value::isString(tag)) {
return {false, value::TypeTags::Nothing, 0};
}
restrictFieldsSet.emplace(value::getStringView(tag, val));
}
auto [tag, val] = value::makeNewObject();
auto obj = value::getObjectView(val);
value::ValueGuard guard{tag, val};
if (tagInObj == value::TypeTags::bsonObject) {
auto be = value::bitcastTo<const char*>(valInObj);
auto end = be + ConstDataView(be).read<LittleEndian<uint32_t>>();
// Skip document length.
be += 4;
while (*be != 0) {
auto sv = bson::fieldNameView(be);
if (restrictFieldsSet.count(sv) == 0) {
auto [tag, val] = bson::convertFrom<false>(be, end, sv.size());
obj->push_back(sv, tag, val);
}
be = bson::advance(be, sv.size());
}
} else if (tagInObj == value::TypeTags::Object) {
auto objRoot = value::getObjectView(valInObj);
for (size_t idx = 0; idx < objRoot->size(); ++idx) {
StringData sv(objRoot->field(idx));
if (restrictFieldsSet.count(sv) == 0) {
auto [tag, val] = objRoot->getAt(idx);
auto [copyTag, copyVal] = value::copyValue(tag, val);
obj->push_back(sv, copyTag, copyVal);
}
}
}
guard.reset();
return {true, tag, val};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinNewArray(ArityType arity) {
auto [tag, val] = value::makeNewArray();
value::ValueGuard guard{tag, val};
auto arr = value::getArrayView(val);
if (arity) {
arr->reserve(arity);
for (ArityType idx = 0; idx < arity; ++idx) {
auto [owned, tag, val] = getFromStack(idx);
auto [tagCopy, valCopy] = value::copyValue(tag, val);
arr->push_back(tagCopy, valCopy);
}
}
guard.reset();
return {true, tag, val};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinKeepFields(ArityType arity) {
auto [ownedInObj, tagInObj, valInObj] = getFromStack(0);
// We operate only on objects.
if (!value::isObject(tagInObj)) {
return {false, value::TypeTags::Nothing, 0};
}
// Build the set of fields to keep.
StringDataSet keepFieldsSet;
for (uint8_t idx = 1; idx < arity; ++idx) {
auto [owned, tag, val] = getFromStack(idx);
if (!value::isString(tag)) {
return {false, value::TypeTags::Nothing, 0};
}
keepFieldsSet.emplace(value::getStringView(tag, val));
}
auto [tag, val] = value::makeNewObject();
auto obj = value::getObjectView(val);
value::ValueGuard guard{tag, val};
if (tagInObj == value::TypeTags::bsonObject) {
auto be = value::bitcastTo<const char*>(valInObj);
auto end = be + ConstDataView(be).read<LittleEndian<uint32_t>>();
// Skip document length.
be += 4;
while (*be != 0) {
auto sv = bson::fieldNameView(be);
if (keepFieldsSet.count(sv) == 1) {
auto [tag, val] = bson::convertFrom<false>(be, end, sv.size());
obj->push_back(sv, tag, val);
}
be = bson::advance(be, sv.size());
}
} else if (tagInObj == value::TypeTags::Object) {
auto objRoot = value::getObjectView(valInObj);
for (size_t idx = 0; idx < objRoot->size(); ++idx) {
StringData sv(objRoot->field(idx));
if (keepFieldsSet.count(sv) == 1) {
auto [tag, val] = objRoot->getAt(idx);
auto [copyTag, copyVal] = value::copyValue(tag, val);
obj->push_back(sv, copyTag, copyVal);
}
}
}
guard.reset();
return {true, tag, val};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinNewArrayFromRange(
ArityType arity) {
auto [tag, val] = value::makeNewArray();
value::ValueGuard guard{tag, val};
auto arr = value::getArrayView(val);
auto [startOwned, startTag, start] = getFromStack(0);
auto [endOwned, endTag, end] = getFromStack(1);
auto [stepOwned, stepTag, step] = getFromStack(2);
for (auto& tag : {startTag, endTag, stepTag}) {
if (value::TypeTags::NumberInt32 != tag) {
return {false, value::TypeTags::Nothing, 0};
}
}
// Cast to broader type 'int64_t' to prevent overflow during loop.
auto startVal = value::numericCast<int64_t>(startTag, start);
auto endVal = value::numericCast<int64_t>(endTag, end);
auto stepVal = value::numericCast<int64_t>(stepTag, step);
if (stepVal == 0) {
return {false, value::TypeTags::Nothing, 0};
}
// Calculate how much memory is needed to generate the array and avoid going over the memLimit.
auto steps = (endVal - startVal) / stepVal;
// If steps not positive then no amount of steps can get you from start to end. For example
// with start=5, end=7, step=-1 steps would be negative and in this case we would return an
// empty array.
auto length = steps >= 0 ? 1 + steps : 0;
int64_t memNeeded = sizeof(value::Array) + length * value::getApproximateSize(startTag, start);
auto memLimit = internalQueryMaxRangeBytes.load();
uassert(ErrorCodes::ExceededMemoryLimit,
str::stream() << "$range would use too much memory (" << memNeeded
<< " bytes) and cannot spill to disk. Memory limit: " << memLimit
<< " bytes",
memNeeded < memLimit);
arr->reserve(length);
for (auto i = startVal; stepVal > 0 ? i < endVal : i > endVal; i += stepVal) {
arr->push_back(value::TypeTags::NumberInt32, value::bitcastTo<int32_t>(i));
}
guard.reset();
return {true, tag, val};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinNewObj(ArityType arity) {
std::vector<value::TypeTags> typeTags;
std::vector<value::Value> values;
std::vector<std::string> names;
size_t tmpVectorLen = arity >> 1;
typeTags.reserve(tmpVectorLen);
values.reserve(tmpVectorLen);
names.reserve(tmpVectorLen);
for (ArityType idx = 0; idx < arity; idx += 2) {
{
auto [owned, tag, val] = getFromStack(idx);
if (!value::isString(tag)) {
return {false, value::TypeTags::Nothing, 0};
}
names.emplace_back(value::getStringView(tag, val));
}
{
auto [owned, tag, val] = getFromStack(idx + 1);
typeTags.push_back(tag);
values.push_back(val);
}
}
auto [tag, val] = value::makeNewObject();
auto obj = value::getObjectView(val);
value::ValueGuard guard{tag, val};
if (typeTags.size()) {
obj->reserve(typeTags.size());
for (size_t idx = 0; idx < typeTags.size(); ++idx) {
auto [tagCopy, valCopy] = value::copyValue(typeTags[idx], values[idx]);
obj->push_back(names[idx], tagCopy, valCopy);
}
}
guard.reset();
return {true, tag, val};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinKeyStringToString(
ArityType arity) {
auto [owned, tagInKey, valInKey] = getFromStack(0);
// We operate only on keys.
if (tagInKey != value::TypeTags::ksValue) {
return {false, value::TypeTags::Nothing, 0};
}
auto key = value::getKeyStringView(valInKey);
auto [tagStr, valStr] = value::makeNewString(key->toString());
return {true, tagStr, valStr};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinNewKeyString(ArityType arity) {
auto [_, tagInVersion, valInVersion] = getFromStack(0);
if (!value::isNumber(tagInVersion) ||
!(value::numericCast<int64_t>(tagInVersion, valInVersion) == 0 ||
value::numericCast<int64_t>(tagInVersion, valInVersion) == 1)) {
return {false, value::TypeTags::Nothing, 0};
}
KeyString::Version version =
static_cast<KeyString::Version>(value::numericCast<int64_t>(tagInVersion, valInVersion));
auto [__, tagInOrdering, valInOrdering] = getFromStack(1);
if (!value::isNumber(tagInOrdering)) {
return {false, value::TypeTags::Nothing, 0};
}
auto orderingBits = value::numericCast<int32_t>(tagInOrdering, valInOrdering);
BSONObjBuilder bb;
for (size_t i = 0; i < Ordering::kMaxCompoundIndexKeys; ++i) {
bb.append(""_sd, (orderingBits & (1 << i)) ? 1 : 0);
}
KeyString::HeapBuilder kb{version, Ordering::make(bb.done())};
for (size_t idx = 2; idx < arity - 1u; ++idx) {
auto [_, tag, val] = getFromStack(idx);
if (value::isNumber(tag)) {
auto num = value::numericCast<int64_t>(tag, val);
kb.appendNumberLong(num);
} else if (value::isString(tag)) {
auto str = value::getStringView(tag, val);
kb.appendString(str);
} else if (tag == value::TypeTags::MinKey || tag == value::TypeTags::MaxKey) {
BSONObjBuilder bob;
if (tag == value::TypeTags::MinKey) {
bob.appendMinKey("");
} else {
bob.appendMaxKey("");
}
kb.appendBSONElement(bob.obj().firstElement(), nullptr);
} else {
uasserted(4822802, "unsuppored key string type");
}
}
auto [___, tagInDisrim, valInDiscrim] = getFromStack(arity - 1);
if (!value::isNumber(tagInDisrim)) {
return {false, value::TypeTags::Nothing, 0};
}
auto discrimNum = value::numericCast<int64_t>(tagInDisrim, valInDiscrim);
if (discrimNum < 0 || discrimNum > 2) {
return {false, value::TypeTags::Nothing, 0};
}
kb.appendDiscriminator(static_cast<KeyString::Discriminator>(discrimNum));
return {true,
value::TypeTags::ksValue,
value::bitcastFrom<KeyString::Value*>(new KeyString::Value(kb.release()))};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAbs(ArityType arity) {
invariant(arity == 1);
auto [_, tagOperand, valOperand] = getFromStack(0);
return genericAbs(tagOperand, valOperand);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinCeil(ArityType arity) {
invariant(arity == 1);
auto [_, tagOperand, valOperand] = getFromStack(0);
return genericCeil(tagOperand, valOperand);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinFloor(ArityType arity) {
invariant(arity == 1);
auto [_, tagOperand, valOperand] = getFromStack(0);
return genericFloor(tagOperand, valOperand);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinTrunc(ArityType arity) {
invariant(arity == 1);
auto [_, tagOperand, valOperand] = getFromStack(0);
return genericTrunc(tagOperand, valOperand);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinExp(ArityType arity) {
invariant(arity == 1);
auto [_, tagOperand, valOperand] = getFromStack(0);
return genericExp(tagOperand, valOperand);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinLn(ArityType arity) {
invariant(arity == 1);
auto [_, tagOperand, valOperand] = getFromStack(0);
return genericLn(tagOperand, valOperand);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinLog10(ArityType arity) {
invariant(arity == 1);
auto [_, tagOperand, valOperand] = getFromStack(0);
return genericLog10(tagOperand, valOperand);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinSqrt(ArityType arity) {
invariant(arity == 1);
auto [_, tagOperand, valOperand] = getFromStack(0);
return genericSqrt(tagOperand, valOperand);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAddToArray(ArityType arity) {
auto [ownAgg, tagAgg, valAgg] = getFromStack(0);
auto [_, tagField, valField] = getFromStack(1);
// Create a new array is it does not exist yet.
if (tagAgg == value::TypeTags::Nothing) {
ownAgg = true;
std::tie(tagAgg, valAgg) = value::makeNewArray();
} else {
// Take ownership of the accumulator.
topStack(false, value::TypeTags::Nothing, 0);
}
value::ValueGuard guard{tagAgg, valAgg};
invariant(ownAgg && tagAgg == value::TypeTags::Array);
auto arr = value::getArrayView(valAgg);
// Push back the value. Note that array will ignore Nothing.
auto [tagCopy, valCopy] = value::copyValue(tagField, valField);
arr->push_back(tagCopy, valCopy);
guard.reset();
return {ownAgg, tagAgg, valAgg};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinMergeObjects(ArityType arity) {
auto [_, tagField, valField] = getFromStack(1);
// Move the incoming accumulator state from the stack. Given that we are now the owner of the
// state we are free to do any in-place update as we see fit.
auto [tagAgg, valAgg] = moveOwnedFromStack(0);
value::ValueGuard guard{tagAgg, valAgg};
// Create a new object if it does not exist yet.
if (tagAgg == value::TypeTags::Nothing) {
std::tie(tagAgg, valAgg) = value::makeNewObject();
}
invariant(tagAgg == value::TypeTags::Object);
if (tagField == value::TypeTags::Nothing || tagField == value::TypeTags::Null) {
guard.reset();
return {true, tagAgg, valAgg};
}
auto obj = value::getObjectView(valAgg);
StringMap<std::pair<value::TypeTags, value::Value>> currObjMap;
for (auto currObjEnum = value::ObjectEnumerator{tagField, valField}; !currObjEnum.atEnd();
currObjEnum.advance()) {
currObjMap[currObjEnum.getFieldName()] = currObjEnum.getViewOfValue();
}
// Process the accumulated fields and if a field within the current object already exists
// within the existing accuultor, we set the value of that field within the accumuator to the
// value contained within the current object. Preserves the order of existing fields in the
// accumulator
for (size_t idx = 0, numFields = obj->size(); idx < numFields; ++idx) {
auto it = currObjMap.find(obj->field(idx));
if (it != currObjMap.end()) {
auto [currObjTag, currObjVal] = it->second;
auto [currObjTagCopy, currObjValCopy] = value::copyValue(currObjTag, currObjVal);
obj->setAt(idx, currObjTagCopy, currObjValCopy);
currObjMap.erase(it);
}
}
// Copy the remaining fields of the current object being processed to the
// accumulator. Fields that were already present in the accumulated fields
// have been set already. Preserves the relative order of the new fields
for (auto currObjEnum = value::ObjectEnumerator{tagField, valField}; !currObjEnum.atEnd();
currObjEnum.advance()) {
auto it = currObjMap.find(currObjEnum.getFieldName());
if (it != currObjMap.end()) {
auto [currObjTag, currObjVal] = it->second;
auto [currObjTagCopy, currObjValCopy] = value::copyValue(currObjTag, currObjVal);
obj->push_back(currObjEnum.getFieldName(), currObjTagCopy, currObjValCopy);
}
}
guard.reset();
return {true, tagAgg, valAgg};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAddToSet(ArityType arity) {
auto [ownAgg, tagAgg, valAgg] = getFromStack(0);
auto [_, tagField, valField] = getFromStack(1);
// Create a new array is it does not exist yet.
if (tagAgg == value::TypeTags::Nothing) {
ownAgg = true;
std::tie(tagAgg, valAgg) = value::makeNewArraySet();
} else {
// Take ownership of the accumulator.
topStack(false, value::TypeTags::Nothing, 0);
}
value::ValueGuard guard{tagAgg, valAgg};
invariant(ownAgg && tagAgg == value::TypeTags::ArraySet);
auto arr = value::getArraySetView(valAgg);
// Push back the value. Note that array will ignore Nothing.
auto [tagCopy, valCopy] = value::copyValue(tagField, valField);
arr->push_back(tagCopy, valCopy);
guard.reset();
return {ownAgg, tagAgg, valAgg};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinCollAddToSet(ArityType arity) {
auto [ownAgg, tagAgg, valAgg] = getFromStack(0);
auto [ownColl, tagColl, valColl] = getFromStack(1);
auto [_, tagField, valField] = getFromStack(2);
// If the collator is Nothing or if it's some unexpected type, don't push back the value
// and just return the accumulator.
if (tagColl != value::TypeTags::collator) {
topStack(false, value::TypeTags::Nothing, 0);
return {ownAgg, tagAgg, valAgg};
}
// Create a new array is it does not exist yet.
if (tagAgg == value::TypeTags::Nothing) {
ownAgg = true;
std::tie(tagAgg, valAgg) = value::makeNewArraySet(value::getCollatorView(valColl));
} else {
// Take ownership of the accumulator.
topStack(false, value::TypeTags::Nothing, 0);
}
value::ValueGuard guard{tagAgg, valAgg};
invariant(ownAgg && tagAgg == value::TypeTags::ArraySet);
auto arr = value::getArraySetView(valAgg);
// Push back the value. Note that array will ignore Nothing.
auto [tagCopy, valCopy] = value::copyValue(tagField, valField);
arr->push_back(tagCopy, valCopy);
guard.reset();
return {ownAgg, tagAgg, valAgg};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinRunJsPredicate(ArityType arity) {
invariant(arity == 2);
auto [predicateOwned, predicateType, predicateValue] = getFromStack(0);
auto [inputOwned, inputType, inputValue] = getFromStack(1);
if (predicateType != value::TypeTags::jsFunction || !value::isObject(inputType)) {
return {false, value::TypeTags::Nothing, value::bitcastFrom<int64_t>(0)};
}
BSONObj obj;
if (inputType == value::TypeTags::Object) {
BSONObjBuilder objBuilder;
bson::convertToBsonObj(objBuilder, value::getObjectView(inputValue));
obj = objBuilder.obj();
} else if (inputType == value::TypeTags::bsonObject) {
obj = BSONObj(value::getRawPointerView(inputValue));
} else {
MONGO_UNREACHABLE;
}
auto predicate = value::getJsFunctionView(predicateValue);
auto predicateResult = predicate->runAsPredicate(obj);
return {false, value::TypeTags::Boolean, value::bitcastFrom<bool>(predicateResult)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinReplaceOne(ArityType arity) {
invariant(arity == 3);
auto [ownedInputStr, typeTagInputStr, valueInputStr] = getFromStack(0);
auto [ownedFindStr, typeTagFindStr, valueFindStr] = getFromStack(1);
auto [ownedReplacementStr, typeTagReplacementStr, valueReplacementStr] = getFromStack(2);
if (!value::isString(typeTagInputStr) || !value::isString(typeTagFindStr) ||
!value::isString(typeTagReplacementStr)) {
return {false, value::TypeTags::Nothing, 0};
}
auto input = value::getStringView(typeTagInputStr, valueInputStr);
auto find = value::getStringView(typeTagFindStr, valueFindStr);
auto replacement = value::getStringView(typeTagReplacementStr, valueReplacementStr);
// If find string is empty, return nothing, since an empty find will match every position in a
// string.
if (find.empty()) {
return {false, value::TypeTags::Nothing, 0};
}
// If find string is not found, return the original string.
size_t startIndex = input.find(find);
if (startIndex == std::string::npos) {
topStack(false, value::TypeTags::Nothing, 0);
return {ownedInputStr, typeTagInputStr, valueInputStr};
}
StringBuilder output;
size_t endIndex = startIndex + find.size();
output << input.substr(0, startIndex);
output << replacement;
output << input.substr(endIndex);
auto strData = output.stringData();
auto [outputStrTypeTag, outputStrValue] = sbe::value::makeNewString(strData);
return {true, outputStrTypeTag, outputStrValue};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDoubleDoubleSum(ArityType arity) {
invariant(arity >= 1);
value::TypeTags resultTag = value::TypeTags::NumberInt32;
bool haveDate = false;
// Sweep across all tags and pick the result type.
for (ArityType idx = 0; idx < arity; ++idx) {
auto [own, tag, val] = getFromStack(idx);
if (tag == value::TypeTags::Date) {
if (haveDate) {
uassert(4848404, "only one date allowed in an $add expression", !haveDate);
}
// Date is a simple 64 bit integer.
haveDate = true;
tag = value::TypeTags::NumberInt64;
}
if (value::isNumber(tag)) {
resultTag = value::getWidestNumericalType(resultTag, tag);
} else if (tag == value::TypeTags::Nothing || tag == value::TypeTags::Null) {
// What to do about null and nothing?
return {false, value::TypeTags::Nothing, 0};
} else {
// What to do about non-numeric types like arrays and objects?
return {false, value::TypeTags::Nothing, 0};
}
}
if (resultTag == value::TypeTags::NumberDecimal) {
Decimal128 sum;
for (ArityType idx = 0; idx < arity; ++idx) {
auto [own, tag, val] = getFromStack(idx);
if (tag == value::TypeTags::Date) {
sum = sum.add(Decimal128(value::bitcastTo<int64_t>(val)));
} else {
sum = sum.add(value::numericCast<Decimal128>(tag, val));
}
}
if (haveDate) {
return {false, value::TypeTags::Date, value::bitcastFrom<int64_t>(sum.toLong())};
} else {
auto [tag, val] = value::makeCopyDecimal(sum);
return {true, tag, val};
}
} else {
DoubleDoubleSummation sum;
for (ArityType idx = 0; idx < arity; ++idx) {
auto [own, tag, val] = getFromStack(idx);
if (tag == value::TypeTags::NumberInt32) {
sum.addInt(value::numericCast<int32_t>(tag, val));
} else if (tag == value::TypeTags::NumberInt64) {
sum.addLong(value::numericCast<int64_t>(tag, val));
} else if (tag == value::TypeTags::NumberDouble) {
sum.addDouble(value::numericCast<double>(tag, val));
} else if (tag == value::TypeTags::Date) {
sum.addLong(value::bitcastTo<int64_t>(val));
}
}
if (haveDate) {
uassert(ErrorCodes::Overflow, "date overflow in $add", sum.fitsLong());
return {false, value::TypeTags::Date, value::bitcastFrom<int64_t>(sum.getLong())};
} else {
switch (resultTag) {
case value::TypeTags::NumberInt32: {
auto result = sum.getLong();
if (sum.fitsLong() && result >= std::numeric_limits<int32_t>::min() &&
result <= std::numeric_limits<int32_t>::max()) {
return {false,
value::TypeTags::NumberInt32,
value::bitcastFrom<int32_t>(result)};
}
// Fall through to the larger type.
}
case value::TypeTags::NumberInt64: {
if (sum.fitsLong()) {
return {false,
value::TypeTags::NumberInt64,
value::bitcastFrom<int64_t>(sum.getLong())};
}
// Fall through to the larger type.
}
case value::TypeTags::NumberDouble: {
return {false,
value::TypeTags::NumberDouble,
value::bitcastFrom<double>(sum.getDouble())};
}
default:
MONGO_UNREACHABLE;
}
}
}
return {false, value::TypeTags::Nothing, 0};
}
/**
* A helper for the builtinDate method. The formal parameters yearOrWeekYear and monthOrWeek carry
* values depending on wether the date is a year-month-day or ISOWeekYear.
*/
using DateFn = std::function<Date_t(
TimeZone, long long, long long, long long, long long, long long, long long, long long)>;
std::tuple<bool, value::TypeTags, value::Value> builtinDateHelper(
DateFn computeDateFn,
std::tuple<bool, value::TypeTags, value::Value> tzdb,
std::tuple<bool, value::TypeTags, value::Value> yearOrWeekYear,
std::tuple<bool, value::TypeTags, value::Value> monthOrWeek,
std::tuple<bool, value::TypeTags, value::Value> day,
std::tuple<bool, value::TypeTags, value::Value> hour,
std::tuple<bool, value::TypeTags, value::Value> minute,
std::tuple<bool, value::TypeTags, value::Value> second,
std::tuple<bool, value::TypeTags, value::Value> millisecond,
std::tuple<bool, value::TypeTags, value::Value> timezone) {
auto [ownedTzdb, typeTagTzdb, valueTzdb] = tzdb;
auto [ownedYearOrWeekYear, typeTagYearOrWeekYear, valueYearOrWeekYear] = yearOrWeekYear;
auto [ownedMonthOrWeek, typeTagMonthOrWeek, valueMonthOrWeek] = monthOrWeek;
auto [ownedDay, typeTagDay, valueDay] = day;
auto [ownedHr, typeTagHr, valueHr] = hour;
auto [ownedMin, typeTagMin, valueMin] = minute;
auto [ownedSec, typeTagSec, valueSec] = second;
auto [ownedMillis, typeTagMillis, valueMillis] = millisecond;
auto [ownedTz, typeTagTz, valueTz] = timezone;
if (typeTagTzdb != value::TypeTags::timeZoneDB || !value::isNumber(typeTagYearOrWeekYear) ||
!value::isNumber(typeTagMonthOrWeek) || !value::isNumber(typeTagDay) ||
!value::isNumber(typeTagHr) || !value::isNumber(typeTagMin) ||
!value::isNumber(typeTagSec) || !value::isNumber(typeTagMillis) ||
!value::isString(typeTagTz)) {
return {false, value::TypeTags::Nothing, 0};
}
auto timeZoneDB = value::getTimeZoneDBView(valueTzdb);
invariant(timeZoneDB);
auto tzString = value::getStringView(typeTagTz, valueTz);
const auto tz = tzString == "" ? timeZoneDB->utcZone() : timeZoneDB->getTimeZone(tzString);
auto date =
computeDateFn(tz,
value::numericCast<int64_t>(typeTagYearOrWeekYear, valueYearOrWeekYear),
value::numericCast<int64_t>(typeTagMonthOrWeek, valueMonthOrWeek),
value::numericCast<int64_t>(typeTagDay, valueDay),
value::numericCast<int64_t>(typeTagHr, valueHr),
value::numericCast<int64_t>(typeTagMin, valueMin),
value::numericCast<int64_t>(typeTagSec, valueSec),
value::numericCast<int64_t>(typeTagMillis, valueMillis));
return {false, value::TypeTags::Date, value::bitcastFrom<int64_t>(date.asInt64())};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDate(ArityType arity) {
auto timeZoneDBTuple = getFromStack(0);
auto yearTuple = getFromStack(1);
auto monthTuple = getFromStack(2);
auto dayTuple = getFromStack(3);
auto hourTuple = getFromStack(4);
auto minuteTuple = getFromStack(5);
auto secondTuple = getFromStack(6);
auto millisTuple = getFromStack(7);
auto timezoneTuple = getFromStack(8);
return builtinDateHelper(
[](TimeZone tz,
long long year,
long long month,
long long day,
long long hour,
long long min,
long long sec,
long long millis) -> Date_t {
return tz.createFromDateParts(year, month, day, hour, min, sec, millis);
},
timeZoneDBTuple,
yearTuple,
monthTuple,
dayTuple,
hourTuple,
minuteTuple,
secondTuple,
millisTuple,
timezoneTuple);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDateDiff(ArityType arity) {
invariant(arity == 5 || arity == 6); // 6th parameter is 'startOfWeek'.
auto [timezoneDBOwn, timezoneDBTag, timezoneDBValue] = getFromStack(0);
if (timezoneDBTag != value::TypeTags::timeZoneDB) {
return {false, value::TypeTags::Nothing, 0};
}
auto timezoneDB = value::getTimeZoneDBView(timezoneDBValue);
// Get startDate.
auto [startDateOwn, startDateTag, startDateValue] = getFromStack(1);
if (!coercibleToDate(startDateTag)) {
return {false, value::TypeTags::Nothing, 0};
}
auto startDate = getDate(startDateTag, startDateValue);
// Get endDate.
auto [endDateOwn, endDateTag, endDateValue] = getFromStack(2);
if (!coercibleToDate(endDateTag)) {
return {false, value::TypeTags::Nothing, 0};
}
auto endDate = getDate(endDateTag, endDateValue);
// Get unit.
auto [unitOwn, unitTag, unitValue] = getFromStack(3);
if (!value::isString(unitTag)) {
return {false, value::TypeTags::Nothing, 0};
}
auto unitString = value::getStringView(unitTag, unitValue);
if (!isValidTimeUnit(unitString)) {
return {false, value::TypeTags::Nothing, 0};
}
auto unit = parseTimeUnit(unitString);
// Get timezone.
auto [timezoneOwn, timezoneTag, timezoneValue] = getFromStack(4);
if (!isValidTimezone(timezoneTag, timezoneValue, timezoneDB)) {
return {false, value::TypeTags::Nothing, 0};
}
auto timezone = getTimezone(timezoneTag, timezoneValue, timezoneDB);
// Get startOfWeek, if 'startOfWeek' parameter was passed and time unit is the week.
DayOfWeek startOfWeek{kStartOfWeekDefault};
if (6 == arity) {
auto [startOfWeekOwn, startOfWeekTag, startOfWeekValue] = getFromStack(5);
if (!value::isString(startOfWeekTag)) {
return {false, value::TypeTags::Nothing, 0};
}
if (TimeUnit::week == unit) {
auto startOfWeekString = value::getStringView(startOfWeekTag, startOfWeekValue);
if (!isValidDayOfWeek(startOfWeekString)) {
return {false, value::TypeTags::Nothing, 0};
}
startOfWeek = parseDayOfWeek(startOfWeekString);
}
}
auto result = dateDiff(startDate, endDate, unit, timezone, startOfWeek);
return {false, value::TypeTags::NumberInt64, value::bitcastFrom<int64_t>(result)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDateWeekYear(ArityType arity) {
auto timeZoneDBTuple = getFromStack(0);
auto yearTuple = getFromStack(1);
auto weekTuple = getFromStack(2);
auto dayTuple = getFromStack(3);
auto hourTuple = getFromStack(4);
auto minuteTuple = getFromStack(5);
auto secondTuple = getFromStack(6);
auto millisTuple = getFromStack(7);
auto timezoneTuple = getFromStack(8);
return builtinDateHelper(
[](TimeZone tz,
long long year,
long long month,
long long day,
long long hour,
long long min,
long long sec,
long long millis) -> Date_t {
return tz.createFromIso8601DateParts(year, month, day, hour, min, sec, millis);
},
timeZoneDBTuple,
yearTuple,
weekTuple,
dayTuple,
hourTuple,
minuteTuple,
secondTuple,
millisTuple,
timezoneTuple);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDateToParts(ArityType arity) {
auto [timezoneDBOwn, timezoneDBTag, timezoneDBVal] = getFromStack(0);
if (timezoneDBTag != value::TypeTags::timeZoneDB) {
return {false, value::TypeTags::Nothing, 0};
}
auto timezoneDB = value::getTimeZoneDBView(timezoneDBVal);
auto [dateOwn, dateTag, dateVal] = getFromStack(1);
// Get timezone.
auto [timezoneOwn, timezoneTag, timezoneVal] = getFromStack(2);
if (!value::isString(timezoneTag)) {
return {false, value::TypeTags::Nothing, 0};
}
TimeZone timezone = getTimezone(timezoneTag, timezoneVal, timezoneDB);
// Get date.
if (dateTag != value::TypeTags::Date && dateTag != value::TypeTags::Timestamp &&
dateTag != value::TypeTags::ObjectId && dateTag != value::TypeTags::bsonObjectId) {
return {false, value::TypeTags::Nothing, 0};
}
Date_t date = getDate(dateTag, dateVal);
// Get date parts.
auto dateParts = timezone.dateParts(date);
auto [dateObjTag, dateObjVal] = value::makeNewObject();
value::ValueGuard guard{dateObjTag, dateObjVal};
auto dateObj = value::getObjectView(dateObjVal);
dateObj->reserve(7);
dateObj->push_back("year", value::TypeTags::NumberInt32, dateParts.year);
dateObj->push_back("month", value::TypeTags::NumberInt32, dateParts.month);
dateObj->push_back("day", value::TypeTags::NumberInt32, dateParts.dayOfMonth);
dateObj->push_back("hour", value::TypeTags::NumberInt32, dateParts.hour);
dateObj->push_back("minute", value::TypeTags::NumberInt32, dateParts.minute);
dateObj->push_back("second", value::TypeTags::NumberInt32, dateParts.second);
dateObj->push_back("millisecond", value::TypeTags::NumberInt32, dateParts.millisecond);
guard.reset();
return {true, dateObjTag, dateObjVal};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinIsoDateToParts(ArityType arity) {
auto [timezoneDBOwn, timezoneDBTag, timezoneDBVal] = getFromStack(0);
if (timezoneDBTag != value::TypeTags::timeZoneDB) {
return {false, value::TypeTags::Nothing, 0};
}
auto timezoneDB = value::getTimeZoneDBView(timezoneDBVal);
auto [dateOwn, dateTag, dateVal] = getFromStack(1);
// Get timezone.
auto [timezoneOwn, timezoneTag, timezoneVal] = getFromStack(2);
if (!value::isString(timezoneTag)) {
return {false, value::TypeTags::Nothing, 0};
}
TimeZone timezone = getTimezone(timezoneTag, timezoneVal, timezoneDB);
// Get date.
if (dateTag != value::TypeTags::Date && dateTag != value::TypeTags::Timestamp &&
dateTag != value::TypeTags::ObjectId && dateTag != value::TypeTags::bsonObjectId) {
return {false, value::TypeTags::Nothing, 0};
}
Date_t date = getDate(dateTag, dateVal);
// Get date parts.
auto dateParts = timezone.dateIso8601Parts(date);
auto [dateObjTag, dateObjVal] = value::makeNewObject();
value::ValueGuard guard{dateObjTag, dateObjVal};
auto dateObj = value::getObjectView(dateObjVal);
dateObj->reserve(7);
dateObj->push_back("isoWeekYear", value::TypeTags::NumberInt32, dateParts.year);
dateObj->push_back("isoWeek", value::TypeTags::NumberInt32, dateParts.weekOfYear);
dateObj->push_back("isoDayOfWeek", value::TypeTags::NumberInt32, dateParts.dayOfWeek);
dateObj->push_back("hour", value::TypeTags::NumberInt32, dateParts.hour);
dateObj->push_back("minute", value::TypeTags::NumberInt32, dateParts.minute);
dateObj->push_back("second", value::TypeTags::NumberInt32, dateParts.second);
dateObj->push_back("millisecond", value::TypeTags::NumberInt32, dateParts.millisecond);
guard.reset();
return {true, dateObjTag, dateObjVal};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDayOfYear(ArityType arity) {
invariant(arity == 3);
auto [timezoneDBOwn, timezoneDBTag, timezoneDBValue] = getFromStack(0);
auto [dateOwn, dateTag, dateValue] = getFromStack(1);
auto [timezoneOwn, timezoneTag, timezoneValue] = getFromStack(2);
return genericDayOfYear(
timezoneDBTag, timezoneDBValue, dateTag, dateValue, timezoneTag, timezoneValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDayOfMonth(ArityType arity) {
invariant(arity == 3);
auto [timezoneDBOwn, timezoneDBTag, timezoneDBValue] = getFromStack(0);
auto [dateOwn, dateTag, dateValue] = getFromStack(1);
auto [timezoneOwn, timezoneTag, timezoneValue] = getFromStack(2);
return genericDayOfMonth(
timezoneDBTag, timezoneDBValue, dateTag, dateValue, timezoneTag, timezoneValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDayOfWeek(ArityType arity) {
invariant(arity == 3);
auto [timezoneDBOwn, timezoneDBTag, timezoneDBValue] = getFromStack(0);
auto [dateOwn, dateTag, dateValue] = getFromStack(1);
auto [timezoneOwn, timezoneTag, timezoneValue] = getFromStack(2);
return genericDayOfWeek(
timezoneDBTag, timezoneDBValue, dateTag, dateValue, timezoneTag, timezoneValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinBitTestPosition(ArityType arity) {
invariant(arity == 3);
auto [ownedMask, maskTag, maskValue] = getFromStack(0);
auto [ownedInput, valueTag, value] = getFromStack(1);
// Carries a flag to indicate the desired testing behavior this was invoked under. The testing
// behavior is used to determine if we need to bail out of the bit position comparison early in
// the depending if a bit is found to be set or unset.
auto [_, tagBitTestBehavior, valueBitTestBehavior] = getFromStack(2);
invariant(tagBitTestBehavior == value::TypeTags::NumberInt32);
if (!value::isArray(maskTag) || !value::isBinData(valueTag)) {
return {false, value::TypeTags::Nothing, 0};
}
auto bitPositions = value::getArrayView(maskValue);
auto binDataSize = static_cast<int64_t>(value::getBSONBinDataSize(valueTag, value));
auto binData = value::getBSONBinData(valueTag, value);
auto bitTestBehavior = BitTestBehavior{value::bitcastTo<int32_t>(valueBitTestBehavior)};
auto isBitSet = false;
for (size_t idx = 0; idx < bitPositions->size(); ++idx) {
auto [tagBitPosition, valueBitPosition] = bitPositions->getAt(idx);
auto bitPosition = value::bitcastTo<int64_t>(valueBitPosition);
if (bitPosition >= binDataSize * 8) {
// If position to test is longer than the data to test against, zero-extend.
isBitSet = false;
} else {
// Convert the bit position to a byte position within a byte. Note that byte positions
// start at position 0 in the document's value BinData array representation, and bit
// positions start at the least significant bit.
auto byteIdx = bitPosition / 8;
auto currentBit = bitPosition % 8;
auto currentByte = binData[byteIdx];
isBitSet = currentByte & (1 << currentBit);
}
// Bail out early if we succeed with the any case or fail with the all case. To do this, we
// negate a test to determine if we need to continue looping over the bit position list. So
// the first part of the disjunction checks when a bit is set and the test is invoked by the
// AllSet or AnyClear expressions. The second test checks if a bit isn't set and we are
// checking the AllClear or the AnySet cases.
if (!((isBitSet &&
(bitTestBehavior == BitTestBehavior::AllSet ||
bitTestBehavior == BitTestBehavior::AnyClear)) ||
(!isBitSet &&
(bitTestBehavior == BitTestBehavior::AllClear ||
bitTestBehavior == BitTestBehavior::AnySet)))) {
return {false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(bitTestBehavior == BitTestBehavior::AnyClear ||
bitTestBehavior == BitTestBehavior::AnySet)};
}
}
return {false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(bitTestBehavior == BitTestBehavior::AllSet ||
bitTestBehavior == BitTestBehavior::AllClear)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinBitTestZero(ArityType arity) {
invariant(arity == 2);
auto [maskOwned, maskTag, maskValue] = getFromStack(0);
auto [inputOwned, inputTag, inputValue] = getFromStack(1);
if ((maskTag != value::TypeTags::NumberInt32 && maskTag != value::TypeTags::NumberInt64) ||
(inputTag != value::TypeTags::NumberInt32 && inputTag != value::TypeTags::NumberInt64)) {
return {false, value::TypeTags::Nothing, 0};
}
auto maskNum = value::numericCast<int64_t>(maskTag, maskValue);
auto inputNum = value::numericCast<int64_t>(inputTag, inputValue);
auto result = (maskNum & inputNum) == 0;
return {false, value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinBitTestMask(ArityType arity) {
invariant(arity == 2);
auto [maskOwned, maskTag, maskValue] = getFromStack(0);
auto [inputOwned, inputTag, inputValue] = getFromStack(1);
if ((maskTag != value::TypeTags::NumberInt32 && maskTag != value::TypeTags::NumberInt64) ||
(inputTag != value::TypeTags::NumberInt32 && inputTag != value::TypeTags::NumberInt64)) {
return {false, value::TypeTags::Nothing, 0};
}
auto maskNum = value::numericCast<int64_t>(maskTag, maskValue);
auto inputNum = value::numericCast<int64_t>(inputTag, inputValue);
auto result = (maskNum & inputNum) == maskNum;
return {false, value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinBsonSize(ArityType arity) {
auto [_, tagOperand, valOperand] = getFromStack(0);
if (tagOperand == value::TypeTags::Object) {
BSONObjBuilder objBuilder;
bson::convertToBsonObj(objBuilder, value::getObjectView(valOperand));
int32_t sz = objBuilder.done().objsize();
return {false, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(sz)};
} else if (tagOperand == value::TypeTags::bsonObject) {
auto beginObj = value::getRawPointerView(valOperand);
int32_t sz = ConstDataView(beginObj).read<LittleEndian<int32_t>>();
return {false, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(sz)};
}
return {false, value::TypeTags::Nothing, 0};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinToUpper(ArityType arity) {
auto [_, operandTag, operandVal] = getFromStack(0);
if (value::isString(operandTag)) {
auto [strTag, strVal] = value::copyValue(operandTag, operandVal);
auto buf = value::getRawStringView(strTag, strVal);
auto range = std::make_pair(buf, buf + value::getStringLength(strTag, strVal));
boost::to_upper(range);
return {true, strTag, strVal};
}
return {false, value::TypeTags::Nothing, 0};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinToLower(ArityType arity) {
auto [_, operandTag, operandVal] = getFromStack(0);
if (value::isString(operandTag)) {
auto [strTag, strVal] = value::copyValue(operandTag, operandVal);
auto buf = value::getRawStringView(strTag, strVal);
auto range = std::make_pair(buf, buf + value::getStringLength(strTag, strVal));
boost::to_lower(range);
return {true, strTag, strVal};
}
return {false, value::TypeTags::Nothing, 0};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinCoerceToString(ArityType arity) {
auto [operandOwn, operandTag, operandVal] = getFromStack(0);
if (value::isString(operandTag)) {
topStack(false, value::TypeTags::Nothing, 0);
return {operandOwn, operandTag, operandVal};
}
if (operandTag == value::TypeTags::bsonSymbol) {
// Values of type StringBig and Values of type bsonSymbol have identical representations,
// so we can simply take ownership of the argument, change the type tag to StringBig, and
// return it.
topStack(false, value::TypeTags::Nothing, 0);
return {operandOwn, value::TypeTags::StringBig, operandVal};
}
switch (operandTag) {
case value::TypeTags::NumberInt32: {
std::string str = str::stream() << value::bitcastTo<int32_t>(operandVal);
auto [strTag, strVal] = value::makeNewString(str);
return {true, strTag, strVal};
}
case value::TypeTags::NumberInt64: {
std::string str = str::stream() << value::bitcastTo<int64_t>(operandVal);
auto [strTag, strVal] = value::makeNewString(str);
return {true, strTag, strVal};
}
case value::TypeTags::NumberDouble: {
std::string str = str::stream() << value::bitcastTo<double>(operandVal);
auto [strTag, strVal] = value::makeNewString(str);
return {true, strTag, strVal};
}
case value::TypeTags::NumberDecimal: {
std::string str = value::bitcastTo<Decimal128>(operandVal).toString();
auto [strTag, strVal] = value::makeNewString(str);
return {true, strTag, strVal};
}
case value::TypeTags::Date: {
std::string str = str::stream()
<< TimeZoneDatabase::utcZone().formatDate(
kISOFormatString,
Date_t::fromMillisSinceEpoch(value::bitcastTo<int64_t>(operandVal)));
auto [strTag, strVal] = value::makeNewString(str);
return {true, strTag, strVal};
}
case value::TypeTags::Timestamp: {
Timestamp ts{value::bitcastTo<uint64_t>(operandVal)};
auto [strTag, strVal] = value::makeNewString(ts.toString());
return {true, strTag, strVal};
}
case value::TypeTags::Null: {
auto [strTag, strVal] = value::makeNewString("");
return {true, strTag, strVal};
}
default:
break;
}
return {false, value::TypeTags::Nothing, 0};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAcos(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericAcos(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAcosh(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericAcosh(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAsin(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericAsin(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAsinh(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericAsinh(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAtan(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericAtan(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAtanh(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericAtanh(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinAtan2(ArityType arity) {
auto [owned1, operandTag1, operandValue1] = getFromStack(0);
auto [owned2, operandTag2, operandValue2] = getFromStack(1);
return genericAtan2(operandTag1, operandValue1, operandTag2, operandValue2);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinCos(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericCos(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinCosh(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericCosh(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDegreesToRadians(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericDegreesToRadians(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinRadiansToDegrees(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericRadiansToDegrees(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinSin(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericSin(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinSinh(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericSinh(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinTan(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericTan(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinTanh(ArityType arity) {
auto [_, operandTag, operandValue] = getFromStack(0);
return genericTanh(operandTag, operandValue);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinRound(ArityType arity) {
invariant(arity == 1);
auto [owned, tag, val] = getFromStack(0);
// Round 'val' to the closest integer, with ties rounding to the closest even integer.
// If 'val' is +Inf, -Inf, or NaN, this function will simply return 'val' as-is.
switch (tag) {
case value::TypeTags::NumberInt32:
case value::TypeTags::NumberInt64:
// The value is already an integer, so just return it as-is.
return {false, tag, val};
case value::TypeTags::NumberDouble: {
// std::nearbyint()'s behavior relies on a thread-local "rounding mode", so
// we use boost::numeric::RoundEven<double>::nearbyint() instead. We should
// switch over to roundeven() once it becomes available in the standard library.
// (See https://en.cppreference.com/w/c/experimental/fpext1 for details.)
auto operand = value::bitcastTo<double>(val);
auto rounded = boost::numeric::RoundEven<double>::nearbyint(operand);
return {false, tag, value::bitcastFrom<double>(rounded)};
}
case value::TypeTags::NumberDecimal: {
auto operand = value::bitcastTo<Decimal128>(val);
auto rounded = operand.round(Decimal128::RoundingMode::kRoundTiesToEven);
if (operand.isEqual(rounded)) {
// If the output of rounding is equal to the input, then we can just take
// ownership of 'operand' and return it. (This is more efficient than calling
// makeCopyDecimal(), which would allocate memory on the heap.)
topStack(false, value::TypeTags::Nothing, 0);
return {owned, tag, val};
}
auto [tag, val] = value::makeCopyDecimal(rounded);
return {true, tag, val};
}
default:
return {false, value::TypeTags::Nothing, 0};
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinConcat(ArityType arity) {
StringBuilder result;
for (ArityType idx = 0; idx < arity; ++idx) {
auto [_, tag, value] = getFromStack(idx);
if (!value::isString(tag)) {
return {false, value::TypeTags::Nothing, 0};
}
result << sbe::value::getStringView(tag, value);
}
auto [strTag, strValue] = sbe::value::makeNewString(result.str());
return {true, strTag, strValue};
}
std::pair<value::TypeTags, value::Value> ByteCode::genericIsMember(value::TypeTags lhsTag,
value::Value lhsVal,
value::TypeTags rhsTag,
value::Value rhsVal,
CollatorInterface* collator) {
if (!value::isArray(rhsTag)) {
return {value::TypeTags::Nothing, 0};
}
if (rhsTag == value::TypeTags::ArraySet) {
auto arrSet = value::getArraySetView(rhsVal);
if (CollatorInterface::collatorsMatch(collator, arrSet->getCollator())) {
auto& values = arrSet->values();
return {value::TypeTags::Boolean,
value::bitcastFrom<bool>(values.find({lhsTag, lhsVal}) != values.end())};
}
}
auto rhsArr = value::ArrayEnumerator{rhsTag, rhsVal};
while (!rhsArr.atEnd()) {
auto [rhsTag, rhsVal] = rhsArr.getViewOfValue();
auto [tag, val] = value::compareValue(lhsTag, lhsVal, rhsTag, rhsVal, collator);
if (tag == value::TypeTags::NumberInt32 && value::bitcastTo<int32_t>(val) == 0) {
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(true)};
}
rhsArr.advance();
}
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(false)};
}
std::pair<value::TypeTags, value::Value> ByteCode::genericIsMember(value::TypeTags lhsTag,
value::Value lhsVal,
value::TypeTags rhsTag,
value::Value rhsVal,
value::TypeTags collTag,
value::Value collVal) {
if (collTag != value::TypeTags::collator) {
return {value::TypeTags::Nothing, 0};
}
auto collator = value::getCollatorView(collVal);
return genericIsMember(lhsTag, lhsVal, rhsTag, rhsVal, collator);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinIsMember(ArityType arity) {
invariant(arity == 2);
auto [ownedInput, inputTag, inputVal] = getFromStack(0);
auto [ownedArr, arrTag, arrVal] = getFromStack(1);
auto [resultTag, resultVal] = genericIsMember(inputTag, inputVal, arrTag, arrVal);
return {false, resultTag, resultVal};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinCollIsMember(ArityType arity) {
invariant(arity == 3);
auto [ownedColl, collTag, collVal] = getFromStack(0);
auto [ownedInput, inputTag, inputVal] = getFromStack(1);
auto [ownedArr, arrTag, arrVal] = getFromStack(2);
auto [resultTag, resultVal] =
genericIsMember(inputTag, inputVal, arrTag, arrVal, collTag, collVal);
return {false, resultTag, resultVal};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinIndexOfBytes(ArityType arity) {
auto [strOwn, strTag, strVal] = getFromStack(0);
auto [substrOwn, substrTag, substrVal] = getFromStack(1);
if ((!value::isString(strTag)) || (!value::isString(substrTag))) {
return {false, value::TypeTags::Nothing, 0};
}
auto str = value::getStringView(strTag, strVal);
auto substring = value::getStringView(substrTag, substrVal);
int64_t startIndex = 0, endIndex = str.size();
if (arity >= 3) {
auto [startOwn, startTag, startVal] = getFromStack(2);
if (startTag != value::TypeTags::NumberInt64) {
return {false, value::TypeTags::Nothing, 0};
}
startIndex = value::bitcastTo<int64_t>(startVal);
// Check index is positive.
if (startIndex < 0) {
return {false, value::TypeTags::Nothing, 0};
}
// Check for valid bounds.
if (static_cast<size_t>(startIndex) > str.size()) {
return {false, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(-1)};
}
}
if (arity >= 4) {
auto [endOwn, endTag, endVal] = getFromStack(3);
if (endTag != value::TypeTags::NumberInt64) {
return {false, value::TypeTags::Nothing, 0};
}
endIndex = value::bitcastTo<int64_t>(endVal);
// Check index is positive.
if (endIndex < 0) {
return {false, value::TypeTags::Nothing, 0};
}
// Check for valid bounds.
if (endIndex < startIndex) {
return {false, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(-1)};
}
}
auto index = str.substr(startIndex, endIndex - startIndex).find(substring);
if (index != std::string::npos) {
return {
false, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(startIndex + index)};
}
return {false, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(-1)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinIndexOfCP(ArityType arity) {
auto [strOwn, strTag, strVal] = getFromStack(0);
auto [substrOwn, substrTag, substrVal] = getFromStack(1);
if ((!value::isString(strTag)) || (!value::isString(substrTag))) {
return {false, value::TypeTags::Nothing, 0};
}
auto str = value::getStringView(strTag, strVal);
auto substr = value::getStringView(substrTag, substrVal);
int64_t startCodePointIndex = 0, endCodePointIndexArg = str.size();
if (arity >= 3) {
auto [startOwn, startTag, startVal] = getFromStack(2);
if (startTag != value::TypeTags::NumberInt64) {
return {false, value::TypeTags::Nothing, 0};
}
startCodePointIndex = value::bitcastTo<int64_t>(startVal);
// Check index is positive.
if (startCodePointIndex < 0) {
return {false, value::TypeTags::Nothing, 0};
}
// Check for valid bounds.
if (static_cast<size_t>(startCodePointIndex) > str.size()) {
return {false, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(-1)};
}
}
if (arity >= 4) {
auto [endOwn, endTag, endVal] = getFromStack(3);
if (endTag != value::TypeTags::NumberInt64) {
return {false, value::TypeTags::Nothing, 0};
}
endCodePointIndexArg = value::bitcastTo<int64_t>(endVal);
// Check index is positive.
if (endCodePointIndexArg < 0) {
return {false, value::TypeTags::Nothing, 0};
}
// Check for valid bounds.
if (endCodePointIndexArg < startCodePointIndex) {
return {false, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(-1)};
}
}
// Handle edge case if both string and substring are empty strings.
if (startCodePointIndex == 0 && str.empty() && substr.empty()) {
return {true, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(0)};
}
// Need to get byte indexes for start and end indexes.
int64_t startByteIndex = 0, byteIndex = 0, codePointIndex;
for (codePointIndex = 0; static_cast<size_t>(byteIndex) < str.size(); codePointIndex++) {
if (codePointIndex == startCodePointIndex) {
startByteIndex = byteIndex;
}
uassert(5075307,
"$indexOfCP found bad UTF-8 in the input",
!str::isUTF8ContinuationByte(str[byteIndex]));
byteIndex += str::getCodePointLength(str[byteIndex]);
}
int64_t endCodePointIndex = std::min(codePointIndex, endCodePointIndexArg);
byteIndex = startByteIndex;
for (codePointIndex = startCodePointIndex; codePointIndex < endCodePointIndex;
++codePointIndex) {
if (str.substr(byteIndex, substr.size()).compare(substr) == 0) {
return {
false, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(codePointIndex)};
}
byteIndex += str::getCodePointLength(str[byteIndex]);
}
return {false, value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(-1)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinIsTimeUnit(ArityType arity) {
invariant(arity == 1);
auto [timeUnitOwn, timeUnitTag, timeUnitValue] = getFromStack(0);
if (!value::isString(timeUnitTag)) {
return {false, value::TypeTags::Nothing, 0};
}
return {false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(
isValidTimeUnit(value::getStringView(timeUnitTag, timeUnitValue)))};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinIsDayOfWeek(ArityType arity) {
invariant(arity == 1);
auto [dayOfWeekOwn, dayOfWeekTag, dayOfWeekValue] = getFromStack(0);
if (!value::isString(dayOfWeekTag)) {
return {false, value::TypeTags::Nothing, 0};
}
return {false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(
isValidDayOfWeek(value::getStringView(dayOfWeekTag, dayOfWeekValue)))};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinIsTimezone(ArityType arity) {
auto [timezoneDBOwn, timezoneDBTag, timezoneDBVal] = getFromStack(0);
if (timezoneDBTag != value::TypeTags::timeZoneDB) {
return {false, value::TypeTags::Nothing, 0};
}
auto timezoneDB = value::getTimeZoneDBView(timezoneDBVal);
auto [timezoneOwn, timezoneTag, timezoneVal] = getFromStack(1);
if (!value::isString(timezoneTag)) {
return {false, value::TypeTags::Boolean, false};
}
auto timezoneStr = value::getStringView(timezoneTag, timezoneVal);
if (timezoneDB->isTimeZoneIdentifier(timezoneStr)) {
return {false, value::TypeTags::Boolean, true};
}
return {false, value::TypeTags::Boolean, false};
}
namespace {
std::tuple<bool, value::TypeTags, value::Value> setUnion(
const std::vector<value::TypeTags>& argTags,
const std::vector<value::Value>& argVals,
const CollatorInterface* collator = nullptr) {
auto [resTag, resVal] = value::makeNewArraySet(collator);
value::ValueGuard resGuard{resTag, resVal};
auto resView = value::getArraySetView(resVal);
for (size_t idx = 0; idx < argVals.size(); ++idx) {
auto argTag = argTags[idx];
auto argVal = argVals[idx];
auto arrIter = value::ArrayEnumerator{argTag, argVal};
while (!arrIter.atEnd()) {
auto [elTag, elVal] = arrIter.getViewOfValue();
auto [copyTag, copyVal] = value::copyValue(elTag, elVal);
resView->push_back(copyTag, copyVal);
arrIter.advance();
}
}
resGuard.reset();
return {true, resTag, resVal};
}
std::tuple<bool, value::TypeTags, value::Value> setIntersection(
const std::vector<value::TypeTags>& argTags,
const std::vector<value::Value>& argVals,
const CollatorInterface* collator = nullptr) {
auto intersectionMap =
value::ValueMapType<size_t>{0, value::ValueHash(collator), value::ValueEq(collator)};
auto [resTag, resVal] = value::makeNewArraySet(collator);
value::ValueGuard resGuard{resTag, resVal};
for (size_t idx = 0; idx < argVals.size(); ++idx) {
auto tag = argTags[idx];
auto val = argVals[idx];
bool atLeastOneCommonElement = false;
auto enumerator = value::ArrayEnumerator{tag, val};
while (!enumerator.atEnd()) {
auto [elTag, elVal] = enumerator.getViewOfValue();
if (idx == 0) {
intersectionMap[{elTag, elVal}] = 1;
} else {
if (auto it = intersectionMap.find({elTag, elVal}); it != intersectionMap.end()) {
if (it->second == idx) {
it->second++;
atLeastOneCommonElement = true;
}
}
}
enumerator.advance();
}
if (idx > 0 && !atLeastOneCommonElement) {
resGuard.reset();
return {true, resTag, resVal};
}
}
auto resView = value::getArraySetView(resVal);
for (auto&& [item, counter] : intersectionMap) {
if (counter == argVals.size()) {
auto [elTag, elVal] = item;
auto [copyTag, copyVal] = value::copyValue(elTag, elVal);
resView->push_back(copyTag, copyVal);
}
}
resGuard.reset();
return {true, resTag, resVal};
}
std::tuple<bool, value::TypeTags, value::Value> setDifference(
value::TypeTags lhsTag,
value::Value lhsVal,
value::TypeTags rhsTag,
value::Value rhsVal,
const CollatorInterface* collator = nullptr) {
auto [resTag, resVal] = value::makeNewArraySet(collator);
value::ValueGuard resGuard{resTag, resVal};
auto resView = value::getArraySetView(resVal);
value::ValueSetType setValuesSecondArg(0, value::ValueHash(collator), value::ValueEq(collator));
auto rhsIter = value::ArrayEnumerator(rhsTag, rhsVal);
while (!rhsIter.atEnd()) {
auto [elTag, elVal] = rhsIter.getViewOfValue();
setValuesSecondArg.insert({elTag, elVal});
rhsIter.advance();
}
auto lhsIter = value::ArrayEnumerator(lhsTag, lhsVal);
while (!lhsIter.atEnd()) {
auto [elTag, elVal] = lhsIter.getViewOfValue();
if (setValuesSecondArg.count({elTag, elVal}) == 0) {
auto [copyTag, copyVal] = value::copyValue(elTag, elVal);
resView->push_back(copyTag, copyVal);
}
lhsIter.advance();
}
resGuard.reset();
return {true, resTag, resVal};
}
} // namespace
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinCollSetUnion(ArityType arity) {
invariant(arity >= 1);
auto [_, collTag, collVal] = getFromStack(0);
if (collTag != value::TypeTags::collator) {
return {false, value::TypeTags::Nothing, 0};
}
std::vector<value::TypeTags> argTags;
std::vector<value::Value> argVals;
for (size_t idx = 1; idx < arity; ++idx) {
auto [owned, tag, val] = getFromStack(idx);
if (!value::isArray(tag)) {
return {false, value::TypeTags::Nothing, 0};
}
argTags.push_back(tag);
argVals.push_back(val);
}
return setUnion(argTags, argVals, value::getCollatorView(collVal));
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinSetUnion(ArityType arity) {
std::vector<value::TypeTags> argTags;
std::vector<value::Value> argVals;
for (size_t idx = 0; idx < arity; ++idx) {
auto [_, tag, val] = getFromStack(idx);
if (!value::isArray(tag)) {
return {false, value::TypeTags::Nothing, 0};
}
argTags.push_back(tag);
argVals.push_back(val);
}
return setUnion(argTags, argVals);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinCollSetIntersection(
ArityType arity) {
invariant(arity >= 1);
auto [_, collTag, collVal] = getFromStack(0);
if (collTag != value::TypeTags::collator) {
return {false, value::TypeTags::Nothing, 0};
}
std::vector<value::TypeTags> argTags;
std::vector<value::Value> argVals;
for (size_t idx = 1; idx < arity; ++idx) {
auto [owned, tag, val] = getFromStack(idx);
if (!value::isArray(tag)) {
return {false, value::TypeTags::Nothing, 0};
}
argTags.push_back(tag);
argVals.push_back(val);
}
return setIntersection(argTags, argVals, value::getCollatorView(collVal));
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinSetIntersection(ArityType arity) {
std::vector<value::TypeTags> argTags;
std::vector<value::Value> argVals;
for (size_t idx = 0; idx < arity; ++idx) {
auto [_, tag, val] = getFromStack(idx);
if (!value::isArray(tag)) {
return {false, value::TypeTags::Nothing, 0};
}
argTags.push_back(tag);
argVals.push_back(val);
}
return setIntersection(argTags, argVals);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinCollSetDifference(
ArityType arity) {
invariant(arity == 3);
auto [_, collTag, collVal] = getFromStack(0);
if (collTag != value::TypeTags::collator) {
return {false, value::TypeTags::Nothing, 0};
}
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(1);
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(2);
if (!value::isArray(lhsTag) || !value::isArray(rhsTag)) {
return {false, value::TypeTags::Nothing, 0};
}
return setDifference(lhsTag, lhsVal, rhsTag, rhsVal, value::getCollatorView(collVal));
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinSetDifference(ArityType arity) {
invariant(arity == 2);
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(1);
if (!value::isArray(lhsTag) || !value::isArray(rhsTag)) {
return {false, value::TypeTags::Nothing, 0};
}
return setDifference(lhsTag, lhsVal, rhsTag, rhsVal);
}
namespace {
/**
* A helper function to create the result object {"match" : .., "idx" : ..., "captures" :
* ...} from the result of pcre_exec().
*/
std::tuple<bool, value::TypeTags, value::Value> buildRegexMatchResultObject(
StringData inputString,
const std::vector<int>& capturesBuffer,
size_t numCaptures,
uint32_t& startBytePos,
uint32_t& codePointPos) {
auto verifyBounds = [&inputString](auto startPos, auto limitPos, auto isCapture) {
// If a capture group was not matched, then the 'startPos' and 'limitPos' will both be -1.
// These bounds cannot occur for a match on the full string.
if (startPos == -1 && limitPos == -1 && isCapture) {
return true;
}
if (startPos == -1 || limitPos == -1) {
LOGV2_ERROR(5073412,
"Unexpected error occurred while executing regexFind.",
"startPos"_attr = startPos,
"limitPos"_attr = limitPos);
return false;
}
if (startPos < 0 || static_cast<size_t>(startPos) > inputString.size() || limitPos < 0 ||
static_cast<size_t>(limitPos) > inputString.size() || startPos > limitPos) {
LOGV2_ERROR(5073413,
"Unexpected error occurred while executing regexFind.",
"startPos"_attr = startPos,
"limitPos"_attr = limitPos);
return false;
}
return true;
};
// Extract the matched string: its start and (end+1) indices are in the first two elements of
// capturesBuffer.
if (!verifyBounds(capturesBuffer[0], capturesBuffer[1], false)) {
return {false, value::TypeTags::Nothing, 0};
}
auto matchStartIdx = capturesBuffer[0];
auto matchedString = inputString.substr(matchStartIdx, capturesBuffer[1] - matchStartIdx);
auto [matchedTag, matchedVal] = value::makeNewString(matchedString);
value::ValueGuard matchedGuard{matchedTag, matchedVal};
// We iterate through the input string's contents preceding the match index, in order to convert
// the byte offset to a code point offset.
for (auto byteIdx = startBytePos; byteIdx < static_cast<uint32_t>(matchStartIdx);
++codePointPos) {
byteIdx += str::getCodePointLength(inputString[byteIdx]);
}
startBytePos = matchStartIdx;
auto [arrTag, arrVal] = value::makeNewArray();
value::ValueGuard arrGuard{arrTag, arrVal};
auto arrayView = value::getArrayView(arrVal);
// The next '2 * numCaptures' entries (after the first two entries) of 'capturesBuffer'
// hold the (start, limit) pairs of indexes, for each of the capture groups. We skip the first
// two elements and start iteration from 3rd element so that we only construct the strings for
// capture groups.
if (numCaptures) {
arrayView->reserve(numCaptures);
for (size_t i = 0; i < numCaptures; ++i) {
const auto start = capturesBuffer[2 * (i + 1)];
const auto limit = capturesBuffer[2 * (i + 1) + 1];
if (!verifyBounds(start, limit, true)) {
return {false, value::TypeTags::Nothing, 0};
}
if (start == -1 && limit == -1) {
arrayView->push_back(value::TypeTags::Null, 0);
} else {
auto captureString = inputString.substr(start, limit - start);
auto [tag, val] = value::makeNewString(captureString);
arrayView->push_back(tag, val);
}
}
}
auto [resTag, resVal] = value::makeNewObject();
value::ValueGuard resGuard{resTag, resVal};
auto resObjectView = value::getObjectView(resVal);
resObjectView->reserve(3);
matchedGuard.reset();
resObjectView->push_back("match", matchedTag, matchedVal);
resObjectView->push_back(
"idx", value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(codePointPos));
arrGuard.reset();
resObjectView->push_back("captures", arrTag, arrVal);
resGuard.reset();
return {true, resTag, resVal};
}
/**
* A helper function to extract the next match in the subject string using the compiled regex
* pattern.
* - pcre: The wrapper object containing the compiled pcre expression
* - inputString: The subject string.
* - capturesBuffer: Array to be populated with the found matched string and capture groups.
* - startBytePos: The position from where the search should start given in bytes.
* - codePointPos: The same position in terms of code points.
* - isMatch: Boolean flag to mark if the caller function is $regexMatch, in which case the result
* returned is true/false.
*/
std::tuple<bool, value::TypeTags, value::Value> pcreNextMatch(value::PcreRegex* pcre,
StringData inputString,
std::vector<int>& capturesBuffer,
uint32_t& startBytePos,
uint32_t& codePointPos,
bool isMatch = false) {
auto execResult = pcre->execute(inputString, startBytePos, capturesBuffer);
auto numCaptures = pcre->getNumberCaptures();
if (execResult < -1 || execResult > static_cast<int>(numCaptures) + 1) {
LOGV2_ERROR(5073414,
"Error occurred while executing regular expression.",
"execResult"_attr = execResult);
return {false, value::TypeTags::Nothing, 0};
}
if (isMatch) {
// $regexMatch returns true or false.
bool match = (execResult != PCRE_ERROR_NOMATCH);
return {false, value::TypeTags::Boolean, value::bitcastFrom<bool>(match)};
} else {
// $regexFind and $regexFindAll build result object or return null.
if (execResult == PCRE_ERROR_NOMATCH) {
return {false, value::TypeTags::Null, 0};
}
return buildRegexMatchResultObject(
inputString, capturesBuffer, numCaptures, startBytePos, codePointPos);
}
}
/**
* A helper function to extract the first match in the subject string using the compiled regex
* pattern. See 'pcreNextMatch' function for parameters description.
*/
std::tuple<bool, value::TypeTags, value::Value> pcreFirstMatch(
value::PcreRegex* pcre,
StringData inputString,
bool isMatch = false,
std::vector<int>* capturesBuffer = nullptr,
uint32_t* startBytePos = nullptr,
uint32_t* codePointPos = nullptr) {
std::vector<int> tmpCapturesBuffer;
uint32_t tmpStartBytePos = 0;
uint32_t tmpCodePointPos = 0;
capturesBuffer = capturesBuffer ? capturesBuffer : &tmpCapturesBuffer;
startBytePos = startBytePos ? startBytePos : &tmpStartBytePos;
codePointPos = codePointPos ? codePointPos : &tmpCodePointPos;
// The first two-thirds of the capturesBuffer is used to pass back captured substrings' start
// and (end+1) indexes. The remaining third of the vector is used as workspace by pcre_exec()
// while matching capturing subpatterns, and is not available for passing back information.
auto numCaptures = pcre->getNumberCaptures();
capturesBuffer->resize((1 + numCaptures) * 3);
return pcreNextMatch(pcre, inputString, *capturesBuffer, *startBytePos, *codePointPos, isMatch);
}
/**
* A helper function with common logic for $regexMatch and $regexFind functions. Both extract only
* the first match to a regular expression, but return different result objects.
*/
std::tuple<bool, value::TypeTags, value::Value> genericPcreRegexSingleMatch(
value::TypeTags typeTagPcreRegex,
value::Value valuePcreRegex,
value::TypeTags typeTagInputStr,
value::Value valueInputStr,
bool isMatch) {
if (!value::isStringOrSymbol(typeTagInputStr) || !value::isPcreRegex(typeTagPcreRegex)) {
return {false, value::TypeTags::Nothing, 0};
}
auto inputString = value::getStringOrSymbolView(typeTagInputStr, valueInputStr);
auto pcreRegex = value::getPcreRegexView(valuePcreRegex);
return pcreFirstMatch(pcreRegex, inputString, isMatch);
}
std::pair<value::TypeTags, value::Value> collComparisonKey(value::TypeTags tag,
value::Value val,
const CollatorInterface* collator) {
using namespace std::literals;
// This function should only be called if 'collator' is non-null and 'tag' is a collatable type.
invariant(collator);
invariant(value::isCollatableType(tag));
// For strings, call CollatorInterface::getComparisonKey() to obtain the comparison key.
if (value::isString(tag)) {
return value::makeNewString(
collator->getComparisonKey(value::getStringView(tag, val)).getKeyData());
}
// For collatable types other than strings (such as arrays and objects), we take the slow
// path and round-trip the value through BSON.
BSONObjBuilder input;
bson::appendValueToBsonObj<BSONObjBuilder>(input, ""_sd, tag, val);
BSONObjBuilder output;
CollationIndexKey::collationAwareIndexKeyAppend(input.obj().firstElement(), collator, &output);
BSONObj outputView = output.done();
auto ptr = outputView.objdata();
auto be = ptr + 4;
auto end = ptr + ConstDataView(ptr).read<LittleEndian<uint32_t>>();
return bson::convertFrom<false>(be, end, 0);
}
} // namespace
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinRegexCompile(ArityType arity) {
invariant(arity == 2);
auto [patternOwned, patternTypeTag, patternValue] = getFromStack(0);
auto [optionsOwned, optionsTypeTag, optionsValue] = getFromStack(1);
if (!value::isString(patternTypeTag) || !value::isString(optionsTypeTag)) {
return {false, value::TypeTags::Nothing, 0};
}
auto pattern = value::getStringView(patternTypeTag, patternValue);
auto options = value::getStringView(optionsTypeTag, optionsValue);
if (pattern.find('\0', 0) != std::string::npos || options.find('\0', 0) != std::string::npos) {
return {false, value::TypeTags::Nothing, 0};
}
auto [pcreTag, pcreValue] = value::makeNewPcreRegex(pattern, options);
return {true, pcreTag, pcreValue};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinRegexMatch(ArityType arity) {
invariant(arity == 2);
auto [ownedPcreRegex, typeTagPcreRegex, valuePcreRegex] = getFromStack(0);
auto [ownedInputStr, typeTagInputStr, valueInputStr] = getFromStack(1);
return genericPcreRegexSingleMatch(
typeTagPcreRegex, valuePcreRegex, typeTagInputStr, valueInputStr, true);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinRegexFind(ArityType arity) {
invariant(arity == 2);
auto [ownedPcreRegex, typeTagPcreRegex, valuePcreRegex] = getFromStack(0);
auto [ownedInputStr, typeTagInputStr, valueInputStr] = getFromStack(1);
return genericPcreRegexSingleMatch(
typeTagPcreRegex, valuePcreRegex, typeTagInputStr, valueInputStr, false);
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinRegexFindAll(ArityType arity) {
invariant(arity == 2);
auto [ownedPcre, typeTagPcreRegex, valuePcreRegex] = getFromStack(0);
auto [ownedStr, typeTagInputStr, valueInputStr] = getFromStack(1);
if (!value::isString(typeTagInputStr) || typeTagPcreRegex != value::TypeTags::pcreRegex) {
return {false, value::TypeTags::Nothing, 0};
}
auto inputString = value::getStringView(typeTagInputStr, valueInputStr);
auto pcre = value::getPcreRegexView(valuePcreRegex);
std::vector<int> capturesBuffer;
uint32_t startBytePos = 0;
uint32_t codePointPos = 0;
bool isFirstMatch = true;
// Prepare the result array of matching objects.
auto [arrTag, arrVal] = value::makeNewArray();
value::ValueGuard arrGuard{arrTag, arrVal};
auto arrayView = value::getArrayView(arrVal);
int resultSize = 0;
do {
auto [_, matchTag, matchVal] = [&]() {
if (isFirstMatch) {
isFirstMatch = false;
return pcreFirstMatch(
pcre, inputString, false, &capturesBuffer, &startBytePos, &codePointPos);
}
return pcreNextMatch(pcre, inputString, capturesBuffer, startBytePos, codePointPos);
}();
value::ValueGuard matchGuard{matchTag, matchVal};
if (matchTag == value::TypeTags::Null) {
break;
}
if (matchTag != value::TypeTags::Object) {
return {false, value::TypeTags::Nothing, 0};
}
resultSize += getApproximateSize(matchTag, matchVal);
uassert(5126606,
"$regexFindAll: the size of buffer to store output exceeded the 64MB limit",
resultSize <= mongo::BufferMaxSize);
matchGuard.reset();
arrayView->push_back(matchTag, matchVal);
// Move indexes after the current matched string to prepare for the next search.
auto [mstrTag, mstrVal] = value::getObjectView(matchVal)->getField("match");
auto matchString = value::getStringView(mstrTag, mstrVal);
if (matchString.empty()) {
startBytePos += str::getCodePointLength(inputString[startBytePos]);
++codePointPos;
} else {
startBytePos += matchString.size();
for (size_t byteIdx = 0; byteIdx < matchString.size(); ++codePointPos) {
byteIdx += str::getCodePointLength(matchString[byteIdx]);
}
}
} while (startBytePos < inputString.size());
arrGuard.reset();
return {true, arrTag, arrVal};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinShardFilter(ArityType arity) {
invariant(arity == 2);
auto [ownedFilter, filterTag, filterValue] = getFromStack(0);
auto [ownedShardKey, shardKeyTag, shardKeyValue] = getFromStack(1);
if (filterTag != value::TypeTags::shardFilterer || shardKeyTag != value::TypeTags::bsonObject) {
if (filterTag == value::TypeTags::shardFilterer &&
shardKeyTag == value::TypeTags::Nothing) {
LOGV2_WARNING(5071200,
"No shard key found in document, it may have been inserted manually "
"into shard",
"keyPattern"_attr =
value::getShardFiltererView(filterValue)->getKeyPattern());
}
return {false, value::TypeTags::Nothing, 0};
}
BSONObj keyAsUnownedBson{sbe::value::bitcastTo<const char*>(shardKeyValue)};
return {false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(
value::getShardFiltererView(filterValue)->keyBelongsToMe(keyAsUnownedBson))};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinShardHash(ArityType arity) {
invariant(arity == 1);
auto [ownedShardKey, shardKeyTag, shardKeyValue] = getFromStack(0);
// Compute the shard key hash value by round-tripping it through BSONObj as it is currently the
// only way to do it if we do not want to duplicate the hash computation code.
// TODO SERVER-55622
BSONObjBuilder input;
bson::appendValueToBsonObj<BSONObjBuilder>(input, ""_sd, shardKeyTag, shardKeyValue);
auto hashVal =
BSONElementHasher::hash64(input.obj().firstElement(), BSONElementHasher::DEFAULT_HASH_SEED);
return {false, value::TypeTags::NumberInt64, value::bitcastFrom<decltype(hashVal)>(hashVal)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinExtractSubArray(ArityType arity) {
// We need to ensure that 'size_t' is wide enough to store 32-bit index.
static_assert(sizeof(size_t) >= sizeof(int32_t), "size_t must be at least 32-bits");
auto [arrayOwned, arrayTag, arrayValue] = getFromStack(0);
auto [limitOwned, limitTag, limitValue] = getFromStack(1);
if (!value::isArray(arrayTag) || limitTag != value::TypeTags::NumberInt32) {
return {false, value::TypeTags::Nothing, 0};
}
auto limit = value::bitcastTo<int32_t>(limitValue);
auto absWithSign = [](int32_t value) -> std::pair<bool, size_t> {
if (value < 0) {
// Upcast 'value' to 'int64_t' prevent overflow during the sign change.
return {true, -static_cast<int64_t>(value)};
}
return {false, value};
};
size_t start = 0;
bool isNegativeStart = false;
size_t length = 0;
if (arity == 2) {
std::tie(isNegativeStart, start) = absWithSign(limit);
length = start;
if (!isNegativeStart) {
start = 0;
}
} else {
if (limit < 0) {
return {false, value::TypeTags::Nothing, 0};
}
length = limit;
auto [skipOwned, skipTag, skipValue] = getFromStack(2);
if (skipTag != value::TypeTags::NumberInt32) {
return {false, value::TypeTags::Nothing, 0};
}
auto skip = value::bitcastTo<int32_t>(skipValue);
std::tie(isNegativeStart, start) = absWithSign(skip);
}
auto [resultTag, resultValue] = value::makeNewArray();
value::ValueGuard resultGuard{resultTag, resultValue};
auto resultView = value::getArrayView(resultValue);
if (arrayTag == value::TypeTags::Array) {
auto arrayView = value::getArrayView(arrayValue);
auto arraySize = arrayView->size();
auto convertedStart = [&]() -> size_t {
if (isNegativeStart) {
if (start > arraySize) {
return 0;
} else {
return arraySize - start;
}
} else {
return std::min(start, arraySize);
}
}();
size_t end = convertedStart + std::min(length, arraySize - convertedStart);
if (convertedStart < end) {
resultView->reserve(end - convertedStart);
for (size_t i = convertedStart; i < end; i++) {
auto [tag, value] = arrayView->getAt(i);
auto [copyTag, copyValue] = value::copyValue(tag, value);
resultView->push_back(copyTag, copyValue);
}
}
} else {
auto advance = [](value::ArrayEnumerator& enumerator, size_t offset) {
size_t i = 0;
while (i < offset && !enumerator.atEnd()) {
i++;
enumerator.advance();
}
};
value::ArrayEnumerator startEnumerator{arrayTag, arrayValue};
if (isNegativeStart) {
value::ArrayEnumerator windowEndEnumerator{arrayTag, arrayValue};
advance(windowEndEnumerator, start);
while (!startEnumerator.atEnd() && !windowEndEnumerator.atEnd()) {
startEnumerator.advance();
windowEndEnumerator.advance();
}
invariant(windowEndEnumerator.atEnd());
} else {
advance(startEnumerator, start);
}
size_t i = 0;
while (i < length && !startEnumerator.atEnd()) {
auto [tag, value] = startEnumerator.getViewOfValue();
auto [copyTag, copyValue] = value::copyValue(tag, value);
resultView->push_back(copyTag, copyValue);
i++;
startEnumerator.advance();
}
}
resultGuard.reset();
return {true, resultTag, resultValue};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinIsArrayEmpty(ArityType arity) {
invariant(arity == 1);
auto [arrayOwned, arrayType, arrayValue] = getFromStack(0);
if (!value::isArray(arrayType)) {
return {false, value::TypeTags::Nothing, 0};
}
if (arrayType == value::TypeTags::Array) {
auto arrayView = value::getArrayView(arrayValue);
return {false, value::TypeTags::Boolean, value::bitcastFrom<bool>(arrayView->size() == 0)};
} else if (arrayType == value::TypeTags::bsonArray || arrayType == value::TypeTags::ArraySet) {
value::ArrayEnumerator enumerator(arrayType, arrayValue);
return {false, value::TypeTags::Boolean, value::bitcastFrom<bool>(enumerator.atEnd())};
} else {
// Earlier in this function we bailed out if the 'arrayType' wasn't Array, ArraySet or
// bsonArray, so it should be impossible to reach this point.
MONGO_UNREACHABLE
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinHasNullBytes(ArityType arity) {
invariant(arity == 1);
auto [strOwned, strType, strValue] = getFromStack(0);
if (!value::isString(strType)) {
return {false, value::TypeTags::Nothing, 0};
}
auto stringView = value::getStringView(strType, strValue);
auto hasNullBytes = stringView.find('\0') != std::string::npos;
return {false, value::TypeTags::Boolean, value::bitcastFrom<bool>(hasNullBytes)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinGetRegexPattern(ArityType arity) {
invariant(arity == 1);
auto [regexOwned, regexType, regexValue] = getFromStack(0);
if (regexType != value::TypeTags::bsonRegex) {
return {false, value::TypeTags::Nothing, 0};
}
auto regex = value::getBsonRegexView(regexValue);
auto [strType, strValue] = value::makeNewString(regex.pattern);
return {true, strType, strValue};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinGetRegexFlags(ArityType arity) {
invariant(arity == 1);
auto [regexOwned, regexType, regexValue] = getFromStack(0);
if (regexType != value::TypeTags::bsonRegex) {
return {false, value::TypeTags::Nothing, 0};
}
auto regex = value::getBsonRegexView(regexValue);
auto [strType, strValue] = value::makeNewString(regex.flags);
return {true, strType, strValue};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinGenerateSortKey(ArityType arity) {
invariant(arity == 2);
auto [ssOwned, ssTag, ssVal] = getFromStack(0);
auto [objOwned, objTag, objVal] = getFromStack(1);
if (ssTag != value::TypeTags::sortSpec || !value::isObject(objTag)) {
return {false, value::TypeTags::Nothing, 0};
}
auto ss = value::getSortSpecView(ssVal);
auto obj = [objTag = objTag, objVal = objVal]() {
if (objTag == value::TypeTags::bsonObject) {
return BSONObj{value::bitcastTo<const char*>(objVal)};
} else if (objTag == value::TypeTags::Object) {
BSONObjBuilder objBuilder;
bson::convertToBsonObj(objBuilder, value::getObjectView(objVal));
return objBuilder.obj();
} else {
MONGO_UNREACHABLE_TASSERT(5037004);
}
}();
return {true,
value::TypeTags::ksValue,
value::bitcastFrom<KeyString::Value*>(new KeyString::Value(ss->generateSortKey(obj)))};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinReverseArray(ArityType arity) {
invariant(arity == 1);
auto [inputOwned, inputType, inputVal] = getFromStack(0);
if (!value::isArray(inputType)) {
return {false, value::TypeTags::Nothing, 0};
}
auto [resultTag, resultVal] = value::makeNewArray();
auto resultView = value::getArrayView(resultVal);
value::ValueGuard resultGuard{resultTag, resultVal};
if (inputType == value::TypeTags::Array) {
auto inputView = value::getArrayView(inputVal);
size_t inputSize = inputView->size();
if (inputSize) {
resultView->reserve(inputSize);
for (size_t i = 0; i < inputSize; i++) {
auto [origTag, origVal] = inputView->getAt(inputSize - 1 - i);
auto [copyTag, copyVal] = copyValue(origTag, origVal);
resultView->push_back(copyTag, copyVal);
}
}
resultGuard.reset();
return {true, resultTag, resultVal};
} else if (inputType == value::TypeTags::bsonArray || inputType == value::TypeTags::ArraySet) {
value::ArrayEnumerator enumerator{inputType, inputVal};
// Using intermediate vector since bsonArray and ArraySet don't
// support reverse iteration.
std::vector<std::pair<value::TypeTags, value::Value>> inputContents;
if (inputType == value::TypeTags::ArraySet) {
// Reserve space to avoid resizing on push_back calls.
auto arraySetView = value::getArraySetView(inputVal);
inputContents.reserve(arraySetView->size());
}
while (!enumerator.atEnd()) {
inputContents.push_back(enumerator.getViewOfValue());
enumerator.advance();
}
if (inputContents.size()) {
resultView->reserve(inputContents.size());
// Run through the array backwards and copy into the result array.
for (auto it = inputContents.rbegin(); it != inputContents.rend(); ++it) {
auto [copyTag, copyVal] = copyValue(it->first, it->second);
resultView->push_back(copyTag, copyVal);
}
}
resultGuard.reset();
return {true, resultTag, resultVal};
} else {
// Earlier in this function we bailed out if the 'inputType' wasn't
// Array, ArraySet or bsonArray, so it should be impossible to reach
// this point.
MONGO_UNREACHABLE;
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinSortArray(ArityType arity) {
invariant(arity == 2 || arity == 3);
auto [inputOwned, inputType, inputVal] = getFromStack(0);
if (!value::isArray(inputType)) {
return {false, value::TypeTags::Nothing, 0};
}
auto [specOwned, specTag, specVal] = getFromStack(1);
if (!value::isObject(specTag)) {
return {false, value::TypeTags::Nothing, 0};
}
CollatorInterface* collator = nullptr;
if (arity == 3) {
auto [collatorOwned, collatorType, collatorVal] = getFromStack(2);
if (collatorType == value::TypeTags::collator) {
collator = value::getCollatorView(collatorVal);
} else {
// If a third parameter was supplied but it is not a Collator, return Nothing.
return {false, value::TypeTags::Nothing, 0};
}
}
auto cmp = value::SbePatternValueCmp(specTag, specVal, collator);
auto [resultTag, resultVal] = value::makeNewArray();
auto resultView = value::getArrayView(resultVal);
value::ValueGuard resultGuard{resultTag, resultVal};
if (inputType == value::TypeTags::Array) {
auto inputView = value::getArrayView(inputVal);
size_t inputSize = inputView->size();
if (inputSize) {
resultView->reserve(inputSize);
std::vector<std::pair<value::TypeTags, value::Value>> sortVector;
for (size_t i = 0; i < inputSize; i++) {
sortVector.push_back(inputView->getAt(i));
}
std::sort(sortVector.begin(), sortVector.end(), cmp);
for (size_t i = 0; i < inputSize; i++) {
auto [tag, val] = sortVector[i];
auto [copyTag, copyVal] = copyValue(tag, val);
resultView->push_back(copyTag, copyVal);
}
}
resultGuard.reset();
return {true, resultTag, resultVal};
} else if (inputType == value::TypeTags::bsonArray || inputType == value::TypeTags::ArraySet) {
value::ArrayEnumerator enumerator{inputType, inputVal};
// Using intermediate vector since bsonArray and ArraySet don't
// support reverse iteration.
std::vector<std::pair<value::TypeTags, value::Value>> inputContents;
if (inputType == value::TypeTags::ArraySet) {
// Reserve space to avoid resizing on push_back calls.
auto arraySetView = value::getArraySetView(inputVal);
inputContents.reserve(arraySetView->size());
}
while (!enumerator.atEnd()) {
inputContents.push_back(enumerator.getViewOfValue());
enumerator.advance();
}
std::sort(inputContents.begin(), inputContents.end(), cmp);
if (inputContents.size()) {
resultView->reserve(inputContents.size());
for (auto it = inputContents.begin(); it != inputContents.end(); ++it) {
auto [copyTag, copyVal] = copyValue(it->first, it->second);
resultView->push_back(copyTag, copyVal);
}
}
resultGuard.reset();
return {true, resultTag, resultVal};
} else {
// Earlier in this function we bailed out if the 'inputType' wasn't
// Array, ArraySet or bsonArray, so it should be impossible to reach
// this point.
MONGO_UNREACHABLE;
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinDateAdd(ArityType arity) {
invariant(arity == 5);
auto [timezoneDBOwn, timezoneDBTag, timezoneDBVal] = getFromStack(0);
if (timezoneDBTag != value::TypeTags::timeZoneDB) {
return {false, value::TypeTags::Nothing, 0};
}
auto timezoneDB = value::getTimeZoneDBView(timezoneDBVal);
auto [startDateOwn, startDateTag, startDateVal] = getFromStack(1);
if (!coercibleToDate(startDateTag)) {
return {false, value::TypeTags::Nothing, 0};
}
auto startDate = getDate(startDateTag, startDateVal);
auto [unitOwn, unitTag, unitVal] = getFromStack(2);
if (!value::isString(unitTag)) {
return {false, value::TypeTags::Nothing, 0};
}
std::string unitStr{value::getStringView(unitTag, unitVal)};
if (!isValidTimeUnit(unitStr)) {
return {false, value::TypeTags::Nothing, 0};
}
auto unit = parseTimeUnit(unitStr);
auto [amountOwn, amountTag, amountVal] = getFromStack(3);
if (amountTag != value::TypeTags::NumberInt64) {
return {false, value::TypeTags::Nothing, 0};
}
auto amount = value::bitcastTo<int64_t>(amountVal);
auto [timezoneOwn, timezoneTag, timezoneVal] = getFromStack(4);
if (!value::isString(timezoneTag) || !isValidTimezone(timezoneTag, timezoneVal, timezoneDB)) {
return {false, value::TypeTags::Nothing, 0};
}
auto timezone = getTimezone(timezoneTag, timezoneVal, timezoneDB);
auto resDate = dateAdd(startDate, unit, amount, timezone);
return {
false, value::TypeTags::Date, value::bitcastFrom<int64_t>(resDate.toMillisSinceEpoch())};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinFtsMatch(ArityType arity) {
invariant(arity == 2);
auto [matcherOwn, matcherTag, matcherVal] = getFromStack(0);
auto [inputOwn, inputTag, inputVal] = getFromStack(1);
if (matcherTag != value::TypeTags::ftsMatcher || !value::isObject(inputTag)) {
return {false, value::TypeTags::Nothing, 0};
}
auto obj = [inputTag = inputTag, inputVal = inputVal]() {
if (inputTag == value::TypeTags::bsonObject) {
return BSONObj{value::bitcastTo<const char*>(inputVal)};
}
invariant(inputTag == value::TypeTags::Object);
BSONObjBuilder builder;
bson::convertToBsonObj(builder, value::getObjectView(inputVal));
return builder.obj();
}();
const bool matches = value::getFtsMatcherView(matcherVal)->matches(obj);
return {false, value::TypeTags::Boolean, value::bitcastFrom<bool>(matches)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinTsSecond(ArityType arity) {
invariant(arity == 1);
auto [inputValueOwn, inputTypeTag, inputValue] = getFromStack(0);
if (inputTypeTag != value::TypeTags::Timestamp) {
return {false, value::TypeTags::Nothing, 0};
}
auto timestamp = Timestamp(value::bitcastTo<uint64_t>(inputValue));
return {false, value::TypeTags::NumberInt64, value::bitcastFrom<uint64_t>(timestamp.getSecs())};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinTsIncrement(ArityType arity) {
invariant(arity == 1);
auto [inputValueOwn, inputTypeTag, inputValue] = getFromStack(0);
if (inputTypeTag != value::TypeTags::Timestamp) {
return {false, value::TypeTags::Nothing, 0};
}
auto timestamp = Timestamp(value::bitcastTo<uint64_t>(inputValue));
return {false, value::TypeTags::NumberInt64, value::bitcastFrom<uint64_t>(timestamp.getInc())};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::builtinHash(ArityType arity) {
auto hashVal = value::hashInit();
for (ArityType idx = 0; idx < arity; ++idx) {
auto [owned, tag, val] = getFromStack(idx);
hashVal = value::hashCombine(hashVal, value::hashValue(tag, val));
}
return {false, value::TypeTags::NumberInt64, value::bitcastFrom<decltype(hashVal)>(hashVal)};
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::dispatchBuiltin(Builtin f,
ArityType arity) {
switch (f) {
case Builtin::dateDiff:
return builtinDateDiff(arity);
case Builtin::dateParts:
return builtinDate(arity);
case Builtin::datePartsWeekYear:
return builtinDateWeekYear(arity);
case Builtin::dateToParts:
return builtinDateToParts(arity);
case Builtin::isoDateToParts:
return builtinIsoDateToParts(arity);
case Builtin::dayOfYear:
return builtinDayOfYear(arity);
case Builtin::dayOfMonth:
return builtinDayOfMonth(arity);
case Builtin::dayOfWeek:
return builtinDayOfWeek(arity);
case Builtin::split:
return builtinSplit(arity);
case Builtin::regexMatch:
return builtinRegexMatch(arity);
case Builtin::replaceOne:
return builtinReplaceOne(arity);
case Builtin::dropFields:
return builtinDropFields(arity);
case Builtin::newArray:
return builtinNewArray(arity);
case Builtin::keepFields:
return builtinKeepFields(arity);
case Builtin::newArrayFromRange:
return builtinNewArrayFromRange(arity);
case Builtin::newObj:
return builtinNewObj(arity);
case Builtin::ksToString:
return builtinKeyStringToString(arity);
case Builtin::newKs:
return builtinNewKeyString(arity);
case Builtin::abs:
return builtinAbs(arity);
case Builtin::ceil:
return builtinCeil(arity);
case Builtin::floor:
return builtinFloor(arity);
case Builtin::trunc:
return builtinTrunc(arity);
case Builtin::exp:
return builtinExp(arity);
case Builtin::ln:
return builtinLn(arity);
case Builtin::log10:
return builtinLog10(arity);
case Builtin::sqrt:
return builtinSqrt(arity);
case Builtin::addToArray:
return builtinAddToArray(arity);
case Builtin::mergeObjects:
return builtinMergeObjects(arity);
case Builtin::addToSet:
return builtinAddToSet(arity);
case Builtin::collAddToSet:
return builtinCollAddToSet(arity);
case Builtin::doubleDoubleSum:
return builtinDoubleDoubleSum(arity);
case Builtin::aggDoubleDoubleSum:
return builtinAggDoubleDoubleSum(arity);
case Builtin::doubleDoubleSumFinalize:
return builtinDoubleDoubleSumFinalize<>(arity);
case Builtin::doubleDoubleMergeSumFinalize:
// This is for sharding support of aggregations that use 'doubleDoubleSum' algorithm.
// We should keep precision for integral values when the partial sum is to be merged.
return builtinDoubleDoubleSumFinalize<true /*keepIntegerPrecision*/>(arity);
case Builtin::aggStdDev:
return builtinAggStdDev(arity);
case Builtin::stdDevPopFinalize:
return builtinStdDevPopFinalize(arity);
case Builtin::stdDevSampFinalize:
return builtinStdDevSampFinalize(arity);
case Builtin::bitTestZero:
return builtinBitTestZero(arity);
case Builtin::bitTestMask:
return builtinBitTestMask(arity);
case Builtin::bitTestPosition:
return builtinBitTestPosition(arity);
case Builtin::bsonSize:
return builtinBsonSize(arity);
case Builtin::toUpper:
return builtinToUpper(arity);
case Builtin::toLower:
return builtinToLower(arity);
case Builtin::coerceToString:
return builtinCoerceToString(arity);
case Builtin::acos:
return builtinAcos(arity);
case Builtin::acosh:
return builtinAcosh(arity);
case Builtin::asin:
return builtinAsin(arity);
case Builtin::asinh:
return builtinAsinh(arity);
case Builtin::atan:
return builtinAtan(arity);
case Builtin::atanh:
return builtinAtanh(arity);
case Builtin::atan2:
return builtinAtan2(arity);
case Builtin::cos:
return builtinCos(arity);
case Builtin::cosh:
return builtinCosh(arity);
case Builtin::degreesToRadians:
return builtinDegreesToRadians(arity);
case Builtin::radiansToDegrees:
return builtinRadiansToDegrees(arity);
case Builtin::sin:
return builtinSin(arity);
case Builtin::sinh:
return builtinSinh(arity);
case Builtin::tan:
return builtinTan(arity);
case Builtin::tanh:
return builtinTanh(arity);
case Builtin::round:
return builtinRound(arity);
case Builtin::concat:
return builtinConcat(arity);
case Builtin::isMember:
return builtinIsMember(arity);
case Builtin::collIsMember:
return builtinCollIsMember(arity);
case Builtin::indexOfBytes:
return builtinIndexOfBytes(arity);
case Builtin::indexOfCP:
return builtinIndexOfCP(arity);
case Builtin::isDayOfWeek:
return builtinIsDayOfWeek(arity);
case Builtin::isTimeUnit:
return builtinIsTimeUnit(arity);
case Builtin::isTimezone:
return builtinIsTimezone(arity);
case Builtin::setUnion:
return builtinSetUnion(arity);
case Builtin::setIntersection:
return builtinSetIntersection(arity);
case Builtin::setDifference:
return builtinSetDifference(arity);
case Builtin::collSetUnion:
return builtinCollSetUnion(arity);
case Builtin::collSetIntersection:
return builtinCollSetIntersection(arity);
case Builtin::collSetDifference:
return builtinCollSetDifference(arity);
case Builtin::runJsPredicate:
return builtinRunJsPredicate(arity);
case Builtin::regexCompile:
return builtinRegexCompile(arity);
case Builtin::regexFind:
return builtinRegexFind(arity);
case Builtin::regexFindAll:
return builtinRegexFindAll(arity);
case Builtin::shardFilter:
return builtinShardFilter(arity);
case Builtin::shardHash:
return builtinShardHash(arity);
case Builtin::extractSubArray:
return builtinExtractSubArray(arity);
case Builtin::isArrayEmpty:
return builtinIsArrayEmpty(arity);
case Builtin::reverseArray:
return builtinReverseArray(arity);
case Builtin::sortArray:
return builtinSortArray(arity);
case Builtin::dateAdd:
return builtinDateAdd(arity);
case Builtin::hasNullBytes:
return builtinHasNullBytes(arity);
case Builtin::getRegexPattern:
return builtinGetRegexPattern(arity);
case Builtin::getRegexFlags:
return builtinGetRegexFlags(arity);
case Builtin::hash:
return builtinHash(arity);
case Builtin::ftsMatch:
return builtinFtsMatch(arity);
case Builtin::generateSortKey:
return builtinGenerateSortKey(arity);
case Builtin::tsSecond:
return builtinTsSecond(arity);
case Builtin::tsIncrement:
return builtinTsIncrement(arity);
}
MONGO_UNREACHABLE;
}
void ByteCode::swapStack() {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(1);
// Swap values only if they are not physically same. This is necessary for the
// "swap and pop" idiom for returning a value from the top of the stack (used
// by ELocalBind). For example, consider the case where a series of swap, pop,
// swap, pop... instructions are executed and the value at stack[0] and
// stack[1] are physically identical, but stack[1] is owned and stack[0] is
// not. After swapping them, the 'pop' instruction would free the owned one and
// leave the unowned value dangling. The only exception to this is shallow
// values (values which fit directly inside a 64 bit Value and don't need
// to be freed explicitly).
if (!(rhsTag == lhsTag && rhsVal == lhsVal)) {
setStack(0, lhsOwned, lhsTag, lhsVal);
setStack(1, rhsOwned, rhsTag, rhsVal);
} else {
// See explanation above.
tassert(56123,
"Attempting to swap two identical values when top of stack is owned",
!rhsOwned || isShallowType(rhsTag));
}
}
std::tuple<bool, value::TypeTags, value::Value> ByteCode::runLambdaInternal(
const CodeFragment* code, int64_t position) {
runInternal(code, value::bitcastTo<int64_t>(position));
swapStack();
popStack();
auto [retOwn, retTag, retVal] = getFromStack(0);
popStack();
return {retOwn, retTag, retVal};
}
void ByteCode::runInternal(const CodeFragment* code, int64_t position) {
auto pcPointer = code->instrs().data() + position;
auto pcEnd = pcPointer + code->instrs().size();
for (;;) {
if (pcPointer == pcEnd) {
break;
} else {
Instruction i = readFromMemory<Instruction>(pcPointer);
pcPointer += sizeof(i);
switch (i.tag) {
case Instruction::pushConstVal: {
auto tag = readFromMemory<value::TypeTags>(pcPointer);
pcPointer += sizeof(tag);
auto val = readFromMemory<value::Value>(pcPointer);
pcPointer += sizeof(val);
pushStack(false, tag, val);
break;
}
case Instruction::pushAccessVal: {
auto accessor = readFromMemory<value::SlotAccessor*>(pcPointer);
pcPointer += sizeof(accessor);
auto [tag, val] = accessor->getViewOfValue();
pushStack(false, tag, val);
break;
}
case Instruction::pushMoveVal: {
auto accessor = readFromMemory<value::SlotAccessor*>(pcPointer);
pcPointer += sizeof(accessor);
auto [tag, val] = accessor->copyOrMoveValue();
pushStack(true, tag, val);
break;
}
case Instruction::pushLocalVal: {
auto stackOffset = readFromMemory<int>(pcPointer);
pcPointer += sizeof(stackOffset);
auto [owned, tag, val] = getFromStack(stackOffset);
pushStack(false, tag, val);
break;
}
case Instruction::pushMoveLocalVal: {
auto stackOffset = readFromMemory<int>(pcPointer);
pcPointer += sizeof(stackOffset);
auto [owned, tag, val] = getFromStack(stackOffset);
setStack(stackOffset, false, value::TypeTags::Nothing, 0);
pushStack(owned, tag, val);
break;
}
case Instruction::pushLocalLambda: {
auto offset = readFromMemory<int>(pcPointer);
pcPointer += sizeof(offset);
auto newPosition = pcPointer - code->instrs().data() + offset;
pushStack(false,
value::TypeTags::LocalLambda,
value::bitcastFrom<int64_t>(newPosition));
break;
}
case Instruction::pop: {
auto [owned, tag, val] = getFromStack(0);
popStack();
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::swap: {
swapStack();
break;
}
case Instruction::add: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [owned, tag, val] = genericAdd(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(owned, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::sub: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [owned, tag, val] = genericSub(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(owned, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::mul: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [owned, tag, val] = genericMul(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(owned, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::div: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [owned, tag, val] = genericDiv(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(owned, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::idiv: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [owned, tag, val] = genericIDiv(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(owned, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::mod: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [owned, tag, val] = genericMod(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(owned, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::negate: {
auto [owned, tag, val] = getFromStack(0);
auto [resultOwned, resultTag, resultVal] = genericSub(
value::TypeTags::NumberInt32, value::bitcastFrom<int32_t>(0), tag, val);
topStack(resultOwned, resultTag, resultVal);
if (owned) {
value::releaseValue(resultTag, resultVal);
}
break;
}
case Instruction::numConvert: {
auto tag = readFromMemory<value::TypeTags>(pcPointer);
pcPointer += sizeof(tag);
auto [owned, lhsTag, lhsVal] = getFromStack(0);
auto [rhsOwned, rhsTag, rhsVal] = genericNumConvert(lhsTag, lhsVal, tag);
topStack(rhsOwned, rhsTag, rhsVal);
if (owned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::logicNot: {
auto [owned, tag, val] = getFromStack(0);
auto [resultTag, resultVal] = genericNot(tag, val);
topStack(false, resultTag, resultVal);
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::less: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [tag, val] = genericCompare<std::less<>>(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::collLess: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
popStack();
auto [collOwned, collTag, collVal] = getFromStack(0);
auto [tag, val] = genericCompare<std::less<>>(
lhsTag, lhsVal, rhsTag, rhsVal, collTag, collVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
if (collOwned) {
value::releaseValue(collTag, collVal);
}
break;
}
case Instruction::lessEq: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [tag, val] =
genericCompare<std::less_equal<>>(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::collLessEq: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
popStack();
auto [collOwned, collTag, collVal] = getFromStack(0);
auto [tag, val] = genericCompare<std::less_equal<>>(
lhsTag, lhsVal, rhsTag, rhsVal, collTag, collVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
if (collOwned) {
value::releaseValue(collTag, collVal);
}
break;
}
case Instruction::greater: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [tag, val] =
genericCompare<std::greater<>>(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::collGreater: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
popStack();
auto [collOwned, collTag, collVal] = getFromStack(0);
auto [tag, val] = genericCompare<std::greater<>>(
lhsTag, lhsVal, rhsTag, rhsVal, collTag, collVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
if (collOwned) {
value::releaseValue(collTag, collVal);
}
break;
}
case Instruction::greaterEq: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [tag, val] =
genericCompare<std::greater_equal<>>(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::collGreaterEq: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
popStack();
auto [collOwned, collTag, collVal] = getFromStack(0);
auto [tag, val] = genericCompare<std::greater_equal<>>(
lhsTag, lhsVal, rhsTag, rhsVal, collTag, collVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
if (collOwned) {
value::releaseValue(collTag, collVal);
}
break;
}
case Instruction::eq: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [tag, val] =
genericCompare<std::equal_to<>>(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::collEq: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
popStack();
auto [collOwned, collTag, collVal] = getFromStack(0);
auto [tag, val] = genericCompare<std::equal_to<>>(
lhsTag, lhsVal, rhsTag, rhsVal, collTag, collVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
if (collOwned) {
value::releaseValue(collTag, collVal);
}
break;
}
case Instruction::neq: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [tag, val] =
genericCompare<std::equal_to<>>(lhsTag, lhsVal, rhsTag, rhsVal);
std::tie(tag, val) = genericNot(tag, val);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::collNeq: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
popStack();
auto [collOwned, collTag, collVal] = getFromStack(0);
auto [tag, val] = genericCompare<std::equal_to<>>(
lhsTag, lhsVal, rhsTag, rhsVal, collTag, collVal);
std::tie(tag, val) = genericNot(tag, val);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
if (collOwned) {
value::releaseValue(collTag, collVal);
}
break;
}
case Instruction::cmp3w: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [tag, val] = compare3way(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::collCmp3w: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
popStack();
auto [collOwned, collTag, collVal] = getFromStack(0);
auto [tag, val] = compare3way(lhsTag, lhsVal, rhsTag, rhsVal, collTag, collVal);
topStack(false, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
if (collOwned) {
value::releaseValue(collTag, collVal);
}
break;
}
case Instruction::fillEmpty: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
if (lhsTag == value::TypeTags::Nothing) {
topStack(rhsOwned, rhsTag, rhsVal);
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
} else {
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
}
break;
}
case Instruction::getField: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [owned, tag, val] = getField(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(owned, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::getElement: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [owned, tag, val] = getElement(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(owned, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::getArraySize: {
auto [owned, tag, val] = getFromStack(0);
auto [resultOwned, resultTag, resultVal] = getArraySize(tag, val);
topStack(resultOwned, resultTag, resultVal);
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::collComparisonKey: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
if (lhsTag != value::TypeTags::Nothing && rhsTag == value::TypeTags::collator) {
// If lhs is a collatable type, call collComparisonKey() to obtain the
// comparison key. If lhs is not a collatable type, we can just leave it
// on the stack as-is.
if (value::isCollatableType(lhsTag)) {
auto collator = value::getCollatorView(rhsVal);
auto [tag, val] = collComparisonKey(lhsTag, lhsVal, collator);
topStack(true, tag, val);
} else {
// Set 'lhsOwned' to false so that lhs doesn't get released below.
lhsOwned = false;
}
} else {
// If lhs was Nothing or rhs wasn't Collator, return Nothing.
topStack(false, value::TypeTags::Nothing, 0);
}
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::getFieldOrElement: {
auto [rhsOwned, rhsTag, rhsVal] = getFromStack(0);
popStack();
auto [lhsOwned, lhsTag, lhsVal] = getFromStack(0);
auto [owned, tag, val] = getFieldOrElement(lhsTag, lhsVal, rhsTag, rhsVal);
topStack(owned, tag, val);
if (rhsOwned) {
value::releaseValue(rhsTag, rhsVal);
}
if (lhsOwned) {
value::releaseValue(lhsTag, lhsVal);
}
break;
}
case Instruction::traverseP: {
auto [owned, tag, val] = traverseP(code);
for (uint8_t cnt = 0; cnt < 2; ++cnt) {
popAndReleaseStack();
}
pushStack(owned, tag, val);
break;
}
case Instruction::traverseF: {
auto [owned, tag, val] = traverseF(code);
for (uint8_t cnt = 0; cnt < 3; ++cnt) {
popAndReleaseStack();
}
pushStack(owned, tag, val);
break;
}
case Instruction::setField: {
auto [owned, tag, val] = setField();
popAndReleaseStack();
popAndReleaseStack();
popAndReleaseStack();
pushStack(owned, tag, val);
break;
}
case Instruction::aggSum: {
auto [fieldOwned, fieldTag, fieldVal] = getFromStack(0);
popStack();
auto [accOwned, accTag, accVal] = getFromStack(0);
auto [owned, tag, val] = aggSum(accTag, accVal, fieldTag, fieldVal);
topStack(owned, tag, val);
if (fieldOwned) {
value::releaseValue(fieldTag, fieldVal);
}
if (accOwned) {
value::releaseValue(accTag, accVal);
}
break;
}
case Instruction::aggMin: {
auto [fieldOwned, fieldTag, fieldVal] = getFromStack(0);
popStack();
auto [accOwned, accTag, accVal] = getFromStack(0);
auto [owned, tag, val] = aggMin(accTag, accVal, fieldTag, fieldVal);
topStack(owned, tag, val);
if (fieldOwned) {
value::releaseValue(fieldTag, fieldVal);
}
if (accOwned) {
value::releaseValue(accTag, accVal);
}
break;
}
case Instruction::aggCollMin: {
auto [fieldOwned, fieldTag, fieldVal] = getFromStack(0);
popStack();
auto [collOwned, collTag, collVal] = getFromStack(0);
popStack();
auto [accOwned, accTag, accVal] = getFromStack(0);
// Skip aggregation step if the collation is Nothing or an unexpected type.
if (collTag != value::TypeTags::collator) {
auto [tag, val] = value::copyValue(accTag, accVal);
topStack(true, tag, val);
break;
}
auto collator = value::getCollatorView(collVal);
auto [owned, tag, val] = aggMin(accTag, accVal, fieldTag, fieldVal, collator);
topStack(owned, tag, val);
if (fieldOwned) {
value::releaseValue(fieldTag, fieldVal);
}
if (collOwned) {
value::releaseValue(collTag, collVal);
}
if (accOwned) {
value::releaseValue(accTag, accVal);
}
break;
}
case Instruction::aggMax: {
auto [fieldOwned, fieldTag, fieldVal] = getFromStack(0);
popStack();
auto [accOwned, accTag, accVal] = getFromStack(0);
auto [owned, tag, val] = aggMax(accTag, accVal, fieldTag, fieldVal);
topStack(owned, tag, val);
if (fieldOwned) {
value::releaseValue(fieldTag, fieldVal);
}
if (accOwned) {
value::releaseValue(accTag, accVal);
}
break;
}
case Instruction::aggCollMax: {
auto [fieldOwned, fieldTag, fieldVal] = getFromStack(0);
popStack();
auto [collOwned, collTag, collVal] = getFromStack(0);
popStack();
auto [accOwned, accTag, accVal] = getFromStack(0);
// Skip aggregation step if the collation is Nothing or an unexpected type.
if (collTag != value::TypeTags::collator) {
auto [tag, val] = value::copyValue(accTag, accVal);
topStack(true, tag, val);
break;
}
auto collator = value::getCollatorView(collVal);
auto [owned, tag, val] = aggMax(accTag, accVal, fieldTag, fieldVal, collator);
topStack(owned, tag, val);
if (fieldOwned) {
value::releaseValue(fieldTag, fieldVal);
}
if (collOwned) {
value::releaseValue(collTag, collVal);
}
if (accOwned) {
value::releaseValue(accTag, accVal);
}
break;
}
case Instruction::aggFirst: {
auto [fieldOwned, fieldTag, fieldVal] = getFromStack(0);
popStack();
auto [accOwned, accTag, accVal] = getFromStack(0);
auto [owned, tag, val] = aggFirst(accTag, accVal, fieldTag, fieldVal);
topStack(owned, tag, val);
if (fieldOwned) {
value::releaseValue(fieldTag, fieldVal);
}
if (accOwned) {
value::releaseValue(accTag, accVal);
}
break;
}
case Instruction::aggLast: {
auto [fieldOwned, fieldTag, fieldVal] = getFromStack(0);
popStack();
auto [accOwned, accTag, accVal] = getFromStack(0);
auto [owned, tag, val] = aggLast(accTag, accVal, fieldTag, fieldVal);
topStack(owned, tag, val);
if (fieldOwned) {
value::releaseValue(fieldTag, fieldVal);
}
if (accOwned) {
value::releaseValue(accTag, accVal);
}
break;
}
case Instruction::exists: {
auto [owned, tag, val] = getFromStack(0);
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(tag != value::TypeTags::Nothing));
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isNull: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(tag == value::TypeTags::Null));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isObject: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(value::isObject(tag)));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isArray: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(value::isArray(tag)));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isString: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(value::isString(tag)));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isNumber: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(value::isNumber(tag)));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isBinData: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(value::isBinData(tag)));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isDate: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(tag == value::TypeTags::Date));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isNaN: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(value::isNaN(tag, val)));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isInfinity: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(value::isInfinity(tag, val)));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isRecordId: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(value::isRecordId(tag)));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isMinKey: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(tag == value::TypeTags::MinKey));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isMaxKey: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(tag == value::TypeTags::MaxKey));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::isTimestamp: {
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
topStack(false,
value::TypeTags::Boolean,
value::bitcastFrom<bool>(tag == value::TypeTags::Timestamp));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::typeMatch: {
auto typeMask = readFromMemory<uint32_t>(pcPointer);
pcPointer += sizeof(typeMask);
auto [owned, tag, val] = getFromStack(0);
if (tag != value::TypeTags::Nothing) {
bool matches = static_cast<bool>(getBSONTypeMask(tag) & typeMask);
topStack(
false, value::TypeTags::Boolean, value::bitcastFrom<bool>(matches));
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::function:
case Instruction::functionSmall: {
auto f = readFromMemory<Builtin>(pcPointer);
pcPointer += sizeof(f);
ArityType arity{0};
if (i.tag == Instruction::function) {
arity = readFromMemory<ArityType>(pcPointer);
pcPointer += sizeof(ArityType);
} else {
arity = readFromMemory<SmallArityType>(pcPointer);
pcPointer += sizeof(SmallArityType);
}
auto [owned, tag, val] = dispatchBuiltin(f, arity);
for (ArityType cnt = 0; cnt < arity; ++cnt) {
popAndReleaseStack();
}
pushStack(owned, tag, val);
break;
}
case Instruction::jmp: {
auto jumpOffset = readFromMemory<int>(pcPointer);
pcPointer += sizeof(jumpOffset);
pcPointer += jumpOffset;
break;
}
case Instruction::jmpTrue: {
auto jumpOffset = readFromMemory<int>(pcPointer);
pcPointer += sizeof(jumpOffset);
auto [owned, tag, val] = getFromStack(0);
popStack();
if (tag == value::TypeTags::Boolean && value::bitcastTo<bool>(val)) {
pcPointer += jumpOffset;
}
if (owned) {
value::releaseValue(tag, val);
}
break;
}
case Instruction::jmpNothing: {
auto jumpOffset = readFromMemory<int>(pcPointer);
pcPointer += sizeof(jumpOffset);
auto [owned, tag, val] = getFromStack(0);
if (tag == value::TypeTags::Nothing) {
pcPointer += jumpOffset;
}
break;
}
case Instruction::ret: {
pcPointer = pcEnd;
break;
}
case Instruction::fail: {
auto [ownedCode, tagCode, valCode] = getFromStack(1);
invariant(tagCode == value::TypeTags::NumberInt64);
auto [ownedMsg, tagMsg, valMsg] = getFromStack(0);
invariant(value::isString(tagMsg));
ErrorCodes::Error code{
static_cast<ErrorCodes::Error>(value::bitcastTo<int64_t>(valCode))};
std::string message{value::getStringView(tagMsg, valMsg)};
uasserted(code, message);
break;
}
default:
MONGO_UNREACHABLE;
}
}
}
}
std::tuple<uint8_t, value::TypeTags, value::Value> ByteCode::run(const CodeFragment* code) {
uassert(6040900, "The evaluation stack must be empty", _argStack.size() == 0);
ON_BLOCK_EXIT([&] {
auto size = _argStack.size();
for (size_t i = 0; i < size; ++i) {
auto [owned, tag] = _argStack.ownedAndTag(i);
if (owned) {
value::releaseValue(tag, _argStack.value(i));
}
}
_argStack.resize(0);
});
runInternal(code, 0);
uassert(4822801, "The evaluation stack must hold only a single value", _argStack.size() == 1);
auto [owned, tag] = _argStack.ownedAndTag(0);
auto val = _argStack.value(0);
// Transfer ownership of tag/val to the caller
_argStack.resize(0);
return {owned, tag, val};
}
bool ByteCode::runPredicate(const CodeFragment* code) {
auto [owned, tag, val] = run(code);
bool pass = (tag == value::TypeTags::Boolean) && value::bitcastTo<bool>(val);
if (owned) {
value::releaseValue(tag, val);
}
return pass;
}
} // namespace vm
} // namespace sbe
} // namespace mongo
|