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
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
|
/**
* Copyright (C) 2018-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.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/pipeline/expression.h"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <cstdio>
#include <vector>
#include "mongo/db/commands/feature_compatibility_version_documentation.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/pipeline/document.h"
#include "mongo/db/pipeline/expression_context.h"
#include "mongo/db/pipeline/value.h"
#include "mongo/db/query/datetime/date_time_support.h"
#include "mongo/platform/bits.h"
#include "mongo/platform/decimal128.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/string_map.h"
#include "mongo/util/summation.h"
namespace mongo {
using Parser = Expression::Parser;
using namespace mongoutils;
using boost::intrusive_ptr;
using std::map;
using std::move;
using std::pair;
using std::set;
using std::string;
using std::vector;
/// Helper function to easily wrap constants with $const.
static Value serializeConstant(Value val) {
if (val.missing()) {
return Value("$$REMOVE"_sd);
}
return Value(DOC("$const" << val));
}
/* --------------------------- Expression ------------------------------ */
string Expression::removeFieldPrefix(const string& prefixedField) {
uassert(16419,
str::stream() << "field path must not contain embedded null characters"
<< prefixedField.find("\0")
<< ",",
prefixedField.find('\0') == string::npos);
const char* pPrefixedField = prefixedField.c_str();
uassert(15982,
str::stream() << "field path references must be prefixed with a '$' ('" << prefixedField
<< "'",
pPrefixedField[0] == '$');
return string(pPrefixedField + 1);
}
intrusive_ptr<Expression> Expression::parseObject(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONObj obj,
const VariablesParseState& vps) {
if (obj.isEmpty()) {
return ExpressionObject::create(expCtx, {});
}
if (obj.firstElementFieldName()[0] == '$') {
// Assume this is an expression like {$add: [...]}.
return parseExpression(expCtx, obj, vps);
}
return ExpressionObject::parse(expCtx, obj, vps);
}
namespace {
struct ParserRegistration {
Parser parser;
boost::optional<ServerGlobalParams::FeatureCompatibility::Version> requiredMinVersion;
};
StringMap<ParserRegistration> parserMap;
}
void Expression::registerExpression(
string key,
Parser parser,
boost::optional<ServerGlobalParams::FeatureCompatibility::Version> requiredMinVersion) {
auto op = parserMap.find(key);
massert(17064,
str::stream() << "Duplicate expression (" << key << ") registered.",
op == parserMap.end());
parserMap[key] = {parser, requiredMinVersion};
}
intrusive_ptr<Expression> Expression::parseExpression(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONObj obj,
const VariablesParseState& vps) {
uassert(15983,
str::stream() << "An object representing an expression must have exactly one "
"field: "
<< obj.toString(),
obj.nFields() == 1);
// Look up the parser associated with the expression name.
const char* opName = obj.firstElementFieldName();
auto it = parserMap.find(opName);
uassert(ErrorCodes::InvalidPipelineOperator,
str::stream() << "Unrecognized expression '" << opName << "'",
it != parserMap.end());
// Make sure we are allowed to use this expression under the current feature compatibility
// version.
auto& entry = it->second;
uassert(
ErrorCodes::QueryFeatureNotAllowed,
// TODO SERVER-31968 we would like to include the current version and the required minimum
// version in this error message, but using FeatureCompatibilityVersion::toString() would
// introduce a dependency cycle.
str::stream() << opName
<< " is not allowed in the current feature compatibility version. See "
<< feature_compatibility_version_documentation::kCompatibilityLink
<< " for more information.",
!expCtx->maxFeatureCompatibilityVersion || !entry.requiredMinVersion ||
(*entry.requiredMinVersion <= *expCtx->maxFeatureCompatibilityVersion));
return entry.parser(expCtx, obj.firstElement(), vps);
}
Expression::ExpressionVector ExpressionNary::parseArguments(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement exprElement,
const VariablesParseState& vps) {
ExpressionVector out;
if (exprElement.type() == Array) {
BSONForEach(elem, exprElement.Obj()) {
out.push_back(Expression::parseOperand(expCtx, elem, vps));
}
} else { // Assume it's an operand that accepts a single argument.
out.push_back(Expression::parseOperand(expCtx, exprElement, vps));
}
return out;
}
intrusive_ptr<Expression> Expression::parseOperand(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement exprElement,
const VariablesParseState& vps) {
BSONType type = exprElement.type();
if (type == String && exprElement.valuestr()[0] == '$') {
/* if we got here, this is a field path expression */
return ExpressionFieldPath::parse(expCtx, exprElement.str(), vps);
} else if (type == Object) {
return Expression::parseObject(expCtx, exprElement.Obj(), vps);
} else if (type == Array) {
return ExpressionArray::parse(expCtx, exprElement, vps);
} else {
return ExpressionConstant::parse(expCtx, exprElement, vps);
}
}
namespace {
/**
* UTF-8 multi-byte code points consist of one leading byte of the form 11xxxxxx, and potentially
* many continuation bytes of the form 10xxxxxx. This method checks whether 'charByte' is a leading
* byte.
*/
bool isLeadingByte(char charByte) {
return (charByte & 0xc0) == 0xc0;
}
/**
* UTF-8 single-byte code points are of the form 0xxxxxxx. This method checks whether 'charByte' is
* a single-byte code point.
*/
bool isSingleByte(char charByte) {
return (charByte & 0x80) == 0x0;
}
size_t getCodePointLength(char charByte) {
if (isSingleByte(charByte)) {
return 1;
}
invariant(isLeadingByte(charByte));
// In UTF-8, the number of leading ones is the number of bytes the code point takes up.
return countLeadingZeros64(~(uint64_t(charByte) << (64 - 8)));
}
} // namespace
/* ------------------------- Register Date Expressions ----------------------------- */
REGISTER_EXPRESSION(dayOfMonth, ExpressionDayOfMonth::parse);
REGISTER_EXPRESSION(dayOfWeek, ExpressionDayOfWeek::parse);
REGISTER_EXPRESSION(dayOfYear, ExpressionDayOfYear::parse);
REGISTER_EXPRESSION(hour, ExpressionHour::parse);
REGISTER_EXPRESSION(isoDayOfWeek, ExpressionIsoDayOfWeek::parse);
REGISTER_EXPRESSION(isoWeek, ExpressionIsoWeek::parse);
REGISTER_EXPRESSION(isoWeekYear, ExpressionIsoWeekYear::parse);
REGISTER_EXPRESSION(millisecond, ExpressionMillisecond::parse);
REGISTER_EXPRESSION(minute, ExpressionMinute::parse);
REGISTER_EXPRESSION(month, ExpressionMonth::parse);
REGISTER_EXPRESSION(second, ExpressionSecond::parse);
REGISTER_EXPRESSION(week, ExpressionWeek::parse);
REGISTER_EXPRESSION(year, ExpressionYear::parse);
/* ----------------------- ExpressionAbs ---------------------------- */
Value ExpressionAbs::evaluateNumericArg(const Value& numericArg) const {
BSONType type = numericArg.getType();
if (type == NumberDouble) {
return Value(std::abs(numericArg.getDouble()));
} else if (type == NumberDecimal) {
return Value(numericArg.getDecimal().toAbs());
} else {
long long num = numericArg.getLong();
uassert(28680,
"can't take $abs of long long min",
num != std::numeric_limits<long long>::min());
long long absVal = std::abs(num);
return type == NumberLong ? Value(absVal) : Value::createIntOrLong(absVal);
}
}
REGISTER_EXPRESSION(abs, ExpressionAbs::parse);
const char* ExpressionAbs::getOpName() const {
return "$abs";
}
/* ------------------------- ExpressionAdd ----------------------------- */
Value ExpressionAdd::evaluate(const Document& root) const {
// We'll try to return the narrowest possible result value while avoiding overflow, loss
// of precision due to intermediate rounding or implicit use of decimal types. To do that,
// compute a compensated sum for non-decimal values and a separate decimal sum for decimal
// values, and track the current narrowest type.
DoubleDoubleSummation nonDecimalTotal;
Decimal128 decimalTotal;
BSONType totalType = NumberInt;
bool haveDate = false;
const size_t n = vpOperand.size();
for (size_t i = 0; i < n; ++i) {
Value val = vpOperand[i]->evaluate(root);
switch (val.getType()) {
case NumberDecimal:
decimalTotal = decimalTotal.add(val.getDecimal());
totalType = NumberDecimal;
break;
case NumberDouble:
nonDecimalTotal.addDouble(val.getDouble());
if (totalType != NumberDecimal)
totalType = NumberDouble;
break;
case NumberLong:
nonDecimalTotal.addLong(val.getLong());
if (totalType == NumberInt)
totalType = NumberLong;
break;
case NumberInt:
nonDecimalTotal.addDouble(val.getInt());
break;
case Date:
uassert(16612, "only one date allowed in an $add expression", !haveDate);
haveDate = true;
nonDecimalTotal.addLong(val.getDate().toMillisSinceEpoch());
break;
default:
uassert(16554,
str::stream() << "$add only supports numeric or date types, not "
<< typeName(val.getType()),
val.nullish());
return Value(BSONNULL);
}
}
if (haveDate) {
int64_t longTotal;
if (totalType == NumberDecimal) {
longTotal = decimalTotal.add(nonDecimalTotal.getDecimal()).toLong();
} else {
uassert(ErrorCodes::Overflow, "date overflow in $add", nonDecimalTotal.fitsLong());
longTotal = nonDecimalTotal.getLong();
}
return Value(Date_t::fromMillisSinceEpoch(longTotal));
}
switch (totalType) {
case NumberDecimal:
return Value(decimalTotal.add(nonDecimalTotal.getDecimal()));
case NumberLong:
dassert(nonDecimalTotal.isInteger());
if (nonDecimalTotal.fitsLong())
return Value(nonDecimalTotal.getLong());
// Fallthrough.
case NumberInt:
if (nonDecimalTotal.fitsLong())
return Value::createIntOrLong(nonDecimalTotal.getLong());
// Fallthrough.
case NumberDouble:
return Value(nonDecimalTotal.getDouble());
default:
massert(16417, "$add resulted in a non-numeric type", false);
}
}
REGISTER_EXPRESSION(add, ExpressionAdd::parse);
const char* ExpressionAdd::getOpName() const {
return "$add";
}
/* ------------------------- ExpressionAllElementsTrue -------------------------- */
Value ExpressionAllElementsTrue::evaluate(const Document& root) const {
const Value arr = vpOperand[0]->evaluate(root);
uassert(17040,
str::stream() << getOpName() << "'s argument must be an array, but is "
<< typeName(arr.getType()),
arr.isArray());
const vector<Value>& array = arr.getArray();
for (vector<Value>::const_iterator it = array.begin(); it != array.end(); ++it) {
if (!it->coerceToBool()) {
return Value(false);
}
}
return Value(true);
}
REGISTER_EXPRESSION(allElementsTrue, ExpressionAllElementsTrue::parse);
const char* ExpressionAllElementsTrue::getOpName() const {
return "$allElementsTrue";
}
/* ------------------------- ExpressionAnd ----------------------------- */
intrusive_ptr<Expression> ExpressionAnd::optimize() {
/* optimize the conjunction as much as possible */
intrusive_ptr<Expression> pE(ExpressionNary::optimize());
/* if the result isn't a conjunction, we can't do anything */
ExpressionAnd* pAnd = dynamic_cast<ExpressionAnd*>(pE.get());
if (!pAnd)
return pE;
/*
Check the last argument on the result; if it's not constant (as
promised by ExpressionNary::optimize(),) then there's nothing
we can do.
*/
const size_t n = pAnd->vpOperand.size();
// ExpressionNary::optimize() generates an ExpressionConstant for {$and:[]}.
verify(n > 0);
intrusive_ptr<Expression> pLast(pAnd->vpOperand[n - 1]);
const ExpressionConstant* pConst = dynamic_cast<ExpressionConstant*>(pLast.get());
if (!pConst)
return pE;
/*
Evaluate and coerce the last argument to a boolean. If it's false,
then we can replace this entire expression.
*/
bool last = pConst->getValue().coerceToBool();
if (!last) {
intrusive_ptr<ExpressionConstant> pFinal(
ExpressionConstant::create(getExpressionContext(), Value(false)));
return pFinal;
}
/*
If we got here, the final operand was true, so we don't need it
anymore. If there was only one other operand, we don't need the
conjunction either. Note we still need to keep the promise that
the result will be a boolean.
*/
if (n == 2) {
intrusive_ptr<Expression> pFinal(
ExpressionCoerceToBool::create(getExpressionContext(), pAnd->vpOperand[0]));
return pFinal;
}
/*
Remove the final "true" value, and return the new expression.
CW TODO:
Note that because of any implicit conversions, we may need to
apply an implicit boolean conversion.
*/
pAnd->vpOperand.resize(n - 1);
return pE;
}
Value ExpressionAnd::evaluate(const Document& root) const {
const size_t n = vpOperand.size();
for (size_t i = 0; i < n; ++i) {
Value pValue(vpOperand[i]->evaluate(root));
if (!pValue.coerceToBool())
return Value(false);
}
return Value(true);
}
REGISTER_EXPRESSION(and, ExpressionAnd::parse);
const char* ExpressionAnd::getOpName() const {
return "$and";
}
/* ------------------------- ExpressionAnyElementTrue -------------------------- */
Value ExpressionAnyElementTrue::evaluate(const Document& root) const {
const Value arr = vpOperand[0]->evaluate(root);
uassert(17041,
str::stream() << getOpName() << "'s argument must be an array, but is "
<< typeName(arr.getType()),
arr.isArray());
const vector<Value>& array = arr.getArray();
for (vector<Value>::const_iterator it = array.begin(); it != array.end(); ++it) {
if (it->coerceToBool()) {
return Value(true);
}
}
return Value(false);
}
REGISTER_EXPRESSION(anyElementTrue, ExpressionAnyElementTrue::parse);
const char* ExpressionAnyElementTrue::getOpName() const {
return "$anyElementTrue";
}
/* ---------------------- ExpressionArray --------------------------- */
Value ExpressionArray::evaluate(const Document& root) const {
vector<Value> values;
values.reserve(vpOperand.size());
for (auto&& expr : vpOperand) {
Value elemVal = expr->evaluate(root);
values.push_back(elemVal.missing() ? Value(BSONNULL) : std::move(elemVal));
}
return Value(std::move(values));
}
Value ExpressionArray::serialize(bool explain) const {
vector<Value> expressions;
expressions.reserve(vpOperand.size());
for (auto&& expr : vpOperand) {
expressions.push_back(expr->serialize(explain));
}
return Value(std::move(expressions));
}
intrusive_ptr<Expression> ExpressionArray::optimize() {
bool allValuesConstant = true;
for (auto&& expr : vpOperand) {
expr = expr->optimize();
if (!dynamic_cast<ExpressionConstant*>(expr.get())) {
allValuesConstant = false;
}
}
// If all values in ExpressionArray are constant evaluate to ExpressionConstant.
if (allValuesConstant) {
return ExpressionConstant::create(getExpressionContext(), evaluate(Document()));
}
return this;
}
const char* ExpressionArray::getOpName() const {
// This should never be called, but is needed to inherit from ExpressionNary.
return "$array";
}
/* ------------------------- ExpressionArrayElemAt -------------------------- */
Value ExpressionArrayElemAt::evaluate(const Document& root) const {
const Value array = vpOperand[0]->evaluate(root);
const Value indexArg = vpOperand[1]->evaluate(root);
if (array.nullish() || indexArg.nullish()) {
return Value(BSONNULL);
}
uassert(28689,
str::stream() << getOpName() << "'s first argument must be an array, but is "
<< typeName(array.getType()),
array.isArray());
uassert(28690,
str::stream() << getOpName() << "'s second argument must be a numeric value,"
<< " but is "
<< typeName(indexArg.getType()),
indexArg.numeric());
uassert(28691,
str::stream() << getOpName() << "'s second argument must be representable as"
<< " a 32-bit integer: "
<< indexArg.coerceToDouble(),
indexArg.integral());
long long i = indexArg.coerceToLong();
if (i < 0 && static_cast<size_t>(std::abs(i)) > array.getArrayLength()) {
// Positive indices that are too large are handled automatically by Value.
return Value();
} else if (i < 0) {
// Index from the back of the array.
i = array.getArrayLength() + i;
}
const size_t index = static_cast<size_t>(i);
return array[index];
}
REGISTER_EXPRESSION(arrayElemAt, ExpressionArrayElemAt::parse);
const char* ExpressionArrayElemAt::getOpName() const {
return "$arrayElemAt";
}
/* ------------------------- ExpressionObjectToArray -------------------------- */
Value ExpressionObjectToArray::evaluate(const Document& root) const {
const Value targetVal = vpOperand[0]->evaluate(root);
if (targetVal.nullish()) {
return Value(BSONNULL);
}
uassert(40390,
str::stream() << "$objectToArray requires a document input, found: "
<< typeName(targetVal.getType()),
(targetVal.getType() == BSONType::Object));
vector<Value> output;
FieldIterator iter = targetVal.getDocument().fieldIterator();
while (iter.more()) {
Document::FieldPair pair = iter.next();
MutableDocument keyvalue;
keyvalue.addField("k", Value(pair.first));
keyvalue.addField("v", pair.second);
output.push_back(keyvalue.freezeToValue());
}
return Value(output);
}
REGISTER_EXPRESSION(objectToArray, ExpressionObjectToArray::parse);
const char* ExpressionObjectToArray::getOpName() const {
return "$objectToArray";
}
/* ------------------------- ExpressionArrayToObject -------------------------- */
Value ExpressionArrayToObject::evaluate(const Document& root) const {
const Value input = vpOperand[0]->evaluate(root);
if (input.nullish()) {
return Value(BSONNULL);
}
uassert(40386,
str::stream() << "$arrayToObject requires an array input, found: "
<< typeName(input.getType()),
input.isArray());
MutableDocument output;
const vector<Value>& array = input.getArray();
if (array.empty()) {
return output.freezeToValue();
}
// There are two accepted input formats in an array: [ [key, val] ] or [ {k:key, v:val} ]. The
// first array element determines the format for the rest of the array. Mixing input formats is
// not allowed.
bool inputArrayFormat;
if (array[0].isArray()) {
inputArrayFormat = true;
} else if (array[0].getType() == BSONType::Object) {
inputArrayFormat = false;
} else {
uasserted(40398,
str::stream() << "Unrecognised input type format for $arrayToObject: "
<< typeName(array[0].getType()));
}
for (auto&& elem : array) {
if (inputArrayFormat == true) {
uassert(
40396,
str::stream() << "$arrayToObject requires a consistent input format. Elements must"
"all be arrays or all be objects. Array was detected, now found: "
<< typeName(elem.getType()),
elem.isArray());
const vector<Value>& valArray = elem.getArray();
uassert(40397,
str::stream() << "$arrayToObject requires an array of size 2 arrays,"
"found array of size: "
<< valArray.size(),
(valArray.size() == 2));
uassert(40395,
str::stream() << "$arrayToObject requires an array of key-value pairs, where "
"the key must be of type string. Found key type: "
<< typeName(valArray[0].getType()),
(valArray[0].getType() == BSONType::String));
output[valArray[0].getString()] = valArray[1];
} else {
uassert(
40391,
str::stream() << "$arrayToObject requires a consistent input format. Elements must"
"all be arrays or all be objects. Object was detected, now found: "
<< typeName(elem.getType()),
(elem.getType() == BSONType::Object));
uassert(40392,
str::stream() << "$arrayToObject requires an object keys of 'k' and 'v'. "
"Found incorrect number of keys:"
<< elem.getDocument().size(),
(elem.getDocument().size() == 2));
Value key = elem.getDocument().getField("k");
Value value = elem.getDocument().getField("v");
uassert(40393,
str::stream() << "$arrayToObject requires an object with keys 'k' and 'v'. "
"Missing either or both keys from: "
<< elem.toString(),
(!key.missing() && !value.missing()));
uassert(
40394,
str::stream() << "$arrayToObject requires an object with keys 'k' and 'v', where "
"the value of 'k' must be of type string. Found type: "
<< typeName(key.getType()),
(key.getType() == BSONType::String));
output[key.getString()] = value;
}
}
return output.freezeToValue();
}
REGISTER_EXPRESSION(arrayToObject, ExpressionArrayToObject::parse);
const char* ExpressionArrayToObject::getOpName() const {
return "$arrayToObject";
}
/* ------------------------- ExpressionCeil -------------------------- */
Value ExpressionCeil::evaluateNumericArg(const Value& numericArg) const {
// There's no point in taking the ceiling of integers or longs, it will have no effect.
switch (numericArg.getType()) {
case NumberDouble:
return Value(std::ceil(numericArg.getDouble()));
case NumberDecimal:
// Round toward the nearest decimal with a zero exponent in the positive direction.
return Value(numericArg.getDecimal().quantize(Decimal128::kNormalizedZero,
Decimal128::kRoundTowardPositive));
default:
return numericArg;
}
}
REGISTER_EXPRESSION(ceil, ExpressionCeil::parse);
const char* ExpressionCeil::getOpName() const {
return "$ceil";
}
/* -------------------- ExpressionCoerceToBool ------------------------- */
intrusive_ptr<ExpressionCoerceToBool> ExpressionCoerceToBool::create(
const intrusive_ptr<ExpressionContext>& expCtx, const intrusive_ptr<Expression>& pExpression) {
intrusive_ptr<ExpressionCoerceToBool> pNew(new ExpressionCoerceToBool(expCtx, pExpression));
return pNew;
}
ExpressionCoerceToBool::ExpressionCoerceToBool(const intrusive_ptr<ExpressionContext>& expCtx,
const intrusive_ptr<Expression>& pTheExpression)
: Expression(expCtx), pExpression(pTheExpression) {}
intrusive_ptr<Expression> ExpressionCoerceToBool::optimize() {
/* optimize the operand */
pExpression = pExpression->optimize();
/* if the operand already produces a boolean, then we don't need this */
/* LATER - Expression to support a "typeof" query? */
Expression* pE = pExpression.get();
if (dynamic_cast<ExpressionAnd*>(pE) || dynamic_cast<ExpressionOr*>(pE) ||
dynamic_cast<ExpressionNot*>(pE) || dynamic_cast<ExpressionCoerceToBool*>(pE))
return pExpression;
return intrusive_ptr<Expression>(this);
}
void ExpressionCoerceToBool::_doAddDependencies(DepsTracker* deps) const {
pExpression->addDependencies(deps);
}
Value ExpressionCoerceToBool::evaluate(const Document& root) const {
Value pResult(pExpression->evaluate(root));
bool b = pResult.coerceToBool();
if (b)
return Value(true);
return Value(false);
}
Value ExpressionCoerceToBool::serialize(bool explain) const {
// When not explaining, serialize to an $and expression. When parsed, the $and expression
// will be optimized back into a ExpressionCoerceToBool.
const char* name = explain ? "$coerceToBool" : "$and";
return Value(DOC(name << DOC_ARRAY(pExpression->serialize(explain))));
}
/* ----------------------- ExpressionCompare --------------------------- */
namespace {
struct BoundOp {
ExpressionCompare::CmpOp op;
auto operator()(const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement bsonExpr,
const VariablesParseState& vps) const {
return ExpressionCompare::parse(expCtx, std::move(bsonExpr), vps, op);
}
};
} // namespace
REGISTER_EXPRESSION(cmp, BoundOp{ExpressionCompare::CMP});
REGISTER_EXPRESSION(eq, BoundOp{ExpressionCompare::EQ});
REGISTER_EXPRESSION(gt, BoundOp{ExpressionCompare::GT});
REGISTER_EXPRESSION(gte, BoundOp{ExpressionCompare::GTE});
REGISTER_EXPRESSION(lt, BoundOp{ExpressionCompare::LT});
REGISTER_EXPRESSION(lte, BoundOp{ExpressionCompare::LTE});
REGISTER_EXPRESSION(ne, BoundOp{ExpressionCompare::NE});
intrusive_ptr<Expression> ExpressionCompare::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement bsonExpr,
const VariablesParseState& vps,
CmpOp op) {
intrusive_ptr<ExpressionCompare> expr = new ExpressionCompare(expCtx, op);
ExpressionVector args = parseArguments(expCtx, bsonExpr, vps);
expr->validateArguments(args);
expr->vpOperand = args;
return expr;
}
boost::intrusive_ptr<ExpressionCompare> ExpressionCompare::create(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
CmpOp cmpOp,
const boost::intrusive_ptr<Expression>& exprLeft,
const boost::intrusive_ptr<Expression>& exprRight) {
boost::intrusive_ptr<ExpressionCompare> expr = new ExpressionCompare(expCtx, cmpOp);
expr->vpOperand = {exprLeft, exprRight};
return expr;
}
namespace {
// Lookup table for truth value returns
struct CmpLookup {
const bool truthValue[3]; // truth value for -1, 0, 1
const ExpressionCompare::CmpOp reverse; // reverse(b,a) returns the same as op(a,b)
const char name[5]; // string name with trailing '\0'
};
static const CmpLookup cmpLookup[7] = {
/* -1 0 1 reverse name */
/* EQ */ {{false, true, false}, ExpressionCompare::EQ, "$eq"},
/* NE */ {{true, false, true}, ExpressionCompare::NE, "$ne"},
/* GT */ {{false, false, true}, ExpressionCompare::LT, "$gt"},
/* GTE */ {{false, true, true}, ExpressionCompare::LTE, "$gte"},
/* LT */ {{true, false, false}, ExpressionCompare::GT, "$lt"},
/* LTE */ {{true, true, false}, ExpressionCompare::GTE, "$lte"},
// CMP is special. Only name is used.
/* CMP */ {{false, false, false}, ExpressionCompare::CMP, "$cmp"},
};
}
Value ExpressionCompare::evaluate(const Document& root) const {
Value pLeft(vpOperand[0]->evaluate(root));
Value pRight(vpOperand[1]->evaluate(root));
int cmp = getExpressionContext()->getValueComparator().compare(pLeft, pRight);
// Make cmp one of 1, 0, or -1.
if (cmp == 0) {
// leave as 0
} else if (cmp < 0) {
cmp = -1;
} else if (cmp > 0) {
cmp = 1;
}
if (cmpOp == CMP)
return Value(cmp);
bool returnValue = cmpLookup[cmpOp].truthValue[cmp + 1];
return Value(returnValue);
}
const char* ExpressionCompare::getOpName() const {
return cmpLookup[cmpOp].name;
}
/* ------------------------- ExpressionConcat ----------------------------- */
Value ExpressionConcat::evaluate(const Document& root) const {
const size_t n = vpOperand.size();
StringBuilder result;
for (size_t i = 0; i < n; ++i) {
Value val = vpOperand[i]->evaluate(root);
if (val.nullish())
return Value(BSONNULL);
uassert(16702,
str::stream() << "$concat only supports strings, not " << typeName(val.getType()),
val.getType() == String);
result << val.coerceToString();
}
return Value(result.str());
}
REGISTER_EXPRESSION(concat, ExpressionConcat::parse);
const char* ExpressionConcat::getOpName() const {
return "$concat";
}
/* ------------------------- ExpressionConcatArrays ----------------------------- */
Value ExpressionConcatArrays::evaluate(const Document& root) const {
const size_t n = vpOperand.size();
vector<Value> values;
for (size_t i = 0; i < n; ++i) {
Value val = vpOperand[i]->evaluate(root);
if (val.nullish()) {
return Value(BSONNULL);
}
uassert(28664,
str::stream() << "$concatArrays only supports arrays, not "
<< typeName(val.getType()),
val.isArray());
const auto& subValues = val.getArray();
values.insert(values.end(), subValues.begin(), subValues.end());
}
return Value(std::move(values));
}
REGISTER_EXPRESSION(concatArrays, ExpressionConcatArrays::parse);
const char* ExpressionConcatArrays::getOpName() const {
return "$concatArrays";
}
/* ----------------------- ExpressionCond ------------------------------ */
Value ExpressionCond::evaluate(const Document& root) const {
Value pCond(vpOperand[0]->evaluate(root));
int idx = pCond.coerceToBool() ? 1 : 2;
return vpOperand[idx]->evaluate(root);
}
intrusive_ptr<Expression> ExpressionCond::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
if (expr.type() != Object) {
return Base::parse(expCtx, expr, vps);
}
verify(str::equals(expr.fieldName(), "$cond"));
intrusive_ptr<ExpressionCond> ret = new ExpressionCond(expCtx);
ret->vpOperand.resize(3);
const BSONObj args = expr.embeddedObject();
BSONForEach(arg, args) {
if (str::equals(arg.fieldName(), "if")) {
ret->vpOperand[0] = parseOperand(expCtx, arg, vps);
} else if (str::equals(arg.fieldName(), "then")) {
ret->vpOperand[1] = parseOperand(expCtx, arg, vps);
} else if (str::equals(arg.fieldName(), "else")) {
ret->vpOperand[2] = parseOperand(expCtx, arg, vps);
} else {
uasserted(17083,
str::stream() << "Unrecognized parameter to $cond: " << arg.fieldName());
}
}
uassert(17080, "Missing 'if' parameter to $cond", ret->vpOperand[0]);
uassert(17081, "Missing 'then' parameter to $cond", ret->vpOperand[1]);
uassert(17082, "Missing 'else' parameter to $cond", ret->vpOperand[2]);
return ret;
}
REGISTER_EXPRESSION(cond, ExpressionCond::parse);
const char* ExpressionCond::getOpName() const {
return "$cond";
}
/* ---------------------- ExpressionConstant --------------------------- */
intrusive_ptr<Expression> ExpressionConstant::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement exprElement,
const VariablesParseState& vps) {
return new ExpressionConstant(expCtx, Value(exprElement));
}
intrusive_ptr<ExpressionConstant> ExpressionConstant::create(
const intrusive_ptr<ExpressionContext>& expCtx, const Value& value) {
intrusive_ptr<ExpressionConstant> pEC(new ExpressionConstant(expCtx, value));
return pEC;
}
ExpressionConstant::ExpressionConstant(const boost::intrusive_ptr<ExpressionContext>& expCtx,
const Value& value)
: Expression(expCtx), _value(value) {}
intrusive_ptr<Expression> ExpressionConstant::optimize() {
/* nothing to do */
return intrusive_ptr<Expression>(this);
}
void ExpressionConstant::_doAddDependencies(DepsTracker* deps) const {
/* nothing to do */
}
Value ExpressionConstant::evaluate(const Document& root) const {
return _value;
}
Value ExpressionConstant::serialize(bool explain) const {
return serializeConstant(_value);
}
REGISTER_EXPRESSION(const, ExpressionConstant::parse);
REGISTER_EXPRESSION(literal, ExpressionConstant::parse); // alias
const char* ExpressionConstant::getOpName() const {
return "$const";
}
/* ---------------------- ExpressionDateFromParts ----------------------- */
/* Helper functions also shared with ExpressionDateToParts */
namespace {
boost::optional<TimeZone> makeTimeZone(const TimeZoneDatabase* tzdb,
const Document& root,
const Expression* timeZone) {
invariant(tzdb);
if (!timeZone) {
return mongo::TimeZoneDatabase::utcZone();
}
auto timeZoneId = timeZone->evaluate(root);
if (timeZoneId.nullish()) {
return boost::none;
}
uassert(40517,
str::stream() << "timezone must evaluate to a string, found "
<< typeName(timeZoneId.getType()),
timeZoneId.getType() == BSONType::String);
return tzdb->getTimeZone(timeZoneId.getString());
}
} // namespace
REGISTER_EXPRESSION(dateFromParts, ExpressionDateFromParts::parse);
intrusive_ptr<Expression> ExpressionDateFromParts::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
uassert(40519,
"$dateFromParts only supports an object as its argument",
expr.type() == BSONType::Object);
BSONElement yearElem;
BSONElement monthElem;
BSONElement dayElem;
BSONElement hourElem;
BSONElement minuteElem;
BSONElement secondElem;
BSONElement millisecondElem;
BSONElement isoWeekYearElem;
BSONElement isoWeekElem;
BSONElement isoDayOfWeekElem;
BSONElement timeZoneElem;
const BSONObj args = expr.embeddedObject();
for (auto&& arg : args) {
auto field = arg.fieldNameStringData();
if (field == "year"_sd) {
yearElem = arg;
} else if (field == "month"_sd) {
monthElem = arg;
} else if (field == "day"_sd) {
dayElem = arg;
} else if (field == "hour"_sd) {
hourElem = arg;
} else if (field == "minute"_sd) {
minuteElem = arg;
} else if (field == "second"_sd) {
secondElem = arg;
} else if (field == "millisecond"_sd) {
millisecondElem = arg;
} else if (field == "isoWeekYear"_sd) {
isoWeekYearElem = arg;
} else if (field == "isoWeek"_sd) {
isoWeekElem = arg;
} else if (field == "isoDayOfWeek"_sd) {
isoDayOfWeekElem = arg;
} else if (field == "timezone"_sd) {
timeZoneElem = arg;
} else {
uasserted(40518,
str::stream() << "Unrecognized argument to $dateFromParts: "
<< arg.fieldName());
}
}
if (!yearElem && !isoWeekYearElem) {
uasserted(40516, "$dateFromParts requires either 'year' or 'isoWeekYear' to be present");
}
if (yearElem && (isoWeekYearElem || isoWeekElem || isoDayOfWeekElem)) {
uasserted(40489, "$dateFromParts does not allow mixing natural dates with ISO dates");
}
if (isoWeekYearElem && (yearElem || monthElem || dayElem)) {
uasserted(40525, "$dateFromParts does not allow mixing ISO dates with natural dates");
}
return new ExpressionDateFromParts(
expCtx,
yearElem ? parseOperand(expCtx, yearElem, vps) : nullptr,
monthElem ? parseOperand(expCtx, monthElem, vps) : nullptr,
dayElem ? parseOperand(expCtx, dayElem, vps) : nullptr,
hourElem ? parseOperand(expCtx, hourElem, vps) : nullptr,
minuteElem ? parseOperand(expCtx, minuteElem, vps) : nullptr,
secondElem ? parseOperand(expCtx, secondElem, vps) : nullptr,
millisecondElem ? parseOperand(expCtx, millisecondElem, vps) : nullptr,
isoWeekYearElem ? parseOperand(expCtx, isoWeekYearElem, vps) : nullptr,
isoWeekElem ? parseOperand(expCtx, isoWeekElem, vps) : nullptr,
isoDayOfWeekElem ? parseOperand(expCtx, isoDayOfWeekElem, vps) : nullptr,
timeZoneElem ? parseOperand(expCtx, timeZoneElem, vps) : nullptr);
}
ExpressionDateFromParts::ExpressionDateFromParts(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
intrusive_ptr<Expression> year,
intrusive_ptr<Expression> month,
intrusive_ptr<Expression> day,
intrusive_ptr<Expression> hour,
intrusive_ptr<Expression> minute,
intrusive_ptr<Expression> second,
intrusive_ptr<Expression> millisecond,
intrusive_ptr<Expression> isoWeekYear,
intrusive_ptr<Expression> isoWeek,
intrusive_ptr<Expression> isoDayOfWeek,
intrusive_ptr<Expression> timeZone)
: Expression(expCtx),
_year(std::move(year)),
_month(std::move(month)),
_day(std::move(day)),
_hour(std::move(hour)),
_minute(std::move(minute)),
_second(std::move(second)),
_millisecond(std::move(millisecond)),
_isoWeekYear(std::move(isoWeekYear)),
_isoWeek(std::move(isoWeek)),
_isoDayOfWeek(std::move(isoDayOfWeek)),
_timeZone(std::move(timeZone)) {}
intrusive_ptr<Expression> ExpressionDateFromParts::optimize() {
if (_year) {
_year = _year->optimize();
}
if (_month) {
_month = _month->optimize();
}
if (_day) {
_day = _day->optimize();
}
if (_hour) {
_hour = _hour->optimize();
}
if (_minute) {
_minute = _minute->optimize();
}
if (_second) {
_second = _second->optimize();
}
if (_millisecond) {
_millisecond = _millisecond->optimize();
}
if (_isoWeekYear) {
_isoWeekYear = _isoWeekYear->optimize();
}
if (_isoWeek) {
_isoWeek = _isoWeek->optimize();
}
if (_isoDayOfWeek) {
_isoDayOfWeek = _isoDayOfWeek->optimize();
}
if (_timeZone) {
_timeZone = _timeZone->optimize();
}
if (ExpressionConstant::allNullOrConstant({_year,
_month,
_day,
_hour,
_minute,
_second,
_millisecond,
_isoWeekYear,
_isoWeek,
_isoDayOfWeek,
_timeZone})) {
// Everything is a constant, so we can turn into a constant.
return ExpressionConstant::create(getExpressionContext(), evaluate(Document{}));
}
return this;
}
Value ExpressionDateFromParts::serialize(bool explain) const {
return Value(Document{
{"$dateFromParts",
Document{{"year", _year ? _year->serialize(explain) : Value()},
{"month", _month ? _month->serialize(explain) : Value()},
{"day", _day ? _day->serialize(explain) : Value()},
{"hour", _hour ? _hour->serialize(explain) : Value()},
{"minute", _minute ? _minute->serialize(explain) : Value()},
{"second", _second ? _second->serialize(explain) : Value()},
{"millisecond", _millisecond ? _millisecond->serialize(explain) : Value()},
{"isoWeekYear", _isoWeekYear ? _isoWeekYear->serialize(explain) : Value()},
{"isoWeek", _isoWeek ? _isoWeek->serialize(explain) : Value()},
{"isoDayOfWeek", _isoDayOfWeek ? _isoDayOfWeek->serialize(explain) : Value()},
{"timezone", _timeZone ? _timeZone->serialize(explain) : Value()}}}});
}
bool ExpressionDateFromParts::evaluateNumberWithDefault(const Document& root,
intrusive_ptr<Expression> field,
StringData fieldName,
long long defaultValue,
long long* returnValue) const {
if (!field) {
*returnValue = defaultValue;
return true;
}
auto fieldValue = field->evaluate(root);
if (fieldValue.nullish()) {
return false;
}
uassert(40515,
str::stream() << "'" << fieldName << "' must evaluate to an integer, found "
<< typeName(fieldValue.getType())
<< " with value "
<< fieldValue.toString(),
fieldValue.integral64Bit());
*returnValue = fieldValue.coerceToLong();
return true;
}
Value ExpressionDateFromParts::evaluate(const Document& root) const {
long long hour, minute, second, millisecond;
if (!evaluateNumberWithDefault(root, _hour, "hour"_sd, 0, &hour) ||
!evaluateNumberWithDefault(root, _minute, "minute"_sd, 0, &minute) ||
!evaluateNumberWithDefault(root, _second, "second"_sd, 0, &second) ||
!evaluateNumberWithDefault(root, _millisecond, "millisecond"_sd, 0, &millisecond)) {
// One of the evaluated inputs in nullish.
return Value(BSONNULL);
}
auto timeZone = makeTimeZone(getExpressionContext()->timeZoneDatabase, root, _timeZone.get());
if (!timeZone) {
return Value(BSONNULL);
}
if (_year) {
long long year, month, day;
if (!evaluateNumberWithDefault(root, _year, "year"_sd, 1970, &year) ||
!evaluateNumberWithDefault(root, _month, "month"_sd, 1, &month) ||
!evaluateNumberWithDefault(root, _day, "day"_sd, 1, &day)) {
// One of the evaluated inputs in nullish.
return Value(BSONNULL);
}
uassert(40523,
str::stream() << "'year' must evaluate to an integer in the range " << 0 << " to "
<< 9999
<< ", found "
<< year,
year >= 0 && year <= 9999);
return Value(
timeZone->createFromDateParts(year, month, day, hour, minute, second, millisecond));
}
if (_isoWeekYear) {
long long isoWeekYear, isoWeek, isoDayOfWeek;
if (!evaluateNumberWithDefault(root, _isoWeekYear, "isoWeekYear"_sd, 1970, &isoWeekYear) ||
!evaluateNumberWithDefault(root, _isoWeek, "isoWeek"_sd, 1, &isoWeek) ||
!evaluateNumberWithDefault(root, _isoDayOfWeek, "isoDayOfWeek"_sd, 1, &isoDayOfWeek)) {
// One of the evaluated inputs in nullish.
return Value(BSONNULL);
}
return Value(timeZone->createFromIso8601DateParts(
isoWeekYear, isoWeek, isoDayOfWeek, hour, minute, second, millisecond));
}
MONGO_UNREACHABLE;
}
void ExpressionDateFromParts::_doAddDependencies(DepsTracker* deps) const {
if (_year) {
_year->addDependencies(deps);
}
if (_month) {
_month->addDependencies(deps);
}
if (_day) {
_day->addDependencies(deps);
}
if (_hour) {
_hour->addDependencies(deps);
}
if (_minute) {
_minute->addDependencies(deps);
}
if (_second) {
_second->addDependencies(deps);
}
if (_millisecond) {
_millisecond->addDependencies(deps);
}
if (_isoWeekYear) {
_isoWeekYear->addDependencies(deps);
}
if (_isoWeek) {
_isoWeek->addDependencies(deps);
}
if (_isoDayOfWeek) {
_isoDayOfWeek->addDependencies(deps);
}
if (_timeZone) {
_timeZone->addDependencies(deps);
}
}
/* ---------------------- ExpressionDateFromString --------------------- */
REGISTER_EXPRESSION(dateFromString, ExpressionDateFromString::parse);
intrusive_ptr<Expression> ExpressionDateFromString::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
uassert(40540,
str::stream() << "$dateFromString only supports an object as an argument, found: "
<< typeName(expr.type()),
expr.type() == BSONType::Object);
BSONElement dateStringElem, timeZoneElem, formatElem, onNullElem, onErrorElem;
const BSONObj args = expr.embeddedObject();
for (auto&& arg : args) {
auto field = arg.fieldNameStringData();
if (field == "format"_sd) {
formatElem = arg;
} else if (field == "dateString"_sd) {
dateStringElem = arg;
} else if (field == "timezone"_sd) {
timeZoneElem = arg;
} else if (field == "onNull"_sd) {
onNullElem = arg;
} else if (field == "onError"_sd) {
onErrorElem = arg;
} else {
uasserted(40541,
str::stream() << "Unrecognized argument to $dateFromString: "
<< arg.fieldName());
}
}
uassert(40542, "Missing 'dateString' parameter to $dateFromString", dateStringElem);
return new ExpressionDateFromString(
expCtx,
parseOperand(expCtx, dateStringElem, vps),
timeZoneElem ? parseOperand(expCtx, timeZoneElem, vps) : nullptr,
formatElem ? parseOperand(expCtx, formatElem, vps) : nullptr,
onNullElem ? parseOperand(expCtx, onNullElem, vps) : nullptr,
onErrorElem ? parseOperand(expCtx, onErrorElem, vps) : nullptr);
}
ExpressionDateFromString::ExpressionDateFromString(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
intrusive_ptr<Expression> dateString,
intrusive_ptr<Expression> timeZone,
intrusive_ptr<Expression> format,
intrusive_ptr<Expression> onNull,
intrusive_ptr<Expression> onError)
: Expression(expCtx),
_dateString(std::move(dateString)),
_timeZone(std::move(timeZone)),
_format(std::move(format)),
_onNull(std::move(onNull)),
_onError(std::move(onError)) {}
intrusive_ptr<Expression> ExpressionDateFromString::optimize() {
_dateString = _dateString->optimize();
if (_timeZone) {
_timeZone = _timeZone->optimize();
}
if (_format) {
_format = _format->optimize();
}
if (_onNull) {
_onNull = _onNull->optimize();
}
if (_onError) {
_onError = _onError->optimize();
}
if (ExpressionConstant::allNullOrConstant(
{_dateString, _timeZone, _format, _onNull, _onError})) {
// Everything is a constant, so we can turn into a constant.
return ExpressionConstant::create(getExpressionContext(), evaluate(Document{}));
}
return this;
}
Value ExpressionDateFromString::serialize(bool explain) const {
return Value(
Document{{"$dateFromString",
Document{{"dateString", _dateString->serialize(explain)},
{"timezone", _timeZone ? _timeZone->serialize(explain) : Value()},
{"format", _format ? _format->serialize(explain) : Value()},
{"onNull", _onNull ? _onNull->serialize(explain) : Value()},
{"onError", _onError ? _onError->serialize(explain) : Value()}}}});
}
Value ExpressionDateFromString::evaluate(const Document& root) const {
const Value dateString = _dateString->evaluate(root);
Value formatValue;
// Eagerly validate the format parameter, ignoring if nullish since the input string nullish
// behavior takes precedence.
if (_format) {
formatValue = _format->evaluate(root);
if (!formatValue.nullish()) {
uassert(40684,
str::stream() << "$dateFromString requires that 'format' be a string, found: "
<< typeName(formatValue.getType())
<< " with value "
<< formatValue.toString(),
formatValue.getType() == BSONType::String);
TimeZone::validateFromStringFormat(formatValue.getStringData());
}
}
// Evaluate the timezone parameter before checking for nullish input, as this will throw an
// exception for an invalid timezone string.
auto timeZone = makeTimeZone(getExpressionContext()->timeZoneDatabase, root, _timeZone.get());
// Behavior for nullish input takes precedence over other nullish elements.
if (dateString.nullish()) {
return _onNull ? _onNull->evaluate(root) : Value(BSONNULL);
}
try {
uassert(ErrorCodes::ConversionFailure,
str::stream() << "$dateFromString requires that 'dateString' be a string, found: "
<< typeName(dateString.getType())
<< " with value "
<< dateString.toString(),
dateString.getType() == BSONType::String);
const auto dateTimeString = dateString.getStringData();
if (!timeZone) {
return Value(BSONNULL);
}
if (_format) {
if (formatValue.nullish()) {
return Value(BSONNULL);
}
return Value(getExpressionContext()->timeZoneDatabase->fromString(
dateTimeString, timeZone.get(), formatValue.getStringData()));
}
return Value(
getExpressionContext()->timeZoneDatabase->fromString(dateTimeString, timeZone.get()));
} catch (const ExceptionFor<ErrorCodes::ConversionFailure>&) {
if (_onError) {
return _onError->evaluate(root);
}
throw;
}
}
void ExpressionDateFromString::_doAddDependencies(DepsTracker* deps) const {
_dateString->addDependencies(deps);
if (_timeZone) {
_timeZone->addDependencies(deps);
}
if (_format) {
_format->addDependencies(deps);
}
if (_onNull) {
_onNull->addDependencies(deps);
}
if (_onError) {
_onError->addDependencies(deps);
}
}
/* ---------------------- ExpressionDateToParts ----------------------- */
REGISTER_EXPRESSION(dateToParts, ExpressionDateToParts::parse);
intrusive_ptr<Expression> ExpressionDateToParts::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
uassert(40524,
"$dateToParts only supports an object as its argument",
expr.type() == BSONType::Object);
BSONElement dateElem;
BSONElement timeZoneElem;
BSONElement isoDateElem;
const BSONObj args = expr.embeddedObject();
for (auto&& arg : args) {
auto field = arg.fieldNameStringData();
if (field == "date"_sd) {
dateElem = arg;
} else if (field == "timezone"_sd) {
timeZoneElem = arg;
} else if (field == "iso8601"_sd) {
isoDateElem = arg;
} else {
uasserted(40520,
str::stream() << "Unrecognized argument to $dateToParts: "
<< arg.fieldName());
}
}
uassert(40522, "Missing 'date' parameter to $dateToParts", dateElem);
return new ExpressionDateToParts(
expCtx,
parseOperand(expCtx, dateElem, vps),
timeZoneElem ? parseOperand(expCtx, timeZoneElem, vps) : nullptr,
isoDateElem ? parseOperand(expCtx, isoDateElem, vps) : nullptr);
}
ExpressionDateToParts::ExpressionDateToParts(const boost::intrusive_ptr<ExpressionContext>& expCtx,
intrusive_ptr<Expression> date,
intrusive_ptr<Expression> timeZone,
intrusive_ptr<Expression> iso8601)
: Expression(expCtx),
_date(std::move(date)),
_timeZone(std::move(timeZone)),
_iso8601(std::move(iso8601)) {}
intrusive_ptr<Expression> ExpressionDateToParts::optimize() {
_date = _date->optimize();
if (_timeZone) {
_timeZone = _timeZone->optimize();
}
if (_iso8601) {
_iso8601 = _iso8601->optimize();
}
if (ExpressionConstant::allNullOrConstant({_date, _iso8601, _timeZone})) {
// Everything is a constant, so we can turn into a constant.
return ExpressionConstant::create(getExpressionContext(), evaluate(Document{}));
}
return this;
}
Value ExpressionDateToParts::serialize(bool explain) const {
return Value(
Document{{"$dateToParts",
Document{{"date", _date->serialize(explain)},
{"timezone", _timeZone ? _timeZone->serialize(explain) : Value()},
{"iso8601", _iso8601 ? _iso8601->serialize(explain) : Value()}}}});
}
boost::optional<int> ExpressionDateToParts::evaluateIso8601Flag(const Document& root) const {
if (!_iso8601) {
return false;
}
auto iso8601Output = _iso8601->evaluate(root);
if (iso8601Output.nullish()) {
return boost::none;
}
uassert(40521,
str::stream() << "iso8601 must evaluate to a bool, found "
<< typeName(iso8601Output.getType()),
iso8601Output.getType() == BSONType::Bool);
return iso8601Output.getBool();
}
Value ExpressionDateToParts::evaluate(const Document& root) const {
const Value date = _date->evaluate(root);
auto timeZone = makeTimeZone(getExpressionContext()->timeZoneDatabase, root, _timeZone.get());
if (!timeZone) {
return Value(BSONNULL);
}
auto iso8601 = evaluateIso8601Flag(root);
if (!iso8601) {
return Value(BSONNULL);
}
if (date.nullish()) {
return Value(BSONNULL);
}
auto dateValue = date.coerceToDate();
if (*iso8601) {
auto parts = timeZone->dateIso8601Parts(dateValue);
return Value(Document{{"isoWeekYear", parts.year},
{"isoWeek", parts.weekOfYear},
{"isoDayOfWeek", parts.dayOfWeek},
{"hour", parts.hour},
{"minute", parts.minute},
{"second", parts.second},
{"millisecond", parts.millisecond}});
} else {
auto parts = timeZone->dateParts(dateValue);
return Value(Document{{"year", parts.year},
{"month", parts.month},
{"day", parts.dayOfMonth},
{"hour", parts.hour},
{"minute", parts.minute},
{"second", parts.second},
{"millisecond", parts.millisecond}});
}
}
void ExpressionDateToParts::_doAddDependencies(DepsTracker* deps) const {
_date->addDependencies(deps);
if (_timeZone) {
_timeZone->addDependencies(deps);
}
if (_iso8601) {
_iso8601->addDependencies(deps);
}
}
/* ---------------------- ExpressionDateToString ----------------------- */
REGISTER_EXPRESSION(dateToString, ExpressionDateToString::parse);
intrusive_ptr<Expression> ExpressionDateToString::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
verify(str::equals(expr.fieldName(), "$dateToString"));
uassert(18629,
"$dateToString only supports an object as its argument",
expr.type() == BSONType::Object);
BSONElement formatElem, dateElem, timeZoneElem, onNullElem;
for (auto&& arg : expr.embeddedObject()) {
auto field = arg.fieldNameStringData();
if (field == "format"_sd) {
formatElem = arg;
} else if (field == "date"_sd) {
dateElem = arg;
} else if (field == "timezone"_sd) {
timeZoneElem = arg;
} else if (field == "onNull"_sd) {
onNullElem = arg;
} else {
uasserted(18534,
str::stream() << "Unrecognized argument to $dateToString: "
<< arg.fieldName());
}
}
uassert(18628, "Missing 'date' parameter to $dateToString", !dateElem.eoo());
return new ExpressionDateToString(expCtx,
parseOperand(expCtx, dateElem, vps),
formatElem ? parseOperand(expCtx, formatElem, vps) : nullptr,
timeZoneElem ? parseOperand(expCtx, timeZoneElem, vps)
: nullptr,
onNullElem ? parseOperand(expCtx, onNullElem, vps) : nullptr);
}
ExpressionDateToString::ExpressionDateToString(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
intrusive_ptr<Expression> date,
intrusive_ptr<Expression> format,
intrusive_ptr<Expression> timeZone,
intrusive_ptr<Expression> onNull)
: Expression(expCtx),
_format(std::move(format)),
_date(std::move(date)),
_timeZone(std::move(timeZone)),
_onNull(std::move(onNull)) {}
intrusive_ptr<Expression> ExpressionDateToString::optimize() {
_date = _date->optimize();
if (_timeZone) {
_timeZone = _timeZone->optimize();
}
if (_onNull) {
_onNull = _onNull->optimize();
}
if (_format) {
_format = _format->optimize();
}
if (ExpressionConstant::allNullOrConstant({_date, _format, _timeZone, _onNull})) {
// Everything is a constant, so we can turn into a constant.
return ExpressionConstant::create(getExpressionContext(), evaluate(Document{}));
}
return this;
}
Value ExpressionDateToString::serialize(bool explain) const {
return Value(
Document{{"$dateToString",
Document{{"date", _date->serialize(explain)},
{"format", _format ? _format->serialize(explain) : Value()},
{"timezone", _timeZone ? _timeZone->serialize(explain) : Value()},
{"onNull", _onNull ? _onNull->serialize(explain) : Value()}}}});
}
Value ExpressionDateToString::evaluate(const Document& root) const {
const Value date = _date->evaluate(root);
Value formatValue;
// Eagerly validate the format parameter, ignoring if nullish since the input date nullish
// behavior takes precedence.
if (_format) {
formatValue = _format->evaluate(root);
if (!formatValue.nullish()) {
uassert(18533,
str::stream() << "$dateToString requires that 'format' be a string, found: "
<< typeName(formatValue.getType())
<< " with value "
<< formatValue.toString(),
formatValue.getType() == BSONType::String);
TimeZone::validateToStringFormat(formatValue.getStringData());
}
}
// Evaluate the timezone parameter before checking for nullish input, as this will throw an
// exception for an invalid timezone string.
auto timeZone = makeTimeZone(getExpressionContext()->timeZoneDatabase, root, _timeZone.get());
if (date.nullish()) {
return _onNull ? _onNull->evaluate(root) : Value(BSONNULL);
}
if (!timeZone) {
return Value(BSONNULL);
}
if (_format) {
if (formatValue.nullish()) {
return Value(BSONNULL);
}
return Value(timeZone->formatDate(formatValue.getStringData(), date.coerceToDate()));
}
return Value(timeZone->formatDate(Value::kISOFormatString, date.coerceToDate()));
}
void ExpressionDateToString::_doAddDependencies(DepsTracker* deps) const {
_date->addDependencies(deps);
if (_timeZone) {
_timeZone->addDependencies(deps);
}
if (_onNull) {
_onNull->addDependencies(deps);
}
if (_format) {
_format->addDependencies(deps);
}
}
/* ----------------------- ExpressionDivide ---------------------------- */
Value ExpressionDivide::evaluate(const Document& root) const {
Value lhs = vpOperand[0]->evaluate(root);
Value rhs = vpOperand[1]->evaluate(root);
auto assertNonZero = [](bool nonZero) { uassert(16608, "can't $divide by zero", nonZero); };
if (lhs.numeric() && rhs.numeric()) {
// If, and only if, either side is decimal, return decimal.
if (lhs.getType() == NumberDecimal || rhs.getType() == NumberDecimal) {
Decimal128 numer = lhs.coerceToDecimal();
Decimal128 denom = rhs.coerceToDecimal();
assertNonZero(!denom.isZero());
return Value(numer.divide(denom));
}
double numer = lhs.coerceToDouble();
double denom = rhs.coerceToDouble();
assertNonZero(denom != 0.0);
return Value(numer / denom);
} else if (lhs.nullish() || rhs.nullish()) {
return Value(BSONNULL);
} else {
uasserted(16609,
str::stream() << "$divide only supports numeric types, not "
<< typeName(lhs.getType())
<< " and "
<< typeName(rhs.getType()));
}
}
REGISTER_EXPRESSION(divide, ExpressionDivide::parse);
const char* ExpressionDivide::getOpName() const {
return "$divide";
}
/* ----------------------- ExpressionExp ---------------------------- */
Value ExpressionExp::evaluateNumericArg(const Value& numericArg) const {
// $exp always returns either a double or a decimal number, as e is irrational.
if (numericArg.getType() == NumberDecimal)
return Value(numericArg.coerceToDecimal().exponential());
return Value(exp(numericArg.coerceToDouble()));
}
REGISTER_EXPRESSION(exp, ExpressionExp::parse);
const char* ExpressionExp::getOpName() const {
return "$exp";
}
/* ---------------------- ExpressionObject --------------------------- */
ExpressionObject::ExpressionObject(const boost::intrusive_ptr<ExpressionContext>& expCtx,
vector<pair<string, intrusive_ptr<Expression>>>&& expressions)
: Expression(expCtx), _expressions(std::move(expressions)) {}
intrusive_ptr<ExpressionObject> ExpressionObject::create(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
vector<pair<string, intrusive_ptr<Expression>>>&& expressions) {
return new ExpressionObject(expCtx, std::move(expressions));
}
intrusive_ptr<ExpressionObject> ExpressionObject::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONObj obj,
const VariablesParseState& vps) {
// Make sure we don't have any duplicate field names.
stdx::unordered_set<string> specifiedFields;
vector<pair<string, intrusive_ptr<Expression>>> expressions;
for (auto&& elem : obj) {
// Make sure this element has a valid field name. Use StringData here so that we can detect
// if the field name contains a null byte.
FieldPath::uassertValidFieldName(elem.fieldNameStringData());
auto fieldName = elem.fieldName();
uassert(16406,
str::stream() << "duplicate field name specified in object literal: "
<< obj.toString(),
specifiedFields.find(fieldName) == specifiedFields.end());
specifiedFields.insert(fieldName);
expressions.emplace_back(fieldName, parseOperand(expCtx, elem, vps));
}
return new ExpressionObject{expCtx, std::move(expressions)};
}
intrusive_ptr<Expression> ExpressionObject::optimize() {
bool allValuesConstant = true;
for (auto&& pair : _expressions) {
pair.second = pair.second->optimize();
if (!dynamic_cast<ExpressionConstant*>(pair.second.get())) {
allValuesConstant = false;
}
}
// If all values in ExpressionObject are constant evaluate to ExpressionConstant.
if (allValuesConstant) {
return ExpressionConstant::create(getExpressionContext(), evaluate(Document()));
}
return this;
}
void ExpressionObject::_doAddDependencies(DepsTracker* deps) const {
for (auto&& pair : _expressions) {
pair.second->addDependencies(deps);
}
}
Value ExpressionObject::evaluate(const Document& root) const {
MutableDocument outputDoc;
for (auto&& pair : _expressions) {
outputDoc.addField(pair.first, pair.second->evaluate(root));
}
return outputDoc.freezeToValue();
}
Value ExpressionObject::serialize(bool explain) const {
MutableDocument outputDoc;
for (auto&& pair : _expressions) {
outputDoc.addField(pair.first, pair.second->serialize(explain));
}
return outputDoc.freezeToValue();
}
Expression::ComputedPaths ExpressionObject::getComputedPaths(const std::string& exprFieldPath,
Variables::Id renamingVar) const {
ComputedPaths outputPaths;
for (auto&& pair : _expressions) {
auto exprComputedPaths = pair.second->getComputedPaths(pair.first, renamingVar);
for (auto&& renames : exprComputedPaths.renames) {
auto newPath = FieldPath::getFullyQualifiedPath(exprFieldPath, renames.first);
outputPaths.renames[std::move(newPath)] = renames.second;
}
for (auto&& path : exprComputedPaths.paths) {
outputPaths.paths.insert(FieldPath::getFullyQualifiedPath(exprFieldPath, path));
}
}
return outputPaths;
}
/* --------------------- ExpressionFieldPath --------------------------- */
// this is the old deprecated version only used by tests not using variables
intrusive_ptr<ExpressionFieldPath> ExpressionFieldPath::create(
const boost::intrusive_ptr<ExpressionContext>& expCtx, const string& fieldPath) {
return new ExpressionFieldPath(expCtx, "CURRENT." + fieldPath, Variables::kRootId);
}
// this is the new version that supports every syntax
intrusive_ptr<ExpressionFieldPath> ExpressionFieldPath::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const string& raw,
const VariablesParseState& vps) {
uassert(16873,
str::stream() << "FieldPath '" << raw << "' doesn't start with $",
raw.c_str()[0] == '$'); // c_str()[0] is always a valid reference.
uassert(16872,
str::stream() << "'$' by itself is not a valid FieldPath",
raw.size() >= 2); // need at least "$" and either "$" or a field name
if (raw[1] == '$') {
const StringData rawSD = raw;
const StringData fieldPath = rawSD.substr(2); // strip off $$
const StringData varName = fieldPath.substr(0, fieldPath.find('.'));
Variables::uassertValidNameForUserRead(varName);
return new ExpressionFieldPath(expCtx, fieldPath.toString(), vps.getVariable(varName));
} else {
return new ExpressionFieldPath(expCtx,
"CURRENT." + raw.substr(1), // strip the "$" prefix
vps.getVariable("CURRENT"));
}
}
ExpressionFieldPath::ExpressionFieldPath(const boost::intrusive_ptr<ExpressionContext>& expCtx,
const string& theFieldPath,
Variables::Id variable)
: Expression(expCtx), _fieldPath(theFieldPath), _variable(variable) {}
intrusive_ptr<Expression> ExpressionFieldPath::optimize() {
if (_variable == Variables::kRemoveId) {
// The REMOVE system variable optimizes to a constant missing value.
return ExpressionConstant::create(getExpressionContext(), Value());
}
if (getExpressionContext()->variables.hasConstantValue(_variable)) {
return ExpressionConstant::create(getExpressionContext(), evaluate(Document()));
}
return intrusive_ptr<Expression>(this);
}
bool ExpressionFieldPath::representsPath(const std::string& dottedPath) const {
if (_variable != Variables::kRootId || _fieldPath.getPathLength() == 1) {
// This variable refers to the entire document, or refers to a sub-field of something
// besides the root document. Either way we can't prove that it represents the path given by
// 'dottedPath'.
return false;
}
return _fieldPath.tail().fullPath() == dottedPath;
}
void ExpressionFieldPath::_doAddDependencies(DepsTracker* deps) const {
if (_variable == Variables::kRootId) { // includes CURRENT when it is equivalent to ROOT.
if (_fieldPath.getPathLength() == 1) {
deps->needWholeDocument = true; // need full doc if just "$$ROOT"
} else {
deps->fields.insert(_fieldPath.tail().fullPath());
}
} else if (Variables::isUserDefinedVariable(_variable)) {
deps->vars.insert(_variable);
}
}
Value ExpressionFieldPath::evaluatePathArray(size_t index, const Value& input) const {
dassert(input.isArray());
// Check for remaining path in each element of array
vector<Value> result;
const vector<Value>& array = input.getArray();
for (size_t i = 0; i < array.size(); i++) {
if (array[i].getType() != Object)
continue;
const Value nested = evaluatePath(index, array[i].getDocument());
if (!nested.missing())
result.push_back(nested);
}
return Value(std::move(result));
}
Value ExpressionFieldPath::evaluatePath(size_t index, const Document& input) const {
// Note this function is very hot so it is important that is is well optimized.
// In particular, all return paths should support RVO.
/* if we've hit the end of the path, stop */
if (index == _fieldPath.getPathLength() - 1)
return input[_fieldPath.getFieldName(index)];
// Try to dive deeper
const Value val = input[_fieldPath.getFieldName(index)];
switch (val.getType()) {
case Object:
return evaluatePath(index + 1, val.getDocument());
case Array:
return evaluatePathArray(index + 1, val);
default:
return Value();
}
}
Value ExpressionFieldPath::evaluate(const Document& root) const {
auto& vars = getExpressionContext()->variables;
if (_fieldPath.getPathLength() == 1) // get the whole variable
return vars.getValue(_variable, root);
if (_variable == Variables::kRootId) {
// ROOT is always a document so use optimized code path
return evaluatePath(1, root);
}
Value var = vars.getValue(_variable, root);
switch (var.getType()) {
case Object:
return evaluatePath(1, var.getDocument());
case Array:
return evaluatePathArray(1, var);
default:
return Value();
}
}
Value ExpressionFieldPath::serialize(bool explain) const {
if (_fieldPath.getFieldName(0) == "CURRENT" && _fieldPath.getPathLength() > 1) {
// use short form for "$$CURRENT.foo" but not just "$$CURRENT"
return Value("$" + _fieldPath.tail().fullPath());
} else {
return Value("$$" + _fieldPath.fullPath());
}
}
Expression::ComputedPaths ExpressionFieldPath::getComputedPaths(const std::string& exprFieldPath,
Variables::Id renamingVar) const {
// An expression field path is either considered a rename or a computed path. We need to find
// out which case we fall into.
//
// The caller has told us that renames must have 'varId' as the first component. We also check
// that there is only one additional component---no dotted field paths are allowed! This is
// because dotted ExpressionFieldPaths can actually reshape the document rather than just
// changing the field names. This can happen only if there are arrays along the dotted path.
//
// For example, suppose you have document {a: [{b: 1}, {b: 2}]}. The projection {"c.d": "$a.b"}
// does *not* perform the strict rename to yield document {c: [{d: 1}, {d: 2}]}. Instead, it
// results in the document {c: {d: [1, 2]}}. Due to this reshaping, matches expressed over "a.b"
// before the $project is applied may not have the same behavior when expressed over "c.d" after
// the $project is applied.
ComputedPaths outputPaths;
if (_variable == renamingVar && _fieldPath.getPathLength() == 2u) {
outputPaths.renames[exprFieldPath] = _fieldPath.tail().fullPath();
} else {
outputPaths.paths.insert(exprFieldPath);
}
return outputPaths;
}
/* ------------------------- ExpressionFilter ----------------------------- */
REGISTER_EXPRESSION(filter, ExpressionFilter::parse);
intrusive_ptr<Expression> ExpressionFilter::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vpsIn) {
verify(str::equals(expr.fieldName(), "$filter"));
uassert(28646, "$filter only supports an object as its argument", expr.type() == Object);
// "cond" must be parsed after "as" regardless of BSON order.
BSONElement inputElem;
BSONElement asElem;
BSONElement condElem;
for (auto elem : expr.Obj()) {
if (str::equals(elem.fieldName(), "input")) {
inputElem = elem;
} else if (str::equals(elem.fieldName(), "as")) {
asElem = elem;
} else if (str::equals(elem.fieldName(), "cond")) {
condElem = elem;
} else {
uasserted(28647,
str::stream() << "Unrecognized parameter to $filter: " << elem.fieldName());
}
}
uassert(28648, "Missing 'input' parameter to $filter", !inputElem.eoo());
uassert(28650, "Missing 'cond' parameter to $filter", !condElem.eoo());
// Parse "input", only has outer variables.
intrusive_ptr<Expression> input = parseOperand(expCtx, inputElem, vpsIn);
// Parse "as".
VariablesParseState vpsSub(vpsIn); // vpsSub gets our variable, vpsIn doesn't.
// If "as" is not specified, then use "this" by default.
auto varName = asElem.eoo() ? "this" : asElem.str();
Variables::uassertValidNameForUserWrite(varName);
Variables::Id varId = vpsSub.defineVariable(varName);
// Parse "cond", has access to "as" variable.
intrusive_ptr<Expression> cond = parseOperand(expCtx, condElem, vpsSub);
return new ExpressionFilter(
expCtx, std::move(varName), varId, std::move(input), std::move(cond));
}
ExpressionFilter::ExpressionFilter(const boost::intrusive_ptr<ExpressionContext>& expCtx,
string varName,
Variables::Id varId,
intrusive_ptr<Expression> input,
intrusive_ptr<Expression> filter)
: Expression(expCtx),
_varName(std::move(varName)),
_varId(varId),
_input(std::move(input)),
_filter(std::move(filter)) {}
intrusive_ptr<Expression> ExpressionFilter::optimize() {
// TODO handle when _input is constant.
_input = _input->optimize();
_filter = _filter->optimize();
return this;
}
Value ExpressionFilter::serialize(bool explain) const {
return Value(
DOC("$filter" << DOC("input" << _input->serialize(explain) << "as" << _varName << "cond"
<< _filter->serialize(explain))));
}
Value ExpressionFilter::evaluate(const Document& root) const {
// We are guaranteed at parse time that this isn't using our _varId.
const Value inputVal = _input->evaluate(root);
if (inputVal.nullish())
return Value(BSONNULL);
uassert(28651,
str::stream() << "input to $filter must be an array not "
<< typeName(inputVal.getType()),
inputVal.isArray());
const vector<Value>& input = inputVal.getArray();
if (input.empty())
return inputVal;
vector<Value> output;
auto& vars = getExpressionContext()->variables;
for (const auto& elem : input) {
vars.setValue(_varId, elem);
if (_filter->evaluate(root).coerceToBool()) {
output.push_back(std::move(elem));
}
}
return Value(std::move(output));
}
void ExpressionFilter::_doAddDependencies(DepsTracker* deps) const {
_input->addDependencies(deps);
_filter->addDependencies(deps);
}
/* ------------------------- ExpressionFloor -------------------------- */
Value ExpressionFloor::evaluateNumericArg(const Value& numericArg) const {
// There's no point in taking the floor of integers or longs, it will have no effect.
switch (numericArg.getType()) {
case NumberDouble:
return Value(std::floor(numericArg.getDouble()));
case NumberDecimal:
// Round toward the nearest decimal with a zero exponent in the negative direction.
return Value(numericArg.getDecimal().quantize(Decimal128::kNormalizedZero,
Decimal128::kRoundTowardNegative));
default:
return numericArg;
}
}
REGISTER_EXPRESSION(floor, ExpressionFloor::parse);
const char* ExpressionFloor::getOpName() const {
return "$floor";
}
/* ------------------------- ExpressionLet ----------------------------- */
REGISTER_EXPRESSION(let, ExpressionLet::parse);
intrusive_ptr<Expression> ExpressionLet::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vpsIn) {
verify(str::equals(expr.fieldName(), "$let"));
uassert(16874, "$let only supports an object as its argument", expr.type() == Object);
const BSONObj args = expr.embeddedObject();
// varsElem must be parsed before inElem regardless of BSON order.
BSONElement varsElem;
BSONElement inElem;
BSONForEach(arg, args) {
if (str::equals(arg.fieldName(), "vars")) {
varsElem = arg;
} else if (str::equals(arg.fieldName(), "in")) {
inElem = arg;
} else {
uasserted(16875,
str::stream() << "Unrecognized parameter to $let: " << arg.fieldName());
}
}
uassert(16876, "Missing 'vars' parameter to $let", !varsElem.eoo());
uassert(16877, "Missing 'in' parameter to $let", !inElem.eoo());
// parse "vars"
VariablesParseState vpsSub(vpsIn); // vpsSub gets our vars, vpsIn doesn't.
VariableMap vars;
BSONForEach(varElem, varsElem.embeddedObjectUserCheck()) {
const string varName = varElem.fieldName();
Variables::uassertValidNameForUserWrite(varName);
Variables::Id id = vpsSub.defineVariable(varName);
vars[id] = NameAndExpression(varName,
parseOperand(expCtx, varElem, vpsIn)); // only has outer vars
}
// parse "in"
intrusive_ptr<Expression> subExpression = parseOperand(expCtx, inElem, vpsSub); // has our vars
return new ExpressionLet(expCtx, vars, subExpression);
}
ExpressionLet::ExpressionLet(const boost::intrusive_ptr<ExpressionContext>& expCtx,
const VariableMap& vars,
intrusive_ptr<Expression> subExpression)
: Expression(expCtx), _variables(vars), _subExpression(subExpression) {}
intrusive_ptr<Expression> ExpressionLet::optimize() {
if (_variables.empty()) {
// we aren't binding any variables so just return the subexpression
return _subExpression->optimize();
}
for (VariableMap::iterator it = _variables.begin(), end = _variables.end(); it != end; ++it) {
it->second.expression = it->second.expression->optimize();
}
_subExpression = _subExpression->optimize();
return this;
}
Value ExpressionLet::serialize(bool explain) const {
MutableDocument vars;
for (VariableMap::const_iterator it = _variables.begin(), end = _variables.end(); it != end;
++it) {
vars[it->second.name] = it->second.expression->serialize(explain);
}
return Value(
DOC("$let" << DOC("vars" << vars.freeze() << "in" << _subExpression->serialize(explain))));
}
Value ExpressionLet::evaluate(const Document& root) const {
for (const auto& item : _variables) {
// It is guaranteed at parse-time that these expressions don't use the variable ids we
// are setting
getExpressionContext()->variables.setValue(item.first,
item.second.expression->evaluate(root));
}
return _subExpression->evaluate(root);
}
void ExpressionLet::_doAddDependencies(DepsTracker* deps) const {
for (auto&& idToNameExp : _variables) {
// Add the external dependencies from the 'vars' statement.
idToNameExp.second.expression->addDependencies(deps);
}
// Add subexpression dependencies, which may contain a mix of local and external variable refs.
_subExpression->addDependencies(deps);
}
/* ------------------------- ExpressionMap ----------------------------- */
REGISTER_EXPRESSION(map, ExpressionMap::parse);
intrusive_ptr<Expression> ExpressionMap::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vpsIn) {
verify(str::equals(expr.fieldName(), "$map"));
uassert(16878, "$map only supports an object as its argument", expr.type() == Object);
// "in" must be parsed after "as" regardless of BSON order
BSONElement inputElem;
BSONElement asElem;
BSONElement inElem;
const BSONObj args = expr.embeddedObject();
BSONForEach(arg, args) {
if (str::equals(arg.fieldName(), "input")) {
inputElem = arg;
} else if (str::equals(arg.fieldName(), "as")) {
asElem = arg;
} else if (str::equals(arg.fieldName(), "in")) {
inElem = arg;
} else {
uasserted(16879,
str::stream() << "Unrecognized parameter to $map: " << arg.fieldName());
}
}
uassert(16880, "Missing 'input' parameter to $map", !inputElem.eoo());
uassert(16882, "Missing 'in' parameter to $map", !inElem.eoo());
// parse "input"
intrusive_ptr<Expression> input =
parseOperand(expCtx, inputElem, vpsIn); // only has outer vars
// parse "as"
VariablesParseState vpsSub(vpsIn); // vpsSub gets our vars, vpsIn doesn't.
// If "as" is not specified, then use "this" by default.
auto varName = asElem.eoo() ? "this" : asElem.str();
Variables::uassertValidNameForUserWrite(varName);
Variables::Id varId = vpsSub.defineVariable(varName);
// parse "in"
intrusive_ptr<Expression> in =
parseOperand(expCtx, inElem, vpsSub); // has access to map variable
return new ExpressionMap(expCtx, varName, varId, input, in);
}
ExpressionMap::ExpressionMap(const boost::intrusive_ptr<ExpressionContext>& expCtx,
const string& varName,
Variables::Id varId,
intrusive_ptr<Expression> input,
intrusive_ptr<Expression> each)
: Expression(expCtx), _varName(varName), _varId(varId), _input(input), _each(each) {}
intrusive_ptr<Expression> ExpressionMap::optimize() {
// TODO handle when _input is constant
_input = _input->optimize();
_each = _each->optimize();
return this;
}
Value ExpressionMap::serialize(bool explain) const {
return Value(DOC("$map" << DOC("input" << _input->serialize(explain) << "as" << _varName << "in"
<< _each->serialize(explain))));
}
Value ExpressionMap::evaluate(const Document& root) const {
// guaranteed at parse time that this isn't using our _varId
const Value inputVal = _input->evaluate(root);
if (inputVal.nullish())
return Value(BSONNULL);
uassert(16883,
str::stream() << "input to $map must be an array not " << typeName(inputVal.getType()),
inputVal.isArray());
const vector<Value>& input = inputVal.getArray();
if (input.empty())
return inputVal;
vector<Value> output;
output.reserve(input.size());
for (size_t i = 0; i < input.size(); i++) {
getExpressionContext()->variables.setValue(_varId, input[i]);
Value toInsert = _each->evaluate(root);
if (toInsert.missing())
toInsert = Value(BSONNULL); // can't insert missing values into array
output.push_back(toInsert);
}
return Value(std::move(output));
}
void ExpressionMap::_doAddDependencies(DepsTracker* deps) const {
_input->addDependencies(deps);
_each->addDependencies(deps);
}
Expression::ComputedPaths ExpressionMap::getComputedPaths(const std::string& exprFieldPath,
Variables::Id renamingVar) const {
auto inputFieldPath = dynamic_cast<ExpressionFieldPath*>(_input.get());
if (!inputFieldPath) {
return {{exprFieldPath}, {}};
}
auto inputComputedPaths = inputFieldPath->getComputedPaths("", renamingVar);
if (inputComputedPaths.renames.empty()) {
return {{exprFieldPath}, {}};
}
invariant(inputComputedPaths.renames.size() == 1u);
auto fieldPathRenameIter = inputComputedPaths.renames.find("");
invariant(fieldPathRenameIter != inputComputedPaths.renames.end());
const auto& oldArrayName = fieldPathRenameIter->second;
auto eachComputedPaths = _each->getComputedPaths(exprFieldPath, _varId);
if (eachComputedPaths.renames.empty()) {
return {{exprFieldPath}, {}};
}
// Append the name of the array to the beginning of the old field path.
for (auto&& rename : eachComputedPaths.renames) {
eachComputedPaths.renames[rename.first] =
FieldPath::getFullyQualifiedPath(oldArrayName, rename.second);
}
return eachComputedPaths;
}
/* ------------------------- ExpressionMeta ----------------------------- */
REGISTER_EXPRESSION(meta, ExpressionMeta::parse);
intrusive_ptr<Expression> ExpressionMeta::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vpsIn) {
uassert(17307, "$meta only supports string arguments", expr.type() == String);
if (expr.valueStringData() == "textScore") {
return new ExpressionMeta(expCtx, MetaType::TEXT_SCORE);
} else if (expr.valueStringData() == "randVal") {
return new ExpressionMeta(expCtx, MetaType::RAND_VAL);
} else {
uasserted(17308, "Unsupported argument to $meta: " + expr.String());
}
}
ExpressionMeta::ExpressionMeta(const boost::intrusive_ptr<ExpressionContext>& expCtx,
MetaType metaType)
: Expression(expCtx), _metaType(metaType) {}
Value ExpressionMeta::serialize(bool explain) const {
switch (_metaType) {
case MetaType::TEXT_SCORE:
return Value(DOC("$meta"
<< "textScore"_sd));
case MetaType::RAND_VAL:
return Value(DOC("$meta"
<< "randVal"_sd));
}
MONGO_UNREACHABLE;
}
Value ExpressionMeta::evaluate(const Document& root) const {
switch (_metaType) {
case MetaType::TEXT_SCORE:
return root.hasTextScore() ? Value(root.getTextScore()) : Value();
case MetaType::RAND_VAL:
return root.hasRandMetaField() ? Value(root.getRandMetaField()) : Value();
}
MONGO_UNREACHABLE;
}
void ExpressionMeta::_doAddDependencies(DepsTracker* deps) const {
if (_metaType == MetaType::TEXT_SCORE) {
deps->setNeedsMetadata(DepsTracker::MetadataType::TEXT_SCORE, true);
}
}
/* ----------------------- ExpressionMod ---------------------------- */
Value ExpressionMod::evaluate(const Document& root) const {
Value lhs = vpOperand[0]->evaluate(root);
Value rhs = vpOperand[1]->evaluate(root);
BSONType leftType = lhs.getType();
BSONType rightType = rhs.getType();
if (lhs.numeric() && rhs.numeric()) {
auto assertNonZero = [](bool isZero) { uassert(16610, "can't $mod by zero", !isZero); };
// If either side is decimal, perform the operation in decimal.
if (leftType == NumberDecimal || rightType == NumberDecimal) {
Decimal128 left = lhs.coerceToDecimal();
Decimal128 right = rhs.coerceToDecimal();
assertNonZero(right.isZero());
return Value(left.modulo(right));
}
// ensure we aren't modding by 0
double right = rhs.coerceToDouble();
assertNonZero(right == 0);
if (leftType == NumberDouble || (rightType == NumberDouble && !rhs.integral())) {
// Need to do fmod. Integer-valued double case is handled below.
double left = lhs.coerceToDouble();
return Value(fmod(left, right));
} else if (leftType == NumberLong || rightType == NumberLong) {
// if either is long, return long
long long left = lhs.coerceToLong();
long long rightLong = rhs.coerceToLong();
return Value(left % rightLong);
}
// lastly they must both be ints, return int
int left = lhs.coerceToInt();
int rightInt = rhs.coerceToInt();
return Value(left % rightInt);
} else if (lhs.nullish() || rhs.nullish()) {
return Value(BSONNULL);
} else {
uasserted(16611,
str::stream() << "$mod only supports numeric types, not "
<< typeName(lhs.getType())
<< " and "
<< typeName(rhs.getType()));
}
}
REGISTER_EXPRESSION(mod, ExpressionMod::parse);
const char* ExpressionMod::getOpName() const {
return "$mod";
}
/* ------------------------- ExpressionMultiply ----------------------------- */
Value ExpressionMultiply::evaluate(const Document& root) const {
/*
We'll try to return the narrowest possible result value. To do that
without creating intermediate Values, do the arithmetic for double
and integral types in parallel, tracking the current narrowest
type.
*/
double doubleProduct = 1;
long long longProduct = 1;
Decimal128 decimalProduct; // This will be initialized on encountering the first decimal.
BSONType productType = NumberInt;
const size_t n = vpOperand.size();
for (size_t i = 0; i < n; ++i) {
Value val = vpOperand[i]->evaluate(root);
if (val.numeric()) {
BSONType oldProductType = productType;
productType = Value::getWidestNumeric(productType, val.getType());
if (productType == NumberDecimal) {
// On finding the first decimal, convert the partial product to decimal.
if (oldProductType != NumberDecimal) {
decimalProduct = oldProductType == NumberDouble
? Decimal128(doubleProduct, Decimal128::kRoundTo15Digits)
: Decimal128(static_cast<int64_t>(longProduct));
}
decimalProduct = decimalProduct.multiply(val.coerceToDecimal());
} else {
doubleProduct *= val.coerceToDouble();
if (mongoSignedMultiplyOverflow64(longProduct, val.coerceToLong(), &longProduct)) {
// The 'longProduct' would have overflowed, so we're abandoning it.
productType = NumberDouble;
}
}
} else if (val.nullish()) {
return Value(BSONNULL);
} else {
uasserted(16555,
str::stream() << "$multiply only supports numeric types, not "
<< typeName(val.getType()));
}
}
if (productType == NumberDouble)
return Value(doubleProduct);
else if (productType == NumberLong)
return Value(longProduct);
else if (productType == NumberInt)
return Value::createIntOrLong(longProduct);
else if (productType == NumberDecimal)
return Value(decimalProduct);
else
massert(16418, "$multiply resulted in a non-numeric type", false);
}
REGISTER_EXPRESSION(multiply, ExpressionMultiply::parse);
const char* ExpressionMultiply::getOpName() const {
return "$multiply";
}
/* ----------------------- ExpressionIfNull ---------------------------- */
Value ExpressionIfNull::evaluate(const Document& root) const {
Value pLeft(vpOperand[0]->evaluate(root));
if (!pLeft.nullish())
return pLeft;
Value pRight(vpOperand[1]->evaluate(root));
return pRight;
}
REGISTER_EXPRESSION(ifNull, ExpressionIfNull::parse);
const char* ExpressionIfNull::getOpName() const {
return "$ifNull";
}
/* ----------------------- ExpressionIn ---------------------------- */
Value ExpressionIn::evaluate(const Document& root) const {
Value argument(vpOperand[0]->evaluate(root));
Value arrayOfValues(vpOperand[1]->evaluate(root));
uassert(40081,
str::stream() << "$in requires an array as a second argument, found: "
<< typeName(arrayOfValues.getType()),
arrayOfValues.isArray());
for (auto&& value : arrayOfValues.getArray()) {
if (getExpressionContext()->getValueComparator().evaluate(argument == value)) {
return Value(true);
}
}
return Value(false);
}
REGISTER_EXPRESSION(in, ExpressionIn::parse);
const char* ExpressionIn::getOpName() const {
return "$in";
}
/* ----------------------- ExpressionIndexOfArray ------------------ */
namespace {
void uassertIfNotIntegralAndNonNegative(Value val,
StringData expressionName,
StringData argumentName) {
uassert(40096,
str::stream() << expressionName << "requires an integral " << argumentName
<< ", found a value of type: "
<< typeName(val.getType())
<< ", with value: "
<< val.toString(),
val.integral());
uassert(40097,
str::stream() << expressionName << " requires a nonnegative " << argumentName
<< ", found: "
<< val.toString(),
val.coerceToInt() >= 0);
}
} // namespace
Value ExpressionIndexOfArray::evaluate(const Document& root) const {
Value arrayArg = vpOperand[0]->evaluate(root);
if (arrayArg.nullish()) {
return Value(BSONNULL);
}
uassert(40090,
str::stream() << "$indexOfArray requires an array as a first argument, found: "
<< typeName(arrayArg.getType()),
arrayArg.isArray());
std::vector<Value> array = arrayArg.getArray();
auto args = evaluateAndValidateArguments(root, vpOperand, array.size());
for (int i = args.startIndex; i < args.endIndex; i++) {
if (getExpressionContext()->getValueComparator().evaluate(array[i] ==
args.targetOfSearch)) {
return Value(static_cast<int>(i));
}
}
return Value(-1);
}
ExpressionIndexOfArray::Arguments ExpressionIndexOfArray::evaluateAndValidateArguments(
const Document& root, const ExpressionVector& operands, size_t arrayLength) const {
int startIndex = 0;
if (operands.size() > 2) {
Value startIndexArg = operands[2]->evaluate(root);
uassertIfNotIntegralAndNonNegative(startIndexArg, getOpName(), "starting index");
startIndex = startIndexArg.coerceToInt();
}
int endIndex = arrayLength;
if (operands.size() > 3) {
Value endIndexArg = operands[3]->evaluate(root);
uassertIfNotIntegralAndNonNegative(endIndexArg, getOpName(), "ending index");
// Don't let 'endIndex' exceed the length of the array.
endIndex = std::min(static_cast<int>(arrayLength), endIndexArg.coerceToInt());
}
return {vpOperand[1]->evaluate(root), startIndex, endIndex};
}
/**
* This class handles the case where IndexOfArray is given an ExpressionConstant
* instead of using a vector and searching through it we can use a unordered_map
* for O(1) lookup time.
*/
class ExpressionIndexOfArray::Optimized : public ExpressionIndexOfArray {
public:
Optimized(const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ValueUnorderedMap<vector<int>>& indexMap,
const ExpressionVector& operands)
: ExpressionIndexOfArray(expCtx), _indexMap(std::move(indexMap)) {
vpOperand = operands;
}
virtual Value evaluate(const Document& root) const {
auto args = evaluateAndValidateArguments(root, vpOperand, _indexMap.size());
auto indexVec = _indexMap.find(args.targetOfSearch);
if (indexVec == _indexMap.end())
return Value(-1);
// Search through the vector of indecies for first index in our range.
for (auto index : indexVec->second) {
if (index >= args.startIndex && index < args.endIndex) {
return Value(index);
}
}
// The value we are searching for exists but is not in our range.
return Value(-1);
}
private:
// Maps the values in the array to the positions at which they occur. We need to remember the
// positions so that we can verify they are in the appropriate range.
const ValueUnorderedMap<vector<int>> _indexMap;
};
intrusive_ptr<Expression> ExpressionIndexOfArray::optimize() {
// This will optimize all arguments to this expression.
auto optimized = ExpressionNary::optimize();
if (optimized.get() != this) {
return optimized;
}
// If the input array is an ExpressionConstant we can optimize using a unordered_map instead of
// an
// array.
if (auto constantArray = dynamic_cast<ExpressionConstant*>(vpOperand[0].get())) {
const Value valueArray = constantArray->getValue();
if (valueArray.nullish()) {
return ExpressionConstant::create(getExpressionContext(), Value(BSONNULL));
}
uassert(50809,
str::stream() << "First operand of $indexOfArray must be an array. First "
<< "argument is of type: "
<< typeName(valueArray.getType()),
valueArray.isArray());
auto arr = valueArray.getArray();
// To handle the case of duplicate values the values need to map to a vector of indecies.
auto indexMap =
getExpressionContext()->getValueComparator().makeUnorderedValueMap<vector<int>>();
for (int i = 0; i < int(arr.size()); i++) {
if (indexMap.find(arr[i]) == indexMap.end()) {
indexMap.emplace(arr[i], vector<int>());
}
indexMap[arr[i]].push_back(i);
}
return new Optimized(getExpressionContext(), indexMap, vpOperand);
}
return this;
}
REGISTER_EXPRESSION(indexOfArray, ExpressionIndexOfArray::parse);
const char* ExpressionIndexOfArray::getOpName() const {
return "$indexOfArray";
}
/* ----------------------- ExpressionIndexOfBytes ------------------ */
namespace {
bool stringHasTokenAtIndex(size_t index, const std::string& input, const std::string& token) {
if (token.size() + index > input.size()) {
return false;
}
return input.compare(index, token.size(), token) == 0;
}
} // namespace
Value ExpressionIndexOfBytes::evaluate(const Document& root) const {
Value stringArg = vpOperand[0]->evaluate(root);
if (stringArg.nullish()) {
return Value(BSONNULL);
}
uassert(40091,
str::stream() << "$indexOfBytes requires a string as the first argument, found: "
<< typeName(stringArg.getType()),
stringArg.getType() == String);
const std::string& input = stringArg.getString();
Value tokenArg = vpOperand[1]->evaluate(root);
uassert(40092,
str::stream() << "$indexOfBytes requires a string as the second argument, found: "
<< typeName(tokenArg.getType()),
tokenArg.getType() == String);
const std::string& token = tokenArg.getString();
size_t startIndex = 0;
if (vpOperand.size() > 2) {
Value startIndexArg = vpOperand[2]->evaluate(root);
uassertIfNotIntegralAndNonNegative(startIndexArg, getOpName(), "starting index");
startIndex = static_cast<size_t>(startIndexArg.coerceToInt());
}
size_t endIndex = input.size();
if (vpOperand.size() > 3) {
Value endIndexArg = vpOperand[3]->evaluate(root);
uassertIfNotIntegralAndNonNegative(endIndexArg, getOpName(), "ending index");
// Don't let 'endIndex' exceed the length of the string.
endIndex = std::min(input.size(), static_cast<size_t>(endIndexArg.coerceToInt()));
}
if (startIndex > input.length() || endIndex < startIndex) {
return Value(-1);
}
size_t position = input.substr(0, endIndex).find(token, startIndex);
if (position == std::string::npos) {
return Value(-1);
}
return Value(static_cast<int>(position));
}
REGISTER_EXPRESSION(indexOfBytes, ExpressionIndexOfBytes::parse);
const char* ExpressionIndexOfBytes::getOpName() const {
return "$indexOfBytes";
}
/* ----------------------- ExpressionIndexOfCP --------------------- */
Value ExpressionIndexOfCP::evaluate(const Document& root) const {
Value stringArg = vpOperand[0]->evaluate(root);
if (stringArg.nullish()) {
return Value(BSONNULL);
}
uassert(40093,
str::stream() << "$indexOfCP requires a string as the first argument, found: "
<< typeName(stringArg.getType()),
stringArg.getType() == String);
const std::string& input = stringArg.getString();
Value tokenArg = vpOperand[1]->evaluate(root);
uassert(40094,
str::stream() << "$indexOfCP requires a string as the second argument, found: "
<< typeName(tokenArg.getType()),
tokenArg.getType() == String);
const std::string& token = tokenArg.getString();
size_t startCodePointIndex = 0;
if (vpOperand.size() > 2) {
Value startIndexArg = vpOperand[2]->evaluate(root);
uassertIfNotIntegralAndNonNegative(startIndexArg, getOpName(), "starting index");
startCodePointIndex = static_cast<size_t>(startIndexArg.coerceToInt());
}
// Compute the length (in code points) of the input, and convert 'startCodePointIndex' to a byte
// index.
size_t codePointLength = 0;
size_t startByteIndex = 0;
for (size_t byteIx = 0; byteIx < input.size(); ++codePointLength) {
if (codePointLength == startCodePointIndex) {
// We have determined the byte at which our search will start.
startByteIndex = byteIx;
}
uassert(40095,
"$indexOfCP found bad UTF-8 in the input",
!str::isUTF8ContinuationByte(input[byteIx]));
byteIx += getCodePointLength(input[byteIx]);
}
size_t endCodePointIndex = codePointLength;
if (vpOperand.size() > 3) {
Value endIndexArg = vpOperand[3]->evaluate(root);
uassertIfNotIntegralAndNonNegative(endIndexArg, getOpName(), "ending index");
// Don't let 'endCodePointIndex' exceed the number of code points in the string.
endCodePointIndex =
std::min(codePointLength, static_cast<size_t>(endIndexArg.coerceToInt()));
}
if (startByteIndex == 0 && input.empty() && token.empty()) {
// If we are finding the index of "" in the string "", the below loop will not loop, so we
// need a special case for this.
return Value(0);
}
// We must keep track of which byte, and which code point, we are examining, being careful not
// to overflow either the length of the string or the ending code point.
size_t currentCodePointIndex = startCodePointIndex;
for (size_t byteIx = startByteIndex; currentCodePointIndex < endCodePointIndex;
++currentCodePointIndex) {
if (stringHasTokenAtIndex(byteIx, input, token)) {
return Value(static_cast<int>(currentCodePointIndex));
}
byteIx += getCodePointLength(input[byteIx]);
}
return Value(-1);
}
REGISTER_EXPRESSION(indexOfCP, ExpressionIndexOfCP::parse);
const char* ExpressionIndexOfCP::getOpName() const {
return "$indexOfCP";
}
/* ----------------------- ExpressionLn ---------------------------- */
Value ExpressionLn::evaluateNumericArg(const Value& numericArg) const {
if (numericArg.getType() == NumberDecimal) {
Decimal128 argDecimal = numericArg.getDecimal();
if (argDecimal.isGreater(Decimal128::kNormalizedZero))
return Value(argDecimal.logarithm());
// Fall through for error case.
}
double argDouble = numericArg.coerceToDouble();
uassert(28766,
str::stream() << "$ln's argument must be a positive number, but is " << argDouble,
argDouble > 0 || std::isnan(argDouble));
return Value(std::log(argDouble));
}
REGISTER_EXPRESSION(ln, ExpressionLn::parse);
const char* ExpressionLn::getOpName() const {
return "$ln";
}
/* ----------------------- ExpressionLog ---------------------------- */
Value ExpressionLog::evaluate(const Document& root) const {
Value argVal = vpOperand[0]->evaluate(root);
Value baseVal = vpOperand[1]->evaluate(root);
if (argVal.nullish() || baseVal.nullish())
return Value(BSONNULL);
uassert(28756,
str::stream() << "$log's argument must be numeric, not " << typeName(argVal.getType()),
argVal.numeric());
uassert(28757,
str::stream() << "$log's base must be numeric, not " << typeName(baseVal.getType()),
baseVal.numeric());
if (argVal.getType() == NumberDecimal || baseVal.getType() == NumberDecimal) {
Decimal128 argDecimal = argVal.coerceToDecimal();
Decimal128 baseDecimal = baseVal.coerceToDecimal();
if (argDecimal.isGreater(Decimal128::kNormalizedZero) &&
baseDecimal.isNotEqual(Decimal128(1)) &&
baseDecimal.isGreater(Decimal128::kNormalizedZero)) {
return Value(argDecimal.logarithm(baseDecimal));
}
// Fall through for error cases.
}
double argDouble = argVal.coerceToDouble();
double baseDouble = baseVal.coerceToDouble();
uassert(28758,
str::stream() << "$log's argument must be a positive number, but is " << argDouble,
argDouble > 0 || std::isnan(argDouble));
uassert(28759,
str::stream() << "$log's base must be a positive number not equal to 1, but is "
<< baseDouble,
(baseDouble > 0 && baseDouble != 1) || std::isnan(baseDouble));
return Value(std::log(argDouble) / std::log(baseDouble));
}
REGISTER_EXPRESSION(log, ExpressionLog::parse);
const char* ExpressionLog::getOpName() const {
return "$log";
}
/* ----------------------- ExpressionLog10 ---------------------------- */
Value ExpressionLog10::evaluateNumericArg(const Value& numericArg) const {
if (numericArg.getType() == NumberDecimal) {
Decimal128 argDecimal = numericArg.getDecimal();
if (argDecimal.isGreater(Decimal128::kNormalizedZero))
return Value(argDecimal.logarithm(Decimal128(10)));
// Fall through for error case.
}
double argDouble = numericArg.coerceToDouble();
uassert(28761,
str::stream() << "$log10's argument must be a positive number, but is " << argDouble,
argDouble > 0 || std::isnan(argDouble));
return Value(std::log10(argDouble));
}
REGISTER_EXPRESSION(log10, ExpressionLog10::parse);
const char* ExpressionLog10::getOpName() const {
return "$log10";
}
/* ------------------------ ExpressionNary ----------------------------- */
/**
* Optimize a general Nary expression.
*
* The optimization has the following properties:
* 1) Optimize each of the operators.
* 2) If the operand is associative, flatten internal operators of the same type. I.e.:
* A+B+(C+D)+E => A+B+C+D+E
* 3) If the operand is commutative & associative, group all constant operators. For example:
* c1 + c2 + n1 + c3 + n2 => n1 + n2 + c1 + c2 + c3
* 4) If the operand is associative, execute the operation over all the contiguous constant
* operators and replacing them by the result. For example: c1 + c2 + n1 + c3 + c4 + n5 =>
* c5 = c1 + c2, c6 = c3 + c4 => c5 + n1 + c6 + n5
*
* It returns the optimized expression. It can be exactly the same expression, a modified version
* of the same expression or a completely different expression.
*/
intrusive_ptr<Expression> ExpressionNary::optimize() {
uint32_t constOperandCount = 0;
for (auto& operand : vpOperand) {
operand = operand->optimize();
if (dynamic_cast<ExpressionConstant*>(operand.get())) {
++constOperandCount;
}
}
// If all the operands are constant expressions, collapse the expression into one constant
// expression.
if (constOperandCount == vpOperand.size()) {
return intrusive_ptr<Expression>(
ExpressionConstant::create(getExpressionContext(), evaluate(Document())));
}
// If the expression is associative, we can collapse all the consecutive constant operands into
// one by applying the expression to those consecutive constant operands.
// If the expression is also commutative we can reorganize all the operands so that all of the
// constant ones are together (arbitrarily at the back) and we can collapse all of them into
// one.
if (isAssociative()) {
ExpressionVector constExpressions;
ExpressionVector optimizedOperands;
for (size_t i = 0; i < vpOperand.size();) {
intrusive_ptr<Expression> operand = vpOperand[i];
// If the operand is a constant one, add it to the current list of consecutive constant
// operands.
if (dynamic_cast<ExpressionConstant*>(operand.get())) {
constExpressions.push_back(operand);
++i;
continue;
}
// If the operand is exactly the same type as the one we are currently optimizing and
// is also associative, replace the expression for the operands it has.
// E.g: sum(a, b, sum(c, d), e) => sum(a, b, c, d, e)
ExpressionNary* nary = dynamic_cast<ExpressionNary*>(operand.get());
if (nary && str::equals(nary->getOpName(), getOpName()) && nary->isAssociative()) {
invariant(!nary->vpOperand.empty());
vpOperand[i] = std::move(nary->vpOperand[0]);
vpOperand.insert(
vpOperand.begin() + i + 1, nary->vpOperand.begin() + 1, nary->vpOperand.end());
continue;
}
// If the operand is not a constant nor a same-type expression and the expression is
// not commutative, evaluate an expression of the same type as the one we are
// optimizing on the list of consecutive constant operands and use the resulting value
// as a constant expression operand.
// If the list of consecutive constant operands has less than 2 operands just place
// back the operands.
if (!isCommutative()) {
if (constExpressions.size() > 1) {
ExpressionVector vpOperandSave = std::move(vpOperand);
vpOperand = std::move(constExpressions);
optimizedOperands.emplace_back(
ExpressionConstant::create(getExpressionContext(), evaluate(Document())));
vpOperand = std::move(vpOperandSave);
} else {
optimizedOperands.insert(
optimizedOperands.end(), constExpressions.begin(), constExpressions.end());
}
constExpressions.clear();
}
optimizedOperands.push_back(operand);
++i;
}
if (constExpressions.size() > 1) {
vpOperand = std::move(constExpressions);
optimizedOperands.emplace_back(
ExpressionConstant::create(getExpressionContext(), evaluate(Document())));
} else {
optimizedOperands.insert(
optimizedOperands.end(), constExpressions.begin(), constExpressions.end());
}
vpOperand = std::move(optimizedOperands);
}
return this;
}
void ExpressionNary::_doAddDependencies(DepsTracker* deps) const {
for (auto&& operand : vpOperand) {
operand->addDependencies(deps);
}
}
void ExpressionNary::addOperand(const intrusive_ptr<Expression>& pExpression) {
vpOperand.push_back(pExpression);
}
Value ExpressionNary::serialize(bool explain) const {
const size_t nOperand = vpOperand.size();
vector<Value> array;
/* build up the array */
for (size_t i = 0; i < nOperand; i++)
array.push_back(vpOperand[i]->serialize(explain));
return Value(DOC(getOpName() << array));
}
/* ------------------------- ExpressionNot ----------------------------- */
Value ExpressionNot::evaluate(const Document& root) const {
Value pOp(vpOperand[0]->evaluate(root));
bool b = pOp.coerceToBool();
return Value(!b);
}
REGISTER_EXPRESSION(not, ExpressionNot::parse);
const char* ExpressionNot::getOpName() const {
return "$not";
}
/* -------------------------- ExpressionOr ----------------------------- */
Value ExpressionOr::evaluate(const Document& root) const {
const size_t n = vpOperand.size();
for (size_t i = 0; i < n; ++i) {
Value pValue(vpOperand[i]->evaluate(root));
if (pValue.coerceToBool())
return Value(true);
}
return Value(false);
}
intrusive_ptr<Expression> ExpressionOr::optimize() {
/* optimize the disjunction as much as possible */
intrusive_ptr<Expression> pE(ExpressionNary::optimize());
/* if the result isn't a disjunction, we can't do anything */
ExpressionOr* pOr = dynamic_cast<ExpressionOr*>(pE.get());
if (!pOr)
return pE;
/*
Check the last argument on the result; if it's not constant (as
promised by ExpressionNary::optimize(),) then there's nothing
we can do.
*/
const size_t n = pOr->vpOperand.size();
// ExpressionNary::optimize() generates an ExpressionConstant for {$or:[]}.
verify(n > 0);
intrusive_ptr<Expression> pLast(pOr->vpOperand[n - 1]);
const ExpressionConstant* pConst = dynamic_cast<ExpressionConstant*>(pLast.get());
if (!pConst)
return pE;
/*
Evaluate and coerce the last argument to a boolean. If it's true,
then we can replace this entire expression.
*/
bool last = pConst->getValue().coerceToBool();
if (last) {
intrusive_ptr<ExpressionConstant> pFinal(
ExpressionConstant::create(getExpressionContext(), Value(true)));
return pFinal;
}
/*
If we got here, the final operand was false, so we don't need it
anymore. If there was only one other operand, we don't need the
conjunction either. Note we still need to keep the promise that
the result will be a boolean.
*/
if (n == 2) {
intrusive_ptr<Expression> pFinal(
ExpressionCoerceToBool::create(getExpressionContext(), pOr->vpOperand[0]));
return pFinal;
}
/*
Remove the final "false" value, and return the new expression.
*/
pOr->vpOperand.resize(n - 1);
return pE;
}
REGISTER_EXPRESSION(or, ExpressionOr::parse);
const char* ExpressionOr::getOpName() const {
return "$or";
}
namespace {
/**
* Helper for ExpressionPow to determine wither base^exp can be represented in a 64 bit int.
*
*'base' and 'exp' are both integers. Assumes 'exp' is in the range [0, 63].
*/
bool representableAsLong(long long base, long long exp) {
invariant(exp <= 63);
invariant(exp >= 0);
struct MinMax {
long long min;
long long max;
};
// Array indices correspond to exponents 0 through 63. The values in each index are the min
// and max bases, respectively, that can be raised to that exponent without overflowing a
// 64-bit int. For max bases, this was computed by solving for b in
// b = (2^63-1)^(1/exp) for exp = [0, 63] and truncating b. To calculate min bases, for even
// exps the equation used was b = (2^63-1)^(1/exp), and for odd exps the equation used was
// b = (-2^63)^(1/exp). Since the magnitude of long min is greater than long max, the
// magnitude of some of the min bases raised to odd exps is greater than the corresponding
// max bases raised to the same exponents.
static const MinMax kBaseLimits[] = {
{std::numeric_limits<long long>::min(), std::numeric_limits<long long>::max()}, // 0
{std::numeric_limits<long long>::min(), std::numeric_limits<long long>::max()},
{-3037000499LL, 3037000499LL},
{-2097152, 2097151},
{-55108, 55108},
{-6208, 6208},
{-1448, 1448},
{-512, 511},
{-234, 234},
{-128, 127},
{-78, 78}, // 10
{-52, 52},
{-38, 38},
{-28, 28},
{-22, 22},
{-18, 18},
{-15, 15},
{-13, 13},
{-11, 11},
{-9, 9},
{-8, 8}, // 20
{-8, 7},
{-7, 7},
{-6, 6},
{-6, 6},
{-5, 5},
{-5, 5},
{-5, 5},
{-4, 4},
{-4, 4},
{-4, 4}, // 30
{-4, 4},
{-3, 3},
{-3, 3},
{-3, 3},
{-3, 3},
{-3, 3},
{-3, 3},
{-3, 3},
{-3, 3},
{-2, 2}, // 40
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2}, // 50
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2},
{-2, 2}, // 60
{-2, 2},
{-2, 2},
{-2, 1}};
return base >= kBaseLimits[exp].min && base <= kBaseLimits[exp].max;
};
}
/* ----------------------- ExpressionPow ---------------------------- */
intrusive_ptr<Expression> ExpressionPow::create(
const boost::intrusive_ptr<ExpressionContext>& expCtx, Value base, Value exp) {
intrusive_ptr<ExpressionPow> expr(new ExpressionPow(expCtx));
expr->vpOperand.push_back(
ExpressionConstant::create(expr->getExpressionContext(), std::move(base)));
expr->vpOperand.push_back(
ExpressionConstant::create(expr->getExpressionContext(), std::move(exp)));
return expr;
}
Value ExpressionPow::evaluate(const Document& root) const {
Value baseVal = vpOperand[0]->evaluate(root);
Value expVal = vpOperand[1]->evaluate(root);
if (baseVal.nullish() || expVal.nullish())
return Value(BSONNULL);
BSONType baseType = baseVal.getType();
BSONType expType = expVal.getType();
uassert(28762,
str::stream() << "$pow's base must be numeric, not " << typeName(baseType),
baseVal.numeric());
uassert(28763,
str::stream() << "$pow's exponent must be numeric, not " << typeName(expType),
expVal.numeric());
auto checkNonZeroAndNeg = [](bool isZeroAndNeg) {
uassert(28764, "$pow cannot take a base of 0 and a negative exponent", !isZeroAndNeg);
};
// If either argument is decimal, return a decimal.
if (baseType == NumberDecimal || expType == NumberDecimal) {
Decimal128 baseDecimal = baseVal.coerceToDecimal();
Decimal128 expDecimal = expVal.coerceToDecimal();
checkNonZeroAndNeg(baseDecimal.isZero() && expDecimal.isNegative());
return Value(baseDecimal.power(expDecimal));
}
// pow() will cast args to doubles.
double baseDouble = baseVal.coerceToDouble();
double expDouble = expVal.coerceToDouble();
checkNonZeroAndNeg(baseDouble == 0 && expDouble < 0);
// If either argument is a double, return a double.
if (baseType == NumberDouble || expType == NumberDouble) {
return Value(std::pow(baseDouble, expDouble));
}
// If either number is a long, return a long. If both numbers are ints, then return an int if
// the result fits or a long if it is too big.
const auto formatResult = [baseType, expType](long long res) {
if (baseType == NumberLong || expType == NumberLong) {
return Value(res);
}
return Value::createIntOrLong(res);
};
const long long baseLong = baseVal.getLong();
const long long expLong = expVal.getLong();
// Use this when the result cannot be represented as a long.
const auto computeDoubleResult = [baseLong, expLong]() {
return Value(std::pow(baseLong, expLong));
};
// Avoid doing repeated multiplication or using std::pow if the base is -1, 0, or 1.
if (baseLong == 0) {
if (expLong == 0) {
// 0^0 = 1.
return formatResult(1);
} else if (expLong > 0) {
// 0^x where x > 0 is 0.
return formatResult(0);
}
// We should have checked earlier that 0 to a negative power is banned.
MONGO_UNREACHABLE;
} else if (baseLong == 1) {
return formatResult(1);
} else if (baseLong == -1) {
// -1^0 = -1^2 = -1^4 = -1^6 ... = 1
// -1^1 = -1^3 = -1^5 = -1^7 ... = -1
return formatResult((expLong % 2 == 0) ? 1 : -1);
} else if (expLong > 63 || expLong < 0) {
// If the base is not 0, 1, or -1 and the exponent is too large, or negative,
// the result cannot be represented as a long.
return computeDoubleResult();
}
// It's still possible that the result cannot be represented as a long. If that's the case,
// return a double.
if (!representableAsLong(baseLong, expLong)) {
return computeDoubleResult();
}
// Use repeated multiplication, since pow() casts args to doubles which could result in
// loss of precision if arguments are very large.
const auto computeWithRepeatedMultiplication = [](long long base, long long exp) {
long long result = 1;
while (exp > 1) {
if (exp % 2 == 1) {
result *= base;
exp--;
}
// 'exp' is now guaranteed to be even.
base *= base;
exp /= 2;
}
if (exp) {
invariant(exp == 1);
result *= base;
}
return result;
};
return formatResult(computeWithRepeatedMultiplication(baseLong, expLong));
}
REGISTER_EXPRESSION(pow, ExpressionPow::parse);
const char* ExpressionPow::getOpName() const {
return "$pow";
}
/* ------------------------- ExpressionRange ------------------------------ */
Value ExpressionRange::evaluate(const Document& root) const {
Value startVal(vpOperand[0]->evaluate(root));
Value endVal(vpOperand[1]->evaluate(root));
uassert(34443,
str::stream() << "$range requires a numeric starting value, found value of type: "
<< typeName(startVal.getType()),
startVal.numeric());
uassert(34444,
str::stream() << "$range requires a starting value that can be represented as a 32-bit "
"integer, found value: "
<< startVal.toString(),
startVal.integral());
uassert(34445,
str::stream() << "$range requires a numeric ending value, found value of type: "
<< typeName(endVal.getType()),
endVal.numeric());
uassert(34446,
str::stream() << "$range requires an ending value that can be represented as a 32-bit "
"integer, found value: "
<< endVal.toString(),
endVal.integral());
int current = startVal.coerceToInt();
int end = endVal.coerceToInt();
int step = 1;
if (vpOperand.size() == 3) {
// A step was specified by the user.
Value stepVal(vpOperand[2]->evaluate(root));
uassert(34447,
str::stream() << "$range requires a numeric step value, found value of type:"
<< typeName(stepVal.getType()),
stepVal.numeric());
uassert(34448,
str::stream() << "$range requires a step value that can be represented as a 32-bit "
"integer, found value: "
<< stepVal.toString(),
stepVal.integral());
step = stepVal.coerceToInt();
uassert(34449, "$range requires a non-zero step value", step != 0);
}
std::vector<Value> output;
while ((step > 0 ? current < end : current > end)) {
output.push_back(Value(current));
current += step;
}
return Value(output);
}
REGISTER_EXPRESSION(range, ExpressionRange::parse);
const char* ExpressionRange::getOpName() const {
return "$range";
}
/* ------------------------ ExpressionReduce ------------------------------ */
REGISTER_EXPRESSION(reduce, ExpressionReduce::parse);
intrusive_ptr<Expression> ExpressionReduce::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
uassert(40075,
str::stream() << "$reduce requires an object as an argument, found: "
<< typeName(expr.type()),
expr.type() == Object);
intrusive_ptr<ExpressionReduce> reduce(new ExpressionReduce(expCtx));
// vpsSub is used only to parse 'in', which must have access to $$this and $$value.
VariablesParseState vpsSub(vps);
reduce->_thisVar = vpsSub.defineVariable("this");
reduce->_valueVar = vpsSub.defineVariable("value");
for (auto&& elem : expr.Obj()) {
auto field = elem.fieldNameStringData();
if (field == "input") {
reduce->_input = parseOperand(expCtx, elem, vps);
} else if (field == "initialValue") {
reduce->_initial = parseOperand(expCtx, elem, vps);
} else if (field == "in") {
reduce->_in = parseOperand(expCtx, elem, vpsSub);
} else {
uasserted(40076, str::stream() << "$reduce found an unknown argument: " << field);
}
}
uassert(40077, "$reduce requires 'input' to be specified", reduce->_input);
uassert(40078, "$reduce requires 'initialValue' to be specified", reduce->_initial);
uassert(40079, "$reduce requires 'in' to be specified", reduce->_in);
return reduce;
}
Value ExpressionReduce::evaluate(const Document& root) const {
Value inputVal = _input->evaluate(root);
if (inputVal.nullish()) {
return Value(BSONNULL);
}
uassert(40080,
str::stream() << "$reduce requires that 'input' be an array, found: "
<< inputVal.toString(),
inputVal.isArray());
Value accumulatedValue = _initial->evaluate(root);
auto& vars = getExpressionContext()->variables;
for (auto&& elem : inputVal.getArray()) {
vars.setValue(_thisVar, elem);
vars.setValue(_valueVar, accumulatedValue);
accumulatedValue = _in->evaluate(root);
}
return accumulatedValue;
}
intrusive_ptr<Expression> ExpressionReduce::optimize() {
_input = _input->optimize();
_initial = _initial->optimize();
_in = _in->optimize();
return this;
}
void ExpressionReduce::_doAddDependencies(DepsTracker* deps) const {
_input->addDependencies(deps);
_initial->addDependencies(deps);
_in->addDependencies(deps);
}
Value ExpressionReduce::serialize(bool explain) const {
return Value(Document{{"$reduce",
Document{{"input", _input->serialize(explain)},
{"initialValue", _initial->serialize(explain)},
{"in", _in->serialize(explain)}}}});
}
/* ------------------------ ExpressionReverseArray ------------------------ */
Value ExpressionReverseArray::evaluate(const Document& root) const {
Value input(vpOperand[0]->evaluate(root));
if (input.nullish()) {
return Value(BSONNULL);
}
uassert(34435,
str::stream() << "The argument to $reverseArray must be an array, but was of type: "
<< typeName(input.getType()),
input.isArray());
if (input.getArrayLength() < 2) {
return input;
}
std::vector<Value> array = input.getArray();
std::reverse(array.begin(), array.end());
return Value(array);
}
REGISTER_EXPRESSION(reverseArray, ExpressionReverseArray::parse);
const char* ExpressionReverseArray::getOpName() const {
return "$reverseArray";
}
namespace {
ValueSet arrayToSet(const Value& val, const ValueComparator& valueComparator) {
const vector<Value>& array = val.getArray();
ValueSet valueSet = valueComparator.makeOrderedValueSet();
valueSet.insert(array.begin(), array.end());
return valueSet;
}
}
/* ----------------------- ExpressionSetDifference ---------------------------- */
Value ExpressionSetDifference::evaluate(const Document& root) const {
const Value lhs = vpOperand[0]->evaluate(root);
const Value rhs = vpOperand[1]->evaluate(root);
if (lhs.nullish() || rhs.nullish()) {
return Value(BSONNULL);
}
uassert(17048,
str::stream() << "both operands of $setDifference must be arrays. First "
<< "argument is of type: "
<< typeName(lhs.getType()),
lhs.isArray());
uassert(17049,
str::stream() << "both operands of $setDifference must be arrays. Second "
<< "argument is of type: "
<< typeName(rhs.getType()),
rhs.isArray());
ValueSet rhsSet = arrayToSet(rhs, getExpressionContext()->getValueComparator());
const vector<Value>& lhsArray = lhs.getArray();
vector<Value> returnVec;
for (vector<Value>::const_iterator it = lhsArray.begin(); it != lhsArray.end(); ++it) {
// rhsSet serves the dual role of filtering out elements that were originally present
// in RHS and of eleminating duplicates from LHS
if (rhsSet.insert(*it).second) {
returnVec.push_back(*it);
}
}
return Value(std::move(returnVec));
}
REGISTER_EXPRESSION(setDifference, ExpressionSetDifference::parse);
const char* ExpressionSetDifference::getOpName() const {
return "$setDifference";
}
/* ----------------------- ExpressionSetEquals ---------------------------- */
void ExpressionSetEquals::validateArguments(const ExpressionVector& args) const {
uassert(17045,
str::stream() << "$setEquals needs at least two arguments had: " << args.size(),
args.size() >= 2);
}
Value ExpressionSetEquals::evaluate(const Document& root) const {
const size_t n = vpOperand.size();
const auto& valueComparator = getExpressionContext()->getValueComparator();
ValueSet lhs = valueComparator.makeOrderedValueSet();
for (size_t i = 0; i < n; i++) {
const Value nextEntry = vpOperand[i]->evaluate(root);
uassert(17044,
str::stream() << "All operands of $setEquals must be arrays. One "
<< "argument is of type: "
<< typeName(nextEntry.getType()),
nextEntry.isArray());
if (i == 0) {
lhs.insert(nextEntry.getArray().begin(), nextEntry.getArray().end());
} else {
ValueSet rhs = valueComparator.makeOrderedValueSet();
rhs.insert(nextEntry.getArray().begin(), nextEntry.getArray().end());
if (lhs.size() != rhs.size()) {
return Value(false);
}
if (!std::equal(lhs.begin(), lhs.end(), rhs.begin(), valueComparator.getEqualTo())) {
return Value(false);
}
}
}
return Value(true);
}
REGISTER_EXPRESSION(setEquals, ExpressionSetEquals::parse);
const char* ExpressionSetEquals::getOpName() const {
return "$setEquals";
}
/* ----------------------- ExpressionSetIntersection ---------------------------- */
Value ExpressionSetIntersection::evaluate(const Document& root) const {
const size_t n = vpOperand.size();
const auto& valueComparator = getExpressionContext()->getValueComparator();
ValueSet currentIntersection = valueComparator.makeOrderedValueSet();
for (size_t i = 0; i < n; i++) {
const Value nextEntry = vpOperand[i]->evaluate(root);
if (nextEntry.nullish()) {
return Value(BSONNULL);
}
uassert(17047,
str::stream() << "All operands of $setIntersection must be arrays. One "
<< "argument is of type: "
<< typeName(nextEntry.getType()),
nextEntry.isArray());
if (i == 0) {
currentIntersection.insert(nextEntry.getArray().begin(), nextEntry.getArray().end());
} else {
ValueSet nextSet = arrayToSet(nextEntry, valueComparator);
if (currentIntersection.size() > nextSet.size()) {
// to iterate over whichever is the smaller set
nextSet.swap(currentIntersection);
}
ValueSet::iterator it = currentIntersection.begin();
while (it != currentIntersection.end()) {
if (!nextSet.count(*it)) {
ValueSet::iterator del = it;
++it;
currentIntersection.erase(del);
} else {
++it;
}
}
}
if (currentIntersection.empty()) {
break;
}
}
return Value(vector<Value>(currentIntersection.begin(), currentIntersection.end()));
}
REGISTER_EXPRESSION(setIntersection, ExpressionSetIntersection::parse);
const char* ExpressionSetIntersection::getOpName() const {
return "$setIntersection";
}
/* ----------------------- ExpressionSetIsSubset ---------------------------- */
namespace {
Value setIsSubsetHelper(const vector<Value>& lhs, const ValueSet& rhs) {
// do not shortcircuit when lhs.size() > rhs.size()
// because lhs can have redundant entries
for (vector<Value>::const_iterator it = lhs.begin(); it != lhs.end(); ++it) {
if (!rhs.count(*it)) {
return Value(false);
}
}
return Value(true);
}
}
Value ExpressionSetIsSubset::evaluate(const Document& root) const {
const Value lhs = vpOperand[0]->evaluate(root);
const Value rhs = vpOperand[1]->evaluate(root);
uassert(17046,
str::stream() << "both operands of $setIsSubset must be arrays. First "
<< "argument is of type: "
<< typeName(lhs.getType()),
lhs.isArray());
uassert(17042,
str::stream() << "both operands of $setIsSubset must be arrays. Second "
<< "argument is of type: "
<< typeName(rhs.getType()),
rhs.isArray());
return setIsSubsetHelper(lhs.getArray(),
arrayToSet(rhs, getExpressionContext()->getValueComparator()));
}
/**
* This class handles the case where the RHS set is constant.
*
* Since it is constant we can construct the hashset once which makes the runtime performance
* effectively constant with respect to the size of RHS. Large, constant RHS is expected to be a
* major use case for $redact and this has been verified to improve performance significantly.
*/
class ExpressionSetIsSubset::Optimized : public ExpressionSetIsSubset {
public:
Optimized(const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ValueSet& cachedRhsSet,
const ExpressionVector& operands)
: ExpressionSetIsSubset(expCtx), _cachedRhsSet(cachedRhsSet) {
vpOperand = operands;
}
virtual Value evaluate(const Document& root) const {
const Value lhs = vpOperand[0]->evaluate(root);
uassert(17310,
str::stream() << "both operands of $setIsSubset must be arrays. First "
<< "argument is of type: "
<< typeName(lhs.getType()),
lhs.isArray());
return setIsSubsetHelper(lhs.getArray(), _cachedRhsSet);
}
private:
const ValueSet _cachedRhsSet;
};
intrusive_ptr<Expression> ExpressionSetIsSubset::optimize() {
// perfore basic optimizations
intrusive_ptr<Expression> optimized = ExpressionNary::optimize();
// if ExpressionNary::optimize() created a new value, return it directly
if (optimized.get() != this)
return optimized;
if (ExpressionConstant* ec = dynamic_cast<ExpressionConstant*>(vpOperand[1].get())) {
const Value rhs = ec->getValue();
uassert(17311,
str::stream() << "both operands of $setIsSubset must be arrays. Second "
<< "argument is of type: "
<< typeName(rhs.getType()),
rhs.isArray());
intrusive_ptr<Expression> optimizedWithConstant(
new Optimized(this->getExpressionContext(),
arrayToSet(rhs, getExpressionContext()->getValueComparator()),
vpOperand));
return optimizedWithConstant;
}
return optimized;
}
REGISTER_EXPRESSION(setIsSubset, ExpressionSetIsSubset::parse);
const char* ExpressionSetIsSubset::getOpName() const {
return "$setIsSubset";
}
/* ----------------------- ExpressionSetUnion ---------------------------- */
Value ExpressionSetUnion::evaluate(const Document& root) const {
ValueSet unionedSet = getExpressionContext()->getValueComparator().makeOrderedValueSet();
const size_t n = vpOperand.size();
for (size_t i = 0; i < n; i++) {
const Value newEntries = vpOperand[i]->evaluate(root);
if (newEntries.nullish()) {
return Value(BSONNULL);
}
uassert(17043,
str::stream() << "All operands of $setUnion must be arrays. One argument"
<< " is of type: "
<< typeName(newEntries.getType()),
newEntries.isArray());
unionedSet.insert(newEntries.getArray().begin(), newEntries.getArray().end());
}
return Value(vector<Value>(unionedSet.begin(), unionedSet.end()));
}
REGISTER_EXPRESSION(setUnion, ExpressionSetUnion::parse);
const char* ExpressionSetUnion::getOpName() const {
return "$setUnion";
}
/* ----------------------- ExpressionIsArray ---------------------------- */
Value ExpressionIsArray::evaluate(const Document& root) const {
Value argument = vpOperand[0]->evaluate(root);
return Value(argument.isArray());
}
REGISTER_EXPRESSION(isArray, ExpressionIsArray::parse);
const char* ExpressionIsArray::getOpName() const {
return "$isArray";
}
/* ----------------------- ExpressionSlice ---------------------------- */
Value ExpressionSlice::evaluate(const Document& root) const {
const size_t n = vpOperand.size();
Value arrayVal = vpOperand[0]->evaluate(root);
// Could be either a start index or the length from 0.
Value arg2 = vpOperand[1]->evaluate(root);
if (arrayVal.nullish() || arg2.nullish()) {
return Value(BSONNULL);
}
uassert(28724,
str::stream() << "First argument to $slice must be an array, but is"
<< " of type: "
<< typeName(arrayVal.getType()),
arrayVal.isArray());
uassert(28725,
str::stream() << "Second argument to $slice must be a numeric value,"
<< " but is of type: "
<< typeName(arg2.getType()),
arg2.numeric());
uassert(28726,
str::stream() << "Second argument to $slice can't be represented as"
<< " a 32-bit integer: "
<< arg2.coerceToDouble(),
arg2.integral());
const auto& array = arrayVal.getArray();
size_t start;
size_t end;
if (n == 2) {
// Only count given.
int count = arg2.coerceToInt();
start = 0;
end = array.size();
if (count >= 0) {
end = std::min(end, size_t(count));
} else {
// Negative count's start from the back. If a abs(count) is greater
// than the
// length of the array, return the whole array.
start = std::max(0, static_cast<int>(array.size()) + count);
}
} else {
// We have both a start index and a count.
int startInt = arg2.coerceToInt();
if (startInt < 0) {
// Negative values start from the back. If a abs(start) is greater
// than the length
// of the array, start from 0.
start = std::max(0, static_cast<int>(array.size()) + startInt);
} else {
start = std::min(array.size(), size_t(startInt));
}
Value countVal = vpOperand[2]->evaluate(root);
if (countVal.nullish()) {
return Value(BSONNULL);
}
uassert(28727,
str::stream() << "Third argument to $slice must be numeric, but "
<< "is of type: "
<< typeName(countVal.getType()),
countVal.numeric());
uassert(28728,
str::stream() << "Third argument to $slice can't be represented"
<< " as a 32-bit integer: "
<< countVal.coerceToDouble(),
countVal.integral());
uassert(28729,
str::stream() << "Third argument to $slice must be positive: "
<< countVal.coerceToInt(),
countVal.coerceToInt() > 0);
size_t count = size_t(countVal.coerceToInt());
end = std::min(start + count, array.size());
}
return Value(vector<Value>(array.begin() + start, array.begin() + end));
}
REGISTER_EXPRESSION(slice, ExpressionSlice::parse);
const char* ExpressionSlice::getOpName() const {
return "$slice";
}
/* ----------------------- ExpressionSize ---------------------------- */
Value ExpressionSize::evaluate(const Document& root) const {
Value array = vpOperand[0]->evaluate(root);
uassert(17124,
str::stream() << "The argument to $size must be an array, but was of type: "
<< typeName(array.getType()),
array.isArray());
return Value::createIntOrLong(array.getArray().size());
}
REGISTER_EXPRESSION(size, ExpressionSize::parse);
const char* ExpressionSize::getOpName() const {
return "$size";
}
/* ----------------------- ExpressionSplit --------------------------- */
Value ExpressionSplit::evaluate(const Document& root) const {
Value inputArg = vpOperand[0]->evaluate(root);
Value separatorArg = vpOperand[1]->evaluate(root);
if (inputArg.nullish() || separatorArg.nullish()) {
return Value(BSONNULL);
}
uassert(40085,
str::stream() << "$split requires an expression that evaluates to a string as a first "
"argument, found: "
<< typeName(inputArg.getType()),
inputArg.getType() == BSONType::String);
uassert(40086,
str::stream() << "$split requires an expression that evaluates to a string as a second "
"argument, found: "
<< typeName(separatorArg.getType()),
separatorArg.getType() == BSONType::String);
std::string input = inputArg.getString();
std::string separator = separatorArg.getString();
uassert(40087, "$split requires a non-empty separator", !separator.empty());
std::vector<Value> output;
// Keep track of the index at which the current output string began.
size_t splitStartIndex = 0;
// Iterate through 'input' and check to see if 'separator' matches at any point.
for (size_t i = 0; i < input.size();) {
if (stringHasTokenAtIndex(i, input, separator)) {
// We matched; add the current string to our output and jump ahead.
StringData splitString(input.c_str() + splitStartIndex, i - splitStartIndex);
output.push_back(Value(splitString));
i += separator.size();
splitStartIndex = i;
} else {
// We did not match, continue to the next character.
++i;
}
}
StringData splitString(input.c_str() + splitStartIndex, input.size() - splitStartIndex);
output.push_back(Value(splitString));
return Value(output);
}
REGISTER_EXPRESSION(split, ExpressionSplit::parse);
const char* ExpressionSplit::getOpName() const {
return "$split";
}
/* ----------------------- ExpressionSqrt ---------------------------- */
Value ExpressionSqrt::evaluateNumericArg(const Value& numericArg) const {
auto checkArg = [](bool nonNegative) {
uassert(28714, "$sqrt's argument must be greater than or equal to 0", nonNegative);
};
if (numericArg.getType() == NumberDecimal) {
Decimal128 argDec = numericArg.getDecimal();
checkArg(!argDec.isLess(Decimal128::kNormalizedZero)); // NaN returns Nan without error
return Value(argDec.squareRoot());
}
double argDouble = numericArg.coerceToDouble();
checkArg(!(argDouble < 0)); // NaN returns Nan without error
return Value(sqrt(argDouble));
}
REGISTER_EXPRESSION(sqrt, ExpressionSqrt::parse);
const char* ExpressionSqrt::getOpName() const {
return "$sqrt";
}
/* ----------------------- ExpressionStrcasecmp ---------------------------- */
Value ExpressionStrcasecmp::evaluate(const Document& root) const {
Value pString1(vpOperand[0]->evaluate(root));
Value pString2(vpOperand[1]->evaluate(root));
/* boost::iequals returns a bool not an int so strings must actually be allocated */
string str1 = boost::to_upper_copy(pString1.coerceToString());
string str2 = boost::to_upper_copy(pString2.coerceToString());
int result = str1.compare(str2);
if (result == 0)
return Value(0);
else if (result > 0)
return Value(1);
else
return Value(-1);
}
REGISTER_EXPRESSION(strcasecmp, ExpressionStrcasecmp::parse);
const char* ExpressionStrcasecmp::getOpName() const {
return "$strcasecmp";
}
/* ----------------------- ExpressionSubstrBytes ---------------------------- */
Value ExpressionSubstrBytes::evaluate(const Document& root) const {
Value pString(vpOperand[0]->evaluate(root));
Value pLower(vpOperand[1]->evaluate(root));
Value pLength(vpOperand[2]->evaluate(root));
string str = pString.coerceToString();
uassert(16034,
str::stream() << getOpName()
<< ": starting index must be a numeric type (is BSON type "
<< typeName(pLower.getType())
<< ")",
(pLower.getType() == NumberInt || pLower.getType() == NumberLong ||
pLower.getType() == NumberDouble));
uassert(16035,
str::stream() << getOpName() << ": length must be a numeric type (is BSON type "
<< typeName(pLength.getType())
<< ")",
(pLength.getType() == NumberInt || pLength.getType() == NumberLong ||
pLength.getType() == NumberDouble));
const long long signedLower = pLower.coerceToLong();
uassert(50752,
str::stream() << getOpName() << ": starting index must be non-negative (got: "
<< signedLower
<< ")",
signedLower >= 0);
const string::size_type lower = static_cast<string::size_type>(signedLower);
// If the passed length is negative, we should return the rest of the string.
const long long signedLength = pLength.coerceToLong();
const string::size_type length =
signedLength < 0 ? str.length() : static_cast<string::size_type>(signedLength);
uassert(28656,
str::stream() << getOpName()
<< ": Invalid range, starting index is a UTF-8 continuation byte.",
(lower >= str.length() || !str::isUTF8ContinuationByte(str[lower])));
// Check the byte after the last character we'd return. If it is a continuation byte, that
// means we're in the middle of a UTF-8 character.
uassert(
28657,
str::stream() << getOpName()
<< ": Invalid range, ending index is in the middle of a UTF-8 character.",
(lower + length >= str.length() || !str::isUTF8ContinuationByte(str[lower + length])));
if (lower >= str.length()) {
// If lower > str.length() then string::substr() will throw out_of_range, so return an
// empty string if lower is not a valid string index.
return Value(StringData());
}
return Value(str.substr(lower, length));
}
// $substr is deprecated in favor of $substrBytes, but for now will just parse into a $substrBytes.
REGISTER_EXPRESSION(substrBytes, ExpressionSubstrBytes::parse);
REGISTER_EXPRESSION(substr, ExpressionSubstrBytes::parse);
const char* ExpressionSubstrBytes::getOpName() const {
return "$substrBytes";
}
/* ----------------------- ExpressionSubstrCP ---------------------------- */
Value ExpressionSubstrCP::evaluate(const Document& root) const {
Value inputVal(vpOperand[0]->evaluate(root));
Value lowerVal(vpOperand[1]->evaluate(root));
Value lengthVal(vpOperand[2]->evaluate(root));
std::string str = inputVal.coerceToString();
uassert(34450,
str::stream() << getOpName() << ": starting index must be a numeric type (is BSON type "
<< typeName(lowerVal.getType())
<< ")",
lowerVal.numeric());
uassert(34451,
str::stream() << getOpName()
<< ": starting index cannot be represented as a 32-bit integral value: "
<< lowerVal.toString(),
lowerVal.integral());
uassert(34452,
str::stream() << getOpName() << ": length must be a numeric type (is BSON type "
<< typeName(lengthVal.getType())
<< ")",
lengthVal.numeric());
uassert(34453,
str::stream() << getOpName()
<< ": length cannot be represented as a 32-bit integral value: "
<< lengthVal.toString(),
lengthVal.integral());
int startIndexCodePoints = lowerVal.coerceToInt();
int length = lengthVal.coerceToInt();
uassert(34454,
str::stream() << getOpName() << ": length must be a nonnegative integer.",
length >= 0);
uassert(34455,
str::stream() << getOpName() << ": the starting index must be nonnegative integer.",
startIndexCodePoints >= 0);
size_t startIndexBytes = 0;
for (int i = 0; i < startIndexCodePoints; i++) {
if (startIndexBytes >= str.size()) {
return Value(StringData());
}
uassert(34456,
str::stream() << getOpName() << ": invalid UTF-8 string",
!str::isUTF8ContinuationByte(str[startIndexBytes]));
size_t codePointLength = getCodePointLength(str[startIndexBytes]);
uassert(
34457, str::stream() << getOpName() << ": invalid UTF-8 string", codePointLength <= 4);
startIndexBytes += codePointLength;
}
size_t endIndexBytes = startIndexBytes;
for (int i = 0; i < length && endIndexBytes < str.size(); i++) {
uassert(34458,
str::stream() << getOpName() << ": invalid UTF-8 string",
!str::isUTF8ContinuationByte(str[endIndexBytes]));
size_t codePointLength = getCodePointLength(str[endIndexBytes]);
uassert(
34459, str::stream() << getOpName() << ": invalid UTF-8 string", codePointLength <= 4);
endIndexBytes += codePointLength;
}
return Value(std::string(str, startIndexBytes, endIndexBytes - startIndexBytes));
}
REGISTER_EXPRESSION(substrCP, ExpressionSubstrCP::parse);
const char* ExpressionSubstrCP::getOpName() const {
return "$substrCP";
}
/* ----------------------- ExpressionStrLenBytes ------------------------- */
Value ExpressionStrLenBytes::evaluate(const Document& root) const {
Value str(vpOperand[0]->evaluate(root));
uassert(34473,
str::stream() << "$strLenBytes requires a string argument, found: "
<< typeName(str.getType()),
str.getType() == String);
size_t strLen = str.getString().size();
uassert(34470,
"string length could not be represented as an int.",
strLen <= std::numeric_limits<int>::max());
return Value(static_cast<int>(strLen));
}
REGISTER_EXPRESSION(strLenBytes, ExpressionStrLenBytes::parse);
const char* ExpressionStrLenBytes::getOpName() const {
return "$strLenBytes";
}
/* ----------------------- ExpressionStrLenCP ------------------------- */
Value ExpressionStrLenCP::evaluate(const Document& root) const {
Value val(vpOperand[0]->evaluate(root));
uassert(34471,
str::stream() << "$strLenCP requires a string argument, found: "
<< typeName(val.getType()),
val.getType() == String);
std::string stringVal = val.getString();
size_t strLen = str::lengthInUTF8CodePoints(stringVal);
uassert(34472,
"string length could not be represented as an int.",
strLen <= std::numeric_limits<int>::max());
return Value(static_cast<int>(strLen));
}
REGISTER_EXPRESSION(strLenCP, ExpressionStrLenCP::parse);
const char* ExpressionStrLenCP::getOpName() const {
return "$strLenCP";
}
/* ----------------------- ExpressionSubtract ---------------------------- */
Value ExpressionSubtract::evaluate(const Document& root) const {
Value lhs = vpOperand[0]->evaluate(root);
Value rhs = vpOperand[1]->evaluate(root);
BSONType diffType = Value::getWidestNumeric(rhs.getType(), lhs.getType());
if (diffType == NumberDecimal) {
Decimal128 right = rhs.coerceToDecimal();
Decimal128 left = lhs.coerceToDecimal();
return Value(left.subtract(right));
} else if (diffType == NumberDouble) {
double right = rhs.coerceToDouble();
double left = lhs.coerceToDouble();
return Value(left - right);
} else if (diffType == NumberLong) {
long long right = rhs.coerceToLong();
long long left = lhs.coerceToLong();
return Value(left - right);
} else if (diffType == NumberInt) {
long long right = rhs.coerceToLong();
long long left = lhs.coerceToLong();
return Value::createIntOrLong(left - right);
} else if (lhs.nullish() || rhs.nullish()) {
return Value(BSONNULL);
} else if (lhs.getType() == Date) {
if (rhs.getType() == Date) {
return Value(durationCount<Milliseconds>(lhs.getDate() - rhs.getDate()));
} else if (rhs.numeric()) {
return Value(lhs.getDate() - Milliseconds(rhs.coerceToLong()));
} else {
uasserted(16613,
str::stream() << "cant $subtract a " << typeName(rhs.getType())
<< " from a Date");
}
} else {
uasserted(16556,
str::stream() << "cant $subtract a" << typeName(rhs.getType()) << " from a "
<< typeName(lhs.getType()));
}
}
REGISTER_EXPRESSION(subtract, ExpressionSubtract::parse);
const char* ExpressionSubtract::getOpName() const {
return "$subtract";
}
/* ------------------------- ExpressionSwitch ------------------------------ */
REGISTER_EXPRESSION(switch, ExpressionSwitch::parse);
Value ExpressionSwitch::evaluate(const Document& root) const {
for (auto&& branch : _branches) {
Value caseExpression(branch.first->evaluate(root));
if (caseExpression.coerceToBool()) {
return branch.second->evaluate(root);
}
}
uassert(40066,
"$switch could not find a matching branch for an input, and no default was specified.",
_default);
return _default->evaluate(root);
}
boost::intrusive_ptr<Expression> ExpressionSwitch::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
uassert(40060,
str::stream() << "$switch requires an object as an argument, found: "
<< typeName(expr.type()),
expr.type() == Object);
intrusive_ptr<ExpressionSwitch> expression(new ExpressionSwitch(expCtx));
for (auto&& elem : expr.Obj()) {
auto field = elem.fieldNameStringData();
if (field == "branches") {
// Parse each branch separately.
uassert(40061,
str::stream() << "$switch expected an array for 'branches', found: "
<< typeName(elem.type()),
elem.type() == Array);
for (auto&& branch : elem.Array()) {
uassert(40062,
str::stream() << "$switch expected each branch to be an object, found: "
<< typeName(branch.type()),
branch.type() == Object);
ExpressionPair branchExpression;
for (auto&& branchElement : branch.Obj()) {
auto branchField = branchElement.fieldNameStringData();
if (branchField == "case") {
branchExpression.first = parseOperand(expCtx, branchElement, vps);
} else if (branchField == "then") {
branchExpression.second = parseOperand(expCtx, branchElement, vps);
} else {
uasserted(40063,
str::stream() << "$switch found an unknown argument to a branch: "
<< branchField);
}
}
uassert(40064,
"$switch requires each branch have a 'case' expression",
branchExpression.first);
uassert(40065,
"$switch requires each branch have a 'then' expression.",
branchExpression.second);
expression->_branches.push_back(branchExpression);
}
} else if (field == "default") {
// Optional, arbitrary expression.
expression->_default = parseOperand(expCtx, elem, vps);
} else {
uasserted(40067, str::stream() << "$switch found an unknown argument: " << field);
}
}
uassert(40068, "$switch requires at least one branch.", !expression->_branches.empty());
return expression;
}
void ExpressionSwitch::_doAddDependencies(DepsTracker* deps) const {
for (auto&& branch : _branches) {
branch.first->addDependencies(deps);
branch.second->addDependencies(deps);
}
if (_default) {
_default->addDependencies(deps);
}
}
boost::intrusive_ptr<Expression> ExpressionSwitch::optimize() {
if (_default) {
_default = _default->optimize();
}
std::transform(_branches.begin(),
_branches.end(),
_branches.begin(),
[](ExpressionPair branch) -> ExpressionPair {
return {branch.first->optimize(), branch.second->optimize()};
});
return this;
}
Value ExpressionSwitch::serialize(bool explain) const {
std::vector<Value> serializedBranches;
serializedBranches.reserve(_branches.size());
for (auto&& branch : _branches) {
serializedBranches.push_back(Value(Document{{"case", branch.first->serialize(explain)},
{"then", branch.second->serialize(explain)}}));
}
if (_default) {
return Value(Document{{"$switch",
Document{{"branches", Value(serializedBranches)},
{"default", _default->serialize(explain)}}}});
}
return Value(Document{{"$switch", Document{{"branches", Value(serializedBranches)}}}});
}
/* ------------------------- ExpressionToLower ----------------------------- */
Value ExpressionToLower::evaluate(const Document& root) const {
Value pString(vpOperand[0]->evaluate(root));
string str = pString.coerceToString();
boost::to_lower(str);
return Value(str);
}
REGISTER_EXPRESSION(toLower, ExpressionToLower::parse);
const char* ExpressionToLower::getOpName() const {
return "$toLower";
}
/* ------------------------- ExpressionToUpper -------------------------- */
Value ExpressionToUpper::evaluate(const Document& root) const {
Value pString(vpOperand[0]->evaluate(root));
string str(pString.coerceToString());
boost::to_upper(str);
return Value(str);
}
REGISTER_EXPRESSION(toUpper, ExpressionToUpper::parse);
const char* ExpressionToUpper::getOpName() const {
return "$toUpper";
}
/* -------------------------- ExpressionTrim ------------------------------ */
REGISTER_EXPRESSION(trim, ExpressionTrim::parse);
REGISTER_EXPRESSION(ltrim, ExpressionTrim::parse);
REGISTER_EXPRESSION(rtrim, ExpressionTrim::parse);
intrusive_ptr<Expression> ExpressionTrim::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
const auto name = expr.fieldNameStringData();
TrimType trimType = TrimType::kBoth;
if (name == "$ltrim"_sd) {
trimType = TrimType::kLeft;
} else if (name == "$rtrim"_sd) {
trimType = TrimType::kRight;
} else {
invariant(name == "$trim"_sd);
}
uassert(50696,
str::stream() << name << " only supports an object as an argument, found "
<< typeName(expr.type()),
expr.type() == Object);
boost::intrusive_ptr<Expression> input;
boost::intrusive_ptr<Expression> characters;
for (auto&& elem : expr.Obj()) {
const auto field = elem.fieldNameStringData();
if (field == "input"_sd) {
input = parseOperand(expCtx, elem, vps);
} else if (field == "chars"_sd) {
characters = parseOperand(expCtx, elem, vps);
} else {
uasserted(50694,
str::stream() << name << " found an unknown argument: " << elem.fieldName());
}
}
uassert(50695, str::stream() << name << " requires an 'input' field", input);
return new ExpressionTrim(expCtx, trimType, name, input, characters);
}
namespace {
const std::vector<StringData> kDefaultTrimWhitespaceChars = {
"\0"_sd, // Null character. Avoid using "\u0000" syntax to work around a gcc bug:
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53690.
"\u0020"_sd, // Space
"\u0009"_sd, // Horizontal tab
"\u000A"_sd, // Line feed/new line
"\u000B"_sd, // Vertical tab
"\u000C"_sd, // Form feed
"\u000D"_sd, // Horizontal tab
"\u00A0"_sd, // Non-breaking space
"\u1680"_sd, // Ogham space mark
"\u2000"_sd, // En quad
"\u2001"_sd, // Em quad
"\u2002"_sd, // En space
"\u2003"_sd, // Em space
"\u2004"_sd, // Three-per-em space
"\u2005"_sd, // Four-per-em space
"\u2006"_sd, // Six-per-em space
"\u2007"_sd, // Figure space
"\u2008"_sd, // Punctuation space
"\u2009"_sd, // Thin space
"\u200A"_sd // Hair space
};
/**
* Assuming 'charByte' is the beginning of a UTF-8 code point, returns the number of bytes that
* should be used to represent the code point. Said another way, computes how many continuation
* bytes are expected to be present after 'charByte' in a UTF-8 encoded string.
*/
inline size_t numberOfBytesForCodePoint(char charByte) {
if ((charByte & 0b11111000) == 0b11110000) {
return 4;
} else if ((charByte & 0b11110000) == 0b11100000) {
return 3;
} else if ((charByte & 0b11100000) == 0b11000000) {
return 2;
} else {
return 1;
}
}
/**
* Returns a vector with one entry per code point to trim, or throws an exception if 'utf8String'
* contains invalid UTF-8.
*/
std::vector<StringData> extractCodePointsFromChars(StringData utf8String,
StringData expressionName) {
std::vector<StringData> codePoints;
std::size_t i = 0;
while (i < utf8String.size()) {
uassert(50698,
str::stream() << "Failed to parse \"chars\" argument to " << expressionName
<< ": Detected invalid UTF-8. Got continuation byte when expecting "
"the start of a new code point.",
!str::isUTF8ContinuationByte(utf8String[i]));
codePoints.push_back(utf8String.substr(i, numberOfBytesForCodePoint(utf8String[i])));
i += numberOfBytesForCodePoint(utf8String[i]);
}
uassert(50697,
str::stream()
<< "Failed to parse \"chars\" argument to "
<< expressionName
<< ": Detected invalid UTF-8. Missing expected continuation byte at end of string.",
i <= utf8String.size());
return codePoints;
}
} // namespace
Value ExpressionTrim::evaluate(const Document& root) const {
auto unvalidatedInput = _input->evaluate(root);
if (unvalidatedInput.nullish()) {
return Value(BSONNULL);
}
uassert(50699,
str::stream() << _name << " requires its input to be a string, got "
<< unvalidatedInput.toString()
<< " (of type "
<< typeName(unvalidatedInput.getType())
<< ") instead.",
unvalidatedInput.getType() == BSONType::String);
const StringData input(unvalidatedInput.getStringData());
if (!_characters) {
return Value(doTrim(input, kDefaultTrimWhitespaceChars));
}
auto unvalidatedUserChars = _characters->evaluate(root);
if (unvalidatedUserChars.nullish()) {
return Value(BSONNULL);
}
uassert(50700,
str::stream() << _name << " requires 'chars' to be a string, got "
<< unvalidatedUserChars.toString()
<< " (of type "
<< typeName(unvalidatedUserChars.getType())
<< ") instead.",
unvalidatedUserChars.getType() == BSONType::String);
return Value(
doTrim(input, extractCodePointsFromChars(unvalidatedUserChars.getStringData(), _name)));
}
bool ExpressionTrim::codePointMatchesAtIndex(const StringData& input,
std::size_t indexOfInput,
const StringData& testCP) {
for (size_t i = 0; i < testCP.size(); ++i) {
if (indexOfInput + i >= input.size() || input[indexOfInput + i] != testCP[i]) {
return false;
}
}
return true;
};
StringData ExpressionTrim::trimFromLeft(StringData input, const std::vector<StringData>& trimCPs) {
std::size_t bytesTrimmedFromLeft = 0u;
while (bytesTrimmedFromLeft < input.size()) {
// Look for any matching code point to trim.
auto matchingCP = std::find_if(trimCPs.begin(), trimCPs.end(), [&](auto& testCP) {
return codePointMatchesAtIndex(input, bytesTrimmedFromLeft, testCP);
});
if (matchingCP == trimCPs.end()) {
// Nothing to trim, stop here.
break;
}
bytesTrimmedFromLeft += matchingCP->size();
}
return input.substr(bytesTrimmedFromLeft);
}
StringData ExpressionTrim::trimFromRight(StringData input, const std::vector<StringData>& trimCPs) {
std::size_t bytesTrimmedFromRight = 0u;
while (bytesTrimmedFromRight < input.size()) {
std::size_t indexToTrimFrom = input.size() - bytesTrimmedFromRight;
auto matchingCP = std::find_if(trimCPs.begin(), trimCPs.end(), [&](auto& testCP) {
if (indexToTrimFrom < testCP.size()) {
// We've gone off the left of the string.
return false;
}
return codePointMatchesAtIndex(input, indexToTrimFrom - testCP.size(), testCP);
});
if (matchingCP == trimCPs.end()) {
// Nothing to trim, stop here.
break;
}
bytesTrimmedFromRight += matchingCP->size();
}
return input.substr(0, input.size() - bytesTrimmedFromRight);
}
StringData ExpressionTrim::doTrim(StringData input, const std::vector<StringData>& trimCPs) const {
if (_trimType == TrimType::kBoth || _trimType == TrimType::kLeft) {
input = trimFromLeft(input, trimCPs);
}
if (_trimType == TrimType::kBoth || _trimType == TrimType::kRight) {
input = trimFromRight(input, trimCPs);
}
return input;
}
boost::intrusive_ptr<Expression> ExpressionTrim::optimize() {
_input = _input->optimize();
if (_characters) {
_characters = _characters->optimize();
}
if (ExpressionConstant::allNullOrConstant({_input, _characters})) {
return ExpressionConstant::create(getExpressionContext(), this->evaluate(Document()));
}
return this;
}
Value ExpressionTrim::serialize(bool explain) const {
return Value(
Document{{_name,
Document{{"input", _input->serialize(explain)},
{"chars", _characters ? _characters->serialize(explain) : Value()}}}});
}
void ExpressionTrim::_doAddDependencies(DepsTracker* deps) const {
_input->addDependencies(deps);
if (_characters) {
_characters->addDependencies(deps);
}
}
/* ------------------------- ExpressionTrunc -------------------------- */
Value ExpressionTrunc::evaluateNumericArg(const Value& numericArg) const {
// There's no point in truncating integers or longs, it will have no effect.
switch (numericArg.getType()) {
case NumberDecimal:
return Value(numericArg.getDecimal().quantize(Decimal128::kNormalizedZero,
Decimal128::kRoundTowardZero));
case NumberDouble:
return Value(std::trunc(numericArg.getDouble()));
default:
return numericArg;
}
}
REGISTER_EXPRESSION(trunc, ExpressionTrunc::parse);
const char* ExpressionTrunc::getOpName() const {
return "$trunc";
}
/* ------------------------- ExpressionType ----------------------------- */
Value ExpressionType::evaluate(const Document& root) const {
Value val(vpOperand[0]->evaluate(root));
return Value(StringData(typeName(val.getType())));
}
REGISTER_EXPRESSION(type, ExpressionType::parse);
const char* ExpressionType::getOpName() const {
return "$type";
}
/* -------------------------- ExpressionZip ------------------------------ */
REGISTER_EXPRESSION(zip, ExpressionZip::parse);
intrusive_ptr<Expression> ExpressionZip::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
uassert(34460,
str::stream() << "$zip only supports an object as an argument, found "
<< typeName(expr.type()),
expr.type() == Object);
intrusive_ptr<ExpressionZip> newZip(new ExpressionZip(expCtx));
for (auto&& elem : expr.Obj()) {
const auto field = elem.fieldNameStringData();
if (field == "inputs") {
uassert(34461,
str::stream() << "inputs must be an array of expressions, found "
<< typeName(elem.type()),
elem.type() == Array);
for (auto&& subExpr : elem.Array()) {
newZip->_inputs.push_back(parseOperand(expCtx, subExpr, vps));
}
} else if (field == "defaults") {
uassert(34462,
str::stream() << "defaults must be an array of expressions, found "
<< typeName(elem.type()),
elem.type() == Array);
for (auto&& subExpr : elem.Array()) {
newZip->_defaults.push_back(parseOperand(expCtx, subExpr, vps));
}
} else if (field == "useLongestLength") {
uassert(34463,
str::stream() << "useLongestLength must be a bool, found "
<< typeName(expr.type()),
elem.type() == Bool);
newZip->_useLongestLength = elem.Bool();
} else {
uasserted(34464,
str::stream() << "$zip found an unknown argument: " << elem.fieldName());
}
}
uassert(34465, "$zip requires at least one input array", !newZip->_inputs.empty());
uassert(34466,
"cannot specify defaults unless useLongestLength is true",
(newZip->_useLongestLength || newZip->_defaults.empty()));
uassert(34467,
"defaults and inputs must have the same length",
(newZip->_defaults.empty() || newZip->_defaults.size() == newZip->_inputs.size()));
return std::move(newZip);
}
Value ExpressionZip::evaluate(const Document& root) const {
// Evaluate input values.
vector<vector<Value>> inputValues;
inputValues.reserve(_inputs.size());
size_t minArraySize = 0;
size_t maxArraySize = 0;
for (size_t i = 0; i < _inputs.size(); i++) {
Value evalExpr = _inputs[i]->evaluate(root);
if (evalExpr.nullish()) {
return Value(BSONNULL);
}
uassert(34468,
str::stream() << "$zip found a non-array expression in input: "
<< evalExpr.toString(),
evalExpr.isArray());
inputValues.push_back(evalExpr.getArray());
size_t arraySize = evalExpr.getArrayLength();
if (i == 0) {
minArraySize = arraySize;
maxArraySize = arraySize;
} else {
auto arraySizes = std::minmax({minArraySize, arraySize, maxArraySize});
minArraySize = arraySizes.first;
maxArraySize = arraySizes.second;
}
}
vector<Value> evaluatedDefaults(_inputs.size(), Value(BSONNULL));
// If we need default values, evaluate each expression.
if (minArraySize != maxArraySize) {
for (size_t i = 0; i < _defaults.size(); i++) {
evaluatedDefaults[i] = _defaults[i]->evaluate(root);
}
}
size_t outputLength = _useLongestLength ? maxArraySize : minArraySize;
// The final output array, e.g. [[1, 2, 3], [2, 3, 4]].
vector<Value> output;
// Used to construct each array in the output, e.g. [1, 2, 3].
vector<Value> outputChild;
output.reserve(outputLength);
outputChild.reserve(_inputs.size());
for (size_t row = 0; row < outputLength; row++) {
outputChild.clear();
for (size_t col = 0; col < _inputs.size(); col++) {
if (inputValues[col].size() > row) {
// Add the value from the appropriate input array.
outputChild.push_back(inputValues[col][row]);
} else {
// Add the corresponding default value.
outputChild.push_back(evaluatedDefaults[col]);
}
}
output.push_back(Value(outputChild));
}
return Value(output);
}
boost::intrusive_ptr<Expression> ExpressionZip::optimize() {
std::transform(_inputs.begin(),
_inputs.end(),
_inputs.begin(),
[](intrusive_ptr<Expression> inputExpression) -> intrusive_ptr<Expression> {
return inputExpression->optimize();
});
std::transform(_defaults.begin(),
_defaults.end(),
_defaults.begin(),
[](intrusive_ptr<Expression> defaultExpression) -> intrusive_ptr<Expression> {
return defaultExpression->optimize();
});
return this;
}
Value ExpressionZip::serialize(bool explain) const {
vector<Value> serializedInput;
vector<Value> serializedDefaults;
Value serializedUseLongestLength = Value(_useLongestLength);
for (auto&& expr : _inputs) {
serializedInput.push_back(expr->serialize(explain));
}
for (auto&& expr : _defaults) {
serializedDefaults.push_back(expr->serialize(explain));
}
return Value(DOC("$zip" << DOC("inputs" << Value(serializedInput) << "defaults"
<< Value(serializedDefaults)
<< "useLongestLength"
<< serializedUseLongestLength)));
}
void ExpressionZip::_doAddDependencies(DepsTracker* deps) const {
std::for_each(
_inputs.begin(), _inputs.end(), [&deps](intrusive_ptr<Expression> inputExpression) -> void {
inputExpression->addDependencies(deps);
});
std::for_each(_defaults.begin(),
_defaults.end(),
[&deps](intrusive_ptr<Expression> defaultExpression) -> void {
defaultExpression->addDependencies(deps);
});
}
/* -------------------------- ExpressionConvert ------------------------------ */
namespace {
/**
* $convert supports a big grab bag of conversions, so ConversionTable maintains a collection of
* conversion functions, as well as a table to organize them by inputType and targetType.
*/
class ConversionTable {
public:
using ConversionFunc =
std::function<Value(const boost::intrusive_ptr<ExpressionContext>&, Value)>;
ConversionTable() {
//
// Conversions from NumberDouble
//
table[BSONType::NumberDouble][BSONType::NumberDouble] = &performIdentityConversion;
table[BSONType::NumberDouble][BSONType::String] = &performFormatDouble;
table[BSONType::NumberDouble]
[BSONType::Bool] = [](const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) { return Value(inputValue.coerceToBool()); };
table[BSONType::NumberDouble][BSONType::Date] = &performCastNumberToDate;
table[BSONType::NumberDouble][BSONType::NumberInt] = &performCastDoubleToInt;
table[BSONType::NumberDouble][BSONType::NumberLong] = &performCastDoubleToLong;
table[BSONType::NumberDouble][BSONType::NumberDecimal] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(inputValue.coerceToDecimal());
};
//
// Conversions from String
//
table[BSONType::String][BSONType::NumberDouble] = &parseStringToNumber<double, 0>;
table[BSONType::String][BSONType::String] = &performIdentityConversion;
table[BSONType::String][BSONType::jstOID] = &parseStringToOID;
table[BSONType::String][BSONType::Bool] = &performConvertToTrue;
table[BSONType::String][BSONType::Date] = [](
const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(expCtx->timeZoneDatabase->fromString(inputValue.getStringData(),
mongo::TimeZoneDatabase::utcZone()));
};
table[BSONType::String][BSONType::NumberInt] = &parseStringToNumber<int, 10>;
table[BSONType::String][BSONType::NumberLong] = &parseStringToNumber<long long, 10>;
table[BSONType::String][BSONType::NumberDecimal] = &parseStringToNumber<Decimal128, 0>;
//
// Conversions from jstOID
//
table[BSONType::jstOID][BSONType::String] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(inputValue.getOid().toString());
};
table[BSONType::jstOID][BSONType::jstOID] = &performIdentityConversion;
table[BSONType::jstOID][BSONType::Bool] = &performConvertToTrue;
table[BSONType::jstOID][BSONType::Date] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(inputValue.getOid().asDateT());
};
//
// Conversions from Bool
//
table[BSONType::Bool][BSONType::NumberDouble] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return inputValue.getBool() ? Value(1.0) : Value(0.0);
};
table[BSONType::Bool][BSONType::String] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return inputValue.getBool() ? Value("true"_sd) : Value("false"_sd);
};
table[BSONType::Bool][BSONType::Bool] = &performIdentityConversion;
table[BSONType::Bool][BSONType::NumberInt] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return inputValue.getBool() ? Value(int{1}) : Value(int{0});
};
table[BSONType::Bool][BSONType::NumberLong] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return inputValue.getBool() ? Value(1LL) : Value(0LL);
};
table[BSONType::Bool][BSONType::NumberDecimal] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return inputValue.getBool() ? Value(Decimal128(1)) : Value(Decimal128(0));
};
//
// Conversions from Date
//
table[BSONType::Date][BSONType::NumberDouble] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(static_cast<double>(inputValue.getDate().toMillisSinceEpoch()));
};
table[BSONType::Date][BSONType::String] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
auto dateString = TimeZoneDatabase::utcZone().formatDate(Value::kISOFormatString,
inputValue.getDate());
return Value(dateString);
};
table[BSONType::Date]
[BSONType::Bool] = [](const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) { return Value(inputValue.coerceToBool()); };
table[BSONType::Date][BSONType::Date] = &performIdentityConversion;
table[BSONType::Date][BSONType::NumberLong] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(inputValue.getDate().toMillisSinceEpoch());
};
table[BSONType::Date][BSONType::NumberDecimal] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(
Decimal128(static_cast<int64_t>(inputValue.getDate().toMillisSinceEpoch())));
};
//
// Conversions from NumberInt
//
table[BSONType::NumberInt][BSONType::NumberDouble] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(inputValue.coerceToDouble());
};
table[BSONType::NumberInt][BSONType::String] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(static_cast<std::string>(str::stream() << inputValue.getInt()));
};
table[BSONType::NumberInt]
[BSONType::Bool] = [](const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) { return Value(inputValue.coerceToBool()); };
table[BSONType::NumberInt][BSONType::NumberInt] = &performIdentityConversion;
table[BSONType::NumberInt][BSONType::NumberLong] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(static_cast<long long>(inputValue.getInt()));
};
table[BSONType::NumberInt][BSONType::NumberDecimal] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(inputValue.coerceToDecimal());
};
//
// Conversions from NumberLong
//
table[BSONType::NumberLong][BSONType::NumberDouble] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(inputValue.coerceToDouble());
};
table[BSONType::NumberLong][BSONType::String] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(static_cast<std::string>(str::stream() << inputValue.getLong()));
};
table[BSONType::NumberLong]
[BSONType::Bool] = [](const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) { return Value(inputValue.coerceToBool()); };
table[BSONType::NumberLong][BSONType::Date] = &performCastNumberToDate;
table[BSONType::NumberLong][BSONType::NumberInt] = &performCastLongToInt;
table[BSONType::NumberLong][BSONType::NumberLong] = &performIdentityConversion;
table[BSONType::NumberLong][BSONType::NumberDecimal] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(inputValue.coerceToDecimal());
};
//
// Conversions from NumberDecimal
//
table[BSONType::NumberDecimal][BSONType::NumberDouble] = &performCastDecimalToDouble;
table[BSONType::NumberDecimal][BSONType::String] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return Value(inputValue.getDecimal().toString());
};
table[BSONType::NumberDecimal]
[BSONType::Bool] = [](const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) { return Value(inputValue.coerceToBool()); };
table[BSONType::NumberDecimal][BSONType::Date] = &performCastNumberToDate;
table[BSONType::NumberDecimal][BSONType::NumberInt] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return performCastDecimalToInt(BSONType::NumberInt, inputValue);
};
table[BSONType::NumberDecimal][BSONType::NumberLong] =
[](const boost::intrusive_ptr<ExpressionContext>& expCtx, Value inputValue) {
return performCastDecimalToInt(BSONType::NumberLong, inputValue);
};
table[BSONType::NumberDecimal][BSONType::NumberDecimal] = &performIdentityConversion;
//
// Miscellaneous conversions to Bool
//
table[BSONType::Object][BSONType::Bool] = &performConvertToTrue;
table[BSONType::Array][BSONType::Bool] = &performConvertToTrue;
table[BSONType::BinData][BSONType::Bool] = &performConvertToTrue;
table[BSONType::RegEx][BSONType::Bool] = &performConvertToTrue;
table[BSONType::DBRef][BSONType::Bool] = &performConvertToTrue;
table[BSONType::Code][BSONType::Bool] = &performConvertToTrue;
table[BSONType::Symbol][BSONType::Bool] = &performConvertToTrue;
table[BSONType::CodeWScope][BSONType::Bool] = &performConvertToTrue;
table[BSONType::bsonTimestamp][BSONType::Bool] = &performConvertToTrue;
}
ConversionFunc findConversionFunc(BSONType inputType, BSONType targetType) const {
ConversionFunc foundFunction;
// Note: We can't use BSONType::MinKey (-1) or BSONType::MaxKey (127) as table indexes,
// so we have to treat them as special cases.
if (inputType != BSONType::MinKey && inputType != BSONType::MaxKey &&
targetType != BSONType::MinKey && targetType != BSONType::MaxKey) {
invariant(inputType >= 0 && inputType <= JSTypeMax);
invariant(targetType >= 0 && targetType <= JSTypeMax);
foundFunction = table[inputType][targetType];
} else if (targetType == BSONType::Bool) {
// This is a conversion from MinKey or MaxKey to Bool, which is allowed (and always
// returns true).
foundFunction = &performConvertToTrue;
} else {
// Any other conversions involving MinKey or MaxKey (either as the target or input) are
// illegal.
}
uassert(ErrorCodes::ConversionFailure,
str::stream() << "Unsupported conversion from " << typeName(inputType) << " to "
<< typeName(targetType)
<< " in $convert with no onError value",
foundFunction);
return foundFunction;
}
private:
ConversionFunc table[JSTypeMax + 1][JSTypeMax + 1];
static void validateDoubleValueIsFinite(double inputDouble) {
uassert(ErrorCodes::ConversionFailure,
"Attempt to convert NaN value to integer type in $convert with no onError value",
!std::isnan(inputDouble));
uassert(
ErrorCodes::ConversionFailure,
"Attempt to convert infinity value to integer type in $convert with no onError value",
std::isfinite(inputDouble));
}
static Value performCastDoubleToInt(const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) {
double inputDouble = inputValue.getDouble();
validateDoubleValueIsFinite(inputDouble);
uassert(ErrorCodes::ConversionFailure,
str::stream()
<< "Conversion would overflow target type in $convert with no onError value: "
<< inputDouble,
inputDouble >= std::numeric_limits<int>::lowest() &&
inputDouble <= std::numeric_limits<int>::max());
return Value(static_cast<int>(inputDouble));
}
static Value performCastDoubleToLong(const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) {
double inputDouble = inputValue.getDouble();
validateDoubleValueIsFinite(inputDouble);
uassert(ErrorCodes::ConversionFailure,
str::stream()
<< "Conversion would overflow target type in $convert with no onError value: "
<< inputDouble,
inputDouble >= std::numeric_limits<long long>::lowest() &&
inputDouble < BSONElement::kLongLongMaxPlusOneAsDouble);
return Value(static_cast<long long>(inputDouble));
}
static Value performCastDecimalToInt(BSONType targetType, Value inputValue) {
invariant(targetType == BSONType::NumberInt || targetType == BSONType::NumberLong);
Decimal128 inputDecimal = inputValue.getDecimal();
// Performing these checks up front allows us to provide more specific error messages than
// if we just gave the same error for any 'kInvalid' conversion.
uassert(ErrorCodes::ConversionFailure,
"Attempt to convert NaN value to integer type in $convert with no onError value",
!inputDecimal.isNaN());
uassert(
ErrorCodes::ConversionFailure,
"Attempt to convert infinity value to integer type in $convert with no onError value",
!inputDecimal.isInfinite());
std::uint32_t signalingFlags = Decimal128::SignalingFlag::kNoFlag;
Value result;
if (targetType == BSONType::NumberInt) {
int intVal =
inputDecimal.toInt(&signalingFlags, Decimal128::RoundingMode::kRoundTowardZero);
result = Value(intVal);
} else if (targetType == BSONType::NumberLong) {
long long longVal =
inputDecimal.toLong(&signalingFlags, Decimal128::RoundingMode::kRoundTowardZero);
result = Value(longVal);
} else {
MONGO_UNREACHABLE;
}
// NB: Decimal128::SignalingFlag has a values specifically for overflow, but it is used for
// arithmetic with Decimal128 operands, _not_ for conversions of this style. Overflowing
// conversions only trigger a 'kInvalid' flag.
uassert(ErrorCodes::ConversionFailure,
str::stream()
<< "Conversion would overflow target type in $convert with no onError value: "
<< inputDecimal.toString(),
(signalingFlags & Decimal128::SignalingFlag::kInvalid) == 0);
invariant(signalingFlags == Decimal128::SignalingFlag::kNoFlag);
return result;
}
static Value performCastDecimalToDouble(const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) {
Decimal128 inputDecimal = inputValue.getDecimal();
std::uint32_t signalingFlags = Decimal128::SignalingFlag::kNoFlag;
double result =
inputDecimal.toDouble(&signalingFlags, Decimal128::RoundingMode::kRoundTiesToEven);
uassert(ErrorCodes::ConversionFailure,
str::stream()
<< "Conversion would overflow target type in $convert with no onError value: "
<< inputDecimal.toString(),
signalingFlags == Decimal128::SignalingFlag::kNoFlag ||
signalingFlags == Decimal128::SignalingFlag::kInexact);
return Value(result);
}
static Value performCastLongToInt(const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) {
long long longValue = inputValue.getLong();
uassert(ErrorCodes::ConversionFailure,
str::stream()
<< "Conversion would overflow target type in $convert with no onError value: ",
longValue >= std::numeric_limits<int>::min() &&
longValue <= std::numeric_limits<int>::max());
return Value(static_cast<int>(longValue));
}
static Value performCastNumberToDate(const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) {
long long millisSinceEpoch;
switch (inputValue.getType()) {
case BSONType::NumberLong:
millisSinceEpoch = inputValue.getLong();
break;
case BSONType::NumberDouble:
millisSinceEpoch = performCastDoubleToLong(expCtx, inputValue).getLong();
break;
case BSONType::NumberDecimal:
millisSinceEpoch =
performCastDecimalToInt(BSONType::NumberLong, inputValue).getLong();
break;
default:
MONGO_UNREACHABLE;
}
return Value(Date_t::fromMillisSinceEpoch(millisSinceEpoch));
}
static Value performFormatDouble(const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) {
double doubleValue = inputValue.getDouble();
if (std::isinf(doubleValue)) {
return Value(std::signbit(doubleValue) ? "-Infinity"_sd : "Infinity"_sd);
} else if (std::isnan(doubleValue)) {
return Value("NaN"_sd);
} else if (doubleValue == 0.0 && std::signbit(doubleValue)) {
return Value("-0"_sd);
} else {
return Value(static_cast<std::string>(str::stream() << doubleValue));
}
}
template <class targetType, int base>
static Value parseStringToNumber(const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) {
auto stringValue = inputValue.getStringData();
targetType result;
// Reject any strings in hex format. This check is needed because the
// parseNumberFromStringWithBase call below allows an input hex string prefixed by '0x' when
// parsing to a double.
uassert(ErrorCodes::ConversionFailure,
str::stream() << "Illegal hexadecimal input in $convert with no onError value: "
<< stringValue,
!stringValue.startsWith("0x"));
Status parseStatus = parseNumberFromStringWithBase(stringValue, base, &result);
uassert(ErrorCodes::ConversionFailure,
str::stream() << "Failed to parse number '" << stringValue
<< "' in $convert with no onError value: "
<< parseStatus.reason(),
parseStatus.isOK());
return Value(result);
}
static Value parseStringToOID(const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) {
try {
return Value(OID::createFromString(inputValue.getStringData()));
} catch (const DBException& ex) {
// Rethrow any caught exception as a conversion failure such that 'onError' is evaluated
// and returned.
uasserted(ErrorCodes::ConversionFailure,
str::stream() << "Failed to parse objectId '" << inputValue.getString()
<< "' in $convert with no onError value: "
<< ex.reason());
}
}
static Value performConvertToTrue(const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) {
return Value(true);
}
static Value performIdentityConversion(const boost::intrusive_ptr<ExpressionContext>& expCtx,
Value inputValue) {
return inputValue;
}
};
Expression::Parser makeConversionAlias(const StringData shortcutName, BSONType toType) {
return [=](const intrusive_ptr<ExpressionContext>& expCtx,
BSONElement elem,
const VariablesParseState& vps) -> intrusive_ptr<Expression> {
// Use parseArguments to allow for a singleton array, or the unwrapped version.
auto operands = ExpressionNary::parseArguments(expCtx, elem, vps);
uassert(50723,
str::stream() << shortcutName << " requires a single argument, got "
<< operands.size(),
operands.size() == 1);
return ExpressionConvert::create(expCtx, operands[0], toType);
};
}
} // namespace
REGISTER_EXPRESSION(convert, ExpressionConvert::parse);
// Also register shortcut expressions like $toInt, $toString, etc. which can be used as a shortcut
// for $convert without an 'onNull' or 'onError'.
REGISTER_EXPRESSION(toString, makeConversionAlias("$toString"_sd, BSONType::String));
REGISTER_EXPRESSION(toObjectId, makeConversionAlias("$toObjectId"_sd, BSONType::jstOID));
REGISTER_EXPRESSION(toDate, makeConversionAlias("$toDate"_sd, BSONType::Date));
REGISTER_EXPRESSION(toDouble, makeConversionAlias("$toDouble"_sd, BSONType::NumberDouble));
REGISTER_EXPRESSION(toInt, makeConversionAlias("$toInt"_sd, BSONType::NumberInt));
REGISTER_EXPRESSION(toLong, makeConversionAlias("$toLong"_sd, BSONType::NumberLong));
REGISTER_EXPRESSION(toDecimal, makeConversionAlias("$toDecimal"_sd, BSONType::NumberDecimal));
REGISTER_EXPRESSION(toBool, makeConversionAlias("$toBool"_sd, BSONType::Bool));
boost::intrusive_ptr<Expression> ExpressionConvert::create(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const boost::intrusive_ptr<Expression>& input,
BSONType toType) {
return new ExpressionConvert(expCtx, input, toType);
}
ExpressionConvert::ExpressionConvert(const boost::intrusive_ptr<ExpressionContext>& expCtx,
const boost::intrusive_ptr<Expression>& input,
BSONType toType)
: Expression(expCtx),
_input(input),
_to(ExpressionConstant::create(expCtx, Value(StringData(typeName(toType))))) {}
intrusive_ptr<Expression> ExpressionConvert::parse(
const boost::intrusive_ptr<ExpressionContext>& expCtx,
BSONElement expr,
const VariablesParseState& vps) {
uassert(ErrorCodes::FailedToParse,
str::stream() << "$convert expects an object of named arguments but found: "
<< typeName(expr.type()),
expr.type() == BSONType::Object);
intrusive_ptr<ExpressionConvert> newConvert(new ExpressionConvert(expCtx));
for (auto&& elem : expr.embeddedObject()) {
const auto field = elem.fieldNameStringData();
if (field == "input"_sd) {
newConvert->_input = parseOperand(expCtx, elem, vps);
} else if (field == "to"_sd) {
newConvert->_to = parseOperand(expCtx, elem, vps);
} else if (field == "onError"_sd) {
newConvert->_onError = parseOperand(expCtx, elem, vps);
} else if (field == "onNull"_sd) {
newConvert->_onNull = parseOperand(expCtx, elem, vps);
} else {
uasserted(ErrorCodes::FailedToParse,
str::stream() << "$convert found an unknown argument: "
<< elem.fieldNameStringData());
}
}
uassert(ErrorCodes::FailedToParse, "Missing 'input' parameter to $convert", newConvert->_input);
uassert(ErrorCodes::FailedToParse, "Missing 'to' parameter to $convert", newConvert->_to);
return std::move(newConvert);
}
Value ExpressionConvert::evaluate(const Document& root) const {
auto toValue = _to->evaluate(root);
Value inputValue = _input->evaluate(root);
boost::optional<BSONType> targetType;
if (!toValue.nullish()) {
targetType = computeTargetType(toValue);
}
if (inputValue.nullish()) {
return _onNull ? _onNull->evaluate(root) : Value(BSONNULL);
} else if (!targetType) {
// "to" evaluated to a nullish value.
return Value(BSONNULL);
}
try {
return performConversion(*targetType, inputValue);
} catch (const ExceptionFor<ErrorCodes::ConversionFailure>&) {
if (_onError) {
return _onError->evaluate(root);
} else {
throw;
}
}
}
boost::intrusive_ptr<Expression> ExpressionConvert::optimize() {
_input = _input->optimize();
_to = _to->optimize();
if (_onError) {
_onError = _onError->optimize();
}
if (_onNull) {
_onNull = _onNull->optimize();
}
// Perform constant folding if possible. This does not support folding for $convert operations
// that have constant _to and _input values but non-constant _onError and _onNull values.
// Because _onError and _onNull are evaluated lazily, conversions that do not used the _onError
// and _onNull values could still be legally folded if those values are not needed. Support for
// that case would add more complexity than it's worth, though.
if (ExpressionConstant::allNullOrConstant({_input, _to, _onError, _onNull})) {
return ExpressionConstant::create(getExpressionContext(), evaluate(Document{}));
}
return this;
}
Value ExpressionConvert::serialize(bool explain) const {
return Value(Document{{"$convert",
Document{{"input", _input->serialize(explain)},
{"to", _to->serialize(explain)},
{"onError", _onError ? _onError->serialize(explain) : Value()},
{"onNull", _onNull ? _onNull->serialize(explain) : Value()}}}});
}
void ExpressionConvert::_doAddDependencies(DepsTracker* deps) const {
_input->addDependencies(deps);
_to->addDependencies(deps);
if (_onError) {
_onError->addDependencies(deps);
}
if (_onNull) {
_onNull->addDependencies(deps);
}
}
BSONType ExpressionConvert::computeTargetType(Value targetTypeName) const {
BSONType targetType;
if (targetTypeName.getType() == BSONType::String) {
// typeFromName() does not consider "missing" to be a valid type, but we want to accept it,
// because it is a possible result of the $type aggregation operator.
if (targetTypeName.getStringData() == "missing"_sd) {
return BSONType::EOO;
}
// This will throw if the type name is invalid.
targetType = typeFromName(targetTypeName.getString());
} else if (targetTypeName.numeric()) {
uassert(ErrorCodes::FailedToParse,
"In $convert, numeric 'to' argument is not an integer",
targetTypeName.integral());
int typeCode = targetTypeName.coerceToInt();
uassert(ErrorCodes::FailedToParse,
str::stream()
<< "In $convert, numeric value for 'to' does not correspond to a BSON type: "
<< typeCode,
isValidBSONType(typeCode));
targetType = static_cast<BSONType>(typeCode);
} else {
uasserted(ErrorCodes::FailedToParse,
str::stream() << "$convert's 'to' argument must be a string or number, but is "
<< typeName(targetTypeName.getType()));
}
return targetType;
}
Value ExpressionConvert::performConversion(BSONType targetType, Value inputValue) const {
invariant(!inputValue.nullish());
static const ConversionTable table;
BSONType inputType = inputValue.getType();
return table.findConversionFunc(inputType, targetType)(getExpressionContext(), inputValue);
}
} // namespace mongo
|