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
pub mod types;

use crate::diagnostics::Diagnostic;
use types::TokenType as TT;
pub use types::*;

pub struct ScanResult {
    pub tokens: Vec<Token>,
    pub diagnostics: Vec<Diagnostic>,
}

pub fn scan<'a, T: Into<&'a str>>(input: T) -> ScanResult {
    let mut scanner = Scanner::new(input.into());
    scanner.scan();
    ScanResult {
        tokens: scanner.output,
        diagnostics: scanner.diagnostics,
    }
}

struct Scanner {
    pos: usize,
    input: Vec<char>,
    pub output: Vec<Token>,
    pub diagnostics: Vec<Diagnostic>,
}

macro_rules! tok {
    ($ty:expr, $pos:expr) => {
        Token::new($ty, $pos)
    };
}

impl Scanner {
    // instantiate a new scanner
    pub fn new(input: &str) -> Scanner {
        Scanner {
            pos: 0,
            input: input.chars().collect(),
            output: Vec::new(),
            diagnostics: Vec::new(),
        }
    }

    #[inline]
    fn peek(&self) -> Option<&char> {
        self.input.get(self.pos)
    }

    #[inline]
    fn next(&mut self) -> Option<&char> {
        let ch = self.input.get(self.pos);
        self.pos += 1;
        ch
    }

    #[inline]
    fn push_diag(&mut self, diagnostic: Diagnostic) {
        self.diagnostics.push(diagnostic);
    }

    fn collect_while(&mut self, pred: fn(&char) -> bool) -> String {
        let mut s = String::with_capacity(8);
        while let Some(true) = self.peek().map(pred) {
            s.push(*self.next().unwrap());
        }
        s
    }

    pub fn scan(&mut self) {
        // iterate through string
        while let Some(c) = self.peek() {
            match c {
                _ if c.is_whitespace() => {
                    self.next();
                }
                _ if c.is_digit(10) => self.scan_num(),
                '$' => self.scan_var_pattern(),
                '#' => self.scan_const_pattern(),
                '_' => self.scan_any_pattern(),
                _ if c.is_alphabetic() => self.scan_var(),
                _ => self.scan_symbol(),
            }
        }

        self.output.push(tok!(TT::EOF, (self.pos, self.pos + 1)));
    }

    // matches token with symbol and creates it: private helper function
    fn scan_symbol(&mut self) {
        use TokenType::*;
        let start = self.pos;
        let ty = match self.next().unwrap() {
            '+' => Plus,
            '-' => Minus,
            '*' => Mult,
            '/' => Div,
            '%' => Mod,
            '^' => Exp,
            '=' => Equal,
            '(' => OpenParen,
            ')' => CloseParen,
            '[' => OpenBracket,
            ']' => CloseBracket,
            c => Invalid(c.to_string()),
        };
        let span = start..self.pos;

        if matches!(ty, Invalid(..)) {
            let diag = Diagnostic::span_err(span.clone(), "Invalid token", None)
                .with_note("token must be mathematically significant");
            self.push_diag(diag);
        }
        self.output.push(tok!(ty, span));
    }

    // iterates through any digits to create a token of that value
    fn scan_num(&mut self) {
        let start = self.pos;

        let mut float_str = self.collect_while(|c| c.is_digit(10));
        if let Some('.') = self.peek() {
            float_str.push(*self.next().unwrap());
            float_str.push_str(&self.collect_while(|c| c.is_digit(10)));
        }
        let float = float_str.parse::<f64>().unwrap();

        self.output.push(tok!(TT::Float(float), (start, self.pos)));
    }

    fn scan_var_str(&mut self) -> String {
        self.collect_while(|c| c.is_alphabetic())
    }

    fn scan_var(&mut self) {
        let start = self.pos;

        let var_name = self.scan_var_str();
        self.output
            .push(tok!(TT::Variable(var_name), (start, self.pos)));
    }

    fn scan_var_pattern(&mut self) {
        let start = self.pos;

        let mut pat = String::with_capacity(4);
        // Push the pattern prefix, which we already verified exists.
        pat.push(*self.next().unwrap());
        pat.push_str(&self.scan_var_str());

        self.output
            .push(tok!(TT::VariablePattern(pat), (start, self.pos)));
    }

    fn scan_const_pattern(&mut self) {
        let start = self.pos;

        let mut pat = String::with_capacity(4);
        // Push the pattern prefix, which we already verified exists.
        pat.push(*self.next().unwrap());
        pat.push_str(&self.scan_var_str());

        self.output
            .push(tok!(TT::ConstPattern(pat), (start, self.pos)));
    }

    fn scan_any_pattern(&mut self) {
        let start = self.pos;

        let mut pat = String::with_capacity(4);
        // Push the pattern prefix, which we already verified exists.
        pat.push(*self.next().unwrap());
        pat.push_str(&self.scan_var_str());

        self.output
            .push(tok!(TT::AnyPattern(pat), (start, self.pos)));
    }
}

#[cfg(test)]
mod tests {
    // Tests the Scanner's output against a humanized string representation of the expected tokens.
    // See [Token]'s impl of Display for more details.
    // [Token]: src/scanner/types.rs
    macro_rules! scanner_tests {
        ($($name:ident: $program:expr, $format_str:expr)*) => {
        $(
            #[test]
            fn $name() {
                use crate::common::Span;
                use crate::scanner::scan;

                let mut tokens = scan($program).tokens;
                tokens.pop(); // EOF

                // First check if token string matches.
                let tokens_str = tokens
                    .iter()
                    .map(|tok| tok.to_string())
                    .collect::<Vec<_>>().join(" ");
                assert_eq!(tokens_str, $format_str);

                // Now check the token spans are correct.
                for token in tokens {
                    let Span {lo, hi} = token.span;
                    assert_eq!($program[lo..hi], token.to_string());
                }
            }
        )*
        }
    }

    mod scan {
        scanner_tests! {
            integer: "2", "2"
            float: "3.2", "3.2"
            plus: "+", "+"
            minus: "-", "-"
            mult: "*", "*"
            div: "/", "/"
            modulo: "%", "%"
            exp: "^", "^"
            equal: "=", "="
            open_paren: "(", "("
            close_paren: ")", ")"
            open_bracket: "[", "["
            close_bracket: "]", "]"
            variable_pattern: "$a", "$a"
            const_pattern: "#a", "#a"
            any_pattern: "_a", "_a"

            empty_string: "", ""
            skip_whitespace: "  =  ", "="

            multiple_integers: "1 2 3", "1 2 3"
            multiple_floats: "1.2 2.3 3.4", "1.2 2.3 3.4"
            multiple_numbers_mixed: "1 2.3 4", "1 2.3 4"

            expressions: "1 + 2 ^ 5", "1 + 2 ^ 5"

            variables: "a = 5", "a = 5"
            variables_cap: "ABcd = 5", "ABcd = 5"
        }
    }

    mod scan_invalid {
        scanner_tests! {
            invalid_numbers: "1.2.3", "1.2 . 3"
            invalid_tokens: "@", "@"
            invalid_tokens_mixed_with_valid: "=@/", "= @ /"
            invalid_expressions: "1 + * 2", "1 + * 2"
        }
    }
}