logdive-core 0.1.0

Core library for logdive: structured JSON log parsing, SQLite indexing, and query engine
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
//! Query language: tokenizer, AST, and recursive descent parser.
//!
//! Implements the grammar from the project doc's "Notes → Query language
//! grammar (v1)" section verbatim. AND-only per the 2026-04-19 decisions
//! log entry — OR is deferred to v2.
//!
//! This module owns *only* the parse step: `&str → QueryNode`. Translating
//! a `QueryNode` into SQL and binding parameters is milestone 4's executor.
//! Resolving relative time ranges like `last 2h` against wall-clock time
//! is also the executor's job; the AST just carries the raw spec.
//!
//! # Grammar (from the doc, reproduced for reference)
//!
//! ```text
//! query     := clause (AND clause)*
//! clause    := field OP value
//!            | field CONTAINS string
//!            | TIME_RANGE
//! field     := [a-zA-Z_][a-zA-Z0-9_.]*
//! OP        := "=" | "!=" | ">" | "<"
//! value     := string | number | bool
//! string    := '"' .* '"' | bare_word
//! TIME_RANGE := "last" duration | "since" datetime
//! duration  := number ("m" | "h" | "d")
//! ```

use std::fmt;

// ---------------------------------------------------------------------------
// AST
// ---------------------------------------------------------------------------

/// The top-level query: one or more clauses joined by AND.
///
/// A query with a single clause parses as `And(vec![clause])` so the
/// executor has exactly one code path.
#[derive(Debug, Clone, PartialEq)]
pub enum QueryNode {
    And(Vec<Clause>),
}

/// A single clause — the atomic unit a query is built from.
#[derive(Debug, Clone, PartialEq)]
pub enum Clause {
    /// `field OP value` — e.g. `level = error`, `req_id > 100`.
    Compare {
        field: String,
        op: CompareOp,
        value: QueryValue,
    },
    /// `field CONTAINS string` — substring match on a string column.
    Contains { field: String, value: String },
    /// `last <N><unit>` — relative time range ending at query time.
    LastDuration(Duration),
    /// `since <datetime>` — absolute time range starting at the given moment.
    /// The string is opaque at the parse layer; the executor uses chrono to
    /// resolve it (which allows us to accept multiple formats without
    /// teaching the grammar about any particular one).
    SinceDatetime(String),
}

/// Comparison operator for `field OP value` clauses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompareOp {
    Eq,
    NotEq,
    Gt,
    Lt,
}

impl fmt::Display for CompareOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            CompareOp::Eq => "=",
            CompareOp::NotEq => "!=",
            CompareOp::Gt => ">",
            CompareOp::Lt => "<",
        })
    }
}

/// A literal value appearing on the right-hand side of a comparison.
///
/// The type distinction matters because milestone 4's executor binds
/// numbers and booleans with their native SQLite types so numeric
/// comparison (`req_id > 100`) uses proper ordering rather than lexical.
#[derive(Debug, Clone, PartialEq)]
pub enum QueryValue {
    String(String),
    Integer(i64),
    Float(f64),
    Bool(bool),
}

/// A relative duration parsed from `last <N><unit>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Duration {
    pub amount: u64,
    pub unit: DurationUnit,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DurationUnit {
    Minutes,
    Hours,
    Days,
}

impl DurationUnit {
    /// Total seconds for one unit. The executor multiplies by `amount` to
    /// compute the cutoff timestamp against `now`.
    pub fn seconds(self) -> i64 {
        match self {
            DurationUnit::Minutes => 60,
            DurationUnit::Hours => 60 * 60,
            DurationUnit::Days => 24 * 60 * 60,
        }
    }
}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Parse error with a byte offset into the original input.
///
/// Byte offsets (rather than line/column) are sufficient because queries
/// are single-line. The CLI's milestone 7 pretty printer can slice the
/// original input around `position` to render a caret.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QueryParseError {
    pub position: usize,
    pub message: String,
}

impl fmt::Display for QueryParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "query parse error at position {}: {}",
            self.position, self.message
        )
    }
}

impl std::error::Error for QueryParseError {}

// ---------------------------------------------------------------------------
// Tokens
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
enum Token {
    /// A bare identifier — could be a field name, a bare-word value, or a
    /// keyword depending on position. We resolve keywords at parse time
    /// rather than at tokenization time because "last" used as a field name
    /// (in the unlikely event a log has a field literally called "last")
    /// should still work in `CONTAINS` contexts.
    Ident(String),
    /// A double-quoted string, with the quotes stripped.
    QuotedString(String),
    /// A literal number — stored as text so the parser can decide whether
    /// it's an integer or float.
    Number(String),
    Eq,
    NotEq,
    Gt,
    Lt,
}

#[derive(Debug, Clone)]
struct SpannedToken {
    token: Token,
    position: usize,
}

// ---------------------------------------------------------------------------
// Tokenizer
// ---------------------------------------------------------------------------

/// Return true if `b` is allowed *inside* an identifier (but not necessarily
/// as the first byte). Matches the grammar's field rule plus the extra
/// characters needed for bare-word values and datetime literals: `-` for
/// hyphenated values like `x-request-id`, `:` for colon-separated values
/// like time components, and `.` for both dotted field names and float-like
/// version strings in values.
fn is_ident_continuation(b: u8) -> bool {
    b == b'_' || b == b'.' || b == b'-' || b == b':' || b.is_ascii_alphanumeric()
}

/// Split the input into a stream of tokens with byte-offset positions.
///
/// Whitespace is skipped. Unrecognized bytes produce a `QueryParseError`
/// pointing at the offending character.
fn tokenize(input: &str) -> Result<Vec<SpannedToken>, QueryParseError> {
    let bytes = input.as_bytes();
    let mut i = 0;
    let mut out = Vec::new();

    while i < bytes.len() {
        let c = bytes[i];

        // Whitespace.
        if c.is_ascii_whitespace() {
            i += 1;
            continue;
        }

        // Operators — order matters: check `!=` before `!` would-be, and
        // both before single `<`/`>`/`=`.
        if c == b'!' {
            if i + 1 < bytes.len() && bytes[i + 1] == b'=' {
                out.push(SpannedToken {
                    token: Token::NotEq,
                    position: i,
                });
                i += 2;
                continue;
            }
            return Err(QueryParseError {
                position: i,
                message: "unexpected '!' — did you mean '!='?".to_string(),
            });
        }
        if c == b'=' {
            out.push(SpannedToken {
                token: Token::Eq,
                position: i,
            });
            i += 1;
            continue;
        }
        if c == b'>' {
            out.push(SpannedToken {
                token: Token::Gt,
                position: i,
            });
            i += 1;
            continue;
        }
        if c == b'<' {
            out.push(SpannedToken {
                token: Token::Lt,
                position: i,
            });
            i += 1;
            continue;
        }

        // Quoted string.
        if c == b'"' {
            let start = i;
            i += 1; // consume opening quote
            let content_start = i;
            while i < bytes.len() && bytes[i] != b'"' {
                // No escape handling in v1 — the grammar is `'"' .* '"'`
                // and real log-query users don't embed quotes in values.
                // If this becomes a pain we add escape handling in v2.
                i += 1;
            }
            if i >= bytes.len() {
                return Err(QueryParseError {
                    position: start,
                    message: "unterminated quoted string".to_string(),
                });
            }
            let s = std::str::from_utf8(&bytes[content_start..i])
                .expect("input is &str, slice is UTF-8")
                .to_string();
            i += 1; // consume closing quote
            out.push(SpannedToken {
                token: Token::QuotedString(s),
                position: start,
            });
            continue;
        }

        // Digit-led token.
        //
        // Two possibilities:
        //  - Pure-digit run (with optional fractional part) → Token::Number.
        //    Example: `100`, `1.5`.
        //  - Digit-led run that contains `-` or `:` → Token::Ident. This
        //    supports bare datetime literals like `2024-01-01T10:00:00Z`
        //    after `since`, per the 2026-04-22 decision to let bare dates
        //    tokenize as identifiers. Colon is included for completeness
        //    so time-of-day literals don't need quoting either.
        //
        // The disambiguation happens at the first non-digit, non-dot byte:
        // if that byte is `-` or `:`, we promote the whole run (and keep
        // consuming continuation bytes) to an Ident. Otherwise we stop at
        // the end of the numeric run and emit a Number.
        if c.is_ascii_digit() {
            let start = i;
            let mut saw_dot = false;

            // First phase: consume digits and at most one dot (only when
            // the dot is followed by a digit, preserving the existing
            // `1.5` behaviour). We peek at the next byte after each dot
            // to decide.
            while i < bytes.len() && (bytes[i].is_ascii_digit() || (bytes[i] == b'.' && !saw_dot)) {
                if bytes[i] == b'.' {
                    if i + 1 >= bytes.len() || !bytes[i + 1].is_ascii_digit() {
                        break;
                    }
                    saw_dot = true;
                }
                i += 1;
            }

            // Second phase: if the next byte indicates this digit-led run
            // is actually an ident (datetime, dotted version string,
            // alphanumeric suffix, etc.), keep consuming all ident-
            // continuation bytes and emit an Ident.
            //
            // Promotion triggers:
            //   `-` or `:` — datetime literals (`2024-01-01`, `10:30`)
            //   `.`        — dotted strings beyond one fractional part
            //                (`1.2.3`, which can't be a valid Number)
            //   letter     — alphanumeric suffixes (`3beta`, `v1rc2`)
            //
            // Note: the first phase stops at a *second* dot because the
            // `!saw_dot` guard fires, leaving `bytes[i]` on that second
            // dot — hence `.` being a valid trigger here.
            // Second phase: if the next byte indicates this digit-led run
            // is actually an ident (datetime, multi-dot version string),
            // keep consuming all ident-continuation bytes and emit Ident.
            //
            // Promotion triggers:
            //   `-` or `:` — datetime literals (`2024-01-01`, `10:30`)
            //   `.`        — dotted strings beyond one fractional part
            //                (`1.2.3`); the first phase stops at the
            //                second dot due to its `!saw_dot` guard,
            //                leaving `bytes[i]` on that second dot.
            //
            // Letters are intentionally NOT a promotion trigger: `30m`
            // must tokenize as Number("30") + Ident("m") so the parser's
            // `last <N><unit>` rule works. Users who want digit-led
            // values with letter suffixes (`3beta`) must quote them.
            if i < bytes.len() && (bytes[i] == b'-' || bytes[i] == b':' || bytes[i] == b'.') {
                while i < bytes.len() && is_ident_continuation(bytes[i]) {
                    i += 1;
                }
                let s = std::str::from_utf8(&bytes[start..i])
                    .expect("input is &str, slice is UTF-8")
                    .to_string();
                out.push(SpannedToken {
                    token: Token::Ident(s),
                    position: start,
                });
                continue;
            }

            let s = std::str::from_utf8(&bytes[start..i])
                .expect("ascii digits are UTF-8")
                .to_string();
            out.push(SpannedToken {
                token: Token::Number(s),
                position: start,
            });
            continue;
        }

        // Identifier / bare word: starts with letter or underscore,
        // continues per `is_ident_continuation`. Hyphen and colon are
        // allowed inside so bare-word values like `x-request-id` and
        // colon-separated fragments work; `validate_field_name` later
        // enforces the stricter field-name subset.
        if c == b'_' || c.is_ascii_alphabetic() {
            let start = i;
            while i < bytes.len() && is_ident_continuation(bytes[i]) {
                i += 1;
            }
            let s = std::str::from_utf8(&bytes[start..i])
                .expect("input is &str, slice is UTF-8")
                .to_string();
            out.push(SpannedToken {
                token: Token::Ident(s),
                position: start,
            });
            continue;
        }

        return Err(QueryParseError {
            position: i,
            message: format!("unexpected character {:?}", c as char),
        });
    }

    Ok(out)
}

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

/// Parse a query string into a `QueryNode`.
///
/// This is the only public entry point. Implements the grammar from the
/// project doc top-down via recursive descent, with AND chaining at the
/// outermost level.
pub fn parse(input: &str) -> Result<QueryNode, QueryParseError> {
    let tokens = tokenize(input)?;
    if tokens.is_empty() {
        return Err(QueryParseError {
            position: 0,
            message: "empty query".to_string(),
        });
    }

    let mut p = Parser {
        tokens: &tokens,
        cursor: 0,
    };
    let mut clauses = Vec::new();
    clauses.push(p.parse_clause()?);

    while let Some(tok) = p.peek() {
        // AND is a keyword stored as an Ident. Case-insensitive.
        match &tok.token {
            Token::Ident(s) if s.eq_ignore_ascii_case("and") => {
                p.advance();
                clauses.push(p.parse_clause()?);
            }
            Token::Ident(s) if s.eq_ignore_ascii_case("or") => {
                // Specific, actionable error per the doc's emphasis on good messages.
                return Err(QueryParseError {
                    position: tok.position,
                    message: "OR is not supported in v1; only AND. See project doc decisions log."
                        .to_string(),
                });
            }
            _ => {
                return Err(QueryParseError {
                    position: tok.position,
                    message: "expected 'AND' between clauses".to_string(),
                });
            }
        }
    }

    Ok(QueryNode::And(clauses))
}

struct Parser<'a> {
    tokens: &'a [SpannedToken],
    cursor: usize,
}

impl<'a> Parser<'a> {
    fn peek(&self) -> Option<&'a SpannedToken> {
        self.tokens.get(self.cursor)
    }

    fn advance(&mut self) -> Option<&'a SpannedToken> {
        let t = self.tokens.get(self.cursor);
        if t.is_some() {
            self.cursor += 1;
        }
        t
    }

    /// Position to attribute to an error when the tokens are exhausted.
    fn end_position(&self) -> usize {
        self.tokens
            .last()
            .map(|t| t.position + token_len(&t.token))
            .unwrap_or(0)
    }

    fn parse_clause(&mut self) -> Result<Clause, QueryParseError> {
        let tok = self.peek().ok_or_else(|| QueryParseError {
            position: self.end_position(),
            message: "expected a clause, got end of input".to_string(),
        })?;

        // Time-range clauses are keyword-led.
        if let Token::Ident(s) = &tok.token {
            if s.eq_ignore_ascii_case("last") {
                self.advance();
                return self.parse_last_duration();
            }
            if s.eq_ignore_ascii_case("since") {
                self.advance();
                return self.parse_since_datetime();
            }
        }

        // Otherwise: field-led clause (compare or contains).
        self.parse_field_led_clause()
    }

    fn parse_last_duration(&mut self) -> Result<Clause, QueryParseError> {
        let num_tok = self.advance().ok_or_else(|| QueryParseError {
            position: self.end_position(),
            message: "expected a number after 'last'".to_string(),
        })?;
        let num_str = match &num_tok.token {
            Token::Number(s) => s,
            _ => {
                return Err(QueryParseError {
                    position: num_tok.position,
                    message: "expected a number after 'last'".to_string(),
                });
            }
        };
        if num_str.contains('.') {
            return Err(QueryParseError {
                position: num_tok.position,
                message: "duration amount must be a whole number".to_string(),
            });
        }
        let amount: u64 = num_str.parse().map_err(|_| QueryParseError {
            position: num_tok.position,
            message: format!("invalid duration amount {num_str:?}"),
        })?;

        let unit_tok = self.advance().ok_or_else(|| QueryParseError {
            position: self.end_position(),
            message: "expected a duration unit ('m', 'h', or 'd') after the number".to_string(),
        })?;
        let unit_str = match &unit_tok.token {
            Token::Ident(s) => s,
            _ => {
                return Err(QueryParseError {
                    position: unit_tok.position,
                    message: "expected a duration unit ('m', 'h', or 'd')".to_string(),
                });
            }
        };
        let unit = match unit_str.as_str() {
            "m" => DurationUnit::Minutes,
            "h" => DurationUnit::Hours,
            "d" => DurationUnit::Days,
            other => {
                return Err(QueryParseError {
                    position: unit_tok.position,
                    message: format!("unknown duration unit {other:?}, expected 'm', 'h', or 'd'"),
                });
            }
        };

        Ok(Clause::LastDuration(Duration { amount, unit }))
    }

    fn parse_since_datetime(&mut self) -> Result<Clause, QueryParseError> {
        let tok = self.advance().ok_or_else(|| QueryParseError {
            position: self.end_position(),
            message: "expected a datetime after 'since'".to_string(),
        })?;
        let dt = match &tok.token {
            Token::QuotedString(s) => s.clone(),
            Token::Ident(s) => s.clone(),
            Token::Number(s) => s.clone(),
            _ => {
                return Err(QueryParseError {
                    position: tok.position,
                    message: "expected a datetime after 'since'".to_string(),
                });
            }
        };
        Ok(Clause::SinceDatetime(dt))
    }

    fn parse_field_led_clause(&mut self) -> Result<Clause, QueryParseError> {
        let field_tok = self.advance().expect("caller peeked a token");
        let field = match &field_tok.token {
            Token::Ident(s) => s.clone(),
            _ => {
                return Err(QueryParseError {
                    position: field_tok.position,
                    message: "expected a field name".to_string(),
                });
            }
        };
        validate_field_name(&field, field_tok.position)?;

        let op_tok = self.advance().ok_or_else(|| QueryParseError {
            position: self.end_position(),
            message: "expected an operator after the field name".to_string(),
        })?;

        // CONTAINS is a keyword stored as Ident.
        if let Token::Ident(s) = &op_tok.token {
            if s.eq_ignore_ascii_case("contains") {
                let val_tok = self.advance().ok_or_else(|| QueryParseError {
                    position: self.end_position(),
                    message: "expected a string after 'contains'".to_string(),
                })?;
                let s = match &val_tok.token {
                    Token::QuotedString(s) => s.clone(),
                    Token::Ident(s) => s.clone(),
                    _ => {
                        return Err(QueryParseError {
                            position: val_tok.position,
                            message: "'contains' requires a string value".to_string(),
                        });
                    }
                };
                return Ok(Clause::Contains { field, value: s });
            }
        }

        let op = match &op_tok.token {
            Token::Eq => CompareOp::Eq,
            Token::NotEq => CompareOp::NotEq,
            Token::Gt => CompareOp::Gt,
            Token::Lt => CompareOp::Lt,
            _ => {
                return Err(QueryParseError {
                    position: op_tok.position,
                    message: "expected one of =, !=, >, <, or 'contains'".to_string(),
                });
            }
        };

        let val_tok = self.advance().ok_or_else(|| QueryParseError {
            position: self.end_position(),
            message: "expected a value after the operator".to_string(),
        })?;
        let value = token_to_query_value(val_tok)?;

        Ok(Clause::Compare { field, op, value })
    }
}

/// Enforce the grammar's field regex: `[a-zA-Z_][a-zA-Z0-9_.]*`.
///
/// The tokenizer is more permissive (it allows `-` and `:` inside idents
/// so that bare-word *values* like `x-request-id` and datetime literals
/// tokenize cleanly). We re-validate here because a field name is a
/// stricter subset.
fn validate_field_name(s: &str, position: usize) -> Result<(), QueryParseError> {
    let mut chars = s.chars();
    let first = chars.next().ok_or_else(|| QueryParseError {
        position,
        message: "empty field name".to_string(),
    })?;
    if !(first.is_ascii_alphabetic() || first == '_') {
        return Err(QueryParseError {
            position,
            message: format!("invalid field name {s:?}: must start with a letter or underscore"),
        });
    }
    for c in chars {
        if !(c.is_ascii_alphanumeric() || c == '_' || c == '.') {
            return Err(QueryParseError {
                position,
                message: format!(
                    "invalid field name {s:?}: only letters, digits, underscores, and dots are allowed"
                ),
            });
        }
    }
    Ok(())
}

fn token_to_query_value(tok: &SpannedToken) -> Result<QueryValue, QueryParseError> {
    match &tok.token {
        Token::QuotedString(s) => Ok(QueryValue::String(s.clone())),
        Token::Number(s) => {
            if s.contains('.') {
                let f: f64 = s.parse().map_err(|_| QueryParseError {
                    position: tok.position,
                    message: format!("invalid number {s:?}"),
                })?;
                Ok(QueryValue::Float(f))
            } else {
                let n: i64 = s.parse().map_err(|_| QueryParseError {
                    position: tok.position,
                    message: format!("invalid integer {s:?}"),
                })?;
                Ok(QueryValue::Integer(n))
            }
        }
        Token::Ident(s) => {
            // Booleans as bare words.
            if s.eq_ignore_ascii_case("true") {
                Ok(QueryValue::Bool(true))
            } else if s.eq_ignore_ascii_case("false") {
                Ok(QueryValue::Bool(false))
            } else {
                Ok(QueryValue::String(s.clone()))
            }
        }
        _ => Err(QueryParseError {
            position: tok.position,
            message: "expected a value (string, number, or boolean)".to_string(),
        }),
    }
}

fn token_len(t: &Token) -> usize {
    match t {
        Token::Ident(s) | Token::Number(s) => s.len(),
        Token::QuotedString(s) => s.len() + 2, // approximate, for error positioning only
        Token::Eq | Token::Gt | Token::Lt => 1,
        Token::NotEq => 2,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn and_of(clauses: Vec<Clause>) -> QueryNode {
        QueryNode::And(clauses)
    }

    fn cmp(field: &str, op: CompareOp, value: QueryValue) -> Clause {
        Clause::Compare {
            field: field.to_string(),
            op,
            value,
        }
    }

    // --- Each operator parses correctly ---

    #[test]
    fn eq_operator() {
        assert_eq!(
            parse("level=error").unwrap(),
            and_of(vec![cmp(
                "level",
                CompareOp::Eq,
                QueryValue::String("error".into())
            )])
        );
    }

    #[test]
    fn not_eq_operator() {
        assert_eq!(
            parse("level!=info").unwrap(),
            and_of(vec![cmp(
                "level",
                CompareOp::NotEq,
                QueryValue::String("info".into())
            )])
        );
    }

    #[test]
    fn gt_operator_with_integer() {
        assert_eq!(
            parse("req_id > 100").unwrap(),
            and_of(vec![cmp("req_id", CompareOp::Gt, QueryValue::Integer(100))])
        );
    }

    #[test]
    fn lt_operator_with_float() {
        assert_eq!(
            parse("duration < 1.5").unwrap(),
            and_of(vec![cmp("duration", CompareOp::Lt, QueryValue::Float(1.5))])
        );
    }

    #[test]
    fn contains_operator_with_quoted_string() {
        assert_eq!(
            parse(r#"message contains "database timeout""#).unwrap(),
            and_of(vec![Clause::Contains {
                field: "message".into(),
                value: "database timeout".into(),
            }])
        );
    }

    #[test]
    fn contains_operator_with_bare_word() {
        assert_eq!(
            parse("message contains timeout").unwrap(),
            and_of(vec![Clause::Contains {
                field: "message".into(),
                value: "timeout".into(),
            }])
        );
    }

    #[test]
    fn contains_is_case_insensitive() {
        assert_eq!(
            parse("message CONTAINS boom").unwrap(),
            and_of(vec![Clause::Contains {
                field: "message".into(),
                value: "boom".into(),
            }])
        );
    }

    #[test]
    fn boolean_value() {
        assert_eq!(
            parse("ok=true").unwrap(),
            and_of(vec![cmp("ok", CompareOp::Eq, QueryValue::Bool(true))])
        );
        assert_eq!(
            parse("ok=FALSE").unwrap(),
            and_of(vec![cmp("ok", CompareOp::Eq, QueryValue::Bool(false))])
        );
    }

    #[test]
    fn quoted_string_value_preserves_spaces() {
        assert_eq!(
            parse(r#"service="payments gateway""#).unwrap(),
            and_of(vec![cmp(
                "service",
                CompareOp::Eq,
                QueryValue::String("payments gateway".into())
            )])
        );
    }

    #[test]
    fn dotted_field_name_for_nested_json() {
        assert_eq!(
            parse("user.id=42").unwrap(),
            and_of(vec![cmp("user.id", CompareOp::Eq, QueryValue::Integer(42))])
        );
    }

    // --- Time ranges ---

    #[test]
    fn last_minutes() {
        assert_eq!(
            parse("last 30m").unwrap(),
            and_of(vec![Clause::LastDuration(Duration {
                amount: 30,
                unit: DurationUnit::Minutes
            })])
        );
    }

    #[test]
    fn last_hours() {
        assert_eq!(
            parse("last 2h").unwrap(),
            and_of(vec![Clause::LastDuration(Duration {
                amount: 2,
                unit: DurationUnit::Hours
            })])
        );
    }

    #[test]
    fn last_days() {
        assert_eq!(
            parse("last 7d").unwrap(),
            and_of(vec![Clause::LastDuration(Duration {
                amount: 7,
                unit: DurationUnit::Days
            })])
        );
    }

    #[test]
    fn since_datetime_is_opaque_string() {
        assert_eq!(
            parse("since 2024-01-01").unwrap(),
            and_of(vec![Clause::SinceDatetime("2024-01-01".into())])
        );
    }

    #[test]
    fn since_datetime_can_be_quoted() {
        assert_eq!(
            parse(r#"since "2024-01-01T10:00:00Z""#).unwrap(),
            and_of(vec![Clause::SinceDatetime("2024-01-01T10:00:00Z".into())])
        );
    }

    #[test]
    fn since_datetime_bare_with_time_component_parses() {
        // Regression: digit-led tokens containing `-` or `:` must tokenize
        // as Ident, not blow up mid-number.
        assert_eq!(
            parse("since 2024-01-01T10:00:00Z").unwrap(),
            and_of(vec![Clause::SinceDatetime("2024-01-01T10:00:00Z".into())])
        );
    }

    #[test]
    fn since_datetime_bare_followed_by_and_clause() {
        // The datetime must terminate at whitespace so the AND chain still works.
        assert_eq!(
            parse("since 2024-01-01 AND level=error").unwrap(),
            and_of(vec![
                Clause::SinceDatetime("2024-01-01".into()),
                cmp("level", CompareOp::Eq, QueryValue::String("error".into())),
            ])
        );
    }

    // --- AND chaining ---

    #[test]
    fn two_clauses_with_and() {
        assert_eq!(
            parse("level=error AND service=payments").unwrap(),
            and_of(vec![
                cmp("level", CompareOp::Eq, QueryValue::String("error".into())),
                cmp(
                    "service",
                    CompareOp::Eq,
                    QueryValue::String("payments".into())
                ),
            ])
        );
    }

    #[test]
    fn and_is_case_insensitive() {
        assert_eq!(
            parse("level=error and service=payments").unwrap(),
            and_of(vec![
                cmp("level", CompareOp::Eq, QueryValue::String("error".into())),
                cmp(
                    "service",
                    CompareOp::Eq,
                    QueryValue::String("payments".into())
                ),
            ])
        );
    }

    #[test]
    fn three_clauses_with_time_range() {
        assert_eq!(
            parse("tag=api AND level=error AND last 30m").unwrap(),
            and_of(vec![
                cmp("tag", CompareOp::Eq, QueryValue::String("api".into())),
                cmp("level", CompareOp::Eq, QueryValue::String("error".into())),
                Clause::LastDuration(Duration {
                    amount: 30,
                    unit: DurationUnit::Minutes
                }),
            ])
        );
    }

    // --- Error cases: invalid input produces descriptive messages ---

    #[test]
    fn empty_query_is_an_error() {
        let err = parse("").unwrap_err();
        assert_eq!(err.position, 0);
        assert!(err.message.contains("empty"));
    }

    #[test]
    fn whitespace_only_query_is_an_error() {
        let err = parse("   ").unwrap_err();
        assert!(err.message.contains("empty"));
    }

    #[test]
    fn missing_value_after_operator() {
        let err = parse("level=").unwrap_err();
        assert!(err.message.contains("value"));
    }

    #[test]
    fn missing_operator_after_field() {
        let err = parse("level").unwrap_err();
        assert!(err.message.contains("operator"));
    }

    #[test]
    fn unknown_duration_unit_names_the_unit() {
        let err = parse("last 5y").unwrap_err();
        assert!(err.message.contains("unit"));
        assert!(err.message.contains("\"y\""));
    }

    #[test]
    fn fractional_duration_rejected() {
        let err = parse("last 1.5h").unwrap_err();
        assert!(err.message.contains("whole number"));
    }

    #[test]
    fn or_operator_suggests_v2_deferral() {
        let err = parse("level=error OR level=warn").unwrap_err();
        assert!(err.message.contains("OR"));
        assert!(err.message.contains("AND"));
    }

    #[test]
    fn bang_without_equals_is_actionable() {
        let err = parse("level!error").unwrap_err();
        assert!(err.message.contains("!="));
    }

    #[test]
    fn unterminated_quoted_string_points_at_opening_quote() {
        let input = r#"service="oops"#;
        let err = parse(input).unwrap_err();
        assert_eq!(err.position, input.find('"').unwrap());
        assert!(err.message.contains("unterminated"));
    }

    #[test]
    fn contains_with_number_is_rejected() {
        // The grammar says `field CONTAINS string` — a bare number is not a string.
        let err = parse("message contains 42").unwrap_err();
        assert!(err.message.contains("string"));
    }

    #[test]
    fn invalid_field_name_starting_with_digit() {
        // The tokenizer turns `3foo` into a Number followed by an Ident,
        // so the parser sees a number in field position and complains.
        let err = parse("3foo=x").unwrap_err();
        assert!(err.message.contains("field"));
    }

    #[test]
    fn missing_and_between_clauses_is_actionable() {
        let err = parse("level=error service=payments").unwrap_err();
        assert!(err.message.contains("AND"));
    }

    #[test]
    fn last_without_number() {
        let err = parse("last h").unwrap_err();
        assert!(err.message.contains("number"));
    }

    #[test]
    fn last_without_unit() {
        let err = parse("last 30").unwrap_err();
        assert!(err.message.contains("unit"));
    }

    // --- Sanity checks on tokenizer edge cases ---

    #[test]
    fn tokens_survive_around_operators_with_no_spaces() {
        assert_eq!(
            parse("level=error").unwrap(),
            parse("level = error").unwrap()
        );
        assert_eq!(parse("req_id!=5").unwrap(), parse("req_id != 5").unwrap());
    }

    #[test]
    fn hyphenated_bare_word_value_parses() {
        assert_eq!(
            parse("request_id=x-request-1").unwrap(),
            and_of(vec![cmp(
                "request_id",
                CompareOp::Eq,
                QueryValue::String("x-request-1".into())
            )])
        );
    }

    #[test]
    fn digit_led_value_with_hyphen_is_string_not_number() {
        // `version=1.2.3-beta` — regression guard: this should be a string
        // value, not a parse error from trying to be a number.
        assert_eq!(
            parse("version=1.2.3-beta").unwrap(),
            and_of(vec![cmp(
                "version",
                CompareOp::Eq,
                QueryValue::String("1.2.3-beta".into())
            )])
        );
    }

    #[test]
    fn dotted_version_string_is_not_a_number() {
        // `version=1.2.3` — more than one dot means it can't be a float.
        // Must tokenize as a single Ident/String, not a Number followed
        // by an unexpected `.`.
        assert_eq!(
            parse("version=1.2.3").unwrap(),
            and_of(vec![cmp(
                "version",
                CompareOp::Eq,
                QueryValue::String("1.2.3".into())
            )])
        );
    }

    #[test]
    fn pure_digit_run_is_still_a_number() {
        // Belt-and-braces: the digit-promotion logic must not accidentally
        // turn `100` into an Ident.
        match &parse("req_id=100").unwrap() {
            QueryNode::And(clauses) => match &clauses[0] {
                Clause::Compare {
                    value: QueryValue::Integer(n),
                    ..
                } => assert_eq!(*n, 100),
                other => panic!("expected Integer value, got {other:?}"),
            },
        }
    }
}