sui_sql_macro/
lexer.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::fmt;

/// Lexer for SQL format strings. Format string can contain regular text, or binders surrounded by
/// curly braces. Curly braces are escaped by doubling them up.
pub(crate) struct Lexer<'s> {
    src: &'s str,
    off: usize,
}

/// A lexeme is a token along with its offset in the source string, and the slice of source string
/// that it originated from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Lexeme<'s>(pub Token, pub usize, pub &'s str);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Token {
    /// '{'
    LCurl,
    /// '}'
    RCurl,
    /// Any other text
    Text,
}

impl<'s> Lexer<'s> {
    pub(crate) fn new(src: &'s str) -> Self {
        Self { src, off: 0 }
    }
}

impl<'s> Iterator for Lexer<'s> {
    type Item = Lexeme<'s>;

    fn next(&mut self) -> Option<Self::Item> {
        let off = self.off;
        let bytes = self.src.as_bytes();
        let fst = bytes.first()?;

        Some(match fst {
            b'{' => {
                let span = &self.src[..1];
                self.src = &self.src[1..];
                self.off += 1;
                Lexeme(Token::LCurl, off, span)
            }

            b'}' => {
                let span = &self.src[..1];
                self.src = &self.src[1..];
                self.off += 1;
                Lexeme(Token::RCurl, off, span)
            }

            _ => {
                let end = self.src.find(['{', '}']).unwrap_or(self.src.len());
                let span = &self.src[..end];
                self.src = &self.src[end..];
                self.off += end;
                Lexeme(Token::Text, off, span)
            }
        })
    }
}

impl fmt::Display for Token {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use Token as T;
        match self {
            T::LCurl => write!(f, "'{{'"),
            T::RCurl => write!(f, "'}}'"),
            T::Text => write!(f, "text"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use Lexeme as L;
    use Token as T;

    /// Lexing source material that only contains text and no curly braces.
    #[test]
    fn test_all_text() {
        let lexer = Lexer::new("foo bar");
        let lexemes: Vec<_> = lexer.collect();
        assert_eq!(lexemes, vec![L(T::Text, 0, "foo bar")]);
    }

    /// When the lexer encounters curly braces in the source material it breaks up the text with
    /// curly brace tokens.
    #[test]
    fn test_curlies() {
        let lexer = Lexer::new("foo {bar} baz");
        let lexemes: Vec<_> = lexer.collect();
        assert_eq!(
            lexemes,
            vec![
                L(T::Text, 0, "foo "),
                L(T::LCurl, 4, "{"),
                L(T::Text, 5, "bar"),
                L(T::RCurl, 8, "}"),
                L(T::Text, 9, " baz"),
            ],
        );
    }

    /// Repeated curly braces next to each other are used to escape those braces.
    #[test]
    fn test_escape_curlies() {
        let lexer = Lexer::new("foo {{bar}} baz");
        let lexemes: Vec<_> = lexer.collect();
        assert_eq!(
            lexemes,
            vec![
                L(T::Text, 0, "foo "),
                L(T::LCurl, 4, "{"),
                L(T::LCurl, 5, "{"),
                L(T::Text, 6, "bar"),
                L(T::RCurl, 9, "}"),
                L(T::RCurl, 10, "}"),
                L(T::Text, 11, " baz"),
            ],
        );
    }

    /// Each curly brace is given its own token so that the parser can parse this as an escaped
    /// opening curly followed by an empty binder, followed by a literal closing curly. If the
    /// lexer was responsible for detecting escaped curlies, it would eagerly detect the escaped
    /// closing curly and then the closing curly for the binder.
    #[test]
    fn test_combination_curlies() {
        let lexer = Lexer::new("{{{}}}");
        let lexemes: Vec<_> = lexer.collect();
        assert_eq!(
            lexemes,
            vec![
                L(T::LCurl, 0, "{"),
                L(T::LCurl, 1, "{"),
                L(T::LCurl, 2, "{"),
                L(T::RCurl, 3, "}"),
                L(T::RCurl, 4, "}"),
                L(T::RCurl, 5, "}"),
            ],
        );
    }
}