Skip to main content

powdb_query/
token.rs

1#[derive(Debug, Clone, PartialEq)]
2pub enum Token {
3    // Identifiers and literals
4    Ident(String),     // User, name, email
5    DotIdent(String),  // .name, .age (field access)
6    IntLit(i64),       // 42
7    FloatLit(f64),     // 3.14
8    StringLit(String), // "hello"
9    BoolLit(bool),     // true, false
10    Param(String),     // $age, $name (query parameter)
11
12    // Keywords
13    Type,         // type
14    Filter,       // filter
15    Order,        // order
16    Limit,        // limit
17    Offset,       // offset
18    Insert,       // insert
19    Update,       // update
20    Delete,       // delete
21    Upsert,       // upsert
22    Returning,    // returning
23    Select,       // select (alias for projection)
24    Required,     // required
25    Default,      // default (column default value)
26    Auto,         // auto (auto-incrementing column)
27    Multi,        // multi
28    Link,         // link
29    Index,        // index
30    Unique,       // unique
31    On,           // on
32    Conflict,     // conflict
33    Asc,          // asc
34    Desc,         // desc
35    And,          // and
36    Or,           // or
37    Not,          // not
38    Exists,       // exists
39    Let,          // let
40    As,           // as
41    Match,        // match
42    Group,        // group
43    Join,         // join
44    Inner,        // inner
45    LeftKw,       // left  (keyword — avoids clashing with ast::JoinKind::LeftOuter naming)
46    RightKw,      // right
47    Outer,        // outer
48    Cross,        // cross
49    Transaction,  // transaction
50    Begin,        // begin
51    Commit,       // commit
52    Rollback,     // rollback
53    View,         // view
54    Materialized, // materialized
55    Refresh,      // refresh
56    Union,        // union
57    Having,       // having
58    Distinct,     // distinct
59    In,           // in
60    Between,      // between
61    Like,         // like
62    Count,        // count
63    Avg,          // avg
64    Sum,          // sum
65    Min,          // min
66    Max,          // max
67    Is,           // is
68    Null,         // null
69
70    // String functions
71    Upper,     // upper
72    Lower,     // lower
73    Length,    // length
74    Trim,      // trim
75    Substring, // substring
76    Concat,    // concat
77
78    // Math functions
79    Abs,   // abs
80    Round, // round
81    Ceil,  // ceil
82    Floor, // floor
83    Sqrt,  // sqrt
84    Pow,   // pow
85
86    // Date/time functions
87    Now,      // now
88    Extract,  // extract
89    DateAdd,  // date_add
90    DateDiff, // date_diff
91
92    // Type conversion
93    Cast, // cast
94
95    // CASE WHEN
96    Case, // case
97    When, // when
98    Then, // then
99    Else, // else
100    End,  // end
101
102    // Window functions
103    Over,      // over
104    Partition, // partition
105    RowNumber, // row_number
106    Rank,      // rank
107    DenseRank, // dense_rank
108
109    // DDL
110    Alter,    // alter
111    Drop,     // drop
112    Add,      // add
113    Column,   // column
114    Explain,  // explain
115    Schema,   // schema   (introspection: list types / describe one)
116    Describe, // describe (introspection: describe one type)
117
118    // Operators
119    Eq,       // =
120    Neq,      // !=
121    Lt,       // <
122    Gt,       // >
123    Lte,      // <=
124    Gte,      // >=
125    Assign,   // :=
126    Arrow,    // ->
127    Pipe,     // |
128    Coalesce, // ??
129    Plus,     // +
130    Minus,    // -
131    Star,     // *
132    Slash,    // /
133
134    // Delimiters
135    LBrace, // {
136    RBrace, // }
137    LParen, // (
138    RParen, // )
139    Comma,  // ,
140    Colon,  // :
141    Dot,    // .
142
143    // Special
144    Eof,
145}
146
147impl Token {
148    /// Human-readable name for error messages. Avoids exposing raw Rust Debug
149    /// format like `IntLit(42)` to end users.
150    pub fn display_name(&self) -> String {
151        match self {
152            // Literals
153            Token::Ident(s) => format!("identifier '{s}'"),
154            Token::DotIdent(s) => format!("field '.{s}'"),
155            Token::IntLit(v) => format!("number {v}"),
156            Token::FloatLit(v) => format!("decimal number {v}"),
157            Token::StringLit(s) => {
158                let preview = if s.len() > 20 {
159                    let end = s.floor_char_boundary(20);
160                    format!("{}...", &s[..end])
161                } else {
162                    s.clone()
163                };
164                format!("string \"{preview}\"")
165            }
166            Token::BoolLit(v) => format!("{v}"),
167            Token::Param(s) => format!("parameter '${s}'"),
168
169            // Keywords
170            Token::Type => "'type'".into(),
171            Token::Filter => "'filter'".into(),
172            Token::Order => "'order'".into(),
173            Token::Limit => "'limit'".into(),
174            Token::Offset => "'offset'".into(),
175            Token::Insert => "'insert'".into(),
176            Token::Update => "'update'".into(),
177            Token::Delete => "'delete'".into(),
178            Token::Upsert => "'upsert'".into(),
179            Token::Returning => "'returning'".into(),
180            Token::Select => "'select'".into(),
181            Token::Required => "'required'".into(),
182            Token::Default => "'default'".into(),
183            Token::Auto => "'auto'".into(),
184            Token::Multi => "'multi'".into(),
185            Token::Link => "'link'".into(),
186            Token::Index => "'index'".into(),
187            Token::Unique => "'unique'".into(),
188            Token::On => "'on'".into(),
189            Token::Conflict => "'conflict'".into(),
190            Token::Asc => "'asc'".into(),
191            Token::Desc => "'desc'".into(),
192            Token::And => "'and'".into(),
193            Token::Or => "'or'".into(),
194            Token::Not => "'not'".into(),
195            Token::Exists => "'exists'".into(),
196            Token::Let => "'let'".into(),
197            Token::As => "'as'".into(),
198            Token::Match => "'match'".into(),
199            Token::Group => "'group'".into(),
200            Token::Join => "'join'".into(),
201            Token::Inner => "'inner'".into(),
202            Token::LeftKw => "'left'".into(),
203            Token::RightKw => "'right'".into(),
204            Token::Outer => "'outer'".into(),
205            Token::Cross => "'cross'".into(),
206            Token::Transaction => "'transaction'".into(),
207            Token::Begin => "'begin'".into(),
208            Token::Commit => "'commit'".into(),
209            Token::Rollback => "'rollback'".into(),
210            Token::View => "'view'".into(),
211            Token::Materialized => "'materialized'".into(),
212            Token::Refresh => "'refresh'".into(),
213            Token::Union => "'union'".into(),
214            Token::Having => "'having'".into(),
215            Token::Distinct => "'distinct'".into(),
216            Token::In => "'in'".into(),
217            Token::Between => "'between'".into(),
218            Token::Like => "'like'".into(),
219            Token::Count => "'count'".into(),
220            Token::Avg => "'avg'".into(),
221            Token::Sum => "'sum'".into(),
222            Token::Min => "'min'".into(),
223            Token::Max => "'max'".into(),
224            Token::Is => "'is'".into(),
225            Token::Null => "'null'".into(),
226
227            // Functions
228            Token::Upper => "'upper'".into(),
229            Token::Lower => "'lower'".into(),
230            Token::Length => "'length'".into(),
231            Token::Trim => "'trim'".into(),
232            Token::Substring => "'substring'".into(),
233            Token::Concat => "'concat'".into(),
234            Token::Abs => "'abs'".into(),
235            Token::Round => "'round'".into(),
236            Token::Ceil => "'ceil'".into(),
237            Token::Floor => "'floor'".into(),
238            Token::Sqrt => "'sqrt'".into(),
239            Token::Pow => "'pow'".into(),
240            Token::Now => "'now'".into(),
241            Token::Extract => "'extract'".into(),
242            Token::DateAdd => "'date_add'".into(),
243            Token::DateDiff => "'date_diff'".into(),
244            Token::Cast => "'cast'".into(),
245            Token::Case => "'case'".into(),
246            Token::When => "'when'".into(),
247            Token::Then => "'then'".into(),
248            Token::Else => "'else'".into(),
249            Token::End => "'end'".into(),
250
251            // Window
252            Token::Over => "'over'".into(),
253            Token::Partition => "'partition'".into(),
254            Token::RowNumber => "'row_number'".into(),
255            Token::Rank => "'rank'".into(),
256            Token::DenseRank => "'dense_rank'".into(),
257
258            // DDL
259            Token::Alter => "'alter'".into(),
260            Token::Drop => "'drop'".into(),
261            Token::Add => "'add'".into(),
262            Token::Column => "'column'".into(),
263            Token::Explain => "'explain'".into(),
264            Token::Schema => "'schema'".into(),
265            Token::Describe => "'describe'".into(),
266
267            // Operators
268            Token::Eq => "'='".into(),
269            Token::Neq => "'!='".into(),
270            Token::Lt => "'<'".into(),
271            Token::Gt => "'>'".into(),
272            Token::Lte => "'<='".into(),
273            Token::Gte => "'>='".into(),
274            Token::Assign => "':='".into(),
275            Token::Arrow => "'->'".into(),
276            Token::Pipe => "'|'".into(),
277            Token::Coalesce => "'??'".into(),
278            Token::Plus => "'+'".into(),
279            Token::Minus => "'-'".into(),
280            Token::Star => "'*'".into(),
281            Token::Slash => "'/'".into(),
282
283            // Delimiters
284            Token::LBrace => "'{'".into(),
285            Token::RBrace => "'}'".into(),
286            Token::LParen => "'('".into(),
287            Token::RParen => "')'".into(),
288            Token::Comma => "','".into(),
289            Token::Colon => "':'".into(),
290            Token::Dot => "'.'".into(),
291
292            Token::Eof => "end of input".into(),
293        }
294    }
295
296    /// The lowercase source spelling of this token when it is a reserved
297    /// keyword (or built-in literal word), or `None` for identifiers,
298    /// literals, operators, and delimiters. Inverts the lexer's word→token
299    /// table so the parser can tell a caller *which* reserved word collided
300    /// with an identifier position and how to quote it (`` `type` ``).
301    pub fn keyword_str(&self) -> Option<&'static str> {
302        Some(match self {
303            Token::Type => "type",
304            Token::Filter => "filter",
305            Token::Order => "order",
306            Token::Limit => "limit",
307            Token::Offset => "offset",
308            Token::Insert => "insert",
309            Token::Update => "update",
310            Token::Delete => "delete",
311            Token::Upsert => "upsert",
312            Token::Returning => "returning",
313            Token::Select => "select",
314            Token::Required => "required",
315            Token::Default => "default",
316            Token::Auto => "auto",
317            Token::Multi => "multi",
318            Token::Link => "link",
319            Token::Index => "index",
320            Token::Unique => "unique",
321            Token::On => "on",
322            Token::Conflict => "conflict",
323            Token::Asc => "asc",
324            Token::Desc => "desc",
325            Token::And => "and",
326            Token::Or => "or",
327            Token::Not => "not",
328            Token::Exists => "exists",
329            Token::Let => "let",
330            Token::As => "as",
331            Token::Match => "match",
332            Token::Group => "group",
333            Token::Join => "join",
334            Token::Inner => "inner",
335            Token::LeftKw => "left",
336            Token::RightKw => "right",
337            Token::Outer => "outer",
338            Token::Cross => "cross",
339            Token::Transaction => "transaction",
340            Token::Begin => "begin",
341            Token::Commit => "commit",
342            Token::Rollback => "rollback",
343            Token::View => "view",
344            Token::Materialized => "materialized",
345            Token::Refresh => "refresh",
346            Token::Union => "union",
347            Token::Having => "having",
348            Token::Distinct => "distinct",
349            Token::In => "in",
350            Token::Between => "between",
351            Token::Like => "like",
352            Token::Count => "count",
353            Token::Avg => "avg",
354            Token::Sum => "sum",
355            Token::Min => "min",
356            Token::Max => "max",
357            Token::Is => "is",
358            Token::Null => "null",
359            Token::Upper => "upper",
360            Token::Lower => "lower",
361            Token::Length => "length",
362            Token::Trim => "trim",
363            Token::Substring => "substring",
364            Token::Concat => "concat",
365            Token::Abs => "abs",
366            Token::Round => "round",
367            Token::Ceil => "ceil",
368            Token::Floor => "floor",
369            Token::Sqrt => "sqrt",
370            Token::Pow => "pow",
371            Token::Now => "now",
372            Token::Extract => "extract",
373            Token::DateAdd => "date_add",
374            Token::DateDiff => "date_diff",
375            Token::Cast => "cast",
376            Token::Case => "case",
377            Token::When => "when",
378            Token::Then => "then",
379            Token::Else => "else",
380            Token::End => "end",
381            Token::Over => "over",
382            Token::Partition => "partition",
383            Token::RowNumber => "row_number",
384            Token::Rank => "rank",
385            Token::DenseRank => "dense_rank",
386            Token::Alter => "alter",
387            Token::Drop => "drop",
388            Token::Add => "add",
389            Token::Column => "column",
390            Token::Explain => "explain",
391            Token::Schema => "schema",
392            Token::Describe => "describe",
393            _ => return None,
394        })
395    }
396}