promql_parser/parser/
ast.rs

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
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::label::{Labels, Matchers, METRIC_NAME};
use crate::parser::token::{
    self, token_display, T_BOTTOMK, T_COUNT_VALUES, T_END, T_QUANTILE, T_START, T_TOPK,
};
use crate::parser::token::{Token, TokenId, TokenType};
use crate::parser::value::ValueType;
use crate::parser::{indent, Function, FunctionArgs, Prettier, MAX_CHARACTERS_PER_LINE};
use crate::util::display_duration;
use chrono::{DateTime, Utc};
use std::fmt::{self, Write};
use std::ops::Neg;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

/// LabelModifier acts as
///
/// # Aggregation Modifier
///
/// - Exclude means `ignoring`
/// - Include means `on`
///
/// # Vector Match Modifier
///
/// - Exclude means `without` removes the listed labels from the result vector,
///   while all other labels are preserved in the output.
///
/// - Include means `by` does the opposite and drops labels that are not listed in the by clause,
///   even if their label values are identical between all elements of the vector.
///
/// if empty listed labels, meaning no grouping
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub enum LabelModifier {
    Include(Labels),
    Exclude(Labels),
}

impl LabelModifier {
    pub fn labels(&self) -> &Labels {
        match self {
            LabelModifier::Include(l) => l,
            LabelModifier::Exclude(l) => l,
        }
    }

    pub fn is_include(&self) -> bool {
        matches!(*self, LabelModifier::Include(_))
    }

    pub fn include(ls: Vec<&str>) -> Self {
        Self::Include(Labels::new(ls))
    }

    pub fn exclude(ls: Vec<&str>) -> Self {
        Self::Exclude(Labels::new(ls))
    }
}

/// The label list provided with the group_left or group_right modifier contains
/// additional labels from the "one"-side to be included in the result metrics.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
#[cfg_attr(feature = "ser", serde(rename_all = "kebab-case"))]
pub enum VectorMatchCardinality {
    OneToOne,
    ManyToOne(Labels),
    OneToMany(Labels),
    ManyToMany, // logical/set binary operators
}

impl VectorMatchCardinality {
    pub fn labels(&self) -> Option<&Labels> {
        match self {
            VectorMatchCardinality::ManyToOne(l) => Some(l),
            VectorMatchCardinality::OneToMany(l) => Some(l),
            VectorMatchCardinality::ManyToMany => None,
            VectorMatchCardinality::OneToOne => None,
        }
    }

    pub fn many_to_one(ls: Vec<&str>) -> Self {
        Self::ManyToOne(Labels::new(ls))
    }

    pub fn one_to_many(ls: Vec<&str>) -> Self {
        Self::OneToMany(Labels::new(ls))
    }
}

/// Binary Expr Modifier
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BinModifier {
    /// The matching behavior for the operation if both operands are Vectors.
    /// If they are not this field is None.
    pub card: VectorMatchCardinality,

    /// on/ignoring on labels.
    /// like a + b, no match modifier is needed.
    pub matching: Option<LabelModifier>,
    /// If a comparison operator, return 0/1 rather than filtering.
    pub return_bool: bool,
}

impl fmt::Display for BinModifier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = String::from(self.bool_str());

        if let Some(matching) = &self.matching {
            match matching {
                LabelModifier::Include(ls) => write!(s, "on ({ls}) ")?,
                LabelModifier::Exclude(ls) if !ls.is_empty() => write!(s, "ignoring ({ls}) ")?,
                _ => (),
            }
        }

        match &self.card {
            VectorMatchCardinality::ManyToOne(ls) => write!(s, "group_left ({ls}) ")?,
            VectorMatchCardinality::OneToMany(ls) => write!(s, "group_right ({ls}) ")?,
            _ => (),
        }

        if s.trim().is_empty() {
            write!(f, "")
        } else {
            write!(f, " {}", s.trim_end()) // there is a leading space here
        }
    }
}

impl Default for BinModifier {
    fn default() -> Self {
        Self {
            card: VectorMatchCardinality::OneToOne,
            matching: None,
            return_bool: false,
        }
    }
}

impl BinModifier {
    pub fn with_card(mut self, card: VectorMatchCardinality) -> Self {
        self.card = card;
        self
    }

    pub fn with_matching(mut self, matching: Option<LabelModifier>) -> Self {
        self.matching = matching;
        self
    }

    pub fn with_return_bool(mut self, return_bool: bool) -> Self {
        self.return_bool = return_bool;
        self
    }

    pub fn is_labels_joint(&self) -> bool {
        matches!(
            (self.card.labels(), &self.matching),
            (Some(labels), Some(matching)) if labels.is_joint(matching.labels())
        )
    }

    pub fn intersect_labels(&self) -> Option<Vec<String>> {
        if let Some(labels) = self.card.labels() {
            if let Some(matching) = &self.matching {
                return Some(labels.intersect(matching.labels()).labels);
            }
        };
        None
    }

    pub fn is_matching_on(&self) -> bool {
        matches!(&self.matching, Some(matching) if matching.is_include())
    }

    pub fn is_matching_labels_not_empty(&self) -> bool {
        matches!(&self.matching, Some(matching) if !matching.labels().is_empty())
    }

    pub fn bool_str(&self) -> &str {
        if self.return_bool {
            "bool "
        } else {
            ""
        }
    }
}

#[cfg(feature = "ser")]
pub(crate) fn serialize_bin_modifier<S>(
    this: &Option<BinModifier>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    use serde::ser::SerializeMap;
    use serde_json::json;

    let mut map = serializer.serialize_map(Some(2))?;

    map.serialize_entry(
        "bool",
        &this.as_ref().map(|t| t.return_bool).unwrap_or(false),
    )?;
    if let Some(t) = this {
        if let Some(labels) = &t.matching {
            map.serialize_key("matching")?;

            match labels {
                LabelModifier::Include(labels) => {
                    let value = json!({
                        "card": t.card,
                        "include": [],
                        "labels": labels,
                        "on": true,
                    });
                    map.serialize_value(&value)?;
                }
                LabelModifier::Exclude(labels) => {
                    let value = json!({
                        "card": t.card,
                        "include": [],
                        "labels": labels,
                        "on": false,
                    });
                    map.serialize_value(&value)?;
                }
            }
        } else {
            let value = json!({
                "card": t.card,
                "include": [],
                "labels": [],
                "on": false,
            });
            map.serialize_entry("matching", &value)?;
        }
    } else {
        map.serialize_entry("matching", &None::<bool>)?;
    }

    map.end()
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Offset {
    Pos(Duration),
    Neg(Duration),
}

impl Offset {
    #[cfg(feature = "ser")]
    pub(crate) fn as_millis(&self) -> i128 {
        match self {
            Self::Pos(dur) => dur.as_millis() as i128,
            Self::Neg(dur) => -(dur.as_millis() as i128),
        }
    }

    #[cfg(feature = "ser")]
    pub(crate) fn serialize_offset<S>(
        offset: &Option<Self>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let value = offset.as_ref().map(|o| o.as_millis()).unwrap_or(0);
        serializer.serialize_i128(value)
    }
}

impl fmt::Display for Offset {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Offset::Pos(dur) => write!(f, "{}", display_duration(dur)),
            Offset::Neg(dur) => write!(f, "-{}", display_duration(dur)),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AtModifier {
    Start,
    End,
    /// at can be earlier than UNIX_EPOCH
    At(SystemTime),
}

impl fmt::Display for AtModifier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AtModifier::Start => write!(f, "@ {}()", token_display(T_START)),
            AtModifier::End => write!(f, "@ {}()", token_display(T_END)),
            AtModifier::At(time) => {
                let d = time
                    .duration_since(SystemTime::UNIX_EPOCH)
                    .unwrap_or(Duration::ZERO); // This should not happen
                write!(f, "@ {:.3}", d.as_secs() as f64)
            }
        }
    }
}

#[cfg(feature = "ser")]
impl serde::Serialize for AtModifier {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(Some(2))?;
        match self {
            AtModifier::Start => {
                map.serialize_entry("startOrEnd", &Some("start"))?;
                map.serialize_entry("timestamp", &None::<u128>)?;
            }
            AtModifier::End => {
                map.serialize_entry("startOrEnd", &Some("end"))?;
                map.serialize_entry("timestamp", &None::<u128>)?;
            }
            AtModifier::At(time) => {
                map.serialize_entry("startOrEnd", &None::<&str>)?;
                map.serialize_entry(
                    "timestamp",
                    &time
                        .duration_since(SystemTime::UNIX_EPOCH)
                        .unwrap_or(Duration::ZERO)
                        .as_millis(),
                )?;
            }
        }

        map.end()
    }
}

impl TryFrom<TokenId> for AtModifier {
    type Error = String;

    fn try_from(id: TokenId) -> Result<Self, Self::Error> {
        match id {
            T_START => Ok(AtModifier::Start),
            T_END => Ok(AtModifier::End),
            _ => Err(format!(
                "invalid @ modifier preprocessor '{}', START or END is valid.",
                token::token_display(id)
            )),
        }
    }
}

impl TryFrom<Token> for AtModifier {
    type Error = String;

    fn try_from(token: Token) -> Result<Self, Self::Error> {
        AtModifier::try_from(token.id())
    }
}

impl TryFrom<NumberLiteral> for AtModifier {
    type Error = String;

    fn try_from(num: NumberLiteral) -> Result<Self, Self::Error> {
        AtModifier::try_from(num.val)
    }
}

impl TryFrom<Expr> for AtModifier {
    type Error = String;

    fn try_from(ex: Expr) -> Result<Self, Self::Error> {
        match ex {
            Expr::NumberLiteral(nl) => AtModifier::try_from(nl),
            _ => Err("invalid float value after @ modifier".into()),
        }
    }
}

impl TryFrom<f64> for AtModifier {
    type Error = String;

    fn try_from(secs: f64) -> Result<Self, Self::Error> {
        let err_info = format!("timestamp out of bounds for @ modifier: {secs}");

        if secs.is_nan() || secs.is_infinite() || secs >= f64::MAX || secs <= f64::MIN {
            return Err(err_info);
        }
        let milli = (secs * 1000f64).round().abs() as u64;

        let duration = Duration::from_millis(milli);
        let mut st = Some(SystemTime::UNIX_EPOCH);
        if secs.is_sign_positive() {
            st = SystemTime::UNIX_EPOCH.checked_add(duration);
        }
        if secs.is_sign_negative() {
            st = SystemTime::UNIX_EPOCH.checked_sub(duration);
        }

        st.map(Self::At).ok_or(err_info)
    }
}

/// EvalStmt holds an expression and information on the range it should
/// be evaluated on.
#[allow(rustdoc::broken_intra_doc_links)]
#[derive(Debug, Clone)]
pub struct EvalStmt {
    /// Expression to be evaluated.
    pub expr: Expr,

    /// The time boundaries for the evaluation. If start equals end an instant
    /// is evaluated.
    pub start: SystemTime,
    pub end: SystemTime,
    /// Time between two evaluated instants for the range [start:end].
    pub interval: Duration,
    /// Lookback delta to use for this evaluation.
    pub lookback_delta: Duration,
}

impl fmt::Display for EvalStmt {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "[{}] @ [{}, {}, {}, {}]",
            self.expr,
            DateTime::<Utc>::from(self.start).to_rfc3339(),
            DateTime::<Utc>::from(self.end).to_rfc3339(),
            display_duration(&self.interval),
            display_duration(&self.lookback_delta)
        )
    }
}

/// Grammar:
/// ``` norust
/// <aggr-op> [without|by (<label list>)] ([parameter,] <vector expression>)
/// <aggr-op>([parameter,] <vector expression>) [without|by (<label list>)]
/// ```
///
/// parameter is only required for `count_values`, `quantile`, `topk` and `bottomk`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub struct AggregateExpr {
    /// The used aggregation operation.
    pub op: TokenType,
    /// The Vector expression over which is aggregated.
    pub expr: Box<Expr>,
    /// Parameter used by some aggregators.
    pub param: Option<Box<Expr>>,
    /// modifier is optional for some aggregation operators, like sum.
    pub modifier: Option<LabelModifier>,
}

impl AggregateExpr {
    fn get_op_string(&self) -> String {
        let mut s = self.op.to_string();

        if let Some(modifier) = &self.modifier {
            match modifier {
                LabelModifier::Exclude(ls) => write!(s, " without ({ls}) ").unwrap(),
                LabelModifier::Include(ls) if !ls.is_empty() => write!(s, " by ({ls}) ").unwrap(),
                _ => (),
            }
        }
        s
    }
}

impl fmt::Display for AggregateExpr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.get_op_string())?;

        write!(f, "(")?;
        if let Some(param) = &self.param {
            write!(f, "{param}, ")?;
        }
        write!(f, "{})", self.expr)?;

        Ok(())
    }
}

impl Prettier for AggregateExpr {
    fn format(&self, level: usize, max: usize) -> String {
        let mut s = format!("{}{}(\n", indent(level), self.get_op_string());
        if let Some(param) = &self.param {
            writeln!(s, "{},", param.pretty(level + 1, max)).unwrap();
        }
        writeln!(s, "{}", self.expr.pretty(level + 1, max)).unwrap();
        write!(s, "{})", indent(level)).unwrap();
        s
    }
}

/// UnaryExpr will negate the expr
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnaryExpr {
    pub expr: Box<Expr>,
}

impl fmt::Display for UnaryExpr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "-{}", self.expr)
    }
}

impl Prettier for UnaryExpr {
    fn pretty(&self, level: usize, max: usize) -> String {
        format!(
            "{}-{}",
            indent(level),
            self.expr.pretty(level, max).trim_start()
        )
    }
}

#[cfg(feature = "ser")]
impl serde::Serialize for UnaryExpr {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(Some(2))?;
        map.serialize_entry("op", "-")?;
        map.serialize_entry("expr", &self.expr)?;

        map.end()
    }
}

/// Grammar:
/// ``` norust
/// <vector expr> <bin-op> ignoring(<label list>) group_left(<label list>) <vector expr>
/// <vector expr> <bin-op> ignoring(<label list>) group_right(<label list>) <vector expr>
/// <vector expr> <bin-op> on(<label list>) group_left(<label list>) <vector expr>
/// <vector expr> <bin-op> on(<label list>) group_right(<label list>) <vector expr>
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub struct BinaryExpr {
    /// The operation of the expression.
    pub op: TokenType,
    /// The operands on the left sides of the operator.
    pub lhs: Box<Expr>,
    /// The operands on the right sides of the operator.
    pub rhs: Box<Expr>,
    #[cfg_attr(feature = "ser", serde(flatten))]
    #[cfg_attr(feature = "ser", serde(serialize_with = "serialize_bin_modifier"))]
    pub modifier: Option<BinModifier>,
}

impl BinaryExpr {
    pub fn is_matching_on(&self) -> bool {
        matches!(&self.modifier, Some(modifier) if modifier.is_matching_on())
    }

    pub fn is_matching_labels_not_empty(&self) -> bool {
        matches!(&self.modifier, Some(modifier) if modifier.is_matching_labels_not_empty())
    }

    pub fn return_bool(&self) -> bool {
        matches!(&self.modifier, Some(modifier) if modifier.return_bool)
    }

    /// check if labels of card and matching are joint
    pub fn is_labels_joint(&self) -> bool {
        matches!(&self.modifier, Some(modifier) if modifier.is_labels_joint())
    }

    /// intersect labels of card and matching
    pub fn intersect_labels(&self) -> Option<Vec<String>> {
        self.modifier
            .as_ref()
            .and_then(|modifier| modifier.intersect_labels())
    }

    fn get_op_matching_string(&self) -> String {
        match &self.modifier {
            Some(modifier) => format!("{}{modifier}", self.op),
            None => self.op.to_string(),
        }
    }
}

impl fmt::Display for BinaryExpr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{} {} {}",
            self.lhs,
            self.get_op_matching_string(),
            self.rhs
        )
    }
}

impl Prettier for BinaryExpr {
    fn format(&self, level: usize, max: usize) -> String {
        format!(
            "{}\n{}{}\n{}",
            self.lhs.pretty(level + 1, max),
            indent(level),
            self.get_op_matching_string(),
            self.rhs.pretty(level + 1, max)
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub struct ParenExpr {
    pub expr: Box<Expr>,
}

impl fmt::Display for ParenExpr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({})", self.expr)
    }
}

impl Prettier for ParenExpr {
    fn format(&self, level: usize, max: usize) -> String {
        format!(
            "{}(\n{}\n{})",
            indent(level),
            self.expr.pretty(level + 1, max),
            indent(level)
        )
    }
}

/// Grammar:
/// ```norust
/// <instant_query> '[' <range> ':' [<resolution>] ']' [ @ <float_literal> ] [ offset <duration> ]
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub struct SubqueryExpr {
    pub expr: Box<Expr>,
    #[cfg_attr(feature = "ser", serde(serialize_with = "Offset::serialize_offset"))]
    pub offset: Option<Offset>,
    #[cfg_attr(feature = "ser", serde(flatten))]
    pub at: Option<AtModifier>,
    #[cfg_attr(
        feature = "ser",
        serde(serialize_with = "crate::util::duration::serialize_duration")
    )]
    pub range: Duration,
    /// Default is the global evaluation interval.
    #[cfg_attr(
        feature = "ser",
        serde(serialize_with = "crate::util::duration::serialize_duration_opt")
    )]
    pub step: Option<Duration>,
}

impl SubqueryExpr {
    fn get_time_suffix_string(&self) -> String {
        let step = match &self.step {
            Some(step) => display_duration(step),
            None => String::from(""),
        };
        let range = display_duration(&self.range);

        let mut s = format!("[{range}:{step}]");

        if let Some(at) = &self.at {
            write!(s, " {at}").unwrap();
        }

        if let Some(offset) = &self.offset {
            write!(s, " offset {offset}").unwrap();
        }
        s
    }
}

impl fmt::Display for SubqueryExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.expr, self.get_time_suffix_string())
    }
}

impl Prettier for SubqueryExpr {
    fn pretty(&self, level: usize, max: usize) -> String {
        format!(
            "{}{}",
            self.expr.pretty(level, max),
            self.get_time_suffix_string()
        )
    }
}

#[derive(Debug, Clone)]
pub struct NumberLiteral {
    pub val: f64,
}

impl NumberLiteral {
    pub fn new(val: f64) -> Self {
        Self { val }
    }
}

impl PartialEq for NumberLiteral {
    fn eq(&self, other: &Self) -> bool {
        self.val == other.val || self.val.is_nan() && other.val.is_nan()
    }
}

impl Eq for NumberLiteral {}

impl Neg for NumberLiteral {
    type Output = Self;

    fn neg(self) -> Self::Output {
        NumberLiteral { val: -self.val }
    }
}

impl fmt::Display for NumberLiteral {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.val == f64::INFINITY {
            write!(f, "Inf")
        } else if self.val == f64::NEG_INFINITY {
            write!(f, "-Inf")
        } else if f64::is_nan(self.val) {
            write!(f, "NaN")
        } else {
            write!(f, "{}", self.val)
        }
    }
}

#[cfg(feature = "ser")]
impl serde::Serialize for NumberLiteral {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(Some(1))?;
        map.serialize_entry("val", &self.to_string())?;

        map.end()
    }
}

impl Prettier for NumberLiteral {
    fn needs_split(&self, _max: usize) -> bool {
        false
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub struct StringLiteral {
    pub val: String,
}

impl fmt::Display for StringLiteral {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "\"{}\"", self.val)
    }
}

impl Prettier for StringLiteral {
    fn needs_split(&self, _max: usize) -> bool {
        false
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub struct VectorSelector {
    pub name: Option<String>,
    #[cfg_attr(feature = "ser", serde(flatten))]
    pub matchers: Matchers,
    #[cfg_attr(feature = "ser", serde(serialize_with = "Offset::serialize_offset"))]
    pub offset: Option<Offset>,
    #[cfg_attr(feature = "ser", serde(flatten))]
    pub at: Option<AtModifier>,
}

impl VectorSelector {
    pub fn new(name: Option<String>, matchers: Matchers) -> Self {
        VectorSelector {
            name,
            matchers,
            offset: None,
            at: None,
        }
    }
}

impl Default for VectorSelector {
    fn default() -> Self {
        Self {
            name: None,
            matchers: Matchers::empty(),
            offset: None,
            at: None,
        }
    }
}

impl From<String> for VectorSelector {
    fn from(name: String) -> Self {
        VectorSelector {
            name: Some(name),
            offset: None,
            at: None,
            matchers: Matchers::empty(),
        }
    }
}

/// directly create an instant vector with only METRIC_NAME matcher.
///
/// # Examples
///
/// Basic usage:
///
/// ``` rust
/// use promql_parser::label::Matchers;
/// use promql_parser::parser::VectorSelector;
///
/// let vs = VectorSelector {
///     name: Some(String::from("foo")),
///     offset: None,
///     at: None,
///     matchers: Matchers::empty(),
/// };
///
/// assert_eq!(VectorSelector::from("foo"), vs);
/// ```
impl From<&str> for VectorSelector {
    fn from(name: &str) -> Self {
        VectorSelector::from(name.to_string())
    }
}

impl Neg for VectorSelector {
    type Output = UnaryExpr;

    fn neg(self) -> Self::Output {
        let ex = Expr::VectorSelector(self);
        UnaryExpr { expr: Box::new(ex) }
    }
}

impl fmt::Display for VectorSelector {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(name) = &self.name {
            write!(f, "{name}")?;
        }
        let matchers = &self.matchers.to_string();
        if !matchers.is_empty() {
            write!(f, "{{{matchers}}}")?;
        }
        if let Some(at) = &self.at {
            write!(f, " {at}")?;
        }
        if let Some(offset) = &self.offset {
            write!(f, " offset {offset}")?;
        }
        Ok(())
    }
}

impl Prettier for VectorSelector {
    fn needs_split(&self, _max: usize) -> bool {
        false
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub struct MatrixSelector {
    #[cfg_attr(feature = "ser", serde(flatten))]
    pub vs: VectorSelector,
    #[cfg_attr(
        feature = "ser",
        serde(serialize_with = "crate::util::duration::serialize_duration")
    )]
    pub range: Duration,
}

impl fmt::Display for MatrixSelector {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(name) = &self.vs.name {
            write!(f, "{name}")?;
        }

        let matchers = &self.vs.matchers.to_string();
        if !matchers.is_empty() {
            write!(f, "{{{matchers}}}")?;
        }

        write!(f, "[{}]", display_duration(&self.range))?;

        if let Some(at) = &self.vs.at {
            write!(f, " {at}")?;
        }

        if let Some(offset) = &self.vs.offset {
            write!(f, " offset {offset}")?;
        }

        Ok(())
    }
}

impl Prettier for MatrixSelector {
    fn needs_split(&self, _max: usize) -> bool {
        false
    }
}

/// Call represents Prometheus Function.
/// Some functions have special cases:
///
/// ## exp
///
/// exp(v instant-vector) calculates the exponential function for all elements in v.
/// Special cases are:
///
/// ```promql
/// Exp(+Inf) = +Inf
/// Exp(NaN) = NaN
/// ```
///
/// ## ln
///
/// ln(v instant-vector) calculates the natural logarithm for all elements in v.
/// Special cases are:
///
/// ```promql
/// ln(+Inf) = +Inf
/// ln(0) = -Inf
/// ln(x < 0) = NaN
/// ln(NaN) = NaN
/// ```
///
/// TODO: support more special cases of function call
///
///  - acos()
///  - acosh()
///  - asin()
///  - asinh()
///  - atan()
///  - atanh()
///  - cos()
///  - cosh()
///  - sin()
///  - sinh()
///  - tan()
///  - tanh()
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub struct Call {
    pub func: Function,
    #[cfg_attr(feature = "ser", serde(flatten))]
    pub args: FunctionArgs,
}

impl fmt::Display for Call {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}({})", self.func.name, self.args)
    }
}

impl Prettier for Call {
    fn format(&self, level: usize, max: usize) -> String {
        format!(
            "{}{}(\n{}\n{})",
            indent(level),
            self.func.name,
            self.args.pretty(level + 1, max),
            indent(level)
        )
    }
}

/// Node for extending the AST. [Extension] won't be generate by this parser itself.
#[derive(Debug, Clone)]
pub struct Extension {
    pub expr: Arc<dyn ExtensionExpr>,
}

/// The interface for extending the AST with custom expression node.
pub trait ExtensionExpr: std::fmt::Debug + Send + Sync {
    fn as_any(&self) -> &dyn std::any::Any;

    fn name(&self) -> &str;

    fn value_type(&self) -> ValueType;

    fn children(&self) -> &[Expr];
}

impl PartialEq for Extension {
    fn eq(&self, other: &Self) -> bool {
        format!("{:?}", self) == format!("{:?}", other)
    }
}

impl Eq for Extension {}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
#[cfg_attr(feature = "ser", serde(tag = "type", rename_all = "camelCase"))]
pub enum Expr {
    /// Aggregate represents an aggregation operation on a Vector.
    #[cfg_attr(feature = "ser", serde(rename = "aggregateExpr"))]
    Aggregate(AggregateExpr),

    /// Unary represents a unary operation on another expression.
    /// Currently unary operations are only supported for Scalars.
    #[cfg_attr(feature = "ser", serde(rename = "unaryExpr"))]
    Unary(UnaryExpr),

    /// Binary represents a binary expression between two child expressions.
    #[cfg_attr(feature = "ser", serde(rename = "binaryExpr"))]
    Binary(BinaryExpr),

    /// Paren wraps an expression so it cannot be disassembled as a consequence
    /// of operator precedence.
    #[cfg_attr(feature = "ser", serde(rename = "parenExpr"))]
    Paren(ParenExpr),

    /// SubqueryExpr represents a subquery.
    Subquery(SubqueryExpr),

    /// NumberLiteral represents a number.
    NumberLiteral(NumberLiteral),

    /// StringLiteral represents a string.
    StringLiteral(StringLiteral),

    /// VectorSelector represents a Vector selection.
    VectorSelector(VectorSelector),

    /// MatrixSelector represents a Matrix selection.
    MatrixSelector(MatrixSelector),

    /// Call represents a function call.
    Call(Call),

    /// Extension represents an extension expression. It is for user to attach additional
    /// information to the AST. This parser won't generate Extension node.
    #[cfg_attr(feature = "ser", serde(skip))]
    Extension(Extension),
}

impl Expr {
    pub(crate) fn new_vector_selector(
        name: Option<String>,
        matchers: Matchers,
    ) -> Result<Self, String> {
        let vs = VectorSelector::new(name, matchers);
        Ok(Self::VectorSelector(vs))
    }

    pub(crate) fn new_unary_expr(expr: Expr) -> Result<Self, String> {
        match expr {
            Expr::StringLiteral(_) => Err("unary expression only allowed on expressions of type scalar or vector, got: string".into()),
            Expr::MatrixSelector(_) => Err("unary expression only allowed on expressions of type scalar or vector, got: matrix".into()),
            _ => Ok(-expr),
        }
    }

    pub(crate) fn new_subquery_expr(
        expr: Expr,
        range: Duration,
        step: Option<Duration>,
    ) -> Result<Self, String> {
        let se = Expr::Subquery(SubqueryExpr {
            expr: Box::new(expr),
            offset: None,
            at: None,
            range,
            step,
        });
        Ok(se)
    }

    pub(crate) fn new_paren_expr(expr: Expr) -> Result<Self, String> {
        let ex = Expr::Paren(ParenExpr {
            expr: Box::new(expr),
        });
        Ok(ex)
    }

    /// NOTE: @ and offset is not set here.
    pub(crate) fn new_matrix_selector(expr: Expr, range: Duration) -> Result<Self, String> {
        match expr {
            Expr::VectorSelector(VectorSelector {
                offset: Some(_), ..
            }) => Err("no offset modifiers allowed before range".into()),
            Expr::VectorSelector(VectorSelector { at: Some(_), .. }) => {
                Err("no @ modifiers allowed before range".into())
            }
            Expr::VectorSelector(vs) => {
                let ms = Expr::MatrixSelector(MatrixSelector { vs, range });
                Ok(ms)
            }
            _ => Err("ranges only allowed for vector selectors".into()),
        }
    }

    pub(crate) fn at_expr(self, at: AtModifier) -> Result<Self, String> {
        let already_set_err = Err("@ <timestamp> may not be set multiple times".into());
        match self {
            Expr::VectorSelector(mut vs) => match vs.at {
                None => {
                    vs.at = Some(at);
                    Ok(Expr::VectorSelector(vs))
                }
                Some(_) => already_set_err,
            },
            Expr::MatrixSelector(mut ms) => match ms.vs.at {
                None => {
                    ms.vs.at = Some(at);
                    Ok(Expr::MatrixSelector(ms))
                }
                Some(_) => already_set_err,
            },
            Expr::Subquery(mut s) => match s.at {
                None => {
                    s.at = Some(at);
                    Ok(Expr::Subquery(s))
                }
                Some(_) => already_set_err,
            },
            _ => {
                Err("@ modifier must be preceded by an vector selector or matrix selector or a subquery".into())
            }
        }
    }

    /// set offset field for specified Expr, but CAN ONLY be set once.
    pub(crate) fn offset_expr(self, offset: Offset) -> Result<Self, String> {
        let already_set_err = Err("offset may not be set multiple times".into());
        match self {
            Expr::VectorSelector(mut vs) => match vs.offset {
                None => {
                    vs.offset = Some(offset);
                    Ok(Expr::VectorSelector(vs))
                }
                Some(_) => already_set_err,
            },
            Expr::MatrixSelector(mut ms) => match ms.vs.offset {
                None => {
                    ms.vs.offset = Some(offset);
                    Ok(Expr::MatrixSelector(ms))
                }
                Some(_) => already_set_err,
            },
            Expr::Subquery(mut s) => match s.offset {
                None => {
                    s.offset = Some(offset);
                    Ok(Expr::Subquery(s))
                }
                Some(_) => already_set_err,
            },
            _ => {
                Err("offset modifier must be preceded by an vector selector or matrix selector or a subquery".into())
            }
        }
    }

    pub(crate) fn new_call(func: Function, args: FunctionArgs) -> Result<Expr, String> {
        Ok(Expr::Call(Call { func, args }))
    }

    pub(crate) fn new_binary_expr(
        lhs: Expr,
        op: TokenId,
        modifier: Option<BinModifier>,
        rhs: Expr,
    ) -> Result<Expr, String> {
        let ex = BinaryExpr {
            op: TokenType::new(op),
            lhs: Box::new(lhs),
            rhs: Box::new(rhs),
            modifier,
        };
        Ok(Expr::Binary(ex))
    }

    pub(crate) fn new_aggregate_expr(
        op: TokenId,
        modifier: Option<LabelModifier>,
        args: FunctionArgs,
    ) -> Result<Expr, String> {
        let op = TokenType::new(op);
        if args.is_empty() {
            return Err(format!(
                "no arguments for aggregate expression '{op}' provided"
            ));
        }
        let mut desired_args_count = 1;
        let mut param = None;
        if op.is_aggregator_with_param() {
            desired_args_count = 2;
            param = args.first();
        }
        if args.len() != desired_args_count {
            return Err(format!(
                "wrong number of arguments for aggregate expression provided, expected {}, got {}",
                desired_args_count,
                args.len()
            ));
        }

        match args.last() {
            Some(expr) => Ok(Expr::Aggregate(AggregateExpr {
                op,
                expr,
                param,
                modifier,
            })),
            None => Err(
                "aggregate operation needs a single instant vector parameter, but found none"
                    .into(),
            ),
        }
    }

    pub fn value_type(&self) -> ValueType {
        match self {
            Expr::Aggregate(_) => ValueType::Vector,
            Expr::Unary(ex) => ex.expr.value_type(),
            Expr::Binary(ex) => {
                if ex.lhs.value_type() == ValueType::Scalar
                    && ex.rhs.value_type() == ValueType::Scalar
                {
                    ValueType::Scalar
                } else {
                    ValueType::Vector
                }
            }
            Expr::Paren(ex) => ex.expr.value_type(),
            Expr::Subquery(_) => ValueType::Matrix,
            Expr::NumberLiteral(_) => ValueType::Scalar,
            Expr::StringLiteral(_) => ValueType::String,
            Expr::VectorSelector(_) => ValueType::Vector,
            Expr::MatrixSelector(_) => ValueType::Matrix,
            Expr::Call(ex) => ex.func.return_type,
            Expr::Extension(ex) => ex.expr.value_type(),
        }
    }

    /// only Some if expr is [Expr::NumberLiteral]
    pub(crate) fn scalar_value(&self) -> Option<f64> {
        match self {
            Expr::NumberLiteral(nl) => Some(nl.val),
            _ => None,
        }
    }

    pub fn prettify(&self) -> String {
        self.pretty(0, MAX_CHARACTERS_PER_LINE)
    }
}

impl From<String> for Expr {
    fn from(val: String) -> Self {
        Expr::StringLiteral(StringLiteral { val })
    }
}

impl From<&str> for Expr {
    fn from(s: &str) -> Self {
        Expr::StringLiteral(StringLiteral { val: s.into() })
    }
}

impl From<f64> for Expr {
    fn from(val: f64) -> Self {
        Expr::NumberLiteral(NumberLiteral { val })
    }
}

/// directly create an Expr::VectorSelector from instant vector
///
/// # Examples
///
/// Basic usage:
///
/// ``` rust
/// use promql_parser::label::Matchers;
/// use promql_parser::parser::{Expr, VectorSelector};
///
/// let name = String::from("foo");
/// let vs = VectorSelector::new(Some(name), Matchers::empty());
///
/// assert_eq!(Expr::VectorSelector(vs), Expr::from(VectorSelector::from("foo")));
/// ```
impl From<VectorSelector> for Expr {
    fn from(vs: VectorSelector) -> Self {
        Expr::VectorSelector(vs)
    }
}

impl Neg for Expr {
    type Output = Self;

    fn neg(self) -> Self::Output {
        match self {
            Expr::NumberLiteral(nl) => Expr::NumberLiteral(-nl),
            _ => Expr::Unary(UnaryExpr {
                expr: Box::new(self),
            }),
        }
    }
}

impl fmt::Display for Expr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Expr::Aggregate(ex) => write!(f, "{ex}"),
            Expr::Unary(ex) => write!(f, "{ex}"),
            Expr::Binary(ex) => write!(f, "{ex}"),
            Expr::Paren(ex) => write!(f, "{ex}"),
            Expr::Subquery(ex) => write!(f, "{ex}"),
            Expr::NumberLiteral(ex) => write!(f, "{ex}"),
            Expr::StringLiteral(ex) => write!(f, "{ex}"),
            Expr::VectorSelector(ex) => write!(f, "{ex}"),
            Expr::MatrixSelector(ex) => write!(f, "{ex}"),
            Expr::Call(ex) => write!(f, "{ex}"),
            Expr::Extension(ext) => write!(f, "{ext:?}"),
        }
    }
}

impl Prettier for Expr {
    fn pretty(&self, level: usize, max: usize) -> String {
        match self {
            Expr::Aggregate(ex) => ex.pretty(level, max),
            Expr::Unary(ex) => ex.pretty(level, max),
            Expr::Binary(ex) => ex.pretty(level, max),
            Expr::Paren(ex) => ex.pretty(level, max),
            Expr::Subquery(ex) => ex.pretty(level, max),
            Expr::NumberLiteral(ex) => ex.pretty(level, max),
            Expr::StringLiteral(ex) => ex.pretty(level, max),
            Expr::VectorSelector(ex) => ex.pretty(level, max),
            Expr::MatrixSelector(ex) => ex.pretty(level, max),
            Expr::Call(ex) => ex.pretty(level, max),
            Expr::Extension(ext) => format!("{ext:?}"),
        }
    }
}

/// check_ast checks the validity of the provided AST. This includes type checking.
/// Recursively check correct typing for child nodes and raise errors in case of bad typing.
pub(crate) fn check_ast(expr: Expr) -> Result<Expr, String> {
    match expr {
        Expr::Binary(ex) => check_ast_for_binary_expr(ex),
        Expr::Aggregate(ex) => check_ast_for_aggregate_expr(ex),
        Expr::Call(ex) => check_ast_for_call(ex),
        Expr::Unary(ex) => check_ast_for_unary(ex),
        Expr::Subquery(ex) => check_ast_for_subquery(ex),
        Expr::VectorSelector(ex) => check_ast_for_vector_selector(ex),
        Expr::Paren(_) => Ok(expr),
        Expr::NumberLiteral(_) => Ok(expr),
        Expr::StringLiteral(_) => Ok(expr),
        Expr::MatrixSelector(_) => Ok(expr),
        Expr::Extension(_) => Ok(expr),
    }
}

fn expect_type(
    expected: ValueType,
    actual: Option<ValueType>,
    context: &str,
) -> Result<bool, String> {
    match actual {
        Some(actual) => {
            if actual == expected {
                Ok(true)
            } else {
                Err(format!(
                    "expected type {expected} in {context}, got {actual}"
                ))
            }
        }
        None => Err(format!("expected type {expected} in {context}, got None")),
    }
}

/// the original logic is redundant in prometheus, and the following coding blocks
/// have been optimized for readability, but all logic SHOULD be covered.
fn check_ast_for_binary_expr(mut ex: BinaryExpr) -> Result<Expr, String> {
    if !ex.op.is_operator() {
        return Err(format!(
            "binary expression does not support operator '{}'",
            ex.op
        ));
    }

    if ex.return_bool() && !ex.op.is_comparison_operator() {
        return Err("bool modifier can only be used on comparison operators".into());
    }

    if ex.op.is_comparison_operator()
        && ex.lhs.value_type() == ValueType::Scalar
        && ex.rhs.value_type() == ValueType::Scalar
        && !ex.return_bool()
    {
        return Err("comparisons between scalars must use BOOL modifier".into());
    }

    // For `on` matching, a label can only appear in one of the lists.
    // Every time series of the result vector must be uniquely identifiable.
    if ex.is_matching_on() && ex.is_labels_joint() {
        if let Some(labels) = ex.intersect_labels() {
            if let Some(label) = labels.first() {
                return Err(format!(
                    "label '{label}' must not occur in ON and GROUP clause at once"
                ));
            }
        };
    }

    if ex.op.is_set_operator() {
        if ex.lhs.value_type() == ValueType::Scalar || ex.rhs.value_type() == ValueType::Scalar {
            return Err(format!(
                "set operator '{}' not allowed in binary scalar expression",
                ex.op
            ));
        }

        if ex.lhs.value_type() == ValueType::Vector && ex.rhs.value_type() == ValueType::Vector {
            if let Some(ref modifier) = ex.modifier {
                if matches!(modifier.card, VectorMatchCardinality::OneToMany(_))
                    || matches!(modifier.card, VectorMatchCardinality::ManyToOne(_))
                {
                    return Err(format!("no grouping allowed for '{}' operation", ex.op));
                }
            };
        }

        match &mut ex.modifier {
            Some(modifier) => {
                if modifier.card == VectorMatchCardinality::OneToOne {
                    modifier.card = VectorMatchCardinality::ManyToMany;
                }
            }
            None => {
                ex.modifier =
                    Some(BinModifier::default().with_card(VectorMatchCardinality::ManyToMany));
            }
        }
    }

    if ex.lhs.value_type() != ValueType::Scalar && ex.lhs.value_type() != ValueType::Vector {
        return Err("binary expression must contain only scalar and instant vector types".into());
    }
    if ex.rhs.value_type() != ValueType::Scalar && ex.rhs.value_type() != ValueType::Vector {
        return Err("binary expression must contain only scalar and instant vector types".into());
    }

    if (ex.lhs.value_type() != ValueType::Vector || ex.rhs.value_type() != ValueType::Vector)
        && ex.is_matching_labels_not_empty()
    {
        return Err("vector matching only allowed between vectors".into());
    }

    Ok(Expr::Binary(ex))
}

fn check_ast_for_aggregate_expr(ex: AggregateExpr) -> Result<Expr, String> {
    if !ex.op.is_aggregator() {
        return Err(format!(
            "aggregation operator expected in aggregation expression but got '{}'",
            ex.op
        ));
    }

    expect_type(
        ValueType::Vector,
        Some(ex.expr.value_type()),
        "aggregation expression",
    )?;

    if matches!(ex.op.id(), T_TOPK | T_BOTTOMK | T_QUANTILE) {
        expect_type(
            ValueType::Scalar,
            ex.param.as_ref().map(|ex| ex.value_type()),
            "aggregation expression",
        )?;
    }

    if ex.op.id() == T_COUNT_VALUES {
        expect_type(
            ValueType::String,
            ex.param.as_ref().map(|ex| ex.value_type()),
            "aggregation expression",
        )?;
    }

    Ok(Expr::Aggregate(ex))
}

fn check_ast_for_call(ex: Call) -> Result<Expr, String> {
    let expected_args_len = ex.func.arg_types.len();
    let name = ex.func.name;
    let actual_args_len = ex.args.len();

    if ex.func.variadic {
        let expected_args_len_without_default = expected_args_len - 1;
        if expected_args_len_without_default > actual_args_len {
            return Err(format!(
                "expected at least {expected_args_len_without_default} argument(s) in call to '{name}', got {actual_args_len}"
            ));
        }

        // `label_join` do not have a maximum arguments threshold.
        // this hard code SHOULD be careful if new functions are supported by Prometheus.
        if actual_args_len > expected_args_len && name.ne("label_join") {
            return Err(format!(
                "expected at most {expected_args_len} argument(s) in call to '{name}', got {actual_args_len}"
            ));
        }
    }

    if !ex.func.variadic && expected_args_len != actual_args_len {
        return Err(format!(
            "expected {expected_args_len} argument(s) in call to '{name}', got {actual_args_len}"
        ));
    }

    // special cases from https://prometheus.io/docs/prometheus/latest/querying/functions
    if name.eq("exp") {
        if let Some(val) = ex.args.first().and_then(|ex| ex.scalar_value()) {
            if val.is_nan() || val.is_infinite() {
                return Ok(Expr::Call(ex));
            }
        }
    } else if name.eq("ln") || name.eq("log2") || name.eq("log10") {
        if let Some(val) = ex.args.first().and_then(|ex| ex.scalar_value()) {
            if val.is_nan() || val.is_infinite() || val <= 0.0 {
                return Ok(Expr::Call(ex));
            }
        }
    }

    for (mut idx, actual_arg) in ex.args.args.iter().enumerate() {
        // this only happens when function args are variadic
        if idx >= ex.func.arg_types.len() {
            idx = ex.func.arg_types.len() - 1;
        }

        expect_type(
            ex.func.arg_types[idx],
            Some(actual_arg.value_type()),
            &format!("call to function '{name}'"),
        )?;
    }

    Ok(Expr::Call(ex))
}

fn check_ast_for_unary(ex: UnaryExpr) -> Result<Expr, String> {
    let value_type = ex.expr.value_type();
    if value_type != ValueType::Scalar && value_type != ValueType::Vector {
        return Err(format!(
            "unary expression only allowed on expressions of type scalar or vector, got {value_type}"
        ));
    }

    Ok(Expr::Unary(ex))
}

fn check_ast_for_subquery(ex: SubqueryExpr) -> Result<Expr, String> {
    let value_type = ex.expr.value_type();
    if value_type != ValueType::Vector {
        return Err(format!(
            "subquery is only allowed on vector, got {value_type} instead"
        ));
    }

    Ok(Expr::Subquery(ex))
}

fn check_ast_for_vector_selector(ex: VectorSelector) -> Result<Expr, String> {
    match ex.name {
        Some(ref name) => match ex.matchers.find_matcher_value(METRIC_NAME) {
            Some(val) => Err(format!(
                "metric name must not be set twice: '{}' or '{}'",
                name, val
            )),
            None => Ok(Expr::VectorSelector(ex)),
        },
        None if ex.matchers.is_empty_matchers() => {
            // When name is None, a vector selector must contain at least one non-empty matcher
            // to prevent implicit selection of all metrics (e.g. by a typo).
            Err("vector selector must contain at least one non-empty matcher".into())
        }
        _ => Ok(Expr::VectorSelector(ex)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::label::{MatchOp, Matcher};

    #[test]
    fn test_valid_at_modifier() {
        let cases = vec![
            // tuple: (seconds, elapsed milliseconds before or after UNIX_EPOCH)
            (0.0, 0),
            (1000.3, 1000300),    // after UNIX_EPOCH
            (1000.9, 1000900),    // after UNIX_EPOCH
            (1000.9991, 1000999), // after UNIX_EPOCH
            (1000.9999, 1001000), // after UNIX_EPOCH
            (-1000.3, 1000300),   // before UNIX_EPOCH
            (-1000.9, 1000900),   // before UNIX_EPOCH
        ];

        for (secs, elapsed) in cases {
            match AtModifier::try_from(secs).unwrap() {
                AtModifier::At(st) => {
                    if secs.is_sign_positive() || secs == 0.0 {
                        assert_eq!(
                            elapsed,
                            st.duration_since(SystemTime::UNIX_EPOCH)
                                .unwrap()
                                .as_millis()
                        )
                    } else if secs.is_sign_negative() {
                        assert_eq!(
                            elapsed,
                            SystemTime::UNIX_EPOCH
                                .duration_since(st)
                                .unwrap()
                                .as_millis()
                        )
                    }
                }
                _ => panic!(),
            }
        }

        assert_eq!(
            AtModifier::try_from(Expr::from(1.0)),
            AtModifier::try_from(1.0),
        );
    }

    #[test]
    fn test_invalid_at_modifier() {
        let cases = vec![
            f64::MAX,
            f64::MIN,
            f64::NAN,
            f64::INFINITY,
            f64::NEG_INFINITY,
        ];

        for secs in cases {
            assert!(AtModifier::try_from(secs).is_err())
        }

        assert_eq!(
            AtModifier::try_from(token::T_ADD),
            Err("invalid @ modifier preprocessor '+', START or END is valid.".into())
        );

        assert_eq!(
            AtModifier::try_from(Expr::from("string literal")),
            Err("invalid float value after @ modifier".into())
        );
    }

    #[test]
    fn test_binary_labels() {
        assert_eq!(
            &Labels::new(vec!["foo", "bar"]),
            LabelModifier::Include(Labels::new(vec!["foo", "bar"])).labels()
        );

        assert_eq!(
            &Labels::new(vec!["foo", "bar"]),
            LabelModifier::Exclude(Labels::new(vec!["foo", "bar"])).labels()
        );

        assert_eq!(
            &Labels::new(vec!["foo", "bar"]),
            VectorMatchCardinality::OneToMany(Labels::new(vec!["foo", "bar"]))
                .labels()
                .unwrap()
        );

        assert_eq!(
            &Labels::new(vec!["foo", "bar"]),
            VectorMatchCardinality::ManyToOne(Labels::new(vec!["foo", "bar"]))
                .labels()
                .unwrap()
        );

        assert_eq!(VectorMatchCardinality::OneToOne.labels(), None);
        assert_eq!(VectorMatchCardinality::ManyToMany.labels(), None);
    }

    #[test]
    fn test_neg() {
        assert_eq!(
            -VectorSelector::from("foo"),
            UnaryExpr {
                expr: Box::new(Expr::from(VectorSelector::from("foo")))
            }
        )
    }

    #[test]
    fn test_scalar_value() {
        assert_eq!(Some(1.0), Expr::from(1.0).scalar_value());
        assert_eq!(None, Expr::from("1.0").scalar_value());
    }

    #[test]
    fn test_at_expr() {
        assert_eq!(
            "@ <timestamp> may not be set multiple times",
            Expr::from(VectorSelector::from("foo"))
                .at_expr(AtModifier::try_from(1.0).unwrap())
                .and_then(|ex| ex.at_expr(AtModifier::try_from(1.0).unwrap()))
                .unwrap_err()
        );

        assert_eq!(
            "@ <timestamp> may not be set multiple times",
            Expr::new_matrix_selector(
                Expr::from(VectorSelector::from("foo")),
                Duration::from_secs(1),
            )
            .and_then(|ex| ex.at_expr(AtModifier::try_from(1.0).unwrap()))
            .and_then(|ex| ex.at_expr(AtModifier::try_from(1.0).unwrap()))
            .unwrap_err()
        );

        assert_eq!(
            "@ <timestamp> may not be set multiple times",
            Expr::new_subquery_expr(
                Expr::from(VectorSelector::from("foo")),
                Duration::from_secs(1),
                None,
            )
            .and_then(|ex| ex.at_expr(AtModifier::try_from(1.0).unwrap()))
            .and_then(|ex| ex.at_expr(AtModifier::try_from(1.0).unwrap()))
            .unwrap_err()
        )
    }

    #[test]
    fn test_offset_expr() {
        assert_eq!(
            "offset may not be set multiple times",
            Expr::from(VectorSelector::from("foo"))
                .offset_expr(Offset::Pos(Duration::from_secs(1000)))
                .and_then(|ex| ex.offset_expr(Offset::Pos(Duration::from_secs(1000))))
                .unwrap_err()
        );

        assert_eq!(
            "offset may not be set multiple times",
            Expr::new_matrix_selector(
                Expr::from(VectorSelector::from("foo")),
                Duration::from_secs(1),
            )
            .and_then(|ex| ex.offset_expr(Offset::Pos(Duration::from_secs(1000))))
            .and_then(|ex| ex.offset_expr(Offset::Pos(Duration::from_secs(1000))))
            .unwrap_err()
        );

        assert_eq!(
            "offset may not be set multiple times",
            Expr::new_subquery_expr(
                Expr::from(VectorSelector::from("foo")),
                Duration::from_secs(1),
                None,
            )
            .and_then(|ex| ex.offset_expr(Offset::Pos(Duration::from_secs(1000))))
            .and_then(|ex| ex.offset_expr(Offset::Pos(Duration::from_secs(1000))))
            .unwrap_err()
        );
    }

    #[test]
    fn test_expr_to_string() {
        let mut cases = vec![
            ("1", "1"),
            ("- 1", "-1"),
            ("+ 1", "1"),
            ("Inf", "Inf"),
            ("inf", "Inf"),
            ("+Inf", "Inf"),
            ("- Inf", "-Inf"),
            (".5", "0.5"),
            ("5.", "5"),
            ("123.4567", "123.4567"),
            ("5e-3", "0.005"),
            ("5e3", "5000"),
            ("0xc", "12"),
            ("0755", "493"),
            ("08", "8"),
            ("+5.5e-3", "0.0055"),
            ("-0755", "-493"),
            ("NaN", "NaN"),
            ("NAN", "NaN"),
            ("- 1^2", "-1 ^ 2"),
            ("+1 + -2 * 1", "1 + -2 * 1"),
            ("1 + 2/(3*1)", "1 + 2 / (3 * 1)"),
            ("foo*sum", "foo * sum"),
            ("foo * on(test,blub) bar", "foo * on (test, blub) bar"),
            (
                r#"up{job="hi", instance="in"} offset 5m @ 100"#,
                r#"up{instance="in",job="hi"} @ 100.000 offset 5m"#,
            ),
            (
                r#"up{job="hi", instance="in"}"#,
                r#"up{instance="in",job="hi"}"#,
            ),
            ("sum (up) by (job,instance)", "sum by (job, instance) (up)"),
            (
                "foo / on(test,blub) group_left(bar) bar",
                "foo / on (test, blub) group_left (bar) bar",
            ),
            (
                "foo / on(test,blub) group_right(bar) bar",
                "foo / on (test, blub) group_right (bar) bar",
            ),
            (
                r#"foo{a="b",foo!="bar",test=~"test",bar!~"baz"}"#,
                r#"foo{a="b",bar!~"baz",foo!="bar",test=~"test"}"#,
            ),
            (
                r#"{__name__=~"foo.+",__name__=~".*bar"}"#,
                r#"{__name__=~".*bar",__name__=~"foo.+"}"#,
            ),
            (
                r#"test{a="b"}[5y] OFFSET 3d"#,
                r#"test{a="b"}[5y] offset 3d"#,
            ),
            (
                r#"{a="b"}[5y] OFFSET 3d"#,
                r#"{a="b"}[5y] offset 3d"#,
            ),
            (
                "sum(some_metric) without(and, by, avg, count, alert, annotations)",
                "sum without (and, by, avg, count, alert, annotations) (some_metric)",
            ),
            (
                r#"floor(some_metric{foo!="bar"})"#,
                r#"floor(some_metric{foo!="bar"})"#,
            ),
            (
                "sum(rate(http_request_duration_seconds[10m])) / count(rate(http_request_duration_seconds[10m]))",
                "sum(rate(http_request_duration_seconds[10m])) / count(rate(http_request_duration_seconds[10m]))",
            ),
            ("rate(some_metric[5m])", "rate(some_metric[5m])"),
            ("round(some_metric,5)", "round(some_metric, 5)"),
            (
                r#"absent(sum(nonexistent{job="myjob"}))"#,
                r#"absent(sum(nonexistent{job="myjob"}))"#,
            ),
            (
                "histogram_quantile(0.9,rate(http_request_duration_seconds_bucket[10m]))",
                "histogram_quantile(0.9, rate(http_request_duration_seconds_bucket[10m]))",
            ),
            (
                "histogram_quantile(0.9,sum(rate(http_request_duration_seconds_bucket[10m])) by(job,le))",
                "histogram_quantile(0.9, sum by (job, le) (rate(http_request_duration_seconds_bucket[10m])))",
            ),
            (
                r#"label_join(up{job="api-server",src1="a",src2="b",src3="c"}, "foo", ",", "src1", "src2", "src3")"#,
                r#"label_join(up{job="api-server",src1="a",src2="b",src3="c"}, "foo", ",", "src1", "src2", "src3")"#,
            ),
            (
                r#"min_over_time(rate(foo{bar="baz"}[2s])[5m:])[4m:3s] @ 100"#,
                r#"min_over_time(rate(foo{bar="baz"}[2s])[5m:])[4m:3s] @ 100.000"#,
            ),
            (
                r#"min_over_time(rate(foo{bar="baz"}[2s])[5m:])[4m:3s]"#,
                r#"min_over_time(rate(foo{bar="baz"}[2s])[5m:])[4m:3s]"#,
            ),
            (
                r#"min_over_time(rate(foo{bar="baz"}[2s])[5m:] offset 4m)[4m:3s]"#,
                r#"min_over_time(rate(foo{bar="baz"}[2s])[5m:] offset 4m)[4m:3s]"#,
            ),
            ("some_metric OFFSET 1m [10m:5s]", "some_metric offset 1m[10m:5s]"),
            ("some_metric @123 [10m:5s]", "some_metric @ 123.000[10m:5s]")
        ];

        // the following cases are from https://github.com/prometheus/prometheus/blob/main/promql/parser/printer_test.go
        let mut cases1 = vec![
            (
                r#"sum by() (task:errors:rate10s{job="s"})"#,
                r#"sum(task:errors:rate10s{job="s"})"#,
            ),
            (
                r#"sum by(code) (task:errors:rate10s{job="s"})"#,
                r#"sum by (code) (task:errors:rate10s{job="s"})"#,
            ),
            (
                r#"sum without() (task:errors:rate10s{job="s"})"#,
                r#"sum without () (task:errors:rate10s{job="s"})"#,
            ),
            (
                r#"sum without(instance) (task:errors:rate10s{job="s"})"#,
                r#"sum without (instance) (task:errors:rate10s{job="s"})"#,
            ),
            (
                r#"topk(5, task:errors:rate10s{job="s"})"#,
                r#"topk(5, task:errors:rate10s{job="s"})"#,
            ),
            (
                r#"count_values("value", task:errors:rate10s{job="s"})"#,
                r#"count_values("value", task:errors:rate10s{job="s"})"#,
            ),
            ("a - on() c", "a - on () c"),
            ("a - on(b) c", "a - on (b) c"),
            ("a - on(b) group_left(x) c", "a - on (b) group_left (x) c"),
            (
                "a - on(b) group_left(x, y) c",
                "a - on (b) group_left (x, y) c",
            ),
            ("a - on(b) group_left c", "a - on (b) group_left () c"),
            ("a - ignoring(b) c", "a - ignoring (b) c"),
            ("a - ignoring() c", "a - c"),
            ("up > bool 0", "up > bool 0"),
            ("a offset 1m", "a offset 1m"),
            ("a offset -7m", "a offset -7m"),
            (r#"a{c="d"}[5m] offset 1m"#, r#"a{c="d"}[5m] offset 1m"#),
            ("a[5m] offset 1m", "a[5m] offset 1m"),
            ("a[12m] offset -3m", "a[12m] offset -3m"),
            ("a[1h:5m] offset 1m", "a[1h:5m] offset 1m"),
            (r#"{__name__="a"}"#, r#"{__name__="a"}"#),
            (r#"a{b!="c"}[1m]"#, r#"a{b!="c"}[1m]"#),
            (r#"a{b=~"c"}[1m]"#, r#"a{b=~"c"}[1m]"#),
            (r#"a{b!~"c"}[1m]"#, r#"a{b!~"c"}[1m]"#),
            ("a @ 10", "a @ 10.000"),
            ("a[1m] @ 10", "a[1m] @ 10.000"),
            ("a @ start()", "a @ start()"),
            ("a @ end()", "a @ end()"),
            ("a[1m] @ start()", "a[1m] @ start()"),
            ("a[1m] @ end()", "a[1m] @ end()"),
        ];

        cases.append(&mut cases1);
        for (input, expected) in cases {
            let expr = crate::parser::parse(input).unwrap();
            assert_eq!(expected, expr.to_string())
        }
    }

    #[test]
    fn test_vector_selector_to_string() {
        let cases = vec![
            (VectorSelector::default(), ""),
            (VectorSelector::from("foobar"), "foobar"),
            (
                {
                    let name = Some(String::from("foobar"));
                    let matchers = Matchers::one(Matcher::new(MatchOp::Equal, "a", "x"));
                    VectorSelector::new(name, matchers)
                },
                r#"foobar{a="x"}"#,
            ),
            (
                {
                    let matchers = Matchers::new(vec![
                        Matcher::new(MatchOp::Equal, "a", "x"),
                        Matcher::new(MatchOp::Equal, "b", "y"),
                    ]);
                    VectorSelector::new(None, matchers)
                },
                r#"{a="x",b="y"}"#,
            ),
            (
                {
                    let matchers =
                        Matchers::one(Matcher::new(MatchOp::Equal, METRIC_NAME, "foobar"));
                    VectorSelector::new(None, matchers)
                },
                r#"{__name__="foobar"}"#,
            ),
        ];

        for (vs, expect) in cases {
            assert_eq!(expect, vs.to_string())
        }
    }

    #[test]
    fn test_aggregate_expr_pretty() {
        let cases = vec![
            ("sum(foo)", "sum(foo)"),
            (
                r#"sum by() (task:errors:rate10s{job="s"})"#,
                r#"sum(
  task:errors:rate10s{job="s"}
)"#,
            ),
            (
                r#"sum without(job,foo) (task:errors:rate10s{job="s"})"#,
                r#"sum without (job, foo) (
  task:errors:rate10s{job="s"}
)"#,
            ),
            (
                r#"sum(task:errors:rate10s{job="s"}) without(job,foo)"#,
                r#"sum without (job, foo) (
  task:errors:rate10s{job="s"}
)"#,
            ),
            (
                r#"sum by(job,foo) (task:errors:rate10s{job="s"})"#,
                r#"sum by (job, foo) (
  task:errors:rate10s{job="s"}
)"#,
            ),
            (
                r#"sum (task:errors:rate10s{job="s"}) by(job,foo)"#,
                r#"sum by (job, foo) (
  task:errors:rate10s{job="s"}
)"#,
            ),
            (
                r#"topk(10, ask:errors:rate10s{job="s"})"#,
                r#"topk(
  10,
  ask:errors:rate10s{job="s"}
)"#,
            ),
            (
                r#"sum by(job,foo) (sum by(job,foo) (task:errors:rate10s{job="s"}))"#,
                r#"sum by (job, foo) (
  sum by (job, foo) (
    task:errors:rate10s{job="s"}
  )
)"#,
            ),
            (
                r#"sum by(job,foo) (sum by(job,foo) (sum by(job,foo) (task:errors:rate10s{job="s"})))"#,
                r#"sum by (job, foo) (
  sum by (job, foo) (
    sum by (job, foo) (
      task:errors:rate10s{job="s"}
    )
  )
)"#,
            ),
            (
                r#"sum by(job,foo)
(sum by(job,foo) (task:errors:rate10s{job="s"}))"#,
                r#"sum by (job, foo) (
  sum by (job, foo) (
    task:errors:rate10s{job="s"}
  )
)"#,
            ),
            (
                r#"sum by(job,foo)
(sum(task:errors:rate10s{job="s"}) without(job,foo))"#,
                r#"sum by (job, foo) (
  sum without (job, foo) (
    task:errors:rate10s{job="s"}
  )
)"#,
            ),
            (
                r#"sum by(job,foo) # Comment 1.
(sum by(job,foo) ( # Comment 2.
task:errors:rate10s{job="s"}))"#,
                r#"sum by (job, foo) (
  sum by (job, foo) (
    task:errors:rate10s{job="s"}
  )
)"#,
            ),
        ];

        for (input, expect) in cases {
            let expr = crate::parser::parse(input);
            assert_eq!(expect, expr.unwrap().pretty(0, 10));
        }
    }

    #[test]
    fn test_binary_expr_pretty() {
        let cases = vec![
            ("a+b", "a + b"),
            (
                "a == bool 1",
                "  a
== bool
  1",
            ),
            (
                "a == 1024000",
                "  a
==
  1024000",
            ),
            (
                "a + ignoring(job) b",
                "  a
+ ignoring (job)
  b",
            ),
            (
                "foo_1 + foo_2",
                "  foo_1
+
  foo_2",
            ),
            (
                "foo_1 + foo_2 + foo_3",
                "    foo_1
  +
    foo_2
+
  foo_3",
            ),
            (
                "foo + baar + foo_3",
                "  foo + baar
+
  foo_3",
            ),
            (
                "foo_1 + foo_2 + foo_3 + foo_4",
                "      foo_1
    +
      foo_2
  +
    foo_3
+
  foo_4",
            ),
            (
                "foo_1 + ignoring(foo) foo_2 + ignoring(job) group_left foo_3 + on(instance) group_right foo_4",

                 "      foo_1
    + ignoring (foo)
      foo_2
  + ignoring (job) group_left ()
    foo_3
+ on (instance) group_right ()
  foo_4",
            ),
        ];

        for (input, expect) in cases {
            let expr = crate::parser::parse(input);
            assert_eq!(expect, expr.unwrap().pretty(0, 10));
        }
    }

    #[test]
    fn test_call_expr_pretty() {
        let cases = vec![
            (
                "rate(foo[1m])",
                "rate(
  foo[1m]
)",
            ),
            (
                "sum_over_time(foo[1m])",
                "sum_over_time(
  foo[1m]
)",
            ),
            (
                "rate(long_vector_selector[10m:1m] @ start() offset 1m)",
                "rate(
  long_vector_selector[10m:1m] @ start() offset 1m
)",
            ),
            (
                "histogram_quantile(0.9, rate(foo[1m]))",
                "histogram_quantile(
  0.9,
  rate(
    foo[1m]
  )
)",
            ),
            (
                "histogram_quantile(0.9, rate(foo[1m] @ start()))",
                "histogram_quantile(
  0.9,
  rate(
    foo[1m] @ start()
  )
)",
            ),
            (
                "max_over_time(rate(demo_api_request_duration_seconds_count[1m])[1m:] @ start() offset 1m)",
                "max_over_time(
  rate(
    demo_api_request_duration_seconds_count[1m]
  )[1m:] @ start() offset 1m
)",
            ),
            (
                r#"label_replace(up{job="api-server",service="a:c"}, "foo", "$1", "service", "(.*):.*")"#,
                r#"label_replace(
  up{job="api-server",service="a:c"},
  "foo",
  "$1",
  "service",
  "(.*):.*"
)"#,
            ),
            (
                r#"label_replace(label_replace(up{job="api-server",service="a:c"}, "foo", "$1", "service", "(.*):.*"), "foo", "$1", "service", "(.*):.*")"#,
                r#"label_replace(
  label_replace(
    up{job="api-server",service="a:c"},
    "foo",
    "$1",
    "service",
    "(.*):.*"
  ),
  "foo",
  "$1",
  "service",
  "(.*):.*"
)"#,
            ),
        ];

        for (input, expect) in cases {
            let expr = crate::parser::parse(input);
            assert_eq!(expect, expr.unwrap().pretty(0, 10));
        }
    }

    #[test]
    fn test_paren_expr_pretty() {
        let cases = vec![
            ("(foo)", "(foo)"),
            (
                "(_foo_long_)",
                "(
  _foo_long_
)",
            ),
            (
                "((foo_long))",
                "(
  (foo_long)
)",
            ),
            (
                "((_foo_long_))",
                "(
  (
    _foo_long_
  )
)",
            ),
            (
                "(((foo_long)))",
                "(
  (
    (foo_long)
  )
)",
            ),
            ("(1 + 2)", "(1 + 2)"),
            (
                "(foo + bar)",
                "(
  foo + bar
)",
            ),
            (
                "(foo_long + bar_long)",
                "(
    foo_long
  +
    bar_long
)",
            ),
            (
                "(foo_long + bar_long + bar_2_long)",
                "(
      foo_long
    +
      bar_long
  +
    bar_2_long
)",
            ),
            (
                "((foo_long + bar_long) + bar_2_long)",
                "(
    (
        foo_long
      +
        bar_long
    )
  +
    bar_2_long
)",
            ),
            (
                "(1111 + 2222)",
                "(
    1111
  +
    2222
)",
            ),
            (
                "(sum_over_time(foo[1m]))",
                "(
  sum_over_time(
    foo[1m]
  )
)",
            ),
            (
                r#"(label_replace(up{job="api-server",service="a:c"}, "foo", "$1", "service", "(.*):.*"))"#,
                r#"(
  label_replace(
    up{job="api-server",service="a:c"},
    "foo",
    "$1",
    "service",
    "(.*):.*"
  )
)"#,
            ),
            (
                r#"(label_replace(label_replace(up{job="api-server",service="a:c"}, "foo", "$1", "service", "(.*):.*"), "foo", "$1", "service", "(.*):.*"))"#,
                r#"(
  label_replace(
    label_replace(
      up{job="api-server",service="a:c"},
      "foo",
      "$1",
      "service",
      "(.*):.*"
    ),
    "foo",
    "$1",
    "service",
    "(.*):.*"
  )
)"#,
            ),
            (
                r#"(label_replace(label_replace((up{job="api-server",service="a:c"}), "foo", "$1", "service", "(.*):.*"), "foo", "$1", "service", "(.*):.*"))"#,
                r#"(
  label_replace(
    label_replace(
      (
        up{job="api-server",service="a:c"}
      ),
      "foo",
      "$1",
      "service",
      "(.*):.*"
    ),
    "foo",
    "$1",
    "service",
    "(.*):.*"
  )
)"#,
            ),
        ];

        for (input, expect) in cases {
            let expr = crate::parser::parse(input);
            assert_eq!(expect, expr.unwrap().pretty(0, 10));
        }
    }

    #[test]
    fn test_unary_expr_pretty() {
        let cases = vec![
            ("-1", "-1"),
            ("-vector_selector", "-vector_selector"),
            (
                "(-vector_selector)",
                "(
  -vector_selector
)",
            ),
            (
                "-histogram_quantile(0.9,rate(foo[1m]))",
                "-histogram_quantile(
  0.9,
  rate(
    foo[1m]
  )
)",
            ),
            (
                "-histogram_quantile(0.99, sum by (le) (rate(foo[1m])))",
                "-histogram_quantile(
  0.99,
  sum by (le) (
    rate(
      foo[1m]
    )
  )
)",
            ),
            (
                "-histogram_quantile(0.9, -rate(foo[1m] @ start()))",
                "-histogram_quantile(
  0.9,
  -rate(
    foo[1m] @ start()
  )
)",
            ),
            (
                "(-histogram_quantile(0.9, -rate(foo[1m] @ start())))",
                "(
  -histogram_quantile(
    0.9,
    -rate(
      foo[1m] @ start()
    )
  )
)",
            ),
        ];

        for (input, expect) in cases {
            let expr = crate::parser::parse(input);
            assert_eq!(expect, expr.unwrap().pretty(0, 10));
        }
    }

    #[test]
    fn test_expr_pretty() {
        // Following queries have been taken from https://monitoring.mixins.dev/
        let cases = vec![
            (
                r#"(node_filesystem_avail_bytes{job="node",fstype!=""} / node_filesystem_size_bytes{job="node",fstype!=""} * 100 < 40 and predict_linear(node_filesystem_avail_bytes{job="node",fstype!=""}[6h], 24*60*60) < 0 and node_filesystem_readonly{job="node",fstype!=""} == 0)"#,
                r#"(
            node_filesystem_avail_bytes{fstype!="",job="node"}
          /
            node_filesystem_size_bytes{fstype!="",job="node"}
        *
          100
      <
        40
    and
        predict_linear(
          node_filesystem_avail_bytes{fstype!="",job="node"}[6h],
            24 * 60
          *
            60
        )
      <
        0
  and
      node_filesystem_readonly{fstype!="",job="node"}
    ==
      0
)"#,
            ),
            (
                r#"(node_filesystem_avail_bytes{job="node",fstype!=""} / node_filesystem_size_bytes{job="node",fstype!=""} * 100 < 20 and predict_linear(node_filesystem_avail_bytes{job="node",fstype!=""}[6h], 4*60*60) < 0 and node_filesystem_readonly{job="node",fstype!=""} == 0)"#,
                r#"(
            node_filesystem_avail_bytes{fstype!="",job="node"}
          /
            node_filesystem_size_bytes{fstype!="",job="node"}
        *
          100
      <
        20
    and
        predict_linear(
          node_filesystem_avail_bytes{fstype!="",job="node"}[6h],
            4 * 60
          *
            60
        )
      <
        0
  and
      node_filesystem_readonly{fstype!="",job="node"}
    ==
      0
)"#,
            ),
            (
                r#"(node_timex_offset_seconds > 0.05 and deriv(node_timex_offset_seconds[5m]) >= 0) or (node_timex_offset_seconds < -0.05 and deriv(node_timex_offset_seconds[5m]) <= 0)"#,
                r#"  (
        node_timex_offset_seconds
      >
        0.05
    and
        deriv(
          node_timex_offset_seconds[5m]
        )
      >=
        0
  )
or
  (
        node_timex_offset_seconds
      <
        -0.05
    and
        deriv(
          node_timex_offset_seconds[5m]
        )
      <=
        0
  )"#,
            ),
            (
                r#"1 - ((node_memory_MemAvailable_bytes{job="node"} or (node_memory_Buffers_bytes{job="node"} + node_memory_Cached_bytes{job="node"} + node_memory_MemFree_bytes{job="node"} + node_memory_Slab_bytes{job="node"}) ) / node_memory_MemTotal_bytes{job="node"})"#,
                r#"  1
-
  (
      (
          node_memory_MemAvailable_bytes{job="node"}
        or
          (
                  node_memory_Buffers_bytes{job="node"}
                +
                  node_memory_Cached_bytes{job="node"}
              +
                node_memory_MemFree_bytes{job="node"}
            +
              node_memory_Slab_bytes{job="node"}
          )
      )
    /
      node_memory_MemTotal_bytes{job="node"}
  )"#,
            ),
            (
                r#"min by (job, integration) (rate(alertmanager_notifications_failed_total{job="alertmanager", integration=~".*"}[5m]) / rate(alertmanager_notifications_total{job="alertmanager", integration="~.*"}[5m])) > 0.01"#,
                r#"  min by (job, integration) (
      rate(
        alertmanager_notifications_failed_total{integration=~".*",job="alertmanager"}[5m]
      )
    /
      rate(
        alertmanager_notifications_total{integration="~.*",job="alertmanager"}[5m]
      )
  )
>
  0.01"#,
            ),
            (
                r#"(count by (job) (changes(process_start_time_seconds{job="alertmanager"}[10m]) > 4) / count by (job) (up{job="alertmanager"})) >= 0.5"#,
                r#"  (
      count by (job) (
          changes(
            process_start_time_seconds{job="alertmanager"}[10m]
          )
        >
          4
      )
    /
      count by (job) (
        up{job="alertmanager"}
      )
  )
>=
  0.5"#,
            ),
        ];

        for (input, expect) in cases {
            let expr = crate::parser::parse(input);
            assert_eq!(expect, expr.unwrap().pretty(0, 10));
        }
    }

    #[test]
    fn test_step_invariant_pretty() {
        let cases = vec![
            ("a @ 1", "a @ 1.000"),
            ("a @ start()", "a @ start()"),
            ("vector_selector @ start()", "vector_selector @ start()"),
        ];

        for (input, expect) in cases {
            let expr = crate::parser::parse(input);
            assert_eq!(expect, expr.unwrap().pretty(0, 10));
        }
    }

    #[test]
    fn test_prettify() {
        let cases = vec![
            ("vector_selector", "vector_selector"),
            (
                r#"vector_selector{fooooooooooooooooo="barrrrrrrrrrrrrrrrrrr",barrrrrrrrrrrrrrrrrrr="fooooooooooooooooo",process_name="alertmanager"}"#,
                r#"vector_selector{barrrrrrrrrrrrrrrrrrr="fooooooooooooooooo",fooooooooooooooooo="barrrrrrrrrrrrrrrrrrr",process_name="alertmanager"}"#,
            ),
            (
                r#"matrix_selector{fooooooooooooooooo="barrrrrrrrrrrrrrrrrrr",barrrrrrrrrrrrrrrrrrr="fooooooooooooooooo",process_name="alertmanager"}[1y2w3d]"#,
                r#"matrix_selector{barrrrrrrrrrrrrrrrrrr="fooooooooooooooooo",fooooooooooooooooo="barrrrrrrrrrrrrrrrrrr",process_name="alertmanager"}[382d]"#,
            ),
        ];

        for (input, expect) in cases {
            assert_eq!(expect, crate::parser::parse(input).unwrap().prettify());
        }
    }

    #[test]
    fn test_eval_stmt_to_string() {
        let query = r#"http_requests_total{job="apiserver", handler="/api/comments"}[5m]"#;
        let start = "2024-10-08T07:15:00.022978+00:00";
        let end = "2024-10-08T07:15:30.012978+00:00";
        let expect = r#"[http_requests_total{handler="/api/comments",job="apiserver"}[5m]] @ [2024-10-08T07:15:00.022978+00:00, 2024-10-08T07:15:30.012978+00:00, 1m, 5m]"#;

        let stmt = EvalStmt {
            expr: crate::parser::parse(query).unwrap(),
            start: DateTime::parse_from_rfc3339(start)
                .unwrap()
                .with_timezone(&Utc)
                .into(),
            end: DateTime::parse_from_rfc3339(end)
                .unwrap()
                .with_timezone(&Utc)
                .into(),
            interval: Duration::from_secs(60),
            lookback_delta: Duration::from_secs(300),
        };

        assert_eq!(expect, stmt.to_string());
    }
}