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
/// This is how to use the Forth tokenizer library
/// ```
/// use rust_forth_tokenizer::ForthToken;
/// use rust_forth_tokenizer::ForthTokenizer;
///
///     let tokenizer = ForthTokenizer::new("word : wordname 1 2 3 ; definition");
///     // The code also supports the regular for loop iterator syntax
///     let collected: Vec<_> = tokenizer.into_iter().collect();
///     assert_eq!(
///            &collected,
///            &vec![
///                ForthToken::Command("word"),
///                ForthToken::Colon,
///                ForthToken::Command("wordname"),
///                ForthToken::Number(1),
///                ForthToken::Number(2),
///                ForthToken::Number(3),
///                ForthToken::SemiColon,
///                ForthToken::Command("definition"),
///            ]
///        );
/// ```

/// This Enum lists the token types that are used by the Forth interpreter
#[derive(Debug, PartialEq)]
pub enum ForthToken<'a> {
    Number(i64),
    Command(&'a str),
    // Command, string
    StringCommand(&'a str, &'a str),
    Colon,
    SemiColon,
    DropLineComment(&'a str),
    ParenthesizedRemark(&'a str),
}

/// This is the ForthTokenizer, it is the actual tokenizer
pub struct ForthTokenizer<'a> {
    to_tokenize: &'a str,
}

impl<'a> ForthTokenizer<'a> {
    pub fn new(to_tokenize: &'a str) -> ForthTokenizer<'a> {
        ForthTokenizer { to_tokenize }
    }
}

impl<'a> IntoIterator for ForthTokenizer<'a> {
    type Item = ForthToken<'a>;
    type IntoIter = ForthTokenizerIntoIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        ForthTokenizerIntoIterator {
            to_tokenize: self.to_tokenize,
        }
    }
}

pub struct ForthTokenizerIntoIterator<'a> {
    to_tokenize: &'a str,
}

// The `Iterator` trait only requires a method to be defined for the `next` element.
impl<'a> Iterator for ForthTokenizerIntoIterator<'a> {
    type Item = ForthToken<'a>;

    // The return type is `Option<T>`:
    //     * When the `Iterator` is finished, `None` is returned.
    //     * Otherwise, the next value is wrapped in `Some` and returned.
    fn next(&mut self) -> Option<ForthToken<'a>> {
        // We ignore whitespace
        self.to_tokenize = self.to_tokenize.trim_start();

        if let Some(c) = self.to_tokenize.chars().next() {
            match c {
                '\\' => {
                    let (first, rest) = split_at_newline(self.to_tokenize);
                    self.to_tokenize = rest;
                    Some(ForthToken::DropLineComment(first))
                }
                ':' => {
                    self.to_tokenize = &self.to_tokenize[1..];
                    Some(ForthToken::Colon)
                }
                ';' => {
                    self.to_tokenize = &self.to_tokenize[1..];
                    Some(ForthToken::SemiColon)
                }
                '(' => {
                    let (first, rest) = split_at_token(self.to_tokenize, ')');
                    self.to_tokenize = rest;
                    Some(ForthToken::ParenthesizedRemark(first))
                }
                _ => {
                    let (start, rest) = split_at_ascii_whitespace(self.to_tokenize);
                    self.to_tokenize = rest;

                    if start.ends_with('"') {
                        let (newstart, newrest) = split_at_token(rest, '"');
                        self.to_tokenize = newrest;

                        return Some(ForthToken::StringCommand(&start, newstart));
                    }
                    // Determine if its a number or a command
                    match start.parse::<i64>() {
                        // We found a number, then return it as a number token
                        Ok(n) => Some(ForthToken::Number(n)),
                        // Wasn't a number, treat it as a *word*
                        Err(_) => Some(ForthToken::Command(start)),
                    }
                }
            }
        } else {
            None
        }
    }
}

impl<'a> IntoIterator for &'a ForthTokenizer<'a> {
    type Item = ForthToken<'a>;
    type IntoIter = ForthTokenizerIntoIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        ForthTokenizerIntoIterator {
            to_tokenize: self.to_tokenize,
        }
    }
}

fn split_at_newline(to_split: &str) -> (&str, &str) {
    let mut line_iterator = to_split.splitn(2, &['\n', '\r'][..]);
    if let Some(first) = line_iterator.next() {
        if let Some(rest) = line_iterator.next() {
            match rest.chars().next().unwrap() {
                '\n' => (first, &rest[1..]),
                _ => (first, rest),
            }
        } else {
            (first, "")
        }
    } else {
        ("", "")
    }
}

fn split_at_ascii_whitespace(to_split: &str) -> (&str, &str) {
    let mut line_iterator = to_split.splitn(2, |c: char| c.is_ascii_whitespace());
    if let Some(first) = line_iterator.next() {
        if let Some(rest) = line_iterator.next() {
            match rest.chars().next().unwrap() {
                '\n' => (first, &rest[1..]),
                _ => (first, rest),
            }
        } else {
            (first, "")
        }
    } else {
        ("", "")
    }
}

fn split_at_token(to_split: &str, token: char) -> (&str, &str) {
    let mut line_iterator = to_split.splitn(2, token);
    if let Some(first) = line_iterator.next() {
        if let Some(rest) = line_iterator.next() {
            match rest.chars().next().unwrap() {
                '\n' => (first, &rest[1..]),
                _ => (first, rest),
            }
        } else {
            (first, "")
        }
    } else {
        ("", "")
    }
}

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

    #[test]
    fn test_split_at_newline_1() {
        assert_eq!(split_at_newline(""), ("", ""));
    }

    #[test]
    fn test_split_at_newline_2() {
        assert_eq!(split_at_newline("abc"), ("abc", ""));
    }

    #[test]
    fn test_split_at_newline_3() {
        assert_eq!(split_at_newline("abc\r\ndef"), ("abc", "def"));
    }

    #[test]
    fn test_split_at_newline_4() {
        assert_eq!(split_at_newline("abc\ndef"), ("abc", "def"));
        assert_eq!(split_at_newline(""), ("", ""));
    }
    #[test]
    fn test_split_at_newline_5() {
        assert_eq!(
            split_at_newline("abc\r\ndef\r\nghi\r\njkl"),
            ("abc", "def\r\nghi\r\njkl")
        );
    }

    #[test]
    fn test_split_at_newline_6() {
        assert_eq!(
            split_at_newline("abc\ndef\nghi\njkl"),
            ("abc", "def\nghi\njkl")
        );
        assert_eq!(split_at_newline(""), ("", ""));
    }

    #[test]
    fn test_number_1() {
        let tokenizer = ForthTokenizer::new("1 these 2 are 3 words 4");
        let collected: Vec<_> = tokenizer.into_iter().collect();
        assert_eq!(
            &collected,
            &vec![
                ForthToken::Number(1),
                ForthToken::Command("these"),
                ForthToken::Number(2),
                ForthToken::Command("are"),
                ForthToken::Number(3),
                ForthToken::Command("words"),
                ForthToken::Number(4),
            ]
        );
    }

    #[test]
    fn test_command_1() {
        let tokenizer = ForthTokenizer::new("these are #words 1 with 2 numbers");
        let collected: Vec<_> = tokenizer.into_iter().collect();
        assert_eq!(
            &collected,
            &vec![
                ForthToken::Command("these"),
                ForthToken::Command("are"),
                ForthToken::Command("#words"),
                ForthToken::Number(1),
                ForthToken::Command("with"),
                ForthToken::Number(2),
                ForthToken::Command("numbers"),
            ]
        );
    }

    #[test]
    fn test_colon_1() {
        let tokenizer = ForthTokenizer::new("word : wordname 1 2 3 ; definition");
        let collected: Vec<_> = tokenizer.into_iter().collect();
        assert_eq!(
            &collected,
            &vec![
                ForthToken::Command("word"),
                ForthToken::Colon,
                ForthToken::Command("wordname"),
                ForthToken::Number(1),
                ForthToken::Number(2),
                ForthToken::Number(3),
                ForthToken::SemiColon,
                ForthToken::Command("definition"),
            ]
        );
    }

    #[test]
    fn test_semicolon_1() {
        let tokenizer = ForthTokenizer::new("word : wordname 1 $whatever 3 ; definition");
        let collected: Vec<_> = tokenizer.into_iter().collect();
        assert_eq!(
            &collected,
            &vec![
                ForthToken::Command("word"),
                ForthToken::Colon,
                ForthToken::Command("wordname"),
                ForthToken::Number(1),
                ForthToken::Command("$whatever"),
                ForthToken::Number(3),
                ForthToken::SemiColon,
                ForthToken::Command("definition"),
            ]
        );
    }

    #[test]
    fn test_stringcommand_1() {
        let tokenizer = ForthTokenizer::new("1 2 \" This is a string\" 3 4");
        let collected: Vec<_> = tokenizer.into_iter().collect();
        assert_eq!(
            &collected,
            &vec![
                ForthToken::Number(1),
                ForthToken::Number(2),
                ForthToken::StringCommand("\"", "This is a string"),
                ForthToken::Number(3),
                ForthToken::Number(4),
            ]
        );
    }

    #[test]
    fn test_stringcommand_2() {
        let tokenizer = ForthTokenizer::new("1 2 .s\" This is a string\" 3 4");
        let collected: Vec<_> = tokenizer.into_iter().collect();
        assert_eq!(
            &collected,
            &vec![
                ForthToken::Number(1),
                ForthToken::Number(2),
                ForthToken::StringCommand(".s\"", "This is a string"),
                ForthToken::Number(3),
                ForthToken::Number(4),
            ]
        );
    }

    #[test]
    fn test_droplinecomment_1() {
        // Forgot the space after the 2, this will come out totally differently than a comment
        let tokenizer = ForthTokenizer::new("1 2\\ This is a dropline comment\n\r1 3\r\n4");
        let collected: Vec<_> = tokenizer.into_iter().collect();
        assert_eq!(
            &collected,
            &vec![
                ForthToken::Number(1),
                ForthToken::Command("2\\"),
                ForthToken::Command("This"),
                ForthToken::Command("is"),
                ForthToken::Command("a"),
                ForthToken::Command("dropline"),
                ForthToken::Command("comment"),
                ForthToken::Number(1),
                ForthToken::Number(3),
                ForthToken::Number(4),
            ]
        );
    }

    #[test]
    fn test_droplinecomment_2() {
        let tokenizer = ForthTokenizer::new("1 2 \\ This is a dropline comment\n\r1 3\r\n4");
        let collected: Vec<_> = tokenizer.into_iter().collect();
        assert_eq!(
            &collected,
            &vec![
                ForthToken::Number(1),
                ForthToken::Number(2),
                ForthToken::DropLineComment("\\ This is a dropline comment"),
                ForthToken::Number(1),
                ForthToken::Number(3),
                ForthToken::Number(4),
            ]
        );
    }

    #[test]
    fn test_parenthesized_remark_1() {
        // This isn't maybe intuitive, but we lose the trailing ) because its a delimiter... No easy way to change that that I know of
        let tokenizer = ForthTokenizer::new(
            "1 2 \\ This is a dropline comment ( This is not a parenthesized remark )\n\r1 ( This is in fact a parenthesized remark )3\r\n4",
        );
        let collected: Vec<_> = tokenizer.into_iter().collect();
        assert_eq!(
            &collected,
            &vec![
                ForthToken::Number(1),
                ForthToken::Number(2),
                ForthToken::DropLineComment(
                    "\\ This is a dropline comment ( This is not a parenthesized remark )"
                ),
                ForthToken::Number(1),
                ForthToken::ParenthesizedRemark("( This is in fact a parenthesized remark "),
                ForthToken::Number(3),
                ForthToken::Number(4),
            ]
        );
    }

    #[test]
    fn test_bug_1() {
        let tokenizer = ForthTokenizer::new("1 1 1\n2 2 2\n3 3 3");
        let collected: Vec<_> = tokenizer.into_iter().collect();
        assert_eq!(
            &collected,
            &vec![
                ForthToken::Number(1),
                ForthToken::Number(1),
                ForthToken::Number(1),
                ForthToken::Number(2),
                ForthToken::Number(2),
                ForthToken::Number(2),
                ForthToken::Number(3),
                ForthToken::Number(3),
                ForthToken::Number(3)
            ]
        );
    }
}