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
use std::slice::Iter;

use lazy_regex::*;
use regex::CaptureLocations;

use crate::loc::Loc;
use crate::err::Error;
use crate::err::Error::LexError;

static LEX_RE: Lazy<Regex> = lazy_regex!("^\
    (?:\
    (?P<whitespace>[^\\S\n][^\\S\n]*)\
    |\
    (?P<hashcomment>#[^\\n]*)\
    |\
    (?P<cppcomment>//[^\\n]*)\
    |\
    (?P<newline>\\n)\
    |\
    (?P<lparen>\\()\
    |\
    (?P<rparen>\\))\
    |\
    (?P<dot>\\.)\
    |\
    (?P<doublecolon>::)\
    |\
    (?P<colon>:)\
    |\
    (?P<semicolon>;)\
    |\
    (?P<equals>=)\
    |\
    (?P<comma>,)\
    |\
    (?P<slash>/)\
    |\
    (?P<import_keyword>\\bimport\\b)\
    |\
    (?P<let_keyword>\\blet\\b)\
    |\
    (?P<boolean_literal>\\b(?:true|false)\\b)\
    |\
    (?P<identifier>[a-zA-Z_][a-zA-Z0-9_]*)\
    |\
    (?P<ipv4_literal>\
        (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}\
        (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\
    )\
    |\
    (?P<string_literal>\"(?:\\\\.|[^\"\\\\])*\")\
    |\
    (?P<hex_integer_literal>0x[0-9a-fA-F][0-9a-fA-F]*)\
    |\
    (?P<integer_literal>[-]?[0-9][0-9]*)\
    )\
");

#[derive(Debug, Copy, Clone)]
pub enum TokType {
    Eof,

    Whitespace,
    HashComment,
    CppComment,
    NewLine,

    LParen,
    RParen,
    Dot,
    DoubleColon,
    Colon,
    SemiColon,
    Equals,
    Comma,
    Slash,

    ImportKeyword,
    LetKeyword,
    BooleanLiteral,
    Identifier,
    IPv4Literal,
    StringLiteral,
    HexIntegerLiteral,
    IntegerLiteral,

    Max,
}

impl TokType {
    pub fn iterator() -> Iter<'static, TokType> {
        const TYPES: [TokType; TokType::Max as usize] = [
            TokType::Eof,

            TokType::Whitespace,
            TokType::HashComment,
            TokType::CppComment,
            TokType::NewLine,

            TokType::LParen,
            TokType::RParen,
            TokType::Dot,
            TokType::DoubleColon,
            TokType::Colon,
            TokType::SemiColon,
            TokType::Equals,
            TokType::Comma,
            TokType::Slash,

            TokType::ImportKeyword,
            TokType::LetKeyword,
            TokType::BooleanLiteral,
            TokType::Identifier,
            TokType::IPv4Literal,
            TokType::StringLiteral,
            TokType::HexIntegerLiteral,
            TokType::IntegerLiteral,
        ];
        TYPES.iter()
    }

    pub fn from_caps(caps: &CaptureLocations,
                     ) -> Option<(TokType, usize)> {
        for x in TokType::iterator().skip(1) {
            let match_end = match caps.get(*x as usize) {
                Some((_, to)) => to,
                None => continue,
            };

            if match_end > 0 {
                return Some((*x, match_end));
            }
        }

        println!("no capture");
        None
    }

    pub fn ignore(self) -> bool {
        matches!(self,
            TokType::Whitespace
            | TokType::HashComment
            | TokType::CppComment
            | TokType::NewLine
        )
    }

    pub fn get_val(self, val: &str) -> Option<&str> {
        match self {
        TokType::Identifier => Some(val),
        TokType::HexIntegerLiteral => Some(val),
        TokType::IntegerLiteral => Some(val),
        TokType::BooleanLiteral => Some(val),
        TokType::StringLiteral => Some(val),
        TokType::IPv4Literal => Some(val),
        _ => None,
        }
    }
}

/// Represents a lexeme within the resynth language.
///
/// ## Lifetime
/// For things like identifiers and string literals, a reference is included to the original
/// string. So the [Token] must outlive that buffer.
#[derive(Debug, Copy, Clone)]
pub struct Token<'a> {
    loc: Loc,
    typ: TokType,
    val: Option<&'a str>,
}

impl<'a> Token<'a> {
    pub fn loc(&self) -> Loc {
        self.loc
    }

    pub fn tok_type(&self) -> TokType {
        self.typ
    }

    pub fn optval(&self) -> Option<&'a str> {
        self.val
    }

    pub fn val(&self) -> &'a str {
        self.val.unwrap()
    }
}

impl From<Token<'_>> for String {
    fn from(tok: Token) -> String {
        tok.val.unwrap().to_owned()
    }
}

/// EOF token
pub const EOF: Token = Token {
    loc: Loc::nil(),
    typ: TokType::Eof,
    val: None,
};

/// The lexer takes a [line at a time](Lexer::line) and returns a [vector](Vec) of
/// [tokens](Token). If an error occurs then the location of that error may be retreived from
/// [Lexer::loc].
#[derive(Debug, Default)]
pub struct Lexer {
    loc: Loc,
}

impl Lexer {
    pub fn loc(&self) -> Loc {
        self.loc
    }

    fn throw(&mut self, pos: usize) -> Error {
        self.loc.set_col(pos + 1);
        LexError
    }

    pub fn line<'a>(&mut self, lno: usize, line: &'a str) -> Result<Vec<Token<'a>>, Error> {
        let mut ret = Vec::new();
        let mut pos = 0_usize;
        let mut caps = LEX_RE.capture_locations();

        self.loc = Loc::new(lno, pos + 1);

        while pos < line.len() {
            let s = &line[pos..];
            let res = LEX_RE.captures_read(&mut caps, s);
            let m = match res {
                Some(m) => m,
                None => {
                    return Err(self.throw(pos + 1));
                }
            };

            let (tok_type, match_end) = match TokType::from_caps(&caps) {
                Some(result) => result,
                _ => return Err(self.throw(pos + 1)),
            };
            let tok_val = &s[..m.end()];

            assert!(match_end == m.end());

            /*
            println!("  {:?} {:?} => {}..{}/{} {:?}",
                tok_type,
                LEX_RE.capture_names().nth(tok_type as usize).unwrap().unwrap(),
                pos,
                m.end(),
                match_end,
                tok_val,
            );
            */

            if !tok_type.ignore() {
                ret.push(Token {
                    loc: Loc::new(lno, pos + 1),
                    typ: tok_type,
                    val: tok_type.get_val(tok_val),
                });
            }

            pos += m.end();
        }

        self.loc = Loc::new(lno, pos + 1);

        ret.shrink_to_fit();
        Ok(ret)
    }
}