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
//! Provides a tokenizer for the Elemental interpreter.

use crate::error::*;

/// Outlines the types of tokens that Elemental can process.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum TokenClass {
    Identifier,
    Int,
    Float,
    Assignment,
    Plus,
    Minus,
    Multiply,
    Divide,
    Eq,
    Semicolon,
    Comma,
    Newline,
    OpenParen,
    CloseParen,
    OpenBracket,
    CloseBracket,
}

/// Holds a token's class and its value.
#[derive(Clone, Debug)]
pub struct Token {
    class: TokenClass,
    value: String,
}

impl Token {
    /// Constructs a new `Token` from a value and a `TokenClass`.
    pub fn new(class: TokenClass, value: String) -> Self {
        Self {
            class,
            value,
        }
    }

    /// Gets the class of the token.
    pub fn get_class(&self) -> TokenClass {
        self.class
    }

    /// Gets the value of the token.
    pub fn get_value(&self) -> String {
        self.value.to_owned()
    }

    /// Checks if the token is in the given class.
    pub fn check(&self, class: TokenClass) -> bool {
        self.class == class
    }
}


/// Holds a stream of characters.
pub struct CharStream {
    characters: Vec<char>,
    index: usize,
}

impl CharStream {
    /// Constructs a new character stream from a `String`.
    pub fn from(input: String) -> Self {
        let characters = input.as_str().chars().collect::<Vec<char>>();
        let index = 0;

        Self {
            characters,
            index,
        }
    }

    /// Advances the character stream.
    pub fn next(&mut self) -> Option<char> {
        let character = self.peek();
        if self.index >= self.characters.len() {
            None
        } else {
            self.index += 1;
            character
        }
    }

    /// Peeks at the next character in the stream.
    pub fn peek(&self) -> Option<char> {
        if self.index >= self.characters.len() {
            None
        } else {
            Some (self.characters[self.index])
        }
    }

    /// Looks ahead `n` characters.
    /// 
    /// `Self::lookahead(0)` is equivalent to `Self::peek()`.
    pub fn lookahead(&self, n: usize) -> Option<char> {
        if self.index >= self.characters.len() {
            None
        } else {
            Some (self.characters[self.index + n])
        }
    }

    /// Iterates through a stream of characters, pushing characters to a `String`
    /// so long as they are in a given superstring.  Once a character is found that
    /// is not in the given superstring, stops and returns the `String`.
    pub fn get(&mut self, superstring: &str) -> String {
        let mut current = String::new();
        while let Some(c) = self.peek() {
            if superstring.contains(c) {
                self.next();
                current.push(c);
            } else {
                break;
            }
        }
        current
    }

    /// Skips comments.
    pub fn skip_comments(&mut self) {
        while self.peek() == Some('/') && self.lookahead(1) == Some('/') {
            while self.peek() != Some('\n') {
                self.next();
            }
            // Consume the newline
            self.next();
        }
    }
}


/// Characters that can compose an identifier.
/// 
/// Please note that, though numbers are included here, identifiers cannot start
/// with a numeric digit (`'0'..='9'`).
const IDENTIFIER: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";


/// Numeric values.  These can compose a numeric literal.
/// 
/// Please note that numeric literals cannot start with `'.'`.
const NUMERIC: &str = "01235456789.";


/// Separators & whitespace.  To be ignored.
const SEPARATORS: &str = " \t\n";


/// Holds a stream of tokens.
pub struct Tokenizer {
    tokens: Vec<Token>,
    index: usize,
}

impl Tokenizer {
    /// Constructs a new token stream from a `String`.
    pub fn from(input: String) -> Self {
        let index = 0;
        let mut charstream = CharStream::from(input);
        let mut tokens = Vec::new();

        // Skip any comments
        charstream.skip_comments();

        while let Some(c) = charstream.next() {
            if SEPARATORS.contains(c) {
                continue;
            }

            let token = match c {
                'a'..='z' | 'A'..='Z' | '_' => {
                    let name = format!(
                        "{}{}",
                        c,
                        charstream.get(IDENTIFIER),
                    );
                    Token::new(TokenClass::Identifier, name)
                },
                '0'..='9' => {
                    let raw = format!(
                        "{}{}",
                        c,
                        charstream.get(NUMERIC),
                    );
                    
                    let token = match str::parse::<i64>(&raw) {
                        Ok(_) => Token::new(TokenClass::Int, raw),
                        Err(_) => match str::parse::<f64>(&raw) {
                            Ok(_) => Token::new(TokenClass::Float, raw),
                            Err(_) => {
                                throw(CouldNotParseNumeric);
                                Token::new(TokenClass::Float, "0.0".to_string())
                            },
                        },
                    };
                    token
                },
                '=' => if charstream.peek() == Some('=') {
                    Token::new(TokenClass::Eq, "==".to_string())
                } else if let Some(_) = charstream.peek() {
                    Token::new(TokenClass::Assignment, "=".to_string())
                } else {
                    throw(UnexpectedEof);
                    Token::new(TokenClass::Newline, '\n'.to_string())
                },
                '\n' => Token::new(TokenClass::Newline, '\n'.to_string()),
                '+' => Token::new(TokenClass::Plus, '+'.to_string()),
                '-' => {
                    let chr = match charstream.peek() {
                        Some(p) => p,
                        None => {
                            throw(UnexpectedEof);
                            '\n'
                        },
                    };
                    if NUMERIC.contains(chr) {
                        let raw = format!(
                            "{}{}",
                            c,
                            charstream.get(NUMERIC),
                        );
                        
                        let token = match str::parse::<i64>(&raw) {
                            Ok(_) => Token::new(TokenClass::Int, raw),
                            Err(_) => match str::parse::<f64>(&raw) {
                                Ok(_) => Token::new(TokenClass::Float, raw),
                                Err(_) => {
                                    throw(CouldNotParseNumeric);
                                    Token::new(TokenClass::Float, "0.0".to_string())
                                },
                            },
                        };
                        token
                    } else {
                        Token::new(TokenClass::Minus, '-'.to_string())
                    }
                }
                '*' => Token::new(TokenClass::Multiply, '*'.to_string()),
                '/' => Token::new(TokenClass::Divide, '/'.to_string()),
                ';' => Token::new(TokenClass::Semicolon, ';'.to_string()),
                '(' => Token::new(TokenClass::OpenParen, '('.to_string()),
                ')' => Token::new(TokenClass::CloseParen, ')'.to_string()),
                '[' => Token::new(TokenClass::OpenBracket, '['.to_string()),
                ']' => Token::new(TokenClass::CloseBracket, ']'.to_string()),
                ',' => Token::new(TokenClass::Comma, ';'.to_string()),
                _ => {
                    throw(UnexpectedEof);
                    Token::new(TokenClass::Newline, '\n'.to_string())
                },
            };
            tokens.push(token);

            // Skip comments
            charstream.skip_comments();
        }

        Self {
            tokens,
            index,
        }
    }

    /// Peeks at the next character in the stream.
    pub fn peek(&self) -> Option<Token> {
        if self.index >= self.tokens.len() {
            None
        } else {
            Some (self.tokens[self.index].to_owned())
        }
    }

    /// Advances the character stream.
    pub fn next(&mut self) -> Option<Token> {
        let token = self.peek();
        self.index += 1;
        token
    }

    /// Returns all tokens without consuming the tokenizer.
    pub fn get_tokens(&mut self) -> Vec<Token> {
        self.tokens.to_owned()
    }

    /// Checks whether or not the last token is a semicolon.
    /// 
    /// Lines that end with semicolons are not displayed.
    pub fn chk_silent(&self) -> bool {
        if self.tokens.len() != 0 {
            self.tokens.len() != 0 && self.tokens[self.tokens.len() - 1].get_class() == TokenClass::Semicolon
        } else {
            true
        }
    }

    /// Get the precedence of the next token.
    pub fn get_next_precedence(&self) -> u8 {
        if let Some(t) = self.peek() {
            t.get_class().into()
        } else {
            0
        }
    }
}

#[test]
fn tokenize_00() {
    let input: String = "x = 1.3\ny = 2.6".to_string();
    let mut tokenizer = Tokenizer::from(input);
    println!("Tokens: {:#?}", tokenizer.get_tokens());
}