Skip to main content

squawk_parser/
lib.rs

1// via https://github.com/rust-lang/rust-analyzer/blob/d8887c0758bbd2d5f752d5bd405d4491e90e7ed6/crates/parser/src/lib.rs
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27use drop_bomb::DropBomb;
28use event::Event;
29use grammar::OPERATOR_FIRST;
30use std::cell::Cell;
31use token_set::TokenSet;
32mod event;
33mod generated;
34mod grammar;
35mod input;
36mod lexed_str;
37mod output;
38mod shortcuts;
39mod syntax_kind;
40mod token_set;
41
42pub use crate::{
43    lexed_str::LexedStr,
44    // output::{Output, Step},
45    shortcuts::StrStep,
46    syntax_kind::SyntaxKind,
47};
48
49use crate::input::Input;
50pub use crate::output::Output;
51
52/// See [`Parser::start`].
53pub(crate) struct Marker {
54    pos: u32,
55    bomb: DropBomb,
56}
57
58impl Marker {
59    fn new(pos: u32) -> Marker {
60        Marker {
61            pos,
62            bomb: DropBomb::new("Marker must be either completed or abandoned"),
63        }
64    }
65
66    /// Finishes the syntax tree node and assigns `kind` to it,
67    /// and mark the create a `CompletedMarker` for possible future
68    /// operation like `.precede()` to deal with `forward_parent`.
69    pub(crate) fn complete(mut self, p: &mut Parser<'_>, kind: SyntaxKind) -> CompletedMarker {
70        self.bomb.defuse();
71        let idx = self.pos as usize;
72        match &mut p.events[idx] {
73            Event::Start { kind: slot, .. } => {
74                *slot = kind;
75            }
76            _ => unreachable!(),
77        }
78        p.push_event(Event::Finish);
79        CompletedMarker::new(self.pos, kind)
80    }
81
82    /// Abandons the syntax tree node. All its children
83    /// are attached to its parent instead.
84    pub(crate) fn abandon(mut self, p: &mut Parser<'_>) {
85        self.bomb.defuse();
86        let idx = self.pos as usize;
87        if idx == p.events.len() - 1 {
88            match p.events.pop() {
89                Some(Event::Start {
90                    kind: SyntaxKind::TOMBSTONE,
91                    forward_parent: None,
92                }) => (),
93                _ => unreachable!(),
94            }
95        }
96    }
97}
98
99pub(crate) struct CompletedMarker {
100    pos: u32,
101    kind: SyntaxKind,
102}
103
104impl CompletedMarker {
105    fn new(pos: u32, kind: SyntaxKind) -> Self {
106        CompletedMarker { pos, kind }
107    }
108
109    /// This method allows to create a new node which starts
110    /// *before* the current one. That is, parser could start
111    /// node `A`, then complete it, and then after parsing the
112    /// whole `A`, decide that it should have started some node
113    /// `B` before starting `A`. `precede` allows to do exactly
114    /// that. See also docs about
115    /// [`Event::Start::forward_parent`](crate::event::Event::Start::forward_parent).
116    ///
117    /// Given completed events `[START, FINISH]` and its corresponding
118    /// `CompletedMarker(pos: 0, _)`.
119    /// Append a new `START` events as `[START, FINISH, NEWSTART]`,
120    /// then mark `NEWSTART` as `START`'s parent with saving its relative
121    /// distance to `NEWSTART` into `forward_parent`(=2 in this case);
122    pub(crate) fn precede(self, p: &mut Parser<'_>) -> Marker {
123        let new_pos = p.start();
124        let idx = self.pos as usize;
125        match &mut p.events[idx] {
126            Event::Start { forward_parent, .. } => {
127                *forward_parent = Some(new_pos.pos - self.pos);
128            }
129            _ => unreachable!(),
130        }
131        new_pos
132    }
133
134    /// Extends this completed marker *to the left* up to `m`.
135    pub(crate) fn extend_to(self, p: &mut Parser<'_>, mut m: Marker) -> CompletedMarker {
136        m.bomb.defuse();
137        let idx = m.pos as usize;
138        match &mut p.events[idx] {
139            Event::Start { forward_parent, .. } => {
140                *forward_parent = Some(self.pos - m.pos);
141            }
142            _ => unreachable!(),
143        }
144        self
145    }
146
147    pub(crate) fn kind(&self) -> SyntaxKind {
148        self.kind
149    }
150}
151
152pub fn parse(input: &Input) -> Output {
153    let mut p = Parser::new(input);
154    // 2. lex tokens to event vec via parser aka actually run the parser code,
155    // it calls the methods on the parser to create a vector of events
156    grammar::entry_point(&mut p);
157    let events = p.finish();
158    // 3. forward parents
159    event::process(events)
160}
161
162pub(crate) struct Parser<'t> {
163    inp: &'t Input,
164    pos: usize,
165    events: Vec<Event>,
166    steps: Cell<u32>,
167}
168
169const PARSER_STEP_LIMIT: usize = 15_000_000;
170
171enum TrivaBetween {
172    NotAllowed,
173    Allowed,
174}
175
176const OPERATOR_SIGN: TokenSet = TokenSet::new(&[SyntaxKind::PLUS, SyntaxKind::MINUS]);
177
178/// In order for an operator to end in `+` or `-`, it must contain one of the
179/// following chars:
180///
181/// ```sql
182/// ~ ! @ # % ^ & | ` ?
183/// ```
184///
185/// see: <https://www.postgresql.org/docs/18/sql-createoperator.html>
186const SPECIAL_OP_CHARS: TokenSet = TokenSet::new(&[
187    SyntaxKind::TILDE,
188    SyntaxKind::BANG,
189    SyntaxKind::AT,
190    SyntaxKind::POUND,
191    SyntaxKind::PERCENT,
192    SyntaxKind::CARET,
193    SyntaxKind::AMP,
194    SyntaxKind::PIPE,
195    SyntaxKind::BACKTICK,
196    SyntaxKind::QUESTION,
197]);
198
199impl<'t> Parser<'t> {
200    fn new(inp: &'t Input) -> Parser<'t> {
201        Parser {
202            inp,
203            pos: 0,
204            events: vec![],
205            steps: Cell::new(0),
206        }
207    }
208
209    /// Consume the next token if `kind` matches.
210    pub(crate) fn eat(&mut self, kind: SyntaxKind) -> bool {
211        if !self.at(kind) {
212            return false;
213        }
214        let n_raw_tokens = match kind {
215            SyntaxKind::COLON_EQ
216            | SyntaxKind::NEQ
217            | SyntaxKind::NEQB
218            | SyntaxKind::LTEQ
219            | SyntaxKind::FAT_ARROW
220            | SyntaxKind::GTEQ => 2,
221            SyntaxKind::SIMILAR_TO => {
222                let m = self.start();
223                self.bump(SyntaxKind::SIMILAR_KW);
224                self.bump(SyntaxKind::TO_KW);
225                m.complete(self, SyntaxKind::SIMILAR_TO);
226                return true;
227            }
228            SyntaxKind::AT_TIME_ZONE => {
229                let m = self.start();
230                self.bump(SyntaxKind::AT_KW);
231                self.bump(SyntaxKind::TIME_KW);
232                self.bump(SyntaxKind::ZONE_KW);
233                m.complete(self, SyntaxKind::AT_TIME_ZONE);
234                return true;
235            }
236            SyntaxKind::AT_LOCAL => {
237                let m = self.start();
238                self.bump(SyntaxKind::AT_KW);
239                self.bump(SyntaxKind::LOCAL_KW);
240                m.complete(self, SyntaxKind::AT_LOCAL);
241                return true;
242            }
243            SyntaxKind::IS_NOT_NORMALIZED => {
244                let m = self.start();
245                self.bump(SyntaxKind::IS_KW);
246                self.bump(SyntaxKind::NOT_KW);
247                if matches!(
248                    self.current(),
249                    SyntaxKind::NFC_KW
250                        | SyntaxKind::NFD_KW
251                        | SyntaxKind::NFKC_KW
252                        | SyntaxKind::NFKD_KW
253                ) {
254                    let fm = self.start();
255                    self.bump_any();
256                    fm.complete(self, SyntaxKind::UNICODE_NORMAL_FORM);
257                }
258                self.bump(SyntaxKind::NORMALIZED_KW);
259                m.complete(self, SyntaxKind::IS_NOT_NORMALIZED);
260                return true;
261            }
262            SyntaxKind::IS_NORMALIZED => {
263                let m = self.start();
264                self.bump(SyntaxKind::IS_KW);
265                if matches!(
266                    self.current(),
267                    SyntaxKind::NFC_KW
268                        | SyntaxKind::NFD_KW
269                        | SyntaxKind::NFKC_KW
270                        | SyntaxKind::NFKD_KW
271                ) {
272                    let fm = self.start();
273                    self.bump_any();
274                    fm.complete(self, SyntaxKind::UNICODE_NORMAL_FORM);
275                }
276                self.bump(SyntaxKind::NORMALIZED_KW);
277                m.complete(self, SyntaxKind::IS_NORMALIZED);
278                return true;
279            }
280            SyntaxKind::COLON_COLON => {
281                let m = self.start();
282                self.bump(SyntaxKind::COLON);
283                self.bump(SyntaxKind::COLON);
284                m.complete(self, SyntaxKind::COLON_COLON);
285                return true;
286            }
287            SyntaxKind::IS_JSON => {
288                let m = self.start();
289                self.bump(SyntaxKind::IS_KW);
290                self.bump(SyntaxKind::JSON_KW);
291                grammar::opt_json_keys_unique_clause(self);
292                m.complete(self, SyntaxKind::IS_JSON);
293                return true;
294            }
295            SyntaxKind::IS_NOT_JSON => {
296                let m = self.start();
297                self.bump(SyntaxKind::IS_KW);
298                self.bump(SyntaxKind::NOT_KW);
299                self.bump(SyntaxKind::JSON_KW);
300                grammar::opt_json_keys_unique_clause(self);
301                m.complete(self, SyntaxKind::IS_NOT_JSON);
302                return true;
303            }
304            SyntaxKind::IS_NOT_JSON_OBJECT => {
305                let m = self.start();
306                self.bump(SyntaxKind::IS_KW);
307                self.bump(SyntaxKind::NOT_KW);
308                self.bump(SyntaxKind::JSON_KW);
309                self.bump(SyntaxKind::OBJECT_KW);
310                grammar::opt_json_keys_unique_clause(self);
311                m.complete(self, SyntaxKind::IS_NOT_JSON_OBJECT);
312                return true;
313            }
314            SyntaxKind::IS_NOT_JSON_ARRAY => {
315                let m = self.start();
316                self.bump(SyntaxKind::IS_KW);
317                self.bump(SyntaxKind::NOT_KW);
318                self.bump(SyntaxKind::JSON_KW);
319                self.bump(SyntaxKind::ARRAY_KW);
320                grammar::opt_json_keys_unique_clause(self);
321                m.complete(self, SyntaxKind::IS_NOT_JSON_ARRAY);
322                return true;
323            }
324            SyntaxKind::IS_NOT_JSON_VALUE => {
325                let m = self.start();
326                self.bump(SyntaxKind::IS_KW);
327                self.bump(SyntaxKind::NOT_KW);
328                self.bump(SyntaxKind::JSON_KW);
329                self.bump(SyntaxKind::VALUE_KW);
330                grammar::opt_json_keys_unique_clause(self);
331                m.complete(self, SyntaxKind::IS_NOT_JSON_VALUE);
332                return true;
333            }
334            SyntaxKind::IS_NOT_JSON_SCALAR => {
335                let m = self.start();
336                self.bump(SyntaxKind::IS_KW);
337                self.bump(SyntaxKind::NOT_KW);
338                self.bump(SyntaxKind::JSON_KW);
339                self.bump(SyntaxKind::SCALAR_KW);
340                grammar::opt_json_keys_unique_clause(self);
341                m.complete(self, SyntaxKind::IS_NOT_JSON_SCALAR);
342                return true;
343            }
344            SyntaxKind::IS_JSON_OBJECT => {
345                let m = self.start();
346                self.bump(SyntaxKind::IS_KW);
347                self.bump(SyntaxKind::JSON_KW);
348                self.bump(SyntaxKind::OBJECT_KW);
349                grammar::opt_json_keys_unique_clause(self);
350                m.complete(self, SyntaxKind::IS_JSON_OBJECT);
351                return true;
352            }
353            SyntaxKind::IS_JSON_ARRAY => {
354                let m = self.start();
355                self.bump(SyntaxKind::IS_KW);
356                self.bump(SyntaxKind::JSON_KW);
357                self.bump(SyntaxKind::ARRAY_KW);
358                grammar::opt_json_keys_unique_clause(self);
359                m.complete(self, SyntaxKind::IS_JSON_ARRAY);
360                return true;
361            }
362            SyntaxKind::IS_JSON_VALUE => {
363                let m = self.start();
364                self.bump(SyntaxKind::IS_KW);
365                self.bump(SyntaxKind::JSON_KW);
366                self.bump(SyntaxKind::VALUE_KW);
367                grammar::opt_json_keys_unique_clause(self);
368                m.complete(self, SyntaxKind::IS_JSON_VALUE);
369                return true;
370            }
371            SyntaxKind::IS_JSON_SCALAR => {
372                let m = self.start();
373                self.bump(SyntaxKind::IS_KW);
374                self.bump(SyntaxKind::JSON_KW);
375                self.bump(SyntaxKind::SCALAR_KW);
376                grammar::opt_json_keys_unique_clause(self);
377                m.complete(self, SyntaxKind::IS_JSON_SCALAR);
378                return true;
379            }
380            SyntaxKind::NOT_SIMILAR_TO => {
381                let m = self.start();
382                self.bump(SyntaxKind::NOT_KW);
383                self.bump(SyntaxKind::SIMILAR_KW);
384                self.bump(SyntaxKind::TO_KW);
385                m.complete(self, SyntaxKind::NOT_SIMILAR_TO);
386                return true;
387            }
388            SyntaxKind::IS_NOT_DISTINCT_FROM => {
389                let m = self.start();
390                self.bump(SyntaxKind::IS_KW);
391                self.bump(SyntaxKind::NOT_KW);
392                self.bump(SyntaxKind::DISTINCT_KW);
393                self.bump(SyntaxKind::FROM_KW);
394                m.complete(self, SyntaxKind::IS_NOT_DISTINCT_FROM);
395                return true;
396            }
397            SyntaxKind::OPERATOR_CALL => {
398                let m = self.start();
399                self.bump(SyntaxKind::OPERATOR_KW);
400                self.bump(SyntaxKind::L_PAREN);
401
402                // e.g. `+`, `pg_catalog.+`, `db.pg_catalog.+`
403                grammar::qual_op(self);
404
405                self.expect(SyntaxKind::R_PAREN);
406                m.complete(self, SyntaxKind::OPERATOR_CALL);
407                return true;
408            }
409            SyntaxKind::IS_DISTINCT_FROM => {
410                let m = self.start();
411                self.bump(SyntaxKind::IS_KW);
412                self.bump(SyntaxKind::DISTINCT_KW);
413                self.bump(SyntaxKind::FROM_KW);
414                m.complete(self, SyntaxKind::IS_DISTINCT_FROM);
415                return true;
416            }
417            SyntaxKind::NOT_LIKE => {
418                let m = self.start();
419                self.bump(SyntaxKind::NOT_KW);
420                self.bump(SyntaxKind::LIKE_KW);
421                m.complete(self, SyntaxKind::NOT_LIKE);
422                return true;
423            }
424            SyntaxKind::NOT_ILIKE => {
425                let m = self.start();
426                self.bump(SyntaxKind::NOT_KW);
427                self.bump(SyntaxKind::ILIKE_KW);
428                m.complete(self, SyntaxKind::NOT_ILIKE);
429                return true;
430            }
431            SyntaxKind::NOT_IN => {
432                let m = self.start();
433                self.bump(SyntaxKind::NOT_KW);
434                self.bump(SyntaxKind::IN_KW);
435                m.complete(self, SyntaxKind::NOT_IN);
436                return true;
437            }
438            SyntaxKind::IS_NOT => {
439                let m = self.start();
440                self.bump(SyntaxKind::IS_KW);
441                self.bump(SyntaxKind::NOT_KW);
442                m.complete(self, SyntaxKind::IS_NOT);
443                return true;
444            }
445            SyntaxKind::CUSTOM_OP => {
446                let m = self.start();
447                for _ in 0..self.op_len() {
448                    self.bump_any();
449                }
450                m.complete(self, SyntaxKind::CUSTOM_OP);
451                return true;
452            }
453            _ => 1,
454        };
455        self.do_bump(kind, n_raw_tokens);
456        true
457    }
458
459    fn at_composite2(&self, n: usize, k1: SyntaxKind, k2: SyntaxKind, triva: TrivaBetween) -> bool {
460        let tokens_match =
461            self.inp.kind(self.pos + n) == k1 && self.inp.kind(self.pos + n + 1) == k2;
462        // We need to do this so we can say that:
463        // 1 > > 2, is not the same as 1 >> 2
464        match triva {
465            TrivaBetween::Allowed => tokens_match,
466            TrivaBetween::NotAllowed => {
467                return tokens_match
468                    && self.inp.is_joint(self.pos + n)
469                    && self.next_not_joined_op(n + 1);
470            }
471        }
472    }
473
474    fn at_composite3(&self, n: usize, k1: SyntaxKind, k2: SyntaxKind, k3: SyntaxKind) -> bool {
475        self.inp.kind(self.pos + n) == k1
476            && self.inp.kind(self.pos + n + 1) == k2
477            && self.inp.kind(self.pos + n + 2) == k3
478    }
479
480    fn at_composite4(
481        &self,
482        n: usize,
483        k1: SyntaxKind,
484        k2: SyntaxKind,
485        k3: SyntaxKind,
486        k4: SyntaxKind,
487    ) -> bool {
488        self.inp.kind(self.pos + n) == k1
489            && self.inp.kind(self.pos + n + 1) == k2
490            && self.inp.kind(self.pos + n + 2) == k3
491            && self.inp.kind(self.pos + n + 3) == k4
492    }
493
494    fn next_not_joined_op(&self, n: usize) -> bool {
495        // next isn't an operator so we know we're not joined to it
496        if !self.nth_at_ts(n + 1, OPERATOR_FIRST) {
497            return true;
498        }
499        // current kind isn't joined
500        if !self.inp.is_joint(self.pos + n) {
501            return true;
502        }
503        self.op_len() == n + 1
504    }
505
506    fn op_len(&self) -> usize {
507        if !self.at_ts(OPERATOR_FIRST) {
508            return 0;
509        }
510
511        let mut len = 1;
512        let mut has_special = self.at_ts(SPECIAL_OP_CHARS);
513        while self.inp.is_joint(self.pos + len - 1) && self.nth_at_ts(len, OPERATOR_FIRST) {
514            has_special |= self.nth_at_ts(len, SPECIAL_OP_CHARS);
515            len += 1;
516        }
517
518        // PostgreSQL skips trailing signs from ops if they don't contain a
519        // special char.
520        // This means `2*-3` parses as `2 * -3`.
521        if !has_special {
522            while len > 1 && self.nth_at_ts(len - 1, OPERATOR_SIGN) {
523                len -= 1;
524            }
525        }
526
527        len
528    }
529
530    /// Checks if the current token is in `kinds`.
531    pub(crate) fn at_ts(&self, kinds: TokenSet) -> bool {
532        kinds.contains(self.current())
533    }
534
535    /// Starts a new node in the syntax tree. All nodes and tokens
536    /// consumed between the `start` and the corresponding `Marker::complete`
537    /// belong to the same node.
538    pub(crate) fn start(&mut self) -> Marker {
539        let pos = self.events.len() as u32;
540        self.push_event(Event::tombstone());
541        Marker::new(pos)
542    }
543
544    /// Consume the next token. Panics if the parser isn't currently at `kind`.
545    pub(crate) fn bump(&mut self, kind: SyntaxKind) {
546        assert!(self.eat(kind));
547    }
548
549    /// Advances the parser by one token
550    pub(crate) fn bump_any(&mut self) {
551        let kind = self.nth(0);
552        if kind == SyntaxKind::EOF {
553            return;
554        }
555        self.do_bump(kind, 1);
556    }
557
558    /// Consume the next token if it is `kind` or emit an error
559    /// otherwise.
560    pub(crate) fn expect(&mut self, kind: SyntaxKind) -> bool {
561        if self.eat(kind) {
562            return true;
563        }
564        self.error(format!("expected {kind:?}"));
565        false
566    }
567
568    /// Create an error node and consume the next token.
569    pub(crate) fn err_and_bump(&mut self, message: &str) {
570        self.err_recover(message, TokenSet::EMPTY);
571    }
572
573    /// Create an error node and consume the next token.
574    pub(crate) fn err_recover(&mut self, message: &str, recovery: TokenSet) {
575        // TODO: maybe we actually want this?
576        // if matches!(self.current(), SyntaxKind::L_PAREN | SyntaxKind::R_PAREN) {
577        //     self.error(message);
578        //     return;
579        // }
580
581        if self.at_ts(recovery) {
582            self.error(message);
583            return;
584        }
585
586        let m = self.start();
587        self.error(message);
588        self.bump_any();
589        m.complete(self, SyntaxKind::ERROR);
590    }
591
592    fn do_bump(&mut self, kind: SyntaxKind, n_raw_tokens: u8) {
593        self.pos += n_raw_tokens as usize;
594        self.steps.set(0);
595        self.push_event(Event::Token { kind, n_raw_tokens });
596    }
597
598    fn push_event(&mut self, event: Event) {
599        self.events.push(event);
600    }
601
602    fn finish(self) -> Vec<Event> {
603        self.events
604    }
605
606    /// Emit error with the `message`
607    /// FIXME: this should be much more fancy and support
608    /// structured errors with spans and notes, like rustc
609    /// does.
610    pub(crate) fn error<T: Into<String>>(&mut self, message: T) {
611        let msg = message.into();
612        self.push_event(Event::Error { msg });
613    }
614
615    /// Checks if the current token is `kind`.
616    #[must_use]
617    pub(crate) fn at(&self, kind: SyntaxKind) -> bool {
618        self.nth_at(0, kind)
619    }
620
621    /// Checks if the nth token is in `kinds`.
622    #[must_use]
623    pub(crate) fn nth_at_ts(&self, n: usize, kinds: TokenSet) -> bool {
624        kinds.contains(self.nth(n))
625    }
626
627    #[must_use]
628    pub(crate) fn nth_at(&self, n: usize, kind: SyntaxKind) -> bool {
629        match kind {
630            // =>
631            SyntaxKind::FAT_ARROW => self.at_composite2(
632                n,
633                SyntaxKind::EQ,
634                SyntaxKind::R_ANGLE,
635                TrivaBetween::NotAllowed,
636            ),
637            // :=
638            SyntaxKind::COLON_EQ => self.at_composite2(
639                n,
640                SyntaxKind::COLON,
641                SyntaxKind::EQ,
642                TrivaBetween::NotAllowed,
643            ),
644            // ::
645            SyntaxKind::COLON_COLON => self.at_composite2(
646                n,
647                SyntaxKind::COLON,
648                SyntaxKind::COLON,
649                TrivaBetween::NotAllowed,
650            ),
651            // !=
652            SyntaxKind::NEQ => self.at_composite2(
653                n,
654                SyntaxKind::BANG,
655                SyntaxKind::EQ,
656                TrivaBetween::NotAllowed,
657            ),
658            // <>
659            SyntaxKind::NEQB => self.at_composite2(
660                n,
661                SyntaxKind::L_ANGLE,
662                SyntaxKind::R_ANGLE,
663                TrivaBetween::NotAllowed,
664            ),
665            // is not
666            SyntaxKind::IS_NOT => self.at_composite2(
667                n,
668                SyntaxKind::IS_KW,
669                SyntaxKind::NOT_KW,
670                TrivaBetween::Allowed,
671            ),
672            // not like
673            SyntaxKind::NOT_LIKE => self.at_composite2(
674                n,
675                SyntaxKind::NOT_KW,
676                SyntaxKind::LIKE_KW,
677                TrivaBetween::Allowed,
678            ),
679            // not ilike
680            SyntaxKind::NOT_ILIKE => self.at_composite2(
681                n,
682                SyntaxKind::NOT_KW,
683                SyntaxKind::ILIKE_KW,
684                TrivaBetween::Allowed,
685            ),
686            // not in
687            SyntaxKind::NOT_IN => self.at_composite2(
688                n,
689                SyntaxKind::NOT_KW,
690                SyntaxKind::IN_KW,
691                TrivaBetween::Allowed,
692            ),
693            // at time zone
694            SyntaxKind::AT_TIME_ZONE => self.at_composite3(
695                n,
696                SyntaxKind::AT_KW,
697                SyntaxKind::TIME_KW,
698                SyntaxKind::ZONE_KW,
699            ),
700            // at local
701            SyntaxKind::AT_LOCAL => self.at_composite2(
702                n,
703                SyntaxKind::AT_KW,
704                SyntaxKind::LOCAL_KW,
705                TrivaBetween::Allowed,
706            ),
707            // is distinct from
708            SyntaxKind::IS_DISTINCT_FROM => self.at_composite3(
709                n,
710                SyntaxKind::IS_KW,
711                SyntaxKind::DISTINCT_KW,
712                SyntaxKind::FROM_KW,
713            ),
714            // is not distinct from
715            SyntaxKind::IS_NOT_DISTINCT_FROM => self.at_composite4(
716                n,
717                SyntaxKind::IS_KW,
718                SyntaxKind::NOT_KW,
719                SyntaxKind::DISTINCT_KW,
720                SyntaxKind::FROM_KW,
721            ),
722            // is normalized
723            SyntaxKind::IS_NORMALIZED => {
724                if self.at(SyntaxKind::IS_KW) {
725                    if matches!(
726                        self.nth(1),
727                        SyntaxKind::NFC_KW
728                            | SyntaxKind::NFD_KW
729                            | SyntaxKind::NFKC_KW
730                            | SyntaxKind::NFKD_KW
731                    ) {
732                        if self.nth_at(2, SyntaxKind::NORMALIZED_KW) {
733                            return true;
734                        }
735                    } else {
736                        if self.nth_at(1, SyntaxKind::NORMALIZED_KW) {
737                            return true;
738                        }
739                    }
740                }
741                return false;
742            }
743            // is not normalized
744            SyntaxKind::IS_NOT_NORMALIZED => {
745                if self.at(SyntaxKind::IS_KW) && self.nth_at(1, SyntaxKind::NOT_KW) {
746                    if matches!(
747                        self.nth(2),
748                        SyntaxKind::NFC_KW
749                            | SyntaxKind::NFD_KW
750                            | SyntaxKind::NFKC_KW
751                            | SyntaxKind::NFKD_KW
752                    ) {
753                        if self.nth_at(3, SyntaxKind::NORMALIZED_KW) {
754                            return true;
755                        }
756                    } else if self.nth_at(2, SyntaxKind::NORMALIZED_KW) {
757                        return true;
758                    }
759                }
760                return false;
761            }
762            SyntaxKind::NOT_SIMILAR_TO => self.at_composite3(
763                n,
764                SyntaxKind::NOT_KW,
765                SyntaxKind::SIMILAR_KW,
766                SyntaxKind::TO_KW,
767            ),
768            // similar to
769            SyntaxKind::SIMILAR_TO => self.at_composite2(
770                n,
771                SyntaxKind::SIMILAR_KW,
772                SyntaxKind::TO_KW,
773                TrivaBetween::Allowed,
774            ),
775            // https://www.postgresql.org/docs/17/sql-expressions.html#SQL-EXPRESSIONS-OPERATOR-CALLS
776            // TODO: is this right?
777            SyntaxKind::OPERATOR_CALL => self.at_composite2(
778                n,
779                SyntaxKind::OPERATOR_KW,
780                SyntaxKind::L_PAREN,
781                TrivaBetween::Allowed,
782            ),
783            // is json
784            SyntaxKind::IS_JSON => self.at_composite2(
785                n,
786                SyntaxKind::IS_KW,
787                SyntaxKind::JSON_KW,
788                TrivaBetween::Allowed,
789            ),
790            // is not json
791            SyntaxKind::IS_NOT_JSON => self.at_composite3(
792                n,
793                SyntaxKind::IS_KW,
794                SyntaxKind::NOT_KW,
795                SyntaxKind::JSON_KW,
796            ),
797            // is not json object
798            SyntaxKind::IS_NOT_JSON_OBJECT => self.at_composite4(
799                n,
800                SyntaxKind::IS_KW,
801                SyntaxKind::NOT_KW,
802                SyntaxKind::JSON_KW,
803                SyntaxKind::OBJECT_KW,
804            ),
805            // is not json array
806            SyntaxKind::IS_NOT_JSON_ARRAY => self.at_composite4(
807                n,
808                SyntaxKind::IS_KW,
809                SyntaxKind::NOT_KW,
810                SyntaxKind::JSON_KW,
811                SyntaxKind::ARRAY_KW,
812            ),
813            // is not json value
814            SyntaxKind::IS_NOT_JSON_VALUE => self.at_composite4(
815                n,
816                SyntaxKind::IS_KW,
817                SyntaxKind::NOT_KW,
818                SyntaxKind::JSON_KW,
819                SyntaxKind::VALUE_KW,
820            ),
821            // is not json scalar
822            SyntaxKind::IS_NOT_JSON_SCALAR => self.at_composite4(
823                n,
824                SyntaxKind::IS_KW,
825                SyntaxKind::NOT_KW,
826                SyntaxKind::JSON_KW,
827                SyntaxKind::SCALAR_KW,
828            ),
829            // is json object
830            SyntaxKind::IS_JSON_OBJECT => self.at_composite3(
831                n,
832                SyntaxKind::IS_KW,
833                SyntaxKind::JSON_KW,
834                SyntaxKind::OBJECT_KW,
835            ),
836            // is json array
837            SyntaxKind::IS_JSON_ARRAY => self.at_composite3(
838                n,
839                SyntaxKind::IS_KW,
840                SyntaxKind::JSON_KW,
841                SyntaxKind::ARRAY_KW,
842            ),
843            // is json value
844            SyntaxKind::IS_JSON_VALUE => self.at_composite3(
845                n,
846                SyntaxKind::IS_KW,
847                SyntaxKind::JSON_KW,
848                SyntaxKind::VALUE_KW,
849            ),
850            // is json scalar
851            SyntaxKind::IS_JSON_SCALAR => self.at_composite3(
852                n,
853                SyntaxKind::IS_KW,
854                SyntaxKind::JSON_KW,
855                SyntaxKind::SCALAR_KW,
856            ),
857            // <=
858            SyntaxKind::LTEQ => self.at_composite2(
859                n,
860                SyntaxKind::L_ANGLE,
861                SyntaxKind::EQ,
862                TrivaBetween::NotAllowed,
863            ),
864            // <=
865            SyntaxKind::GTEQ => self.at_composite2(
866                n,
867                SyntaxKind::R_ANGLE,
868                SyntaxKind::EQ,
869                TrivaBetween::NotAllowed,
870            ),
871            SyntaxKind::CUSTOM_OP => {
872                // TODO: is this right?
873                if self.at_ts(OPERATOR_FIRST) {
874                    return true;
875                }
876                return false;
877            }
878            // TODO: we probably shouldn't be using a _ for this but be explicit for each type?
879            _ => self.inp.kind(self.pos + n) == kind,
880        }
881    }
882
883    /// Returns the kind of the current token.
884    /// If parser has already reached the end of input,
885    /// the special `EOF` kind is returned.
886    #[must_use]
887    pub(crate) fn current(&self) -> SyntaxKind {
888        self.nth(0)
889    }
890
891    /// Lookahead operation: returns the kind of the next nth
892    /// token.
893    #[must_use]
894    fn nth(&self, n: usize) -> SyntaxKind {
895        let steps = self.steps.get();
896        assert!(
897            (steps as usize) < PARSER_STEP_LIMIT,
898            "the parser seems stuck"
899        );
900        self.steps.set(steps + 1);
901
902        self.inp.kind(self.pos + n)
903    }
904}