toml_query/
tokenizer.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
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
/// The tokenizer for the query interpreter
use crate::error::{Error, Result};

#[derive(Debug, PartialEq, Eq)]
pub enum Token {
    Identifier {
        ident: String,
        next: Option<Box<Token>>,
    },

    Index {
        idx: usize,
        next: Option<Box<Token>>,
    },
}

impl Token {
    pub fn next(&self) -> Option<&Token> {
        trace!("Matching token (self): {:?}", self);
        match self {
            Token::Identifier { ref next, .. } => next.as_ref().map(|t| &**t),
            Token::Index { ref next, .. } => next.as_ref().map(|t| &**t),
        }
    }

    /// Convenience function for `token.next().is_some()`
    pub fn has_next(&self) -> bool {
        trace!("self.has_next(): {:?}", self.next().is_some());
        self.next().is_some()
    }

    pub fn set_next(&mut self, token: Token) {
        trace!("self.set_next({:?})", token);
        match self {
            Token::Identifier { ref mut next, .. } => *next = Some(Box::new(token)),
            Token::Index { ref mut next, .. } => *next = Some(Box::new(token)),
        }
    }

    /// Pop the last token from the chain of tokens
    ///
    /// Returns None if the current Token has no next token
    pub fn pop_last(&mut self) -> Option<Box<Token>> {
        trace!("self.pop_last()");
        if !self.has_next() {
            trace!("self.pop_last(): No next");
            None
        } else {
            trace!("self.pop_last(): Having next");
            match self {
                Token::Identifier { ref mut next, .. } => {
                    trace!("self.pop_last(): self is Identifier");
                    if next.is_some() {
                        trace!("self.pop_last(): next is Some(_)");
                        let mut n = next.take().unwrap();
                        if n.has_next() {
                            trace!("self.pop_last(): next also has a next");

                            trace!("self.pop_last(): Recursing now");
                            let result = n.pop_last();

                            *next = Some(n);

                            trace!("self.pop_last(): Returning Result");
                            result
                        } else {
                            trace!("self.pop_last(): next itself has no next, returning Some");
                            Some(n)
                        }
                    } else {
                        trace!("self.pop_last(): next is none, returning None");
                        None
                    }
                }

                Token::Index { ref mut next, .. } => {
                    trace!("self.pop_last(): self is Index");
                    if next.is_some() {
                        trace!("self.pop_last(): next is Some(_)");

                        let mut n = next.take().unwrap();
                        if n.has_next() {
                            trace!("self.pop_last(): next also has a next");

                            trace!("self.pop_last(): Recursing now");
                            let result = n.pop_last();

                            *next = Some(n);

                            trace!("self.pop_last(): Returning Result");
                            result
                        } else {
                            trace!("self.pop_last(): next itself has no next, returning Some");
                            Some(n)
                        }
                    } else {
                        trace!("self.pop_last(): next is none, returning None");
                        None
                    }
                }
            }
        }
    }

    #[cfg(test)]
    pub fn identifier(&self) -> &String {
        trace!("self.identifier()");
        match self {
            Token::Identifier { ref ident, .. } => &ident,
            _ => unreachable!(),
        }
    }

    #[cfg(test)]
    pub fn idx(&self) -> usize {
        trace!("self.idx()");
        match self {
            Token::Index { idx: i, .. } => *i,
            _ => unreachable!(),
        }
    }
}

pub fn tokenize_with_seperator(query: &str, seperator: char) -> Result<Token> {
    use std::str::Split;
    trace!(
        "tokenize_with_seperator(query: {:?}, seperator: {:?})",
        query,
        seperator
    );

    /// Creates a Token object from a string
    ///
    /// # Panics
    ///
    /// * If the internal regex does not compile (should never happen)
    /// * If the token is non-valid (that is, a array index with a non-i64)
    /// * If the regex does not find anything
    /// * If the integer in the brackets (`[]`) cannot be parsed to a valid i64
    ///
    /// # Incorrect behaviour
    ///
    /// * If the regex finds multiple captures
    ///
    /// # Returns
    ///
    /// The `Token` object with the correct identifier/index for this token and no next token.
    ///
    fn mk_token_object(s: &str) -> Result<Token> {
        use regex::Regex;
        use std::str::FromStr;

        trace!("mk_token_object(s: {:?})", s);

        lazy_static! {
            static ref RE: Regex = Regex::new(r"^\[\d+\]$").unwrap();
        }

        if !has_array_brackets(s) {
            trace!("returning Ok(Identifier(ident: {:?}, next: None))", s);
            return Ok(Token::Identifier {
                ident: String::from(s),
                next: None,
            });
        }

        match RE.captures(s) {
            None => Err(Error::ArrayAccessWithoutIndex),
            Some(captures) => {
                trace!("Captured: {:?}", captures);
                match captures.get(0) {
                    None => Ok(Token::Identifier {
                        ident: String::from(s),
                        next: None,
                    }),
                    Some(mtch) => {
                        trace!("First capture: {:?}", mtch);

                        let mtch = without_array_brackets(mtch.as_str());
                        trace!(".. without array brackets: {:?}", mtch);

                        let i: usize = FromStr::from_str(&mtch).unwrap(); // save because regex

                        trace!("returning Ok(Index(idx: {}, next: None)", i);
                        Ok(Token::Index { idx: i, next: None })
                    }
                }
            }
        }
    }

    /// Check whether a str begins with '[' and ends with ']'
    fn has_array_brackets(s: &str) -> bool {
        trace!("has_array_brackets({:?})", s);
        s.as_bytes()[0] == b'[' && s.as_bytes()[s.len() - 1] == b']'
    }

    /// Remove '[' and ']' from a str
    fn without_array_brackets(s: &str) -> String {
        trace!("without_array_brackets({:?})", s);
        s.replace("[", "").replace("]", "")
    }

    fn build_token_tree(split: &mut Split<'_, char>, last: &mut Token) -> Result<()> {
        trace!("build_token_tree(split: {:?}, last: {:?})", split, last);
        match split.next() {
            None => { /* No more tokens */ }
            Some(token) => {
                trace!("build_token_tree(...): next from split: {:?}", token);

                if token.is_empty() {
                    trace!("build_token_tree(...): Empty identifier... returning Error");
                    return Err(Error::EmptyIdentifier);
                }

                let mut token = mk_token_object(token)?;
                build_token_tree(split, &mut token)?;
                last.set_next(token);
            }
        }

        trace!("build_token_tree(...): returning Ok(())");
        Ok(())
    }

    if query.is_empty() {
        trace!("Query is empty. Returning error");
        return Err(Error::EmptyQueryError);
    }

    let mut tokens = query.split(seperator);
    trace!("Tokens splitted: {:?}", tokens);

    match tokens.next() {
        None => Err(Error::EmptyQueryError),
        Some(token) => {
            trace!("next Token: {:?}", token);

            if token.is_empty() {
                trace!("Empty token. Returning Error");
                return Err(Error::EmptyIdentifier);
            }

            let mut tok = mk_token_object(token)?;
            build_token_tree(&mut tokens, &mut tok)?;

            trace!("Returning Ok({:?})", tok);
            Ok(tok)
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::error::Error;

    use std::ops::Deref;

    #[test]
    fn test_tokenize_empty_query_to_error() {
        let tokens = tokenize_with_seperator(&String::from(""), '.');
        assert!(tokens.is_err());
        let tokens = tokens.unwrap_err();

        assert!(is_match!(tokens, Error::EmptyQueryError { .. }));
    }

    #[test]
    fn test_tokenize_seperator_only() {
        let tokens = tokenize_with_seperator(&String::from("."), '.');
        assert!(tokens.is_err());
        let tokens = tokens.unwrap_err();

        assert!(is_match!(tokens, Error::EmptyIdentifier { .. }));
    }

    #[test]
    fn test_tokenize_array_brackets_only() {
        let tokens = tokenize_with_seperator(&String::from("[]"), '.');
        assert!(tokens.is_err());
        let tokens = tokens.unwrap_err();

        assert!(is_match!(tokens, Error::ArrayAccessWithoutIndex { .. }));
    }

    #[test]
    fn test_tokenize_identifiers_with_array_brackets_only() {
        let tokens = tokenize_with_seperator(&String::from("a.b.c.[]"), '.');
        assert!(tokens.is_err());
        let tokens = tokens.unwrap_err();

        assert!(is_match!(tokens, Error::ArrayAccessWithoutIndex { .. }));
    }

    #[test]
    fn test_tokenize_identifiers_in_array_brackets() {
        let tokens = tokenize_with_seperator(&String::from("[a]"), '.');
        assert!(tokens.is_err());
        let tokens = tokens.unwrap_err();

        assert!(is_match!(tokens, Error::ArrayAccessWithoutIndex { .. }));
    }

    #[test]
    fn test_tokenize_single_token_query() {
        let tokens = tokenize_with_seperator(&String::from("example"), '.');
        assert!(tokens.is_ok());
        let tokens = tokens.unwrap();

        assert!(match tokens {
            Token::Identifier {
                ref ident,
                next: None,
            } => {
                assert_eq!("example", ident);
                true
            }
            _ => false,
        });
    }

    #[test]
    fn test_tokenize_double_token_query() {
        let tokens = tokenize_with_seperator(&String::from("a.b"), '.');
        assert!(tokens.is_ok());
        let tokens = tokens.unwrap();

        assert!(match tokens {
            Token::Identifier {
                next: Some(ref next),
                ..
            } => {
                assert_eq!("b", next.deref().identifier());
                match next.deref() {
                    Token::Identifier { next: None, .. } => true,
                    _ => false,
                }
            }
            _ => false,
        });
        assert_eq!("a", tokens.identifier());
    }

    #[test]
    fn test_tokenize_ident_then_array_query() {
        let tokens = tokenize_with_seperator(&String::from("a.[0]"), '.');
        assert!(tokens.is_ok());
        let tokens = tokens.unwrap();

        assert_eq!("a", tokens.identifier());
        assert!(match tokens {
            Token::Identifier {
                next: Some(ref next),
                ..
            } => match next.deref() {
                Token::Index { idx: 0, next: None } => true,
                _ => false,
            },
            _ => false,
        });
    }

    #[test]
    fn test_tokenize_many_idents_then_array_query() {
        let tokens = tokenize_with_seperator(&String::from("a.b.c.[1000]"), '.');
        assert!(tokens.is_ok());
        let tokens = tokens.unwrap();

        assert_eq!("a", tokens.identifier());

        let expected = Token::Identifier {
            ident: String::from("a"),
            next: Some(Box::new(Token::Identifier {
                ident: String::from("b"),
                next: Some(Box::new(Token::Identifier {
                    ident: String::from("c"),
                    next: Some(Box::new(Token::Index {
                        idx: 1000,
                        next: None,
                    })),
                })),
            })),
        };

        assert_eq!(expected, tokens);
    }

    #[test]
    fn test_tokenize_empty_token_after_good_token() {
        let tokens = tokenize_with_seperator(&String::from("a..b"), '.');
        assert!(tokens.is_err());
        let tokens = tokens.unwrap_err();

        assert!(is_match!(tokens, Error::EmptyIdentifier { .. }));
    }

    quickcheck! {
        fn test_array_index(i: usize) -> bool {
            match tokenize_with_seperator(&format!("[{}]", i), '.') {
                Ok(Token::Index { next: None, ..  }) => true,
                _                                    => false,
            }
        }
    }

    #[test]
    fn test_pop_last_token_from_single_identifier_token_is_none() {
        let mut token = Token::Identifier {
            ident: String::from("something"),
            next: None,
        };

        let last = token.pop_last();
        assert!(last.is_none());
    }

    #[test]
    fn test_pop_last_token_from_single_index_token_is_none() {
        let mut token = Token::Index { idx: 0, next: None };

        let last = token.pop_last();
        assert!(last.is_none());
    }

    #[test]
    fn test_pop_last_token_from_single_identifier_token_is_one() {
        let mut token = Token::Identifier {
            ident: String::from("some"),
            next: Some(Box::new(Token::Identifier {
                ident: String::from("thing"),
                next: None,
            })),
        };

        let last = token.pop_last();

        assert!(last.is_some());
        let last = last.unwrap();

        assert!(is_match!(*last, Token::Identifier { .. }));
        match *last {
            Token::Identifier { ident, .. } => {
                assert_eq!("thing", ident);
            }
            _ => panic!("What just happened?"),
        }
    }

    #[test]
    fn test_pop_last_token_from_single_index_token_is_one() {
        let mut token = Token::Index {
            idx: 0,
            next: Some(Box::new(Token::Index { idx: 1, next: None })),
        };

        let last = token.pop_last();

        assert!(last.is_some());
        let last = last.unwrap();

        assert!(is_match!(*last, Token::Index { idx: 1, .. }));
    }

    #[test]
    fn test_pop_last_token_from_identifier_chain() {
        let tokens = tokenize_with_seperator(&String::from("a.b.c.d.e.f"), '.');
        assert!(tokens.is_ok());
        let mut tokens = tokens.unwrap();

        let last = tokens.pop_last();
        assert!(last.is_some());
        assert_eq!("f", last.unwrap().identifier());
    }

    #[test]
    fn test_pop_last_token_from_mixed_chain() {
        let tokens = tokenize_with_seperator(&String::from("a.[100].c.[3].e.f"), '.');
        assert!(tokens.is_ok());
        let mut tokens = tokens.unwrap();

        let last = tokens.pop_last();
        assert!(last.is_some());
        assert_eq!("f", last.unwrap().identifier());
    }

    #[test]
    fn test_pop_last_token_from_identifier_chain_is_array() {
        let tokens = tokenize_with_seperator(&String::from("a.b.c.d.e.f.[1000]"), '.');
        assert!(tokens.is_ok());
        let mut tokens = tokens.unwrap();

        let last = tokens.pop_last();
        assert!(last.is_some());
        assert_eq!(1000, last.unwrap().idx());
    }

    #[test]
    fn test_pop_last_token_from_mixed_chain_is_array() {
        let tokens = tokenize_with_seperator(&String::from("a.[100].c.[3].e.f.[1000]"), '.');
        assert!(tokens.is_ok());
        let mut tokens = tokens.unwrap();

        let last = tokens.pop_last();
        assert!(last.is_some());
        assert_eq!(1000, last.unwrap().idx());
    }

    #[test]
    fn test_pop_last_token_from_one_token() {
        let tokens = tokenize_with_seperator(&String::from("a"), '.');
        assert!(tokens.is_ok());
        let mut tokens = tokens.unwrap();

        let last = tokens.pop_last();
        assert!(last.is_none());
    }

    #[test]
    fn test_pop_last_chain() {
        let tokens = tokenize_with_seperator(&String::from("a.[100].c.[3].e.f.[1000]"), '.');
        assert!(tokens.is_ok());
        let mut tokens = tokens.unwrap();

        let last = tokens.pop_last();
        assert!(last.is_some());
        assert_eq!(1000, last.unwrap().idx());

        let last = tokens.pop_last();
        assert!(last.is_some());
        assert_eq!("f", last.unwrap().identifier());

        let last = tokens.pop_last();
        assert!(last.is_some());
        assert_eq!("e", last.unwrap().identifier());

        let last = tokens.pop_last();
        assert!(last.is_some());
        assert_eq!(3, last.unwrap().idx());

        let last = tokens.pop_last();
        assert!(last.is_some());
        assert_eq!("c", last.unwrap().identifier());

        let last = tokens.pop_last();
        assert!(last.is_some());
        assert_eq!(100, last.unwrap().idx());

        let last = tokens.pop_last();
        assert!(last.is_none());
    }
}