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
/// 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),
}

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

impl<'a> ForthTokenizer<'a> {
    pub fn new(to_tokenize: &'a str) -> ForthTokenizer<'a> {
        ForthTokenizer {
            to_tokenize: 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() {
            return 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[..start.len() - 1],
                            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 {
            return 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<'a>(to_split: &'a str) -> (&'a str, &'a 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() {
            return match rest.chars().next().unwrap() {
                '\n' => (first, &rest[1..]),
                _ => (first, rest),
            };
        } else {
            return (first, "");
        }
    } else {
        return ("", "");
    }
}

fn split_at_ascii_whitespace<'a>(to_split: &'a str) -> (&'a str, &'a 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() {
            return match rest.chars().next().unwrap() {
                '\n' => (first, &rest[1..]),
                _ => (first, rest),
            };
        } else {
            return (first, "");
        }
    } else {
        return ("", "");
    }
}

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

#[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_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)
            ]
        );
    }
}