lexer.c 21.1 KB
Newer Older
Damien's avatar
Damien committed
1
2
3
4
5
6
7
8
9
10
11
12
/* lexer.c -- simple tokeniser for Python implementation
 */

#include <stdint.h>
#include <stdio.h>
#include <assert.h>

#include "misc.h"
#include "lexer.h"

#define TAB_SIZE (8)

13
14
15
// TODO seems that CPython allows NULL byte in the input stream
// don't know if that's intentional or not, but we don't allow it

16
struct _mp_lexer_t {
17
18
    const char *name;           // name of source
    void *stream_data;          // data for stream
19
20
    mp_lexer_stream_next_char_t stream_next_char;   // stream callback to get next char
    mp_lexer_stream_close_t stream_close;           // stream callback to free
Damien's avatar
Damien committed
21

22
    unichar chr0, chr1, chr2;   // current cached characters from source
Damien's avatar
Damien committed
23
24
25
26

    uint line;                  // source line
    uint column;                // source column

27
28
    int emit_dent;              // non-zero when there are INDENT/DEDENT tokens to emit
    int nested_bracket_level;   // >0 when there are nested brackets over multiple lines
Damien's avatar
Damien committed
29
30
31
32
33

    uint alloc_indent_level;
    uint num_indent_level;
    uint16_t *indent_level;

34
    vstr_t vstr;
35
    mp_token_t tok_cur;
Damien's avatar
Damien committed
36
37
};

38
bool str_strn_equal(const char *str, const char *strn, int len) {
Damien's avatar
Damien committed
39
40
    uint i = 0;

41
    while (i < len && *str == *strn) {
Damien's avatar
Damien committed
42
43
        ++i;
        ++str;
44
        ++strn;
Damien's avatar
Damien committed
45
46
    }

47
    return i == len && *str == 0;
Damien's avatar
Damien committed
48
49
}

50
void mp_token_show(const mp_token_t *tok) {
51
    printf("(%s:%d:%d) kind:%d str:%p len:%d", tok->src_name, tok->src_line, tok->src_column, tok->kind, tok->str, tok->len);
Damien's avatar
Damien committed
52
53
54
55
56
    if (tok->str != NULL && tok->len > 0) {
        const char *i = tok->str;
        const char *j = i + tok->len;
        printf(" ");
        while (i < j) {
57
58
59
            unichar c = utf8_get_char(i);
            i = utf8_next_char(i);
            if (unichar_isprint(c)) {
Damien's avatar
Damien committed
60
61
62
63
64
65
66
67
68
                printf("%c", c);
            } else {
                printf("?");
            }
        }
    }
    printf("\n");
}

69
void mp_token_show_error_prefix(const mp_token_t *tok) {
Damien's avatar
Damien committed
70
71
72
    printf("(%s:%d:%d) ", tok->src_name, tok->src_line, tok->src_column);
}

73
bool mp_token_show_error(const mp_token_t *tok, const char *msg) {
Damien's avatar
Damien committed
74
75
76
77
    printf("(%s:%d:%d) %s\n", tok->src_name, tok->src_line, tok->src_column, msg);
    return false;
}

78
79
#define CUR_CHAR(lex) ((lex)->chr0)

80
81
static bool is_end(mp_lexer_t *lex) {
    return lex->chr0 == MP_LEXER_CHAR_EOF;
Damien's avatar
Damien committed
82
83
}

84
static bool is_physical_newline(mp_lexer_t *lex) {
Damien's avatar
Damien committed
85
86
87
    return lex->chr0 == '\n' || lex->chr0 == '\r';
}

88
static bool is_char(mp_lexer_t *lex, char c) {
Damien's avatar
Damien committed
89
90
91
    return lex->chr0 == c;
}

92
static bool is_char_or(mp_lexer_t *lex, char c1, char c2) {
Damien's avatar
Damien committed
93
94
95
    return lex->chr0 == c1 || lex->chr0 == c2;
}

96
static bool is_char_or3(mp_lexer_t *lex, char c1, char c2, char c3) {
Damien's avatar
Damien committed
97
98
99
100
    return lex->chr0 == c1 || lex->chr0 == c2 || lex->chr0 == c3;
}

/*
101
static bool is_char_following(mp_lexer_t *lex, char c) {
Damien's avatar
Damien committed
102
103
104
105
    return lex->chr1 == c;
}
*/

106
static bool is_char_following_or(mp_lexer_t *lex, char c1, char c2) {
Damien's avatar
Damien committed
107
108
109
    return lex->chr1 == c1 || lex->chr1 == c2;
}

110
static bool is_char_following_following_or(mp_lexer_t *lex, char c1, char c2) {
Damien's avatar
Damien committed
111
112
113
    return lex->chr2 == c1 || lex->chr2 == c2;
}

114
static bool is_char_and(mp_lexer_t *lex, char c1, char c2) {
Damien's avatar
Damien committed
115
116
117
    return lex->chr0 == c1 && lex->chr1 == c2;
}

118
static bool is_whitespace(mp_lexer_t *lex) {
119
    return unichar_isspace(lex->chr0);
Damien's avatar
Damien committed
120
121
}

122
static bool is_letter(mp_lexer_t *lex) {
123
    return unichar_isalpha(lex->chr0);
Damien's avatar
Damien committed
124
125
}

126
static bool is_digit(mp_lexer_t *lex) {
127
    return unichar_isdigit(lex->chr0);
Damien's avatar
Damien committed
128
129
}

130
static bool is_following_digit(mp_lexer_t *lex) {
131
    return unichar_isdigit(lex->chr1);
Damien's avatar
Damien committed
132
133
134
}

// TODO UNICODE include unicode characters in definition of identifiers
135
static bool is_head_of_identifier(mp_lexer_t *lex) {
Damien's avatar
Damien committed
136
137
138
139
    return is_letter(lex) || lex->chr0 == '_';
}

// TODO UNICODE include unicode characters in definition of identifiers
140
static bool is_tail_of_identifier(mp_lexer_t *lex) {
Damien's avatar
Damien committed
141
142
143
    return is_head_of_identifier(lex) || is_digit(lex);
}

144
145
static void next_char(mp_lexer_t *lex) {
    if (lex->chr0 == MP_LEXER_CHAR_EOF) {
Damien's avatar
Damien committed
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
        return;
    }

    int advance = 1;

    if (lex->chr0 == '\n') {
        // LF is a new line
        ++lex->line;
        lex->column = 1;
    } else if (lex->chr0 == '\r') {
        // CR is a new line
        ++lex->line;
        lex->column = 1;
        if (lex->chr1 == '\n') {
            // CR LF is a single new line
            advance = 2;
        }
    } else if (lex->chr0 == '\t') {
        // a tab
        lex->column = (((lex->column - 1 + TAB_SIZE) / TAB_SIZE) * TAB_SIZE) + 1;
    } else {
        // a character worth one column
        ++lex->column;
    }

    for (; advance > 0; advance--) {
        lex->chr0 = lex->chr1;
        lex->chr1 = lex->chr2;
174
        lex->chr2 = lex->stream_next_char(lex->stream_data);
175
        if (lex->chr2 == MP_LEXER_CHAR_EOF) {
Damien's avatar
Damien committed
176
            // EOF
177
            if (lex->chr1 != MP_LEXER_CHAR_EOF && lex->chr1 != '\n' && lex->chr1 != '\r') {
Damien's avatar
Damien committed
178
179
180
181
182
183
                lex->chr2 = '\n'; // insert newline at end of file
            }
        }
    }
}

184
void indent_push(mp_lexer_t *lex, uint indent) {
Damien's avatar
Damien committed
185
    if (lex->num_indent_level >= lex->alloc_indent_level) {
186
        lex->indent_level = m_renew(uint16_t, lex->indent_level, lex->alloc_indent_level, lex->alloc_indent_level * 2);
Damien's avatar
Damien committed
187
188
189
190
191
        lex->alloc_indent_level *= 2;
    }
    lex->indent_level[lex->num_indent_level++] = indent;
}

192
uint indent_top(mp_lexer_t *lex) {
Damien's avatar
Damien committed
193
194
195
    return lex->indent_level[lex->num_indent_level - 1];
}

196
void indent_pop(mp_lexer_t *lex) {
Damien's avatar
Damien committed
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
    lex->num_indent_level -= 1;
}

// some tricky operator encoding:
//     <op>  = begin with <op>, if this opchar matches then begin here
//     e<op> = end with <op>, if this opchar matches then end
//     E<op> = mandatory end with <op>, this opchar must match, then end
//     c<op> = continue with <op>, if this opchar matches then continue matching
// this means if the start of two ops are the same then they are equal til the last char

static const char *tok_enc =
    "()[]{},:;@~" // singles
    "<e=c<e="     // < <= << <<=
    ">e=c>e="     // > >= >> >>=
    "*e=c*e="     // * *= ** **=
    "+e="         // + +=
    "-e=e>"       // - -= ->
    "&e="         // & &=
    "|e="         // | |=
    "/e=c/e="     // / /= // //=
    "%e="         // % %=
    "^e="         // ^ ^=
    "=e="         // = ==
    "!E="         // !=
    ".c.E.";      // . ...

// TODO static assert that number of tokens is less than 256 so we can safely make this table with byte sized entries
static const uint8_t tok_enc_kind[] = {
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    MP_TOKEN_DEL_PAREN_OPEN, MP_TOKEN_DEL_PAREN_CLOSE,
    MP_TOKEN_DEL_BRACKET_OPEN, MP_TOKEN_DEL_BRACKET_CLOSE,
    MP_TOKEN_DEL_BRACE_OPEN, MP_TOKEN_DEL_BRACE_CLOSE,
    MP_TOKEN_DEL_COMMA, MP_TOKEN_DEL_COLON, MP_TOKEN_DEL_SEMICOLON, MP_TOKEN_DEL_AT, MP_TOKEN_OP_TILDE,

    MP_TOKEN_OP_LESS, MP_TOKEN_OP_LESS_EQUAL, MP_TOKEN_OP_DBL_LESS, MP_TOKEN_DEL_DBL_LESS_EQUAL,
    MP_TOKEN_OP_MORE, MP_TOKEN_OP_MORE_EQUAL, MP_TOKEN_OP_DBL_MORE, MP_TOKEN_DEL_DBL_MORE_EQUAL,
    MP_TOKEN_OP_STAR, MP_TOKEN_DEL_STAR_EQUAL, MP_TOKEN_OP_DBL_STAR, MP_TOKEN_DEL_DBL_STAR_EQUAL,
    MP_TOKEN_OP_PLUS, MP_TOKEN_DEL_PLUS_EQUAL,
    MP_TOKEN_OP_MINUS, MP_TOKEN_DEL_MINUS_EQUAL, MP_TOKEN_DEL_MINUS_MORE,
    MP_TOKEN_OP_AMPERSAND, MP_TOKEN_DEL_AMPERSAND_EQUAL,
    MP_TOKEN_OP_PIPE, MP_TOKEN_DEL_PIPE_EQUAL,
    MP_TOKEN_OP_SLASH, MP_TOKEN_DEL_SLASH_EQUAL, MP_TOKEN_OP_DBL_SLASH, MP_TOKEN_DEL_DBL_SLASH_EQUAL,
    MP_TOKEN_OP_PERCENT, MP_TOKEN_DEL_PERCENT_EQUAL,
    MP_TOKEN_OP_CARET, MP_TOKEN_DEL_CARET_EQUAL,
    MP_TOKEN_DEL_EQUAL, MP_TOKEN_OP_DBL_EQUAL,
    MP_TOKEN_OP_NOT_EQUAL,
Damien George's avatar
Damien George committed
242
    MP_TOKEN_DEL_PERIOD, MP_TOKEN_ELLIPSIS,
Damien's avatar
Damien committed
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
};

// must have the same order as enum in lexer.h
static const char *tok_kw[] = {
    "False",
    "None",
    "True",
    "and",
    "as",
    "assert",
    "break",
    "class",
    "continue",
    "def",
    "del",
    "elif",
    "else",
    "except",
    "finally",
    "for",
    "from",
    "global",
    "if",
    "import",
    "in",
    "is",
    "lambda",
    "nonlocal",
    "not",
    "or",
    "pass",
    "raise",
    "return",
    "try",
    "while",
    "with",
    "yield",
    NULL,
};

283
static void mp_lexer_next_token_into(mp_lexer_t *lex, mp_token_t *tok, bool first_token) {
284
    // skip white space and comments
Damien's avatar
Damien committed
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
    bool had_physical_newline = false;
    while (!is_end(lex)) {
        if (is_physical_newline(lex)) {
            had_physical_newline = true;
            next_char(lex);
        } else if (is_whitespace(lex)) {
            next_char(lex);
        } else if (is_char(lex, '#')) {
            next_char(lex);
            while (!is_end(lex) && !is_physical_newline(lex)) {
                next_char(lex);
            }
            // had_physical_newline will be set on next loop
        } else if (is_char(lex, '\\')) {
            // backslash (outside string literals) must appear just before a physical newline
            next_char(lex);
            if (!is_physical_newline(lex)) {
302
303
304
305
306
307
308
309
310
                // SyntaxError: unexpected character after line continuation character
                tok->src_name = lex->name;
                tok->src_line = lex->line;
                tok->src_column = lex->column;
                tok->kind = MP_TOKEN_BAD_LINE_CONTINUATION;
                vstr_reset(&lex->vstr);
                tok->str = vstr_str(&lex->vstr);
                tok->len = 0;
                return;
Damien's avatar
Damien committed
311
312
313
314
315
316
317
318
            } else {
                next_char(lex);
            }
        } else {
            break;
        }
    }

319
    // set token source information
Damien's avatar
Damien committed
320
321
322
323
    tok->src_name = lex->name;
    tok->src_line = lex->line;
    tok->src_column = lex->column;

324
325
326
327
328
329
330
331
    // start new token text
    vstr_reset(&lex->vstr);

    if (first_token && lex->line == 1 && lex->column != 1) {
        // check that the first token is in the first column
        // if first token is not on first line, we get a physical newline and
        // this check is done as part of normal indent/dedent checking below
        // (done to get equivalence with CPython)
332
        tok->kind = MP_TOKEN_INDENT;
333
334

    } else if (lex->emit_dent < 0) {
335
        tok->kind = MP_TOKEN_DEDENT;
Damien's avatar
Damien committed
336
337
338
        lex->emit_dent += 1;

    } else if (lex->emit_dent > 0) {
339
        tok->kind = MP_TOKEN_INDENT;
Damien's avatar
Damien committed
340
341
        lex->emit_dent -= 1;

342
    } else if (had_physical_newline && lex->nested_bracket_level == 0) {
343
        tok->kind = MP_TOKEN_NEWLINE;
Damien's avatar
Damien committed
344
345
346
347
348
349
350
351
352
353
354
355
356

        uint num_spaces = lex->column - 1;
        lex->emit_dent = 0;
        if (num_spaces == indent_top(lex)) {
        } else if (num_spaces > indent_top(lex)) {
            indent_push(lex, num_spaces);
            lex->emit_dent += 1;
        } else {
            while (num_spaces < indent_top(lex)) {
                indent_pop(lex);
                lex->emit_dent -= 1;
            }
            if (num_spaces != indent_top(lex)) {
357
                tok->kind = MP_TOKEN_DEDENT_MISMATCH;
Damien's avatar
Damien committed
358
359
360
361
362
            }
        }

    } else if (is_end(lex)) {
        if (indent_top(lex) > 0) {
363
            tok->kind = MP_TOKEN_NEWLINE;
Damien's avatar
Damien committed
364
365
366
367
368
369
            lex->emit_dent = 0;
            while (indent_top(lex) > 0) {
                indent_pop(lex);
                lex->emit_dent -= 1;
            }
        } else {
370
            tok->kind = MP_TOKEN_END;
Damien's avatar
Damien committed
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
        }

    } else if (is_char_or(lex, '\'', '\"')
               || (is_char_or3(lex, 'r', 'u', 'b') && is_char_following_or(lex, '\'', '\"'))
               || ((is_char_and(lex, 'r', 'b') || is_char_and(lex, 'b', 'r')) && is_char_following_following_or(lex, '\'', '\"'))) {
        // a string or bytes literal

        // parse type codes
        bool is_raw = false;
        bool is_bytes = false;
        if (is_char(lex, 'u')) {
            next_char(lex);
        } else if (is_char(lex, 'b')) {
            is_bytes = true;
            next_char(lex);
            if (is_char(lex, 'r')) {
                is_raw = true;
                next_char(lex);
            }
        } else if (is_char(lex, 'r')) {
            is_raw = true;
            next_char(lex);
            if (is_char(lex, 'b')) {
                is_bytes = true;
                next_char(lex);
            }
        }

        // set token kind
        if (is_bytes) {
401
            tok->kind = MP_TOKEN_BYTES;
Damien's avatar
Damien committed
402
        } else {
403
            tok->kind = MP_TOKEN_STRING;
Damien's avatar
Damien committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
        }

        // get first quoting character
        char quote_char = '\'';
        if (is_char(lex, '\"')) {
            quote_char = '\"';
        }
        next_char(lex);

        // work out if it's a single or triple quoted literal
        int num_quotes;
        if (is_char_and(lex, quote_char, quote_char)) {
            // triple quotes
            next_char(lex);
            next_char(lex);
            num_quotes = 3;
        } else {
            // single quotes
            num_quotes = 1;
        }

        // parse the literal
        int n_closing = 0;
        while (!is_end(lex) && (num_quotes > 1 || !is_char(lex, '\n')) && n_closing < num_quotes) {
            if (is_char(lex, quote_char)) {
                n_closing += 1;
430
                vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
431
432
433
434
            } else {
                n_closing = 0;
                if (!is_raw && is_char(lex, '\\')) {
                    next_char(lex);
435
436
                    unichar c = CUR_CHAR(lex);
                    switch (c) {
437
438
                        case MP_LEXER_CHAR_EOF: break; // TODO a proper error message?
                        case '\n': c = MP_LEXER_CHAR_EOF; break; // TODO check this works correctly (we are supposed to ignore it
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
                        case '\\': break;
                        case '\'': break;
                        case '"': break;
                        case 'a': c = 0x07; break;
                        case 'b': c = 0x08; break;
                        case 't': c = 0x09; break;
                        case 'n': c = 0x0a; break;
                        case 'v': c = 0x0b; break;
                        case 'f': c = 0x0c; break;
                        case 'r': c = 0x0d; break;
                        // TODO \ooo octal
                        case 'x': // TODO \xhh
                        case 'N': // TODO \N{name} only in strings
                        case 'u': // TODO \uxxxx only in strings
                        case 'U': // TODO \Uxxxxxxxx only in strings
                        default: break; // TODO error message
                    }
456
                    if (c != MP_LEXER_CHAR_EOF) {
457
458
459
460
                        vstr_add_char(&lex->vstr, c);
                    }
                } else {
                    vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
461
462
463
464
465
466
467
                }
            }
            next_char(lex);
        }

        // check we got the required end quotes
        if (n_closing < num_quotes) {
468
            tok->kind = MP_TOKEN_LONELY_STRING_OPEN;
Damien's avatar
Damien committed
469
470
        }

471
472
        // cut off the end quotes from the token text
        vstr_cut_tail(&lex->vstr, n_closing);
Damien's avatar
Damien committed
473
474

    } else if (is_head_of_identifier(lex)) {
475
        tok->kind = MP_TOKEN_NAME;
Damien's avatar
Damien committed
476

477
478
        // get first char
        vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
479
480
        next_char(lex);

481
        // get tail chars
Damien's avatar
Damien committed
482
        while (!is_end(lex) && is_tail_of_identifier(lex)) {
483
            vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
484
485
486
487
            next_char(lex);
        }

    } else if (is_digit(lex) || (is_char(lex, '.') && is_following_digit(lex))) {
488
        tok->kind = MP_TOKEN_NUMBER;
Damien's avatar
Damien committed
489

490
491
        // get first char
        vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
492
493
        next_char(lex);

494
        // get tail chars
Damien's avatar
Damien committed
495
496
        while (!is_end(lex)) {
            if (is_char_or(lex, 'e', 'E')) {
497
                vstr_add_char(&lex->vstr, 'e');
Damien's avatar
Damien committed
498
499
                next_char(lex);
                if (is_char(lex, '+') || is_char(lex, '-')) {
500
                    vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
501
502
503
                    next_char(lex);
                }
            } else if (is_letter(lex) || is_digit(lex) || is_char_or(lex, '_', '.')) {
504
                vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
                next_char(lex);
            } else {
                break;
            }
        }

    } else {
        // search for encoded delimiter or operator

        const char *t = tok_enc;
        uint tok_enc_index = 0;
        for (; *t != 0 && !is_char(lex, *t); t += 1) {
            if (*t == 'e' || *t == 'c') {
                t += 1;
            } else if (*t == 'E') {
                tok_enc_index -= 1;
                t += 1;
            }
            tok_enc_index += 1;
        }

        next_char(lex);

        if (*t == 0) {
            // didn't match any delimiter or operator characters
530
            tok->kind = MP_TOKEN_INVALID;
Damien's avatar
Damien committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554

        } else {
            // matched a delimiter or operator character

            // get the maximum characters for a valid token
            t += 1;
            uint t_index = tok_enc_index;
            for (;;) {
                for (; *t == 'e'; t += 1) {
                    t += 1;
                    t_index += 1;
                    if (is_char(lex, *t)) {
                        next_char(lex);
                        tok_enc_index = t_index;
                        break;
                    }
                }

                if (*t == 'E') {
                    t += 1;
                    if (is_char(lex, *t)) {
                        next_char(lex);
                        tok_enc_index = t_index;
                    } else {
555
                        tok->kind = MP_TOKEN_INVALID;
Damien's avatar
Damien committed
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
                    }
                    break;
                }

                if (*t == 'c') {
                    t += 1;
                    t_index += 1;
                    if (is_char(lex, *t)) {
                        next_char(lex);
                        tok_enc_index = t_index;
                        t += 1;
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }

            // set token kind
            tok->kind = tok_enc_kind[tok_enc_index];

            // compute bracket level for implicit line joining
579
            if (tok->kind == MP_TOKEN_DEL_PAREN_OPEN || tok->kind == MP_TOKEN_DEL_BRACKET_OPEN || tok->kind == MP_TOKEN_DEL_BRACE_OPEN) {
Damien's avatar
Damien committed
580
                lex->nested_bracket_level += 1;
581
            } else if (tok->kind == MP_TOKEN_DEL_PAREN_CLOSE || tok->kind == MP_TOKEN_DEL_BRACKET_CLOSE || tok->kind == MP_TOKEN_DEL_BRACE_CLOSE) {
Damien's avatar
Damien committed
582
583
584
585
586
                lex->nested_bracket_level -= 1;
            }
        }
    }

587
588
589
    // point token text to vstr buffer
    tok->str = vstr_str(&lex->vstr);
    tok->len = vstr_len(&lex->vstr);
Damien's avatar
Damien committed
590

591
    // check for keywords
592
    if (tok->kind == MP_TOKEN_NAME) {
Damien's avatar
Damien committed
593
        for (int i = 0; tok_kw[i] != NULL; i++) {
594
            if (str_strn_equal(tok_kw[i], tok->str, tok->len)) {
595
                tok->kind = MP_TOKEN_KW_FALSE + i;
Damien's avatar
Damien committed
596
597
598
599
600
601
                break;
            }
        }
    }
}

602
603
mp_lexer_t *mp_lexer_new(const char *src_name, void *stream_data, mp_lexer_stream_next_char_t stream_next_char, mp_lexer_stream_close_t stream_close) {
    mp_lexer_t *lex = m_new(mp_lexer_t, 1);
Damien's avatar
Damien committed
604

605
606
607
    lex->name = src_name; // TODO do we need to strdup this?
    lex->stream_data = stream_data;
    lex->stream_next_char = stream_next_char;
608
    lex->stream_close = stream_close;
Damien's avatar
Damien committed
609
610
611
612
613
614
615
616
    lex->line = 1;
    lex->column = 1;
    lex->emit_dent = 0;
    lex->nested_bracket_level = 0;
    lex->alloc_indent_level = 16;
    lex->num_indent_level = 1;
    lex->indent_level = m_new(uint16_t, lex->alloc_indent_level);
    lex->indent_level[0] = 0;
617
    vstr_init(&lex->vstr);
Damien's avatar
Damien committed
618
619

    // preload characters
620
621
622
623
624
    lex->chr0 = stream_next_char(stream_data);
    lex->chr1 = stream_next_char(stream_data);
    lex->chr2 = stream_next_char(stream_data);

    // if input stream is 0, 1 or 2 characters long and doesn't end in a newline, then insert a newline at the end
625
    if (lex->chr0 == MP_LEXER_CHAR_EOF) {
626
        lex->chr0 = '\n';
627
    } else if (lex->chr1 == MP_LEXER_CHAR_EOF) {
Damien's avatar
Damien committed
628
        if (lex->chr0 != '\n' && lex->chr0 != '\r') {
629
            lex->chr1 = '\n';
Damien's avatar
Damien committed
630
        }
631
    } else if (lex->chr2 == MP_LEXER_CHAR_EOF) {
Damien's avatar
Damien committed
632
        if (lex->chr1 != '\n' && lex->chr1 != '\r') {
633
            lex->chr2 = '\n';
Damien's avatar
Damien committed
634
635
636
        }
    }

637
    // preload first token
638
    mp_lexer_next_token_into(lex, &lex->tok_cur, true);
Damien's avatar
Damien committed
639
640
641
642

    return lex;
}

643
void mp_lexer_free(mp_lexer_t *lex) {
644
    if (lex) {
645
646
        if (lex->stream_close) {
            lex->stream_close(lex->stream_data);
647
        }
648
        vstr_clear(&lex->vstr);
649
        m_del_obj(mp_lexer_t, lex);
Damien's avatar
Damien committed
650
651
652
    }
}

653
654
void mp_lexer_to_next(mp_lexer_t *lex) {
    mp_lexer_next_token_into(lex, &lex->tok_cur, false);
Damien's avatar
Damien committed
655
656
}

657
const mp_token_t *mp_lexer_cur(const mp_lexer_t *lex) {
Damien's avatar
Damien committed
658
659
660
    return &lex->tok_cur;
}

661
bool mp_lexer_is_kind(mp_lexer_t *lex, mp_token_kind_t kind) {
Damien's avatar
Damien committed
662
663
664
665
    return lex->tok_cur.kind == kind;
}

/*
666
667
bool mp_lexer_is_str(mp_lexer_t *lex, const char *str) {
    return mp_token_is_str(&lex->tok_cur, str);
Damien's avatar
Damien committed
668
669
}

670
671
672
bool mp_lexer_opt_kind(mp_lexer_t *lex, mp_token_kind_t kind) {
    if (mp_lexer_is_kind(lex, kind)) {
        mp_lexer_to_next(lex);
Damien's avatar
Damien committed
673
674
675
676
677
        return true;
    }
    return false;
}

678
679
680
bool mp_lexer_opt_str(mp_lexer_t *lex, const char *str) {
    if (mp_lexer_is_str(lex, str)) {
        mp_lexer_to_next(lex);
Damien's avatar
Damien committed
681
682
683
684
685
686
        return true;
    }
    return false;
}
*/

687
688
bool mp_lexer_show_error(mp_lexer_t *lex, const char *msg) {
    return mp_token_show_error(&lex->tok_cur, msg);
Damien's avatar
Damien committed
689
}
690

691
bool mp_lexer_show_error_pythonic(mp_lexer_t *lex, const char *msg) {
692
693
694
    printf("  File \"%s\", line %d column %d\n%s\n", lex->tok_cur.src_name, lex->tok_cur.src_line, lex->tok_cur.src_column, msg);
    return false;
}