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
use crate::privatestructs::{Counter, Switch};
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::iter::Peekable;
use std::str::Chars;

mod privatestructs;

/// The constant `OPERATORS` contains a string that lists
/// all possible operators that can be used in expressions.
pub const OPERATORS: &str = "=+-*/%&|<>!^:;.,()[]{}@$?~`";

/// An enumeration of Python tokens.
///
/// # Example
///
/// ```rust
/// use tokenizer_py::{Tokenizer, Token};
///
/// struct BinaryExp{
///     left: Token, center: Token,right: Token,
/// }
/// impl BinaryExp {
///     fn new(left: Token, center: Token, right: Token) -> Self {
///         BinaryExp { left, center, right}
///     }
///     fn execute(&self) -> Result<isize, <isize as std::str::FromStr>::Err> {
///         use Token::{Number, OP};
///         match (&self.left, &self.center, &self.right) {
///             (Number(ref left), OP(ref op), Number(ref right)) => match op.as_str() {
///                 "+" => Ok(left.parse::<isize>()? + right.parse::<isize>()?),
///                 "-" => Ok(left.parse::<isize>()? - right.parse::<isize>()?),
///                 "*" => Ok(left.parse::<isize>()? * right.parse::<isize>()?),
///                 "/" => Ok(left.parse::<isize>()? / right.parse::<isize>()?),
///                 "%" => Ok(left.parse::<isize>()? % right.parse::<isize>()?),
///                 _ => panic!("Invalid operator"),
///             }
///             _ => panic!("Invalid tokens"),
///         }
///     }
/// }
///
/// let tokenizer = Tokenizer::new("10 + 10".to_owned());
/// let mut tokens = tokenizer.tokenize().unwrap();
/// let _ = tokens.pop(); // remove EndMarker
///
/// let binexp = BinaryExp::new(
///     tokens.pop().unwrap(),
///     tokens.pop().unwrap(),
///     tokens.pop().unwrap()
/// );
///
/// assert_eq!(binexp.execute(), Ok(20));
///
/// ```
#[derive(Debug, PartialEq, Eq)]
pub enum Token {
    /// Indicates the end of the program.
    EndMarker,
    /// A name token, such as a function or variable name.
    Name(String),
    /// A number token, such as a literal integer or floating-point number.
    Number(String),
    /// A string token, such as a single or double-quoted string.
    String(String),
    /// A newline token, indicating a new line in the source code.
    NewLine,
    /// An operator token, such as an arithmetic or comparison operator.
    OP(String),
    /// An indent token, indicating that a block of code is being indented.
    Indent(String),
    /// A dedent token, indicating that a block of code is being dedented.
    Dedent,
    /// A comment token, such as a single-line or multi-line comment.
    Comment(String),
    /// A token indicating a new line, for compatibility with the original tokenizer.
    NL,
}


/// An enumeration of possible errors that can occur during tokenization.
///
/// # Examples
///
/// ```
/// use tokenizer_py::{Tokenizer, Token, TokenizerError};
///
/// let tokenizer = Tokenizer::new("1..1".to_string());
/// if let Err(err) = tokenizer.tokenize() {
///     assert_eq!(TokenizerError::Number("1..1".to_owned()), err);
/// }
/// ```
#[derive(PartialEq, Eq)]
pub enum TokenizerError {
    /// An invalid operator was encountered.
    Operator(String),
    /// An invalid number was encountered.
    Number(String),
    /// An invalid indent was encountered.
    Indent(String),
    /// An invalid string was encountered.
    String(String),
}

impl Debug for TokenizerError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            TokenizerError::Operator(s) => write!(f, "Invalid operator: {:?}", s),
            TokenizerError::Number(s) => write!(f, "Invalid number: {:?}", s),
            TokenizerError::Indent(s) => write!(f, "Invalid indent: {:?}", s),
            TokenizerError::String(s) => write!(f, "Invalid string: {:?}", s),
        }
    }
}

impl Display for TokenizerError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            TokenizerError::Operator(s) => write!(f, "Invalid operator: {}", s),
            TokenizerError::Number(s) => write!(f, "Invalid number: {}", s),
            TokenizerError::Indent(s) => write!(f, "Invalid indent: {}", s),
            TokenizerError::String(s) => write!(f, "Invalid string: {}", s),
        }
    }
}

impl Error for TokenizerError {
    fn description(&self) -> &str {
        match *self {
            TokenizerError::Operator(ref s) => s,
            TokenizerError::Number(ref s) => s,
            TokenizerError::Indent(ref s) => s,
            TokenizerError::String(ref s) => s,
        }
    }
}

/// A struct that can tokenize a string into tokens.
///
/// # Examples
///
/// ```
/// use tokenizer_py::{Tokenizer, Token};
///
/// let tokenizer = Tokenizer::new("hello world".to_string());
/// let tokens = tokenizer.tokenize().unwrap();
/// assert_eq!(tokens, vec![
///     Token::Name("hello".to_string()),
///     Token::Name("world".to_string()),
///     Token::EndMarker,
/// ]);
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct Tokenizer {
    text: String,
}


impl Tokenizer {
    /// Creates a new tokenizer that will tokenize the given text.
    ///
    /// # Examples
    ///
    /// ```
    /// use tokenizer_py::Tokenizer;
    ///
    /// let tokenizer = Tokenizer::new("hello world".to_string());
    /// ```
    #[inline]
    pub const fn new(text: String) -> Tokenizer {
        Tokenizer { text }
    }
    /// Tokenizes the text that was provided to the tokenizer's constructor.
    ///
    /// # Examples
    ///
    /// ```
    /// use tokenizer_py::{Token, Tokenizer};
    ///
    /// let tokenizer = Tokenizer::new("hello\nworld".to_string());
    /// let tokens = tokenizer.tokenize().unwrap();
    ///
    /// assert_eq!(tokens, vec![
    ///     Token::Name("hello".to_string()),
    ///     Token::NewLine,
    ///     Token::Name("world".to_string()),
    ///     Token::EndMarker,
    /// ]);
    /// ```
    pub fn tokenize(&self) -> Result<Vec<Token>, TokenizerError> {
        let mut tokens = Vec::new();
        let mut standart_indent = String::new();
        let mut stack_of_indents = Vec::new();
        let mut indent_count = Counter::new();
        let mut line_iter = self.text.chars().peekable();
        let mut is_start_of_line = Switch::new();
        let mut opening = Switch::new();
        while let Some(c) = line_iter.peek() {
            if is_start_of_line.is_on() &&
                stack_of_indents.len() == *indent_count.get() &&
                !stack_of_indents.is_empty() {
                tokens.push(Token::Dedent);
                stack_of_indents.pop();
                indent_count.dec();
            }
            if c.is_whitespace() {
                match c {
                    '\n' => if is_start_of_line.is_on() | opening.is_on() {
                        line_iter.next();
                        tokens.push(Token::NL);
                    } else {
                        line_iter.next();
                        tokens.push(Token::NewLine);
                        is_start_of_line.on();
                    }
                    ' ' | '\t' => if is_start_of_line.is_on() && *indent_count.get() > 0 {
                        let new_indent = self.collect_indent(&mut line_iter)?;
                        if standart_indent.is_empty() {
                            standart_indent.push_str(new_indent.clone().as_str())
                        } else if (new_indent.len() % standart_indent.len()) > 0 {
                            return Err(TokenizerError::Indent(new_indent.clone()));
                        }
                        if *indent_count.get() > stack_of_indents.len() {
                            stack_of_indents.push(new_indent.clone());
                            tokens.push(Token::Indent(new_indent));
                        }
                        is_start_of_line.off();
                    } else {
                        line_iter.next();
                    }
                    _ => { line_iter.next(); }
                }
            } else if c.is_ascii_digit() {
                tokens.push(Token::Number(self.collect_number(&mut line_iter)?));
                is_start_of_line.off();
            } else if c.is_alphabetic() || *c == '_' {
                tokens.push(Token::Name(self.collect_name(&mut line_iter)));
                is_start_of_line.off();
            } else if "\"'".contains(*c) {
                tokens.push(Token::String(self.collect_string(&mut line_iter)?));
                is_start_of_line.off();
            } else if OPERATORS.contains(*c) {
                let op = self.collect_op(&mut line_iter)?;
                match op.as_str() {
                    ":" => indent_count.inc(),
                    "(" | "{" | "[" => opening.on(),
                    ")" | "}" | "]" => opening.off(),
                    _ => {}
                }
                tokens.push(Token::OP(op));
                is_start_of_line.off();
            } else if c == &'#' {
                tokens.push(Token::Comment(self.collect_comment(&mut line_iter)));
            } else {
                line_iter.next();
            }
        }
        tokens.push(Token::EndMarker);
        Ok(tokens)
    }
    /// private method to collect padding as Python tokenizer
    fn collect_indent(&self, line: &mut Peekable<Chars>) -> Result<String, TokenizerError> {
        let mut new_indent = String::new();
        while let Some(c2) = line.peek() {
            match c2 {
                '\t' => new_indent.push('\t'),
                ' ' => new_indent.push(' '),
                _ => break,
            }
            line.next();
        }
        Ok(new_indent)
    }
    /// private method to collect number as Python tokenizer
    fn collect_number(&self, line: &mut Peekable<Chars>) -> Result<String, TokenizerError> {
        let mut number = String::new();
        while let Some(c) = line.next_if(|c| c.is_ascii_digit() || "_.".contains(*c)) {
            number.push(c);
        }
        if number.chars().filter(|c| c == &'.').count() > 1 {
            return Err(TokenizerError::Number(number));
        }
        Ok(number)
    }
    /// private method to collect names as Python tokenizer
    fn collect_name(&self, line: &mut Peekable<Chars>) -> String {
        let mut name = String::new();
        while let Some(c) = line.next_if(
            |c| !c.is_whitespace() && !OPERATORS.contains(*c)) {
            name.push(c);
        }
        name
    }
    /// private method to collect operators as Python tokenizer
    fn collect_op(&self, line: &mut Peekable<Chars>) -> Result<String, TokenizerError> {
        Ok(match line.next().unwrap() {
            '=' => "=".to_owned(),
            '+' => match line.peek() {
                Some('=') => {
                    line.next();
                    "+=".to_owned()
                }
                _ => "+".to_owned(),
            },
            '-' => match line.peek() {
                Some('=') => {
                    line.next();
                    "-=".to_owned()
                }
                _ => "-".to_owned(),
            },
            '*' => match line.peek() {
                Some('=') => {
                    line.next();
                    "*=".to_owned()
                }
                Some('*') => {
                    line.next();
                    match line.peek() {
                        Some('=') => {
                            line.next();
                            "**=".to_owned()
                        }
                        _ => "**".to_owned(),
                    }
                }
                _ => "*".to_owned(),
            },
            '/' => match line.peek() {
                Some('=') => {
                    line.next();
                    "/=".to_owned()
                }
                Some('/') => {
                    line.next();
                    match line.peek() {
                        Some('=') => {
                            line.next();
                            "//=".to_owned()
                        }
                        _ => "//".to_owned(),
                    }
                }
                _ => "/".to_owned(),
            },
            '%' => match line.peek() {
                Some('=') => {
                    line.next();
                    "%=".to_owned()
                }
                _ => "%".to_owned(),
            }
            '&' => match line.peek() {
                Some('=') => {
                    line.next();
                    "&=".to_owned()
                }
                _ => "&".to_owned(),
            },
            '|' => match line.peek() {
                Some('=') => {
                    line.next();
                    "|=".to_owned()
                }
                _ => "|".to_owned(),
            }
            '<' => match line.peek() {
                Some('=') => {
                    line.next();
                    "<=".to_owned()
                }
                Some('<') => {
                    line.next();
                    match line.peek() {
                        Some('=') => {
                            line.next();
                            "<<=".to_owned()
                        }
                        _ => "<<".to_owned(),
                    }
                }
                _ => "<".to_owned(),
            },
            '>' => match line.peek() {
                Some('=') => {
                    line.next();
                    ">=".to_owned()
                }
                Some('>') => {
                    line.next();
                    match line.peek() {
                        Some('=') => {
                            line.next();
                            ">>=".to_owned()
                        }
                        _ => ">>".to_owned(),
                    }
                }
                _ => ">".to_owned(),
            },
            '!' => match line.peek() {
                Some('=') => {
                    line.next();
                    "!=".to_owned()
                }
                _ => "!".to_owned(),
            },
            '^' => match line.peek() {
                Some('=') => {
                    line.next();
                    "^=".to_owned()
                }
                _ => "^".to_owned(),
            }
            ':' => match line.peek() {
                Some('=') => {
                    line.next();
                    ":=".to_owned()
                }
                _ => ":".to_owned(),
            },
            ';' => ";".to_owned(),
            '.' => ".".to_owned(),
            ',' => ",".to_owned(),
            '(' => "(".to_owned(),
            ')' => ")".to_owned(),
            '[' => "[".to_owned(),
            ']' => "]".to_owned(),
            '{' => "{".to_owned(),
            '}' => "}".to_owned(),
            '@' => match line.peek() {
                Some('=') => {
                    line.next();
                    "@=".to_owned()
                }
                _ => "@".to_owned(),
            }
            '$' => "$".to_owned(),
            '?' => "?".to_owned(),
            '~' => "~".to_owned(),
            '`' => "`".to_owned(),
            op => return Err(TokenizerError::Operator(op.to_string()))
        })
    }
    /// private method to collect string as Python tokenizer
    fn collect_string(&self, line: &mut Peekable<Chars>) -> Result<String, TokenizerError> {
        let mut string = String::new();
        let quot = line.next().unwrap();
        while let Some(c) = line.peek() {
            if *c == quot {
                line.next();
                break;
            }
            match c {
                '\\' => if let Some(c) = &line.next() {
                    match c {
                        '\\' => string.push('\\'),
                        '"' => string.push('"'),
                        '\'' => string.push('\''),
                        'n' => string.push('\n'),
                        'r' => string.push('\r'),
                        't' => string.push('\t'),
                        'b' => string.push('\x08'),
                        'f' => string.push('\x0C'),
                        _ => return Err(TokenizerError::String(string)),
                    }
                }
                c => string.push(*c),
            }
            line.next();
        }
        Ok(string)
    }
    /// private method to collect comment as Python tokenizer
    fn collect_comment(&self, line: &mut Peekable<Chars>) -> String {
        let mut comment = String::new();
        while let Some(c) = line.next_if(|c| *c != '\n') {
            comment.push(c);
        }
        comment
    }
}

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

    #[test]
    fn tokenizer_work() {
        let tokenizer = Tokenizer::new("hello\n'world'\n2 + 2".to_owned());
        let tokens = tokenizer.tokenize().unwrap();
        let expects = vec![
            Token::Name("hello".to_owned()),
            Token::NewLine,
            Token::String("world".to_owned()),
            Token::NewLine,
            Token::Number("2".to_owned()),
            Token::OP("+".to_owned()),
            Token::Number("2".to_owned()),
            Token::EndMarker,
        ];
        for (actual, expect) in tokens.iter().zip(expects.iter()) {
            assert_eq!(actual, expect);
        }
    }
}