lexer.c 27.7 KB
Newer Older
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
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

Damien's avatar
Damien committed
27
28
29
#include <stdio.h>
#include <assert.h>

30
#include "py/mpstate.h"
31
#include "py/reader.h"
32
#include "py/lexer.h"
33
#include "py/runtime.h"
Damien's avatar
Damien committed
34

35
36
#if MICROPY_ENABLE_COMPILER

Damien's avatar
Damien committed
37
38
#define TAB_SIZE (8)

39
40
41
// 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

42
// TODO replace with a call to a standard function
43
STATIC bool str_strn_equal(const char *str, const char *strn, mp_uint_t len) {
44
    mp_uint_t i = 0;
Damien's avatar
Damien committed
45

46
    while (i < len && *str == *strn) {
Damien's avatar
Damien committed
47
48
        ++i;
        ++str;
49
        ++strn;
Damien's avatar
Damien committed
50
51
    }

52
    return i == len && *str == 0;
Damien's avatar
Damien committed
53
54
}

55
56
#define CUR_CHAR(lex) ((lex)->chr0)

57
STATIC bool is_end(mp_lexer_t *lex) {
58
    return lex->chr0 == MP_LEXER_EOF;
Damien's avatar
Damien committed
59
60
}

61
STATIC bool is_physical_newline(mp_lexer_t *lex) {
62
    return lex->chr0 == '\n';
Damien's avatar
Damien committed
63
64
}

65
STATIC bool is_char(mp_lexer_t *lex, byte c) {
Damien's avatar
Damien committed
66
67
68
    return lex->chr0 == c;
}

69
STATIC bool is_char_or(mp_lexer_t *lex, byte c1, byte c2) {
Damien's avatar
Damien committed
70
71
72
    return lex->chr0 == c1 || lex->chr0 == c2;
}

73
STATIC bool is_char_or3(mp_lexer_t *lex, byte c1, byte c2, byte c3) {
Damien's avatar
Damien committed
74
75
76
77
    return lex->chr0 == c1 || lex->chr0 == c2 || lex->chr0 == c3;
}

/*
78
STATIC bool is_char_following(mp_lexer_t *lex, byte c) {
Damien's avatar
Damien committed
79
80
81
82
    return lex->chr1 == c;
}
*/

83
STATIC bool is_char_following_or(mp_lexer_t *lex, byte c1, byte c2) {
Damien's avatar
Damien committed
84
85
86
    return lex->chr1 == c1 || lex->chr1 == c2;
}

87
STATIC bool is_char_following_following_or(mp_lexer_t *lex, byte c1, byte c2) {
Damien's avatar
Damien committed
88
89
90
    return lex->chr2 == c1 || lex->chr2 == c2;
}

91
STATIC bool is_char_and(mp_lexer_t *lex, byte c1, byte c2) {
Damien's avatar
Damien committed
92
93
94
    return lex->chr0 == c1 && lex->chr1 == c2;
}

95
STATIC bool is_whitespace(mp_lexer_t *lex) {
96
    return unichar_isspace(lex->chr0);
Damien's avatar
Damien committed
97
98
}

99
STATIC bool is_letter(mp_lexer_t *lex) {
100
    return unichar_isalpha(lex->chr0);
Damien's avatar
Damien committed
101
102
}

103
STATIC bool is_digit(mp_lexer_t *lex) {
104
    return unichar_isdigit(lex->chr0);
Damien's avatar
Damien committed
105
106
}

107
STATIC bool is_following_digit(mp_lexer_t *lex) {
108
    return unichar_isdigit(lex->chr1);
Damien's avatar
Damien committed
109
110
}

111
112
113
STATIC bool is_following_base_char(mp_lexer_t *lex) {
    const unichar chr1 = lex->chr1 | 0x20;
    return chr1 == 'b' || chr1 == 'o' || chr1 == 'x';
114
115
}

116
STATIC bool is_following_odigit(mp_lexer_t *lex) {
117
118
119
    return lex->chr1 >= '0' && lex->chr1 <= '7';
}

120
// to easily parse utf-8 identifiers we allow any raw byte with high bit set
121
STATIC bool is_head_of_identifier(mp_lexer_t *lex) {
122
    return is_letter(lex) || lex->chr0 == '_' || lex->chr0 >= 0x80;
Damien's avatar
Damien committed
123
124
}

125
STATIC bool is_tail_of_identifier(mp_lexer_t *lex) {
Damien's avatar
Damien committed
126
127
128
    return is_head_of_identifier(lex) || is_digit(lex);
}

129
STATIC void next_char(mp_lexer_t *lex) {
130
    if (lex->chr0 == MP_LEXER_EOF) {
Damien's avatar
Damien committed
131
132
133
134
        return;
    }

    if (lex->chr0 == '\n') {
135
        // a new line
Damien's avatar
Damien committed
136
137
138
139
140
141
142
143
144
145
        ++lex->line;
        lex->column = 1;
    } 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;
    }

146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    lex->chr0 = lex->chr1;
    lex->chr1 = lex->chr2;
    lex->chr2 = lex->stream_next_byte(lex->stream_data);

    if (lex->chr0 == '\r') {
        // CR is a new line, converted to LF
        lex->chr0 = '\n';
        if (lex->chr1 == '\n') {
            // CR LF is a single new line
            lex->chr1 = lex->chr2;
            lex->chr2 = lex->stream_next_byte(lex->stream_data);
        }
    }

    if (lex->chr2 == MP_LEXER_EOF) {
        // EOF, check if we need to insert a newline at end of file
        if (lex->chr1 != MP_LEXER_EOF && lex->chr1 != '\n') {
            // if lex->chr1 == '\r' then this makes a CR LF which will be converted to LF above
            // otherwise it just inserts a LF
            lex->chr2 = '\n';
Damien's avatar
Damien committed
166
167
168
169
        }
    }
}

170
STATIC void indent_push(mp_lexer_t *lex, mp_uint_t indent) {
Damien's avatar
Damien committed
171
    if (lex->num_indent_level >= lex->alloc_indent_level) {
172
        // TODO use m_renew_maybe and somehow indicate an error if it fails... probably by using MP_TOKEN_MEMORY_ERROR
173
174
        lex->indent_level = m_renew(uint16_t, lex->indent_level, lex->alloc_indent_level, lex->alloc_indent_level + MICROPY_ALLOC_LEXEL_INDENT_INC);
        lex->alloc_indent_level += MICROPY_ALLOC_LEXEL_INDENT_INC;
Damien's avatar
Damien committed
175
176
177
178
    }
    lex->indent_level[lex->num_indent_level++] = indent;
}

179
STATIC mp_uint_t indent_top(mp_lexer_t *lex) {
Damien's avatar
Damien committed
180
181
182
    return lex->indent_level[lex->num_indent_level - 1];
}

183
STATIC void indent_pop(mp_lexer_t *lex) {
Damien's avatar
Damien committed
184
185
186
187
188
189
190
191
192
193
    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

194
STATIC const char *const tok_enc =
Damien's avatar
Damien committed
195
196
197
198
199
200
201
202
203
204
205
206
    "()[]{},:;@~" // singles
    "<e=c<e="     // < <= << <<=
    ">e=c>e="     // > >= >> >>=
    "*e=c*e="     // * *= ** **=
    "+e="         // + +=
    "-e=e>"       // - -= ->
    "&e="         // & &=
    "|e="         // | |=
    "/e=c/e="     // / /= // //=
    "%e="         // % %=
    "^e="         // ^ ^=
    "=e="         // = ==
207
    "!E=";        // !=
Damien's avatar
Damien committed
208
209

// TODO static assert that number of tokens is less than 256 so we can safely make this table with byte sized entries
210
STATIC const uint8_t tok_enc_kind[] = {
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    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's avatar
Damien committed
228
229
230
};

// must have the same order as enum in lexer.h
231
STATIC const char *const tok_kw[] = {
Damien's avatar
Damien committed
232
233
234
235
236
237
    "False",
    "None",
    "True",
    "and",
    "as",
    "assert",
238
239
240
241
    #if MICROPY_PY_ASYNC_AWAIT
    "async",
    "await",
    #endif
Damien's avatar
Damien committed
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
    "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",
269
    "__debug__",
Damien's avatar
Damien committed
270
271
};

272
273
// This is called with CUR_CHAR() before first hex digit, and should return with
// it pointing to last hex digit
274
275
276
// num_digits must be greater than zero
STATIC bool get_hex(mp_lexer_t *lex, mp_uint_t num_digits, mp_uint_t *result) {
    mp_uint_t num = 0;
277
278
279
280
281
282
    while (num_digits-- != 0) {
        next_char(lex);
        unichar c = CUR_CHAR(lex);
        if (!unichar_isxdigit(c)) {
            return false;
        }
Dave Hylands's avatar
Dave Hylands committed
283
        num = (num << 4) + unichar_xdigit_value(c);
284
285
286
287
288
    }
    *result = num;
    return true;
}

289
290
291
292
STATIC void mp_lexer_next_token_into(mp_lexer_t *lex, bool first_token) {
    // start new token text
    vstr_reset(&lex->vstr);

293
    // skip white space and comments
Damien's avatar
Damien committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
    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)) {
311
                // SyntaxError: unexpected character after line continuation character
312
313
314
                lex->tok_line = lex->line;
                lex->tok_column = lex->column;
                lex->tok_kind = MP_TOKEN_BAD_LINE_CONTINUATION;
315
                return;
Damien's avatar
Damien committed
316
317
318
319
320
321
322
323
            } else {
                next_char(lex);
            }
        } else {
            break;
        }
    }

324
    // set token source information
325
326
    lex->tok_line = lex->line;
    lex->tok_column = lex->column;
327
328
329
330
331
332

    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)
333
        lex->tok_kind = MP_TOKEN_INDENT;
334
335

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

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

343
    } else if (had_physical_newline && lex->nested_bracket_level == 0) {
344
        lex->tok_kind = MP_TOKEN_NEWLINE;
Damien's avatar
Damien committed
345

346
        mp_uint_t num_spaces = lex->column - 1;
Damien's avatar
Damien committed
347
348
349
350
351
352
353
354
355
356
        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
                lex->tok_kind = MP_TOKEN_DEDENT_MISMATCH;
Damien's avatar
Damien committed
358
359
360
361
            }
        }

    } else if (is_end(lex)) {
362
        lex->tok_kind = MP_TOKEN_END;
Damien's avatar
Damien committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391

    } 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) {
392
            lex->tok_kind = MP_TOKEN_BYTES;
Damien's avatar
Damien committed
393
        } else {
394
            lex->tok_kind = MP_TOKEN_STRING;
Damien's avatar
Damien committed
395
396
397
398
399
400
401
402
403
404
        }

        // 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
405
        mp_uint_t num_quotes;
Damien's avatar
Damien committed
406
407
408
409
410
411
412
413
414
415
416
        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
417
        mp_uint_t n_closing = 0;
Damien's avatar
Damien committed
418
419
420
        while (!is_end(lex) && (num_quotes > 1 || !is_char(lex, '\n')) && n_closing < num_quotes) {
            if (is_char(lex, quote_char)) {
                n_closing += 1;
421
                vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
422
423
            } else {
                n_closing = 0;
424
                if (is_char(lex, '\\')) {
Damien's avatar
Damien committed
425
                    next_char(lex);
426
                    unichar c = CUR_CHAR(lex);
427
428
429
430
431
                    if (is_raw) {
                        // raw strings allow escaping of quotes, but the backslash is also emitted
                        vstr_add_char(&lex->vstr, '\\');
                    } else {
                        switch (c) {
432
433
                            case MP_LEXER_EOF: break; // TODO a proper error message?
                            case '\n': c = MP_LEXER_EOF; break; // TODO check this works correctly (we are supposed to ignore it
434
435
436
437
438
439
440
441
442
443
                            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;
444
445
446
447
448
449
450
451
                            case 'u':
                            case 'U':
                                if (is_bytes) {
                                    // b'\u1234' == b'\\u1234'
                                    vstr_add_char(&lex->vstr, '\\');
                                    break;
                                }
                                // Otherwise fall through.
452
453
                            case 'x':
                            {
454
                                mp_uint_t num = 0;
455
                                if (!get_hex(lex, (c == 'x' ? 2 : c == 'u' ? 4 : 8), &num)) {
456
457
                                    // not enough hex chars for escape sequence
                                    lex->tok_kind = MP_TOKEN_INVALID;
458
459
                                }
                                c = num;
460
                                break;
461
                            }
462
463
464
465
466
467
                            case 'N':
                                // Supporting '\N{LATIN SMALL LETTER A}' == 'a' would require keeping the
                                // entire Unicode name table in the core. As of Unicode 6.3.0, that's nearly
                                // 3MB of text; even gzip-compressed and with minimal structure, it'll take
                                // roughly half a meg of storage. This form of Unicode escape may be added
                                // later on, but it's definitely not a priority right now. -- CJA 20140607
468
                                mp_not_implemented("unicode name escapes");
469
                                break;
470
471
472
                            default:
                                if (c >= '0' && c <= '7') {
                                    // Octal sequence, 1-3 chars
473
474
                                    mp_uint_t digits = 3;
                                    mp_uint_t num = c - '0';
475
476
477
478
479
480
481
482
483
484
485
                                    while (is_following_odigit(lex) && --digits != 0) {
                                        next_char(lex);
                                        num = num * 8 + (CUR_CHAR(lex) - '0');
                                    }
                                    c = num;
                                } else {
                                    // unrecognised escape character; CPython lets this through verbatim as '\' and then the character
                                    vstr_add_char(&lex->vstr, '\\');
                                }
                                break;
                        }
486
                    }
487
                    if (c != MP_LEXER_EOF) {
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
                        if (MICROPY_PY_BUILTINS_STR_UNICODE_DYNAMIC) {
                            if (c < 0x110000 && !is_bytes) {
                                vstr_add_char(&lex->vstr, c);
                            } else if (c < 0x100 && is_bytes) {
                                vstr_add_byte(&lex->vstr, c);
                            } else {
                                // unicode character out of range
                                // this raises a generic SyntaxError; could provide more info
                                lex->tok_kind = MP_TOKEN_INVALID;
                            }
                        } else {
                            // without unicode everything is just added as an 8-bit byte
                            if (c < 0x100) {
                                vstr_add_byte(&lex->vstr, c);
                            } else {
                                // 8-bit character out of range
                                // this raises a generic SyntaxError; could provide more info
                                lex->tok_kind = MP_TOKEN_INVALID;
                            }
507
                        }
508
509
                    }
                } else {
510
511
512
                    // Add the "character" as a byte so that we remain 8-bit clean.
                    // This way, strings are parsed correctly whether or not they contain utf-8 chars.
                    vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
513
514
515
516
517
518
519
                }
            }
            next_char(lex);
        }

        // check we got the required end quotes
        if (n_closing < num_quotes) {
520
            lex->tok_kind = MP_TOKEN_LONELY_STRING_OPEN;
Damien's avatar
Damien committed
521
522
        }

523
        // cut off the end quotes from the token text
524
        vstr_cut_tail_bytes(&lex->vstr, n_closing);
Damien's avatar
Damien committed
525
526

    } else if (is_head_of_identifier(lex)) {
527
        lex->tok_kind = MP_TOKEN_NAME;
Damien's avatar
Damien committed
528

529
530
        // get first char (add as byte to remain 8-bit clean and support utf-8)
        vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
531
532
        next_char(lex);

533
        // get tail chars
Damien's avatar
Damien committed
534
        while (!is_end(lex) && is_tail_of_identifier(lex)) {
535
            vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
536
537
538
539
            next_char(lex);
        }

    } else if (is_digit(lex) || (is_char(lex, '.') && is_following_digit(lex))) {
540
541
542
543
544
        bool forced_integer = false;
        if (is_char(lex, '.')) {
            lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
        } else {
            lex->tok_kind = MP_TOKEN_INTEGER;
545
            if (is_char(lex, '0') && is_following_base_char(lex)) {
546
547
548
                forced_integer = true;
            }
        }
Damien's avatar
Damien committed
549

550
551
        // get first char
        vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
552
553
        next_char(lex);

554
        // get tail chars
Damien's avatar
Damien committed
555
        while (!is_end(lex)) {
556
557
            if (!forced_integer && is_char_or(lex, 'e', 'E')) {
                lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
558
                vstr_add_char(&lex->vstr, 'e');
Damien's avatar
Damien committed
559
560
                next_char(lex);
                if (is_char(lex, '+') || is_char(lex, '-')) {
561
                    vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
562
563
                    next_char(lex);
                }
564
565
566
567
            } else if (is_letter(lex) || is_digit(lex) || is_char(lex, '.')) {
                if (is_char_or3(lex, '.', 'j', 'J')) {
                    lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
                }
568
                vstr_add_char(&lex->vstr, CUR_CHAR(lex));
Damien's avatar
Damien committed
569
570
571
572
573
574
                next_char(lex);
            } else {
                break;
            }
        }

575
576
577
578
579
580
581
582
583
584
585
586
    } else if (is_char(lex, '.')) {
        // special handling for . and ... operators, because .. is not a valid operator

        // get first char
        vstr_add_char(&lex->vstr, '.');
        next_char(lex);

        if (is_char_and(lex, '.', '.')) {
            vstr_add_char(&lex->vstr, '.');
            vstr_add_char(&lex->vstr, '.');
            next_char(lex);
            next_char(lex);
587
            lex->tok_kind = MP_TOKEN_ELLIPSIS;
588
        } else {
589
            lex->tok_kind = MP_TOKEN_DEL_PERIOD;
590
591
        }

Damien's avatar
Damien committed
592
593
594
595
    } else {
        // search for encoded delimiter or operator

        const char *t = tok_enc;
596
        mp_uint_t tok_enc_index = 0;
Damien's avatar
Damien committed
597
598
599
600
601
602
603
604
605
606
607
608
609
610
        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
611
            lex->tok_kind = MP_TOKEN_INVALID;
Damien's avatar
Damien committed
612
613
614
615
616
617

        } else {
            // matched a delimiter or operator character

            // get the maximum characters for a valid token
            t += 1;
618
            mp_uint_t t_index = tok_enc_index;
Damien's avatar
Damien committed
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
            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 {
636
                        lex->tok_kind = MP_TOKEN_INVALID;
637
                        goto tok_enc_no_match;
Damien's avatar
Damien committed
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
                    }
                    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
658
            lex->tok_kind = tok_enc_kind[tok_enc_index];
Damien's avatar
Damien committed
659

660
661
            tok_enc_no_match:

Damien's avatar
Damien committed
662
            // compute bracket level for implicit line joining
663
            if (lex->tok_kind == MP_TOKEN_DEL_PAREN_OPEN || lex->tok_kind == MP_TOKEN_DEL_BRACKET_OPEN || lex->tok_kind == MP_TOKEN_DEL_BRACE_OPEN) {
Damien's avatar
Damien committed
664
                lex->nested_bracket_level += 1;
665
            } else if (lex->tok_kind == MP_TOKEN_DEL_PAREN_CLOSE || lex->tok_kind == MP_TOKEN_DEL_BRACKET_CLOSE || lex->tok_kind == MP_TOKEN_DEL_BRACE_CLOSE) {
Damien's avatar
Damien committed
666
667
668
669
670
                lex->nested_bracket_level -= 1;
            }
        }
    }

671
    // check for keywords
672
    if (lex->tok_kind == MP_TOKEN_NAME) {
673
674
675
676
        // We check for __debug__ here and convert it to its value.  This is so
        // the parser gives a syntax error on, eg, x.__debug__.  Otherwise, we
        // need to check for this special token in many places in the compiler.
        // TODO improve speed of these string comparisons
677
        //for (mp_int_t i = 0; tok_kw[i] != NULL; i++) {
678
        for (size_t i = 0; i < MP_ARRAY_SIZE(tok_kw); i++) {
679
            if (str_strn_equal(tok_kw[i], lex->vstr.buf, lex->vstr.len)) {
680
681
                if (i == MP_ARRAY_SIZE(tok_kw) - 1) {
                    // tok_kw[MP_ARRAY_SIZE(tok_kw) - 1] == "__debug__"
682
                    lex->tok_kind = (MP_STATE_VM(mp_optimise_value) == 0 ? MP_TOKEN_KW_TRUE : MP_TOKEN_KW_FALSE);
683
                } else {
684
                    lex->tok_kind = MP_TOKEN_KW_FALSE + i;
685
                }
Damien's avatar
Damien committed
686
687
688
689
690
691
                break;
            }
        }
    }
}

692
mp_lexer_t *mp_lexer_new(qstr src_name, void *stream_data, mp_lexer_stream_next_byte_t stream_next_byte, mp_lexer_stream_close_t stream_close) {
693
    mp_lexer_t *lex = m_new_obj_maybe(mp_lexer_t);
694
695
696
697
698
699
700
701

    // check for memory allocation error
    if (lex == NULL) {
        if (stream_close) {
            stream_close(stream_data);
        }
        return NULL;
    }
Damien's avatar
Damien committed
702

703
    lex->source_name = src_name;
704
    lex->stream_data = stream_data;
705
    lex->stream_next_byte = stream_next_byte;
706
    lex->stream_close = stream_close;
Damien's avatar
Damien committed
707
708
709
710
    lex->line = 1;
    lex->column = 1;
    lex->emit_dent = 0;
    lex->nested_bracket_level = 0;
711
    lex->alloc_indent_level = MICROPY_ALLOC_LEXER_INDENT_INIT;
Damien's avatar
Damien committed
712
    lex->num_indent_level = 1;
713
    lex->indent_level = m_new_maybe(uint16_t, lex->alloc_indent_level);
714
    vstr_init(&lex->vstr, 32);
Damien's avatar
Damien committed
715

716
    // check for memory allocation error
717
718
    // note: vstr_init above may fail on malloc, but so may mp_lexer_next_token_into below
    if (lex->indent_level == NULL) {
719
720
721
722
723
724
725
        mp_lexer_free(lex);
        return NULL;
    }

    // store sentinel for first indentation level
    lex->indent_level[0] = 0;

Damien's avatar
Damien committed
726
    // preload characters
727
728
729
    lex->chr0 = stream_next_byte(stream_data);
    lex->chr1 = stream_next_byte(stream_data);
    lex->chr2 = stream_next_byte(stream_data);
730
731

    // if input stream is 0, 1 or 2 characters long and doesn't end in a newline, then insert a newline at the end
732
    if (lex->chr0 == MP_LEXER_EOF) {
733
        lex->chr0 = '\n';
734
    } else if (lex->chr1 == MP_LEXER_EOF) {
735
736
737
        if (lex->chr0 == '\r') {
            lex->chr0 = '\n';
        } else if (lex->chr0 != '\n') {
738
            lex->chr1 = '\n';
Damien's avatar
Damien committed
739
        }
740
    } else if (lex->chr2 == MP_LEXER_EOF) {
741
742
743
        if (lex->chr1 == '\r') {
            lex->chr1 = '\n';
        } else if (lex->chr1 != '\n') {
744
            lex->chr2 = '\n';
Damien's avatar
Damien committed
745
746
747
        }
    }

748
    // preload first token
749
    mp_lexer_next_token_into(lex, true);
Damien's avatar
Damien committed
750
751
752
753

    return lex;
}

754
755
756
757
758
759
760
761
mp_lexer_t *mp_lexer_new_from_str_len(qstr src_name, const char *str, mp_uint_t len, mp_uint_t free_len) {
    mp_reader_t reader;
    if (!mp_reader_new_mem(&reader, (const byte*)str, len, free_len)) {
        return NULL;
    }
    return mp_lexer_new(src_name, reader.data, (mp_lexer_stream_next_byte_t)reader.readbyte, (mp_lexer_stream_close_t)reader.close);
}

762
763
764
765
766
767
768
769
770
771
772
773
774
#if MICROPY_READER_POSIX || MICROPY_READER_FATFS

mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
    mp_reader_t reader;
    int ret = mp_reader_new_file(&reader, filename);
    if (ret != 0) {
        return NULL;
    }
    return mp_lexer_new(qstr_from_str(filename), reader.data, (mp_lexer_stream_next_byte_t)reader.readbyte, (mp_lexer_stream_close_t)reader.close);
}

#endif

775
void mp_lexer_free(mp_lexer_t *lex) {
776
    if (lex) {
777
778
        if (lex->stream_close) {
            lex->stream_close(lex->stream_data);
779
        }
780
        vstr_clear(&lex->vstr);
781
        m_del(uint16_t, lex->indent_level, lex->alloc_indent_level);
782
        m_del_obj(mp_lexer_t, lex);
Damien's avatar
Damien committed
783
784
785
    }
}

786
void mp_lexer_to_next(mp_lexer_t *lex) {
787
    mp_lexer_next_token_into(lex, false);
Damien's avatar
Damien committed
788
789
}

790
791
#if MICROPY_DEBUG_PRINTERS
void mp_lexer_show_token(const mp_lexer_t *lex) {
792
    printf("(" UINT_FMT ":" UINT_FMT ") kind:%u str:%p len:%zu", lex->tok_line, lex->tok_column, lex->tok_kind, lex->vstr.buf, lex->vstr.len);
793
794
795
796
797
798
799
800
    if (lex->vstr.len > 0) {
        const byte *i = (const byte *)lex->vstr.buf;
        const byte *j = (const byte *)i + lex->vstr.len;
        printf(" ");
        while (i < j) {
            unichar c = utf8_get_char(i);
            i = utf8_next_char(i);
            if (unichar_isprint(c)) {
801
                printf("%c", (int)c);
802
803
804
805
806
807
            } else {
                printf("?");
            }
        }
    }
    printf("\n");
Damien's avatar
Damien committed
808
}
809
#endif
810
811

#endif // MICROPY_ENABLE_COMPILER