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
// Copyright (c) 2016-2020 Fabian Schuiki

//! The categorizing lexer. Tokenizes an input stream of characters, yielding a
//! stream of newline, whitespace, comment, symbol, and text tokens.
//!
//! # Example
//! ```
//! extern crate moore_svlog_syntax;
//! let input = "Löwe 老虎 Léopard\n";
//! let mut cat = moore_svlog_syntax::cat::Cat::new(Box::new(input.char_indices()));
//! let tokens: Vec<_> = cat.collect();
//! ```

pub use self::CatTokenKind::*;
use moore_common::source::*;

/// The categorizing lexer. Divides an input stream of characters (unicode) into
/// coarse groups of tokens. These include whitespace, comments, symbols, and
/// text. The strings contained in the emitted tokens can be concatenated to
/// arrive at the original file, i.e. no information is lost.
pub struct Cat<'a> {
    iter: Box<CharIter<'a>>,
    last: usize,
    chars: (Option<char>, Option<char>),
    indices: (usize, usize),
}

impl<'a> Cat<'a> {
    /// Create a new categorizing lexer from an `CharIter` iterator.
    pub fn new(mut iter: Box<CharIter<'a>>) -> Cat<'a> {
        let last = iter
            .size_hint()
            .1
            .expect("Iterator must provide upper bounds");
        let c0 = iter.next();
        let c1 = iter.next();
        Cat {
            iter: iter,
            last: last,
            chars: (c0.map(|x| x.1), c1.map(|x| x.1)),
            indices: (
                c0.map(|x| x.0).unwrap_or(last),
                c1.map(|x| x.0).unwrap_or(last),
            ),
        }
    }

    /// Advance to the next character in the input stream.
    fn bump(&mut self) {
        let c = self.iter.next();
        self.chars = (self.chars.1, c.map(|x| x.1));
        self.indices = (self.indices.1, c.map(|x| x.0).unwrap_or(self.last));
    }
}

impl<'a> Iterator for Cat<'a> {
    type Item = CatToken;

    fn next(&mut self) -> Option<Self::Item> {
        match self.chars {
            (None, _) => None,

            // Newlines
            (Some('\n'), _) => {
                let t = CatToken(Newline, self.indices.0, self.indices.1);
                self.bump();
                Some(t)
            }

            // Whitespace characters
            (Some(c), _) if is_whitespace(c) => {
                let p0 = self.indices.0;
                while let (Some(c), _) = self.chars {
                    if !is_whitespace(c) {
                        break;
                    }
                    self.bump();
                }
                Some(CatToken(Whitespace, p0, self.indices.0))
            }

            // IEEE 1800-2009 5.4 Comments
            // Consume single-line comments initiated by "//".
            (Some('/'), Some('/')) => {
                let p0 = self.indices.0;
                while let (Some(c), _) = self.chars {
                    if c == '\n' {
                        break;
                    }
                    self.bump();
                }
                Some(CatToken(Comment, p0, self.indices.0))
            }

            // Consume multi-line comments inititated by "/*".
            (Some('/'), Some('*')) => {
                let p0 = self.indices.0;
                while let (Some(c0), Some(c1)) = self.chars {
                    if c0 == '*' && c1 == '/' {
                        self.bump();
                        self.bump();
                        break;
                    }
                    self.bump();
                }
                Some(CatToken(Comment, p0, self.indices.0))
            }

            // Consume symbols.
            // IEEE 1800-2009 5.5 Operators & 11.3 Operators
            (Some(c), _) if is_symbol(c) => {
                let t = CatToken(Symbol(c), self.indices.0, self.indices.1);
                self.bump();
                Some(t)
            }

            // Consume digits.
            (Some(c), _) if is_digit(c) => {
                let p0 = self.indices.0;
                while let (Some(c), _) = self.chars {
                    if !is_digit(c) {
                        break;
                    }
                    self.bump();
                }
                Some(CatToken(Digits, p0, self.indices.0))
            }

            // Consume text.
            (Some(_), _) => {
                let p0 = self.indices.0;
                while let (Some(c), _) = self.chars {
                    if c == '\n' || is_whitespace(c) || is_symbol(c) {
                        break;
                    }
                    self.bump();
                }
                Some(CatToken(Text, p0, self.indices.0))
            }
        }
    }
}

/// Check whether the given character is considered a whitespace in
/// SystemVerilog.
fn is_whitespace(c: char) -> bool {
    c == ' ' || c == '\t' || c == '\r' || c == (0xA0 as char)
}

/// Check whether the given character is a digit.
fn is_digit(c: char) -> bool {
    c >= '0' && c <= '9'
}

/// Check whether the given character is considered a symbol in SystemVerilog.
fn is_symbol(c: char) -> bool {
    match c {
        '(' | ')' | '[' | ']' | '{' | '}' | '#' | ':' | ';' | '.' | ',' | '=' | '+' | '-' | '*'
        | '/' | '~' | '|' | '<' | '>' | '!' | '%' | '^' | '&' | '?' | '\'' | '"' | '`' | '$'
        | '\\' | '@' => true,
        //'_' => true,
        _ => false,
    }
}

/// A token emitted by the categorizing lexer.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct CatToken(pub CatTokenKind, pub usize, pub usize);

/// The different kinds of tokens the categorizing lexer can emit.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum CatTokenKind {
    Newline,
    Whitespace,
    Comment,
    Symbol(char),
    Text,
    Digits,
    Eof,
}

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

    fn lex(input: &str) -> Vec<CatToken> {
        Cat::new(Box::new(input.char_indices())).collect()
    }

    #[test]
    fn empty() {
        assert_eq!(lex(""), vec![]);
    }

    #[test]
    fn non_empty() {
        assert_eq!(
            lex("Löwe 老虎 1234Léopard\n"),
            vec![
                CatToken(Text, 0, 5),
                CatToken(Whitespace, 5, 6),
                CatToken(Text, 6, 12),
                CatToken(Whitespace, 12, 13),
                CatToken(Digits, 13, 17),
                CatToken(Text, 17, 25),
                CatToken(Newline, 25, 26),
            ]
        );
    }
}