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
use crate::sql::symbol;
use std::fmt;

#[derive(Debug, Clone)]
pub struct Scanner {
    message: String,
    tokens: Vec<symbol::Symbol>,
    pos: Pos,
}

#[derive(Debug, Clone)]
struct Pos {
    cursor_l: usize,
    cursor_r: usize,
}

#[derive(Debug)]
pub enum LexerError {
    NotAllowedChar,
    QuoteError,
}

impl fmt::Display for LexerError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            LexerError::NotAllowedChar => write!(f, "please use ascii character."),
            LexerError::QuoteError => write!(f, "please check the quotes"),
        }
    }
}

impl Scanner {
    pub fn new(message: &str) -> Scanner {
        Scanner {
            message: message.to_lowercase().trim().to_string(),
            tokens: vec![],
            pos: Pos {
                cursor_l: 0,
                cursor_r: 0,
            },
        }
    }
    pub fn scan_tokens(&mut self) -> Result<Vec<symbol::Symbol>, LexerError> {
        debug!("Starting scanning message:\n`{}`", self.message);
        let mut chars = self.message.chars();
        let mut is_quoted = false;
        let mut quote = '\0';

        loop {
            match chars.next() {
                Some(x) => {
                    // first meet " or '
                    if !is_quoted && (x == '"' || x == '\'') {
                        quote = x.clone();
                    }
                    if x == quote || is_quoted {
                        self.pos.cursor_r += 1;
                        if !is_quoted {
                            is_quoted = true;
                        } else if x == quote {
                            let word = self.message.get(self.pos.cursor_l + 1..self.pos.cursor_r - 1).unwrap(); // delete quotes
                            self.tokens
                                .push(symbol::sym(word, symbol::Token::Identifier, symbol::Group::Identifier));
                            is_quoted = false;
                            self.pos.cursor_l = self.pos.cursor_r;
                            quote = '\0';
                        }
                    } else if is_identifier_char(x) || is_operator(x) {
                        self.pos.cursor_r += 1;
                    } else {
                        match x {
                            ' ' | '\t' | '\r' | '\n' | '(' | ')' | ',' | ';' => {
                                if self.pos.cursor_l != self.pos.cursor_r {
                                    let word = self.message.get(self.pos.cursor_l..self.pos.cursor_r).unwrap();
                                    debug!("encounter `{}`, last word is `{}`", x, word);

                                    let mut is_multi_keyword = false;

                                    // if this char is delimiter, it must not be a multikeyword
                                    if !is_delimiter(x) {
                                        // if this is possible a multikeyword, search the following chars
                                        match symbol::check_multi_keywords_front(word) {
                                            // parts<Vec[u32]> for how many parts in this possible keyword
                                            Some(parts) => {
                                                debug!("The word `{}` might be a multikeyword", word);

                                                for keyword_total_parts in parts {
                                                    debug!("Assume this keyword has {} parts", keyword_total_parts);

                                                    // copy remaining chars for testing
                                                    let mut test_chars = chars.as_str().chars();
                                                    // for testing if the string a multikeyword. Insert the first word
                                                    // and a space already. (because start scanning from next word)
                                                    let mut test_str = String::from(format!("{} ", word));

                                                    // for checking a new word
                                                    let mut is_last_letter = false;

                                                    // record the right cursor position when checking if multikeyword
                                                    // if match a multikeyword, shift right cursor with steps
                                                    let mut step_counter = 0;

                                                    // How many words added in the test_str
                                                    // if the keyword is 3 parts, the following_parts should be 2
                                                    let mut following_parts = 0;

                                                    loop {
                                                        match test_chars.next() {
                                                            Some(y) => {
                                                                // A multikeyword should be all ASCII alphabetic character
                                                                if y.is_ascii_alphabetic() {
                                                                    if !is_last_letter {
                                                                        is_last_letter = true;
                                                                    }
                                                                    test_str.push(y);
                                                                } else {
                                                                    match y {
                                                                        ' ' | '\t' | '\r' | '\n' => {
                                                                            if is_last_letter {
                                                                                // from letter to space, count one
                                                                                following_parts += 1;
                                                                                // find enough parts, break earlier
                                                                                if following_parts
                                                                                    == keyword_total_parts - 1
                                                                                {
                                                                                    break; // loop
                                                                                }
                                                                                // add ` ` between words
                                                                                test_str.push(' ');
                                                                                is_last_letter = false
                                                                            }
                                                                        }
                                                                        // &, %, *, @, etc.
                                                                        // keywords must be letters
                                                                        _ => break, // loop
                                                                    }
                                                                }
                                                            }
                                                            None => break, // loop
                                                        }
                                                        step_counter += 1;
                                                    }

                                                    debug!("Checking `{}` ...", test_str);
                                                    match symbol::SYMBOLS.get(test_str.as_str()) {
                                                        // a multikeyword
                                                        Some(token) => {
                                                            debug!("Found keyword `{}`", test_str);
                                                            self.tokens.push(token.clone());

                                                            // shift the right cursor to the right of multikeyword
                                                            self.pos.cursor_r += step_counter;
                                                            // skip the chars included in this multikeyword
                                                            for _ in 0..step_counter {
                                                                chars.next();
                                                            }

                                                            is_multi_keyword = true;
                                                            break; // parts
                                                        }
                                                        None => debug!("`{}` not a keyword", test_str),
                                                    }
                                                }
                                            }
                                            None => {}
                                        }
                                    }

                                    // a single word
                                    if !is_multi_keyword {
                                        match symbol::SYMBOLS.get(word) {
                                            // either keyword
                                            Some(token) => {
                                                self.tokens.push(token.clone());
                                            }
                                            // or identifier
                                            None => {
                                                self.tokens.push(symbol::sym(
                                                    word,
                                                    symbol::Token::Identifier,
                                                    symbol::Group::Identifier,
                                                ));
                                            }
                                        }
                                    }
                                }
                                if is_delimiter(x) {
                                    debug!("take `{}`", x);
                                    self.tokens.push(symbol::Symbol::match_delimiter(x).unwrap());
                                }
                                // set the cursor next to `x` in the right
                                self.pos.cursor_r += 1;
                                self.pos.cursor_l = self.pos.cursor_r;
                            }
                            // A special case
                            '*' => {
                                self.tokens.push(symbol::sym(
                                    "*",
                                    symbol::Token::Identifier,
                                    symbol::Group::Identifier,
                                ));
                                self.pos.cursor_r += 1;
                                self.pos.cursor_l = self.pos.cursor_r;
                            }
                            _ => {
                                return Err(LexerError::NotAllowedChar);
                            }
                        }
                    }
                }
                // iter to the end
                None => {
                    if is_quoted {
                        // if find no second quote
                        return Err(LexerError::QuoteError);
                    }
                    break;
                }
            };
        }
        Ok(self.tokens.clone())
    }
}

fn is_identifier_char(ch: char) -> bool {
    ch.is_digit(10) || ch.is_ascii_alphabetic() || ch == '\'' || ch == '.' || ch == '"'
}

fn is_operator(ch: char) -> bool {
    ch == '>' || ch == '=' || ch == '<' || ch == '-' || ch == '+'
}

fn is_delimiter(ch: char) -> bool {
    ch == '(' || ch == ')' || ch == ',' || ch == ';'
}

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

    #[test]
    pub fn test_quote() {
        let message = "'123://'";
        let mut s = Scanner::new(message);
        let tokens = s.scan_tokens().unwrap();
        let mut iter = (&tokens).iter();
        let x = iter.next().unwrap();
        println!("test{:?}", x.name);
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"123://\", Identifier, Identifier"
        );

        let message = "'qqq\"' ,123";
        let mut s = Scanner::new(message);
        let tokens = s.scan_tokens().unwrap();
        let mut iter = (&tokens).iter();
        let x = iter.next().unwrap();
        println!("test{:?}", x.name);
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"qqq\\\"\", Identifier, Identifier"
        );

        let message = "\"qqq\', 123 ";
        let mut s = Scanner::new(message);
        match s.scan_tokens() {
            Ok(_) => {}
            Err(e) => assert_eq!(format!("{}", e), "please check the quotes"),
        }
    }

    #[test]
    pub fn test_scan_tokens() {
        let message = "select customername, contactname, address from customers where address is null;";
        let mut s = Scanner::new(message);
        let tokens = s.scan_tokens().unwrap();
        let mut iter = (&tokens).iter();
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"select\", Select, Keyword"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"customername\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\",\", Comma, Delimiter"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"contactname\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\",\", Comma, Delimiter"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"address\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"from\", From, Keyword"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"customers\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"where\", Where, Keyword"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"address\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"is null\", IsNull, Keyword"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\";\", Semicolon, Delimiter"
        );
        assert!(iter.next().is_none());

        let message = "select * from customers;";
        let mut s = Scanner::new(message);
        let tokens = s.scan_tokens().unwrap();
        let mut iter = (&tokens).iter();
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"select\", Select, Keyword"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"*\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"from\", From, Keyword"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"customers\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\";\", Semicolon, Delimiter"
        );
        assert!(iter.next().is_none());

        let message = "insert \n\r\tinto \t\tcustomers \n(customername,\n\n city)\n\n values ('cardinal', 'norway');";
        let mut s = Scanner::new(message);
        let tokens = s.scan_tokens().unwrap();
        let mut iter = (&tokens).iter();
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"insert into\", InsertInto, Keyword"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"customers\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"(\", ParentLeft, Delimiter"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"customername\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\",\", Comma, Delimiter"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"city\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\")\", ParentRight, Delimiter"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"values\", Values, Keyword"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"(\", ParentLeft, Delimiter"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"cardinal\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\",\", Comma, Delimiter"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"norway\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\")\", ParentRight, Delimiter"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\";\", Semicolon, Delimiter"
        );
        assert!(iter.next().is_none());

        let message = "create table x1;";
        let mut s = Scanner::new(message);
        let tokens = s.scan_tokens().unwrap();
        debug!("{:?}", tokens);
        let mut iter = (&tokens).iter();
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"create table\", CreateTable, Keyword"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\"x1\", Identifier, Identifier"
        );
        let x = iter.next().unwrap();
        assert_eq!(
            format!("{:?}, {:?}, {:?}", x.name, x.token, x.group),
            "\";\", Semicolon, Delimiter"
        );
        assert!(iter.next().is_none());
    }

    #[test]
    fn test_scan_tokens_error() {
        let message = "create table $1234";
        let mut s = Scanner::new(message);
        match s.scan_tokens() {
            Ok(_) => {}
            Err(e) => assert_eq!(format!("{}", e), "please use ascii character."),
        }
    }
}