rusty-promql-parser 0.2.1

A Prometheus PromQL parser written in Rust
Documentation
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
//! Vector and matrix selector parsing for PromQL.
//!
//! Selectors are the fundamental way to query time series data in PromQL.
//!
//! # Vector Selectors (Instant Vectors)
//!
//! A vector selector selects a set of time series with a single sample value
//! for each at the current timestamp.
//!
//! ```text
//! metric_name
//! metric_name{label_matchers}
//! {label_matchers}
//! ```
//!
//! # Matrix Selectors (Range Vectors)
//!
//! A matrix selector extends a vector selector with a time range, selecting
//! multiple samples per time series.
//!
//! ```text
//! metric_name[5m]
//! metric_name{label="value"}[1h]
//! ```
//!
//! # Label Matchers
//!
//! | Operator | Description       | Example               |
//! |----------|-------------------|-----------------------|
//! | `=`      | Exact equality    | `job="prometheus"`    |
//! | `!=`     | Not equal         | `env!="prod"`         |
//! | `=~`     | Regex match       | `path=~"/api/.*"`     |
//! | `!~`     | Regex not match   | `status!~"5.."`       |
//!
//! # Modifiers
//!
//! Selectors can have optional modifiers:
//!
//! - **offset**: Shift the time range back: `metric offset 5m`
//! - **@**: Pin to a specific timestamp: `metric @ 1609459200`
//!
//! # Examples
//!
//! ```rust
//! use rusty_promql_parser::parser::selector::{vector_selector, matrix_selector};
//!
//! // Simple vector selector
//! let (_, sel) = vector_selector("http_requests_total").unwrap();
//! assert_eq!(sel.name, Some("http_requests_total".to_string()));
//!
//! // With label matchers
//! let (_, sel) = vector_selector(r#"http_requests{job="api"}"#).unwrap();
//! assert_eq!(sel.matchers.len(), 1);
//!
//! // Matrix selector with range
//! let (_, sel) = matrix_selector("http_requests[5m]").unwrap();
//! assert_eq!(sel.range_millis(), 5 * 60 * 1000);
//! ```

use nom::{
    IResult, Parser,
    branch::alt,
    bytes::complete::tag,
    character::complete::char,
    combinator::{map, opt, success},
    multi::separated_list1,
    sequence::{delimited, terminated},
};

use crate::lexer::{
    duration::{Duration, duration, signed_duration},
    identifier::{label_name, metric_name},
    number::number,
    string::string_literal,
    whitespace::ws_opt,
};

/// The `@` modifier for timestamp pinning.
///
/// The `@` modifier allows pinning a query to a specific timestamp,
/// or to the start/end of the evaluation range.
///
/// # Examples
///
/// - `metric @ 1609459200` - Pin to Unix timestamp
/// - `metric @ start()` - Pin to evaluation start
/// - `metric @ end()` - Pin to evaluation end
#[derive(Debug, Clone, PartialEq)]
pub enum AtModifier {
    /// Pin to a specific Unix timestamp (in milliseconds).
    Timestamp(i64),
    /// Pin to the start of the evaluation range: `@ start()`
    Start,
    /// Pin to the end of the evaluation range: `@ end()`
    End,
}

impl std::fmt::Display for AtModifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AtModifier::Timestamp(ts) => {
                // Convert milliseconds to seconds with 3 decimal places
                let secs = *ts as f64 / 1000.0;
                write!(f, "@ {:.3}", secs)
            }
            AtModifier::Start => write!(f, "@ start()"),
            AtModifier::End => write!(f, "@ end()"),
        }
    }
}

/// Label matching operator.
///
/// Used in label matchers to specify how to compare label values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LabelMatchOp {
    /// `=` - Exact string equality.
    Equal,
    /// `!=` - String inequality.
    NotEqual,
    /// `=~` - Regex match.
    RegexMatch,
    /// `!~` - Regex not match.
    RegexNotMatch,
}

impl LabelMatchOp {
    /// Get the operator as a string
    pub fn as_str(&self) -> &'static str {
        match self {
            LabelMatchOp::Equal => "=",
            LabelMatchOp::NotEqual => "!=",
            LabelMatchOp::RegexMatch => "=~",
            LabelMatchOp::RegexNotMatch => "!~",
        }
    }

    /// Check if this is a negative matcher (!=, !~)
    pub fn is_negative(&self) -> bool {
        matches!(self, LabelMatchOp::NotEqual | LabelMatchOp::RegexNotMatch)
    }

    /// Check if this is a regex matcher (=~, !~)
    pub fn is_regex(&self) -> bool {
        matches!(self, LabelMatchOp::RegexMatch | LabelMatchOp::RegexNotMatch)
    }
}

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

/// A single label matcher.
///
/// Label matchers filter time series based on their label values.
///
/// # Example
///
/// ```rust
/// use rusty_promql_parser::parser::selector::{LabelMatcher, LabelMatchOp};
///
/// let matcher = LabelMatcher::new("job", LabelMatchOp::Equal, "prometheus");
/// assert_eq!(matcher.to_string(), r#"job="prometheus""#);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LabelMatcher {
    /// Label name (e.g., "job", "__name__").
    pub name: String,
    /// Matching operator.
    pub op: LabelMatchOp,
    /// Value to match against.
    pub value: String,
}

impl LabelMatcher {
    /// Create a new label matcher
    pub fn new(name: impl Into<String>, op: LabelMatchOp, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            op,
            value: value.into(),
        }
    }

    /// Check if this matcher matches the empty string
    pub fn matches_empty(&self) -> bool {
        match self.op {
            LabelMatchOp::Equal => self.value.is_empty(),
            LabelMatchOp::NotEqual => !self.value.is_empty(),
            LabelMatchOp::RegexMatch => {
                // A regex matches empty if it can match ""
                // Common patterns: "", ".*", "^$", etc.
                self.value.is_empty()
                    || self.value == ".*"
                    || self.value == "^$"
                    || self.value == "^.*$"
            }
            LabelMatchOp::RegexNotMatch => {
                // !~ matches empty if the regex doesn't match ""
                // ".+" requires at least one character, so it doesn't match ""
                self.value == ".+"
            }
        }
    }
}

impl std::fmt::Display for LabelMatcher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}{}\"{}\"",
            self.name,
            self.op,
            self.value.escape_default()
        )
    }
}

/// A vector selector expression (instant vector).
///
/// Selects a set of time series with a single sample value for each
/// at the query evaluation time.
///
/// # Example
///
/// ```rust
/// use rusty_promql_parser::parser::selector::{VectorSelector, LabelMatcher, LabelMatchOp};
///
/// let mut sel = VectorSelector::new("http_requests_total");
/// sel.add_matcher(LabelMatcher::new("job", LabelMatchOp::Equal, "api"));
/// assert_eq!(sel.to_string(), r#"http_requests_total{job="api"}"#);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct VectorSelector {
    /// Metric name (optional if label matchers include `__name__`).
    pub name: Option<String>,
    /// Label matchers.
    pub matchers: Vec<LabelMatcher>,
    /// Offset modifier (e.g., `offset 5m`, `offset -1h`).
    pub offset: Option<Duration>,
    /// `@` modifier for timestamp pinning.
    pub at: Option<AtModifier>,
}

impl VectorSelector {
    /// Create a new vector selector with just a metric name
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            matchers: Vec::new(),
            offset: None,
            at: None,
        }
    }

    /// Create a new vector selector with only label matchers
    pub fn with_matchers(matchers: Vec<LabelMatcher>) -> Self {
        Self {
            name: None,
            matchers,
            offset: None,
            at: None,
        }
    }

    /// Add a label matcher
    pub fn add_matcher(&mut self, matcher: LabelMatcher) {
        self.matchers.push(matcher);
    }

    /// Get all matchers including the implicit __name__ matcher
    pub fn all_matchers(&self) -> Vec<LabelMatcher> {
        let mut result = self.matchers.clone();
        if let Some(ref name) = self.name {
            result.push(LabelMatcher::new(
                "__name__",
                LabelMatchOp::Equal,
                name.clone(),
            ));
        }
        result
    }

    /// Check if this selector has at least one non-empty matcher
    /// (Required for valid selectors to avoid selecting all series)
    pub fn has_non_empty_matcher(&self) -> bool {
        // If we have an explicit metric name, that's a non-empty matcher
        if self.name.is_some() {
            return true;
        }

        // Check if any label matcher doesn't match empty
        self.matchers.iter().any(|m| !m.matches_empty())
    }
}

impl std::fmt::Display for VectorSelector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(ref name) = self.name {
            write!(f, "{}", name)?;
        }
        if !self.matchers.is_empty() {
            write!(f, "{{")?;
            for (i, m) in self.matchers.iter().enumerate() {
                if i > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{}", m)?;
            }
            write!(f, "}}")?;
        }
        // @ modifier comes before offset in PromQL
        if let Some(ref at) = self.at {
            write!(f, " {}", at)?;
        }
        if let Some(ref offset) = self.offset {
            write!(f, " offset {}", offset)?;
        }
        Ok(())
    }
}

/// A matrix selector expression (range vector).
///
/// Selects a range of samples over time for each matching time series.
/// Extends a vector selector with a duration in square brackets.
///
/// # Example
///
/// ```rust
/// use rusty_promql_parser::parser::selector::{MatrixSelector, VectorSelector};
/// use rusty_promql_parser::lexer::duration::Duration;
///
/// let sel = MatrixSelector::with_name("http_requests", Duration::from_secs(300));
/// assert_eq!(sel.to_string(), "http_requests[5m]");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct MatrixSelector {
    /// The underlying vector selector.
    pub selector: VectorSelector,
    /// The range duration (e.g., 5m, 1h, 30s).
    pub range: Duration,
}

impl MatrixSelector {
    /// Create a new matrix selector from a vector selector and range
    pub fn new(selector: VectorSelector, range: Duration) -> Self {
        Self { selector, range }
    }

    /// Create a matrix selector with just a metric name and range
    pub fn with_name(name: impl Into<String>, range: Duration) -> Self {
        Self {
            selector: VectorSelector::new(name),
            range,
        }
    }

    /// Get the metric name (if any)
    pub fn name(&self) -> Option<&str> {
        self.selector.name.as_deref()
    }

    /// Get the label matchers
    pub fn matchers(&self) -> &[LabelMatcher] {
        &self.selector.matchers
    }

    /// Get the range duration in milliseconds
    pub fn range_millis(&self) -> i64 {
        self.range.as_millis()
    }

    /// Get the offset duration (if any)
    pub fn offset(&self) -> Option<&Duration> {
        self.selector.offset.as_ref()
    }

    /// Get the offset duration in milliseconds (if any)
    pub fn offset_millis(&self) -> Option<i64> {
        self.selector.offset.map(|d| d.as_millis())
    }

    /// Get the @ modifier (if any)
    pub fn at(&self) -> Option<&AtModifier> {
        self.selector.at.as_ref()
    }
}

impl std::fmt::Display for MatrixSelector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Write name and matchers without offset/at
        if let Some(ref name) = self.selector.name {
            write!(f, "{}", name)?;
        }
        if !self.selector.matchers.is_empty() {
            write!(f, "{{")?;
            for (i, m) in self.selector.matchers.iter().enumerate() {
                if i > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{}", m)?;
            }
            write!(f, "}}")?;
        }
        // Write range
        write!(f, "[{}]", self.range)?;
        // Write @ modifier (if any) - comes before offset
        if let Some(ref at) = self.selector.at {
            write!(f, " {}", at)?;
        }
        // Write offset (if any)
        if let Some(ref offset) = self.selector.offset {
            write!(f, " offset {}", offset)?;
        }
        Ok(())
    }
}

/// Parse a range duration in square brackets: `[5m]`, `[1h30m]`
fn range_duration(input: &str) -> IResult<&str, Duration> {
    delimited(char('['), duration, char(']')).parse(input)
}

/// Parse the offset modifier keyword (case-insensitive)
fn offset_keyword(input: &str) -> IResult<&str, &str> {
    alt((tag("offset"), tag("OFFSET"), tag("Offset"))).parse(input)
}

/// Parse an offset modifier: `offset 5m`, `offset -1h`
///
/// The offset modifier shifts the time range of a vector selector back in time.
/// Negative offsets look forward in time (relative to query evaluation time).
///
/// # Examples
///
/// ```
/// use rusty_promql_parser::parser::selector::offset_modifier;
///
/// let (rest, dur) = offset_modifier(" offset 5m").unwrap();
/// assert!(rest.is_empty());
/// assert_eq!(dur.as_millis(), 300_000);
///
/// let (rest, dur) = offset_modifier(" offset -7m").unwrap();
/// assert!(rest.is_empty());
/// assert_eq!(dur.as_millis(), -420_000);
///
/// let (rest, dur) = offset_modifier(" OFFSET 1h30m").unwrap();
/// assert!(rest.is_empty());
/// assert_eq!(dur.as_millis(), 5_400_000);
/// ```
pub fn offset_modifier(input: &str) -> IResult<&str, Duration> {
    let (rest, _) = ws_opt(input)?;
    let (rest, _) = offset_keyword(rest)?;
    let (rest, _) = ws_opt(rest)?;
    signed_duration(rest)
}

/// Parse the @ modifier: `@ <timestamp>`, `@ start()`, `@ end()`
///
/// The @ modifier allows pinning a query to a specific timestamp,
/// or to the start/end of the evaluation range.
///
/// # Examples
///
/// ```
/// use rusty_promql_parser::parser::selector::at_modifier;
///
/// // Timestamp in seconds
/// let (rest, at) = at_modifier(" @ 1603774568").unwrap();
/// assert!(rest.is_empty());
///
/// // start() preprocessor
/// let (rest, at) = at_modifier(" @ start()").unwrap();
/// assert!(rest.is_empty());
///
/// // end() preprocessor
/// let (rest, at) = at_modifier(" @ end()").unwrap();
/// assert!(rest.is_empty());
/// ```
pub fn at_modifier(input: &str) -> IResult<&str, AtModifier> {
    let (rest, _) = ws_opt(input)?;
    let (rest, _) = char('@')(rest)?;
    let (rest, _) = ws_opt(rest)?;

    // Try start() or end() first
    if let Ok((rest, _)) = tag::<&str, &str, nom::error::Error<&str>>("start()")(rest) {
        return Ok((rest, AtModifier::Start));
    }
    if let Ok((rest, _)) = tag::<&str, &str, nom::error::Error<&str>>("end()")(rest) {
        return Ok((rest, AtModifier::End));
    }

    // Otherwise parse a number (timestamp in seconds)
    let (rest, ts) = number(rest)?;

    // Check for invalid timestamps (Inf, NaN)
    if ts.is_infinite() || ts.is_nan() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    // Convert seconds to milliseconds, rounding to nearest
    let ts_ms = (ts * 1000.0).round() as i64;
    Ok((rest, AtModifier::Timestamp(ts_ms)))
}

/// Parse a matrix selector (range vector)
///
/// A matrix selector consists of a vector selector followed by a range duration
/// in square brackets.
///
/// # Examples
///
/// ```
/// use rusty_promql_parser::parser::selector::matrix_selector;
///
/// // Simple metric with range
/// let (rest, sel) = matrix_selector("http_requests_total[5m]").unwrap();
/// assert!(rest.is_empty());
/// assert_eq!(sel.name(), Some("http_requests_total"));
/// assert_eq!(sel.range_millis(), 5 * 60 * 1000);
///
/// // With label matchers
/// let (rest, sel) = matrix_selector(r#"http_requests_total{job="api"}[1h]"#).unwrap();
/// assert!(rest.is_empty());
/// assert_eq!(sel.matchers().len(), 1);
/// ```
pub fn matrix_selector(input: &str) -> IResult<&str, MatrixSelector> {
    map(
        (base_vector_selector, range_duration, parse_modifiers),
        |(mut selector, range, (at, offset))| {
            selector.at = at;
            selector.offset = offset;
            MatrixSelector::new(selector, range)
        },
    )
    .parse(input)
}

/// Parse @ and offset modifiers in any order.
/// Returns (at_modifier, offset_modifier)
pub(crate) fn parse_modifiers(
    input: &str,
) -> IResult<&str, (Option<AtModifier>, Option<Duration>)> {
    let mut rest = input;
    let mut at = None;
    let mut offset = None;

    loop {
        if let Ok((next, parsed_at)) = at_modifier(rest) {
            if at.is_some() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    rest,
                    nom::error::ErrorKind::Verify,
                )));
            }
            at = Some(parsed_at);
            rest = next;
            continue;
        }

        if let Ok((next, parsed_offset)) = offset_modifier(rest) {
            if offset.is_some() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    rest,
                    nom::error::ErrorKind::Verify,
                )));
            }
            offset = Some(parsed_offset);
            rest = next;
            continue;
        }

        break;
    }

    Ok((rest, (at, offset)))
}

/// Parse a label match operator
fn label_match_op(input: &str) -> IResult<&str, LabelMatchOp> {
    alt((
        map(tag("!="), |_| LabelMatchOp::NotEqual),
        map(tag("!~"), |_| LabelMatchOp::RegexNotMatch),
        map(tag("=~"), |_| LabelMatchOp::RegexMatch),
        map(tag("="), |_| LabelMatchOp::Equal),
    ))
    .parse(input)
}

/// Parse a single label matcher: `label_name op "value"`
fn label_matcher(input: &str) -> IResult<&str, LabelMatcher> {
    map(
        (
            ws_opt,
            label_name,
            ws_opt,
            label_match_op,
            ws_opt,
            string_literal,
        ),
        |(_, name, _, op, _, value)| LabelMatcher::new(name.to_string(), op, value),
    )
    .parse(input)
}

/// Parse a quoted metric name as a matcher: `"metric_name"` inside braces
fn quoted_metric_matcher(input: &str) -> IResult<&str, LabelMatcher> {
    map((ws_opt, string_literal), |(_, name)| {
        LabelMatcher::new("__name__", LabelMatchOp::Equal, name)
    })
    .parse(input)
}

/// Parse a matcher item (either a label matcher or quoted metric name)
fn matcher_item(input: &str) -> IResult<&str, LabelMatcher> {
    alt((label_matcher, quoted_metric_matcher)).parse(input)
}

/// Parse label matchers inside braces: `{label="value", ...}`
pub fn label_matchers(input: &str) -> IResult<&str, Vec<LabelMatcher>> {
    delimited(
        (char('{'), ws_opt),
        alt((
            terminated(
                separated_list1(delimited(ws_opt, char(','), ws_opt), matcher_item),
                opt((ws_opt, char(','))),
            ),
            success(Vec::new()),
        )),
        (ws_opt, char('}')),
    )
    .parse(input)
}

/// Parse a vector selector
///
/// Supports:
/// - `metric_name` - Simple metric name
/// - `metric_name{label="value"}` - Metric with label matchers
/// - `{label="value"}` - Label matchers only
/// - `{"metric_name"}` - Quoted metric name in braces
///
/// # Examples
///
/// ```
/// use rusty_promql_parser::parser::selector::vector_selector;
///
/// let (_, sel) = vector_selector("http_requests_total").unwrap();
/// assert_eq!(sel.name, Some("http_requests_total".to_string()));
///
/// let (_, sel) = vector_selector(r#"foo{bar="baz"}"#).unwrap();
/// assert_eq!(sel.name, Some("foo".to_string()));
/// assert_eq!(sel.matchers.len(), 1);
/// ```
pub fn vector_selector(input: &str) -> IResult<&str, VectorSelector> {
    map(
        (base_vector_selector, parse_modifiers),
        |(mut selector, (at, offset))| {
            selector.at = at;
            selector.offset = offset;
            selector
        },
    )
    .parse(input)
}

/// Parse a vector selector without offset modifier.
/// This is used internally by matrix_selector which handles offset after the range.
pub fn base_vector_selector(input: &str) -> IResult<&str, VectorSelector> {
    // Try to parse metric name first
    let name_result = metric_name(input);

    match name_result {
        Ok((rest, name)) => {
            // Check for label matchers
            let (rest, matchers) = opt(label_matchers).parse(rest)?;
            Ok((
                rest,
                VectorSelector {
                    name: Some(name.to_string()),
                    matchers: matchers.unwrap_or_default(),
                    offset: None,
                    at: None,
                },
            ))
        }
        Err(_) => {
            // No metric name, try label matchers only
            let (rest, matchers) = label_matchers(input)?;

            // Check if any matcher is a __name__ matcher (quoted metric name)
            let name = matchers
                .iter()
                .find(|m| m.name == "__name__" && m.op == LabelMatchOp::Equal)
                .map(|m| m.value.clone());

            // Filter out the __name__= matcher that we're using as the name
            let other_matchers: Vec<_> = if name.is_some() {
                matchers
                    .into_iter()
                    .filter(|m| !(m.name == "__name__" && m.op == LabelMatchOp::Equal))
                    .collect()
            } else {
                matchers
            };

            Ok((
                rest,
                VectorSelector {
                    name,
                    matchers: other_matchers,
                    offset: None,
                    at: None,
                },
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // LabelMatchOp tests
    #[test]
    fn test_label_match_op_parse() {
        assert_eq!(label_match_op("=").unwrap().1, LabelMatchOp::Equal);
        assert_eq!(label_match_op("!=").unwrap().1, LabelMatchOp::NotEqual);
        assert_eq!(label_match_op("=~").unwrap().1, LabelMatchOp::RegexMatch);
        assert_eq!(label_match_op("!~").unwrap().1, LabelMatchOp::RegexNotMatch);
    }

    #[test]
    fn test_label_match_op_display() {
        assert_eq!(LabelMatchOp::Equal.to_string(), "=");
        assert_eq!(LabelMatchOp::NotEqual.to_string(), "!=");
        assert_eq!(LabelMatchOp::RegexMatch.to_string(), "=~");
        assert_eq!(LabelMatchOp::RegexNotMatch.to_string(), "!~");
    }

    #[test]
    fn test_label_match_op_properties() {
        assert!(!LabelMatchOp::Equal.is_negative());
        assert!(LabelMatchOp::NotEqual.is_negative());
        assert!(!LabelMatchOp::RegexMatch.is_negative());
        assert!(LabelMatchOp::RegexNotMatch.is_negative());

        assert!(!LabelMatchOp::Equal.is_regex());
        assert!(!LabelMatchOp::NotEqual.is_regex());
        assert!(LabelMatchOp::RegexMatch.is_regex());
        assert!(LabelMatchOp::RegexNotMatch.is_regex());
    }

    // LabelMatcher tests
    #[test]
    fn test_label_matcher_parse() {
        let (rest, m) = label_matcher(r#"job="prometheus""#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(m.name, "job");
        assert_eq!(m.op, LabelMatchOp::Equal);
        assert_eq!(m.value, "prometheus");
    }

    #[test]
    fn test_label_matcher_parse_with_spaces() {
        let (rest, m) = label_matcher(r#"  job  =  "prometheus"  "#).unwrap();
        assert_eq!(rest, "  "); // Trailing space not consumed
        assert_eq!(m.name, "job");
        assert_eq!(m.value, "prometheus");
    }

    #[test]
    fn test_label_matcher_not_equal() {
        let (_, m) = label_matcher(r#"env!="prod""#).unwrap();
        assert_eq!(m.op, LabelMatchOp::NotEqual);
    }

    #[test]
    fn test_label_matcher_regex() {
        let (_, m) = label_matcher(r#"path=~"/api/.*""#).unwrap();
        assert_eq!(m.op, LabelMatchOp::RegexMatch);
        assert_eq!(m.value, "/api/.*");
    }

    #[test]
    fn test_label_matcher_regex_not() {
        let (_, m) = label_matcher(r#"status!~"5..""#).unwrap();
        assert_eq!(m.op, LabelMatchOp::RegexNotMatch);
    }

    #[test]
    fn test_label_matcher_matches_empty() {
        // Equal empty matches empty
        assert!(LabelMatcher::new("a", LabelMatchOp::Equal, "").matches_empty());
        // Equal non-empty doesn't match empty
        assert!(!LabelMatcher::new("a", LabelMatchOp::Equal, "foo").matches_empty());
        // NotEqual empty doesn't match empty
        assert!(!LabelMatcher::new("a", LabelMatchOp::NotEqual, "").matches_empty());
        // NotEqual non-empty matches empty
        assert!(LabelMatcher::new("a", LabelMatchOp::NotEqual, "foo").matches_empty());
        // Regex .* matches empty
        assert!(LabelMatcher::new("a", LabelMatchOp::RegexMatch, ".*").matches_empty());
        // Regex .+ doesn't match empty
        assert!(!LabelMatcher::new("a", LabelMatchOp::RegexMatch, ".+").matches_empty());
        // Not regex .+ matches empty
        assert!(LabelMatcher::new("a", LabelMatchOp::RegexNotMatch, ".+").matches_empty());
    }

    // VectorSelector tests
    #[test]
    fn test_vector_selector_simple_name() {
        let (rest, sel) = vector_selector("foo").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("foo".to_string()));
        assert!(sel.matchers.is_empty());
    }

    #[test]
    fn test_vector_selector_with_underscore() {
        let (rest, sel) = vector_selector("http_requests_total").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("http_requests_total".to_string()));
    }

    #[test]
    fn test_vector_selector_with_colon() {
        let (rest, sel) = vector_selector("foo:bar:baz").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("foo:bar:baz".to_string()));
    }

    #[test]
    fn test_vector_selector_with_label() {
        let (rest, sel) = vector_selector(r#"foo{bar="baz"}"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("foo".to_string()));
        assert_eq!(sel.matchers.len(), 1);
        assert_eq!(sel.matchers[0].name, "bar");
        assert_eq!(sel.matchers[0].value, "baz");
    }

    #[test]
    fn test_vector_selector_multiple_labels() {
        let (rest, sel) = vector_selector(r#"foo{a="b", c="d"}"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("foo".to_string()));
        assert_eq!(sel.matchers.len(), 2);
        assert_eq!(sel.matchers[0].name, "a");
        assert_eq!(sel.matchers[1].name, "c");
    }

    #[test]
    fn test_vector_selector_trailing_comma() {
        let (rest, sel) = vector_selector(r#"foo{a="b",}"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.matchers.len(), 1);
    }

    #[test]
    fn test_vector_selector_labels_only() {
        let (rest, sel) = vector_selector(r#"{job="prometheus"}"#).unwrap();
        assert!(rest.is_empty());
        assert!(sel.name.is_none());
        assert_eq!(sel.matchers.len(), 1);
        assert_eq!(sel.matchers[0].name, "job");
    }

    #[test]
    fn test_vector_selector_quoted_metric_name() {
        let (rest, sel) = vector_selector(r#"{"foo"}"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("foo".to_string()));
        assert!(sel.matchers.is_empty());
    }

    #[test]
    fn test_vector_selector_quoted_metric_with_labels() {
        let (rest, sel) = vector_selector(r#"{"foo", bar="baz"}"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("foo".to_string()));
        assert_eq!(sel.matchers.len(), 1);
    }

    #[test]
    fn test_vector_selector_all_operators() {
        let (rest, sel) = vector_selector(r#"foo{a="b", c!="d", e=~"f", g!~"h"}"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.matchers.len(), 4);
        assert_eq!(sel.matchers[0].op, LabelMatchOp::Equal);
        assert_eq!(sel.matchers[1].op, LabelMatchOp::NotEqual);
        assert_eq!(sel.matchers[2].op, LabelMatchOp::RegexMatch);
        assert_eq!(sel.matchers[3].op, LabelMatchOp::RegexNotMatch);
    }

    #[test]
    fn test_vector_selector_has_non_empty_matcher() {
        // With metric name - always has non-empty
        let sel = VectorSelector::new("foo");
        assert!(sel.has_non_empty_matcher());

        // With non-empty label value
        let mut sel = VectorSelector::with_matchers(vec![]);
        sel.add_matcher(LabelMatcher::new("job", LabelMatchOp::Equal, "test"));
        assert!(sel.has_non_empty_matcher());

        // With only empty matcher
        let sel =
            VectorSelector::with_matchers(vec![LabelMatcher::new("x", LabelMatchOp::Equal, "")]);
        assert!(!sel.has_non_empty_matcher());
    }

    #[test]
    fn test_vector_selector_display() {
        let mut sel = VectorSelector::new("foo");
        assert_eq!(sel.to_string(), "foo");

        sel.add_matcher(LabelMatcher::new("bar", LabelMatchOp::Equal, "baz"));
        assert_eq!(sel.to_string(), r#"foo{bar="baz"}"#);
    }

    #[test]
    fn test_vector_selector_single_quoted() {
        let (rest, sel) = vector_selector(r#"foo{bar='baz'}"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.matchers[0].value, "baz");
    }

    #[test]
    fn test_vector_selector_backtick() {
        let (rest, sel) = vector_selector(r#"foo{bar=`baz`}"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.matchers[0].value, "baz");
    }

    #[test]
    fn test_vector_selector_keyword_as_metric() {
        // Keywords can be used as metric names
        for keyword in [
            "sum", "min", "max", "avg", "count", "offset", "by", "without",
        ] {
            let result = vector_selector(keyword);
            assert!(
                result.is_ok(),
                "Failed to parse keyword as metric: {}",
                keyword
            );
            let (_, sel) = result.unwrap();
            assert_eq!(sel.name, Some(keyword.to_string()));
        }
    }

    #[test]
    fn test_vector_selector_empty_braces() {
        // Empty braces should parse but result in no matchers
        let (rest, sel) = vector_selector("{}").unwrap();
        assert!(rest.is_empty());
        assert!(sel.name.is_none());
        assert!(sel.matchers.is_empty());
        // Note: validation that this is invalid should happen at a higher level
    }

    // MatrixSelector tests
    #[test]
    fn test_matrix_selector_simple() {
        let (rest, sel) = matrix_selector("foo[5m]").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name(), Some("foo"));
        assert_eq!(sel.range_millis(), 5 * 60 * 1000);
    }

    #[test]
    fn test_matrix_selector_with_labels() {
        let (rest, sel) = matrix_selector(r#"foo{bar="baz"}[5m]"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name(), Some("foo"));
        assert_eq!(sel.matchers().len(), 1);
        assert_eq!(sel.range_millis(), 5 * 60 * 1000);
    }

    #[test]
    fn test_matrix_selector_various_durations() {
        // Seconds
        let (_, sel) = matrix_selector("foo[30s]").unwrap();
        assert_eq!(sel.range_millis(), 30 * 1000);

        // Minutes
        let (_, sel) = matrix_selector("foo[5m]").unwrap();
        assert_eq!(sel.range_millis(), 5 * 60 * 1000);

        // Hours
        let (_, sel) = matrix_selector("foo[1h]").unwrap();
        assert_eq!(sel.range_millis(), 60 * 60 * 1000);

        // Days
        let (_, sel) = matrix_selector("foo[1d]").unwrap();
        assert_eq!(sel.range_millis(), 24 * 60 * 60 * 1000);

        // Weeks
        let (_, sel) = matrix_selector("foo[1w]").unwrap();
        assert_eq!(sel.range_millis(), 7 * 24 * 60 * 60 * 1000);

        // Milliseconds
        let (_, sel) = matrix_selector("foo[100ms]").unwrap();
        assert_eq!(sel.range_millis(), 100);
    }

    #[test]
    fn test_matrix_selector_compound_duration() {
        // 1h30m = 90 minutes
        let (rest, sel) = matrix_selector("foo[1h30m]").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.range_millis(), (60 + 30) * 60 * 1000);
    }

    #[test]
    fn test_matrix_selector_labels_only() {
        let (rest, sel) = matrix_selector(r#"{job="prometheus"}[5m]"#).unwrap();
        assert!(rest.is_empty());
        assert!(sel.name().is_none());
        assert_eq!(sel.matchers().len(), 1);
    }

    #[test]
    fn test_matrix_selector_display() {
        let sel = MatrixSelector::with_name("foo", Duration::from_secs(300));
        assert_eq!(sel.to_string(), "foo[5m]");
    }

    #[test]
    fn test_matrix_selector_display_with_labels() {
        let mut vs = VectorSelector::new("foo");
        vs.add_matcher(LabelMatcher::new("bar", LabelMatchOp::Equal, "baz"));
        let sel = MatrixSelector::new(vs, Duration::from_secs(300));
        assert_eq!(sel.to_string(), r#"foo{bar="baz"}[5m]"#);
    }

    #[test]
    fn test_matrix_selector_no_range_fails() {
        // Vector selector without range should fail for matrix_selector
        let result = matrix_selector("foo");
        assert!(result.is_err());
    }

    #[test]
    fn test_matrix_selector_empty_range_fails() {
        let result = matrix_selector("foo[]");
        assert!(result.is_err());
    }

    // Offset modifier tests
    #[test]
    fn test_offset_modifier_basic() {
        let (rest, dur) = offset_modifier(" offset 5m").unwrap();
        assert!(rest.is_empty());
        assert_eq!(dur.as_millis(), 5 * 60 * 1000);
    }

    #[test]
    fn test_offset_modifier_negative() {
        let (rest, dur) = offset_modifier(" offset -7m").unwrap();
        assert!(rest.is_empty());
        assert_eq!(dur.as_millis(), -7 * 60 * 1000);
    }

    #[test]
    fn test_offset_modifier_uppercase() {
        let (rest, dur) = offset_modifier(" OFFSET 1h30m").unwrap();
        assert!(rest.is_empty());
        assert_eq!(dur.as_millis(), 90 * 60 * 1000);
    }

    #[test]
    fn test_offset_modifier_complex_duration() {
        let (rest, dur) = offset_modifier(" OFFSET 1m30ms").unwrap();
        assert!(rest.is_empty());
        assert_eq!(dur.as_millis(), 60 * 1000 + 30);
    }

    #[test]
    fn test_vector_selector_with_offset() {
        let (rest, sel) = vector_selector("foo offset 5m").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("foo".to_string()));
        assert_eq!(sel.offset.unwrap().as_millis(), 5 * 60 * 1000);
    }

    #[test]
    fn test_vector_selector_with_negative_offset() {
        let (rest, sel) = vector_selector("foo offset -7m").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("foo".to_string()));
        assert_eq!(sel.offset.unwrap().as_millis(), -7 * 60 * 1000);
    }

    #[test]
    fn test_vector_selector_with_labels_and_offset() {
        let (rest, sel) = vector_selector(r#"foo{bar="baz"} offset 1h"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("foo".to_string()));
        assert_eq!(sel.matchers.len(), 1);
        assert_eq!(sel.offset.unwrap().as_millis(), 60 * 60 * 1000);
    }

    #[test]
    fn test_vector_selector_display_with_offset() {
        let mut sel = VectorSelector::new("foo");
        sel.offset = Some(Duration::from_secs(300));
        assert_eq!(sel.to_string(), "foo offset 5m");
    }

    #[test]
    fn test_matrix_selector_with_offset() {
        let (rest, sel) = matrix_selector("foo[5m] offset 1h").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name(), Some("foo"));
        assert_eq!(sel.range_millis(), 5 * 60 * 1000);
        assert_eq!(sel.offset_millis(), Some(60 * 60 * 1000));
    }

    #[test]
    fn test_matrix_selector_with_labels_and_offset() {
        let (rest, sel) = matrix_selector(r#"foo{bar="baz"}[5m] offset 30m"#).unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name(), Some("foo"));
        assert_eq!(sel.matchers().len(), 1);
        assert_eq!(sel.range_millis(), 5 * 60 * 1000);
        assert_eq!(sel.offset_millis(), Some(30 * 60 * 1000));
    }

    #[test]
    fn test_matrix_selector_with_negative_offset() {
        let (rest, sel) = matrix_selector("foo[5m] offset -1h").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.offset_millis(), Some(-60 * 60 * 1000));
    }

    #[test]
    fn test_matrix_selector_display_with_offset() {
        let mut vs = VectorSelector::new("foo");
        vs.offset = Some(Duration::from_secs(3600));
        let sel = MatrixSelector::new(vs, Duration::from_secs(300));
        assert_eq!(sel.to_string(), "foo[5m] offset 1h");
    }

    // @ modifier tests
    #[test]
    fn test_at_modifier_timestamp() {
        let (rest, at) = at_modifier(" @ 1603774568").unwrap();
        assert!(rest.is_empty());
        assert_eq!(at, AtModifier::Timestamp(1_603_774_568_000));
    }

    #[test]
    fn test_at_modifier_negative_timestamp() {
        let (rest, at) = at_modifier(" @ -100").unwrap();
        assert!(rest.is_empty());
        assert_eq!(at, AtModifier::Timestamp(-100_000));
    }

    #[test]
    fn test_at_modifier_float_timestamp() {
        let (rest, at) = at_modifier(" @ 3.33").unwrap();
        assert!(rest.is_empty());
        assert_eq!(at, AtModifier::Timestamp(3_330));
    }

    #[test]
    fn test_at_modifier_start() {
        let (rest, at) = at_modifier(" @ start()").unwrap();
        assert!(rest.is_empty());
        assert_eq!(at, AtModifier::Start);
    }

    #[test]
    fn test_at_modifier_end() {
        let (rest, at) = at_modifier(" @ end()").unwrap();
        assert!(rest.is_empty());
        assert_eq!(at, AtModifier::End);
    }

    #[test]
    fn test_at_modifier_display_timestamp() {
        let at = AtModifier::Timestamp(1_603_774_568_000);
        assert_eq!(at.to_string(), "@ 1603774568.000");
    }

    #[test]
    fn test_at_modifier_display_start() {
        assert_eq!(AtModifier::Start.to_string(), "@ start()");
    }

    #[test]
    fn test_at_modifier_display_end() {
        assert_eq!(AtModifier::End.to_string(), "@ end()");
    }

    #[test]
    fn test_vector_selector_with_at() {
        let (rest, sel) = vector_selector("foo @ 1603774568").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.name, Some("foo".to_string()));
        assert_eq!(sel.at, Some(AtModifier::Timestamp(1_603_774_568_000)));
    }

    #[test]
    fn test_vector_selector_with_at_start() {
        let (rest, sel) = vector_selector("foo @ start()").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.at, Some(AtModifier::Start));
    }

    #[test]
    fn test_vector_selector_with_at_and_offset() {
        // @ before offset
        let (rest, sel) = vector_selector("foo @ 123 offset 5m").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.at, Some(AtModifier::Timestamp(123_000)));
        assert_eq!(sel.offset.unwrap().as_millis(), 5 * 60 * 1000);
    }

    #[test]
    fn test_vector_selector_with_offset_and_at() {
        // offset before @
        let (rest, sel) = vector_selector("foo offset 5m @ 123").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.at, Some(AtModifier::Timestamp(123_000)));
        assert_eq!(sel.offset.unwrap().as_millis(), 5 * 60 * 1000);
    }

    #[test]
    fn test_vector_selector_display_with_at() {
        let mut sel = VectorSelector::new("foo");
        sel.at = Some(AtModifier::Timestamp(123_000));
        assert_eq!(sel.to_string(), "foo @ 123.000");
    }

    #[test]
    fn test_vector_selector_display_with_at_and_offset() {
        let mut sel = VectorSelector::new("foo");
        sel.at = Some(AtModifier::Start);
        sel.offset = Some(Duration::from_secs(300));
        assert_eq!(sel.to_string(), "foo @ start() offset 5m");
    }

    #[test]
    fn test_matrix_selector_with_at() {
        let (rest, sel) = matrix_selector("foo[5m] @ 123").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.at(), Some(&AtModifier::Timestamp(123_000)));
    }

    #[test]
    fn test_matrix_selector_with_at_and_offset() {
        let (rest, sel) = matrix_selector("foo[5m] @ 123 offset 1h").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.at(), Some(&AtModifier::Timestamp(123_000)));
        assert_eq!(sel.offset_millis(), Some(60 * 60 * 1000));
    }

    #[test]
    fn test_matrix_selector_with_offset_and_at() {
        let (rest, sel) = matrix_selector("foo[5m] offset 1h @ 123").unwrap();
        assert!(rest.is_empty());
        assert_eq!(sel.at(), Some(&AtModifier::Timestamp(123_000)));
        assert_eq!(sel.offset_millis(), Some(60 * 60 * 1000));
    }

    #[test]
    fn test_matrix_selector_display_with_at() {
        let mut vs = VectorSelector::new("foo");
        vs.at = Some(AtModifier::Start);
        let sel = MatrixSelector::new(vs, Duration::from_secs(300));
        assert_eq!(sel.to_string(), "foo[5m] @ start()");
    }

    #[test]
    fn test_matrix_selector_display_with_at_and_offset() {
        let mut vs = VectorSelector::new("foo");
        vs.at = Some(AtModifier::Start);
        vs.offset = Some(Duration::from_secs(60));
        let sel = MatrixSelector::new(vs, Duration::from_secs(300));
        assert_eq!(sel.to_string(), "foo[5m] @ start() offset 1m");
    }
}