lexer.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <assert.h>
  29. #include "py/reader.h"
  30. #include "py/lexer.h"
  31. #include "py/runtime.h"
  32. #if MICROPY_ENABLE_COMPILER
  33. #define TAB_SIZE (8)
  34. // TODO seems that CPython allows NULL byte in the input stream
  35. // don't know if that's intentional or not, but we don't allow it
  36. #define MP_LEXER_EOF ((unichar)MP_READER_EOF)
  37. #define CUR_CHAR(lex) ((lex)->chr0)
  38. STATIC bool is_end(mp_lexer_t *lex) {
  39. return lex->chr0 == MP_LEXER_EOF;
  40. }
  41. STATIC bool is_physical_newline(mp_lexer_t *lex) {
  42. return lex->chr0 == '\n';
  43. }
  44. STATIC bool is_char(mp_lexer_t *lex, byte c) {
  45. return lex->chr0 == c;
  46. }
  47. STATIC bool is_char_or(mp_lexer_t *lex, byte c1, byte c2) {
  48. return lex->chr0 == c1 || lex->chr0 == c2;
  49. }
  50. STATIC bool is_char_or3(mp_lexer_t *lex, byte c1, byte c2, byte c3) {
  51. return lex->chr0 == c1 || lex->chr0 == c2 || lex->chr0 == c3;
  52. }
  53. STATIC bool is_char_following(mp_lexer_t *lex, byte c) {
  54. return lex->chr1 == c;
  55. }
  56. STATIC bool is_char_following_or(mp_lexer_t *lex, byte c1, byte c2) {
  57. return lex->chr1 == c1 || lex->chr1 == c2;
  58. }
  59. STATIC bool is_char_following_following_or(mp_lexer_t *lex, byte c1, byte c2) {
  60. return lex->chr2 == c1 || lex->chr2 == c2;
  61. }
  62. STATIC bool is_char_and(mp_lexer_t *lex, byte c1, byte c2) {
  63. return lex->chr0 == c1 && lex->chr1 == c2;
  64. }
  65. STATIC bool is_whitespace(mp_lexer_t *lex) {
  66. return unichar_isspace(lex->chr0);
  67. }
  68. STATIC bool is_letter(mp_lexer_t *lex) {
  69. return unichar_isalpha(lex->chr0);
  70. }
  71. STATIC bool is_digit(mp_lexer_t *lex) {
  72. return unichar_isdigit(lex->chr0);
  73. }
  74. STATIC bool is_following_digit(mp_lexer_t *lex) {
  75. return unichar_isdigit(lex->chr1);
  76. }
  77. STATIC bool is_following_base_char(mp_lexer_t *lex) {
  78. const unichar chr1 = lex->chr1 | 0x20;
  79. return chr1 == 'b' || chr1 == 'o' || chr1 == 'x';
  80. }
  81. STATIC bool is_following_odigit(mp_lexer_t *lex) {
  82. return lex->chr1 >= '0' && lex->chr1 <= '7';
  83. }
  84. STATIC bool is_string_or_bytes(mp_lexer_t *lex) {
  85. return is_char_or(lex, '\'', '\"')
  86. || (is_char_or3(lex, 'r', 'u', 'b') && is_char_following_or(lex, '\'', '\"'))
  87. || ((is_char_and(lex, 'r', 'b') || is_char_and(lex, 'b', 'r'))
  88. && is_char_following_following_or(lex, '\'', '\"'));
  89. }
  90. // to easily parse utf-8 identifiers we allow any raw byte with high bit set
  91. STATIC bool is_head_of_identifier(mp_lexer_t *lex) {
  92. return is_letter(lex) || lex->chr0 == '_' || lex->chr0 >= 0x80;
  93. }
  94. STATIC bool is_tail_of_identifier(mp_lexer_t *lex) {
  95. return is_head_of_identifier(lex) || is_digit(lex);
  96. }
  97. STATIC void next_char(mp_lexer_t *lex) {
  98. if (lex->chr0 == '\n') {
  99. // a new line
  100. ++lex->line;
  101. lex->column = 1;
  102. } else if (lex->chr0 == '\t') {
  103. // a tab
  104. lex->column = (((lex->column - 1 + TAB_SIZE) / TAB_SIZE) * TAB_SIZE) + 1;
  105. } else {
  106. // a character worth one column
  107. ++lex->column;
  108. }
  109. lex->chr0 = lex->chr1;
  110. lex->chr1 = lex->chr2;
  111. lex->chr2 = lex->reader.readbyte(lex->reader.data);
  112. if (lex->chr1 == '\r') {
  113. // CR is a new line, converted to LF
  114. lex->chr1 = '\n';
  115. if (lex->chr2 == '\n') {
  116. // CR LF is a single new line, throw out the extra LF
  117. lex->chr2 = lex->reader.readbyte(lex->reader.data);
  118. }
  119. }
  120. // check if we need to insert a newline at end of file
  121. if (lex->chr2 == MP_LEXER_EOF && lex->chr1 != MP_LEXER_EOF && lex->chr1 != '\n') {
  122. lex->chr2 = '\n';
  123. }
  124. }
  125. STATIC void indent_push(mp_lexer_t *lex, size_t indent) {
  126. if (lex->num_indent_level >= lex->alloc_indent_level) {
  127. lex->indent_level = m_renew(uint16_t, lex->indent_level, lex->alloc_indent_level, lex->alloc_indent_level + MICROPY_ALLOC_LEXEL_INDENT_INC);
  128. lex->alloc_indent_level += MICROPY_ALLOC_LEXEL_INDENT_INC;
  129. }
  130. lex->indent_level[lex->num_indent_level++] = indent;
  131. }
  132. STATIC size_t indent_top(mp_lexer_t *lex) {
  133. return lex->indent_level[lex->num_indent_level - 1];
  134. }
  135. STATIC void indent_pop(mp_lexer_t *lex) {
  136. lex->num_indent_level -= 1;
  137. }
  138. // some tricky operator encoding:
  139. // <op> = begin with <op>, if this opchar matches then begin here
  140. // e<op> = end with <op>, if this opchar matches then end
  141. // c<op> = continue with <op>, if this opchar matches then continue matching
  142. // this means if the start of two ops are the same then they are equal til the last char
  143. STATIC const char *const tok_enc =
  144. "()[]{},:;~" // singles
  145. "<e=c<e=" // < <= << <<=
  146. ">e=c>e=" // > >= >> >>=
  147. "*e=c*e=" // * *= ** **=
  148. "+e=" // + +=
  149. "-e=e>" // - -= ->
  150. "&e=" // & &=
  151. "|e=" // | |=
  152. "/e=c/e=" // / /= // //=
  153. "%e=" // % %=
  154. "^e=" // ^ ^=
  155. "@e=" // @ @=
  156. "=e=" // = ==
  157. "!."; // start of special cases: != . ...
  158. // TODO static assert that number of tokens is less than 256 so we can safely make this table with byte sized entries
  159. STATIC const uint8_t tok_enc_kind[] = {
  160. MP_TOKEN_DEL_PAREN_OPEN, MP_TOKEN_DEL_PAREN_CLOSE,
  161. MP_TOKEN_DEL_BRACKET_OPEN, MP_TOKEN_DEL_BRACKET_CLOSE,
  162. MP_TOKEN_DEL_BRACE_OPEN, MP_TOKEN_DEL_BRACE_CLOSE,
  163. MP_TOKEN_DEL_COMMA, MP_TOKEN_DEL_COLON, MP_TOKEN_DEL_SEMICOLON, MP_TOKEN_OP_TILDE,
  164. MP_TOKEN_OP_LESS, MP_TOKEN_OP_LESS_EQUAL, MP_TOKEN_OP_DBL_LESS, MP_TOKEN_DEL_DBL_LESS_EQUAL,
  165. MP_TOKEN_OP_MORE, MP_TOKEN_OP_MORE_EQUAL, MP_TOKEN_OP_DBL_MORE, MP_TOKEN_DEL_DBL_MORE_EQUAL,
  166. MP_TOKEN_OP_STAR, MP_TOKEN_DEL_STAR_EQUAL, MP_TOKEN_OP_DBL_STAR, MP_TOKEN_DEL_DBL_STAR_EQUAL,
  167. MP_TOKEN_OP_PLUS, MP_TOKEN_DEL_PLUS_EQUAL,
  168. MP_TOKEN_OP_MINUS, MP_TOKEN_DEL_MINUS_EQUAL, MP_TOKEN_DEL_MINUS_MORE,
  169. MP_TOKEN_OP_AMPERSAND, MP_TOKEN_DEL_AMPERSAND_EQUAL,
  170. MP_TOKEN_OP_PIPE, MP_TOKEN_DEL_PIPE_EQUAL,
  171. MP_TOKEN_OP_SLASH, MP_TOKEN_DEL_SLASH_EQUAL, MP_TOKEN_OP_DBL_SLASH, MP_TOKEN_DEL_DBL_SLASH_EQUAL,
  172. MP_TOKEN_OP_PERCENT, MP_TOKEN_DEL_PERCENT_EQUAL,
  173. MP_TOKEN_OP_CARET, MP_TOKEN_DEL_CARET_EQUAL,
  174. MP_TOKEN_OP_AT, MP_TOKEN_DEL_AT_EQUAL,
  175. MP_TOKEN_DEL_EQUAL, MP_TOKEN_OP_DBL_EQUAL,
  176. };
  177. // must have the same order as enum in lexer.h
  178. // must be sorted according to strcmp
  179. STATIC const char *const tok_kw[] = {
  180. "False",
  181. "None",
  182. "True",
  183. "__debug__",
  184. "and",
  185. "as",
  186. "assert",
  187. #if MICROPY_PY_ASYNC_AWAIT
  188. "async",
  189. "await",
  190. #endif
  191. "break",
  192. "class",
  193. "continue",
  194. "def",
  195. "del",
  196. "elif",
  197. "else",
  198. "except",
  199. "finally",
  200. "for",
  201. "from",
  202. "global",
  203. "if",
  204. "import",
  205. "in",
  206. "is",
  207. "lambda",
  208. "nonlocal",
  209. "not",
  210. "or",
  211. "pass",
  212. "raise",
  213. "return",
  214. "try",
  215. "while",
  216. "with",
  217. "yield",
  218. };
  219. // This is called with CUR_CHAR() before first hex digit, and should return with
  220. // it pointing to last hex digit
  221. // num_digits must be greater than zero
  222. STATIC bool get_hex(mp_lexer_t *lex, size_t num_digits, mp_uint_t *result) {
  223. mp_uint_t num = 0;
  224. while (num_digits-- != 0) {
  225. next_char(lex);
  226. unichar c = CUR_CHAR(lex);
  227. if (!unichar_isxdigit(c)) {
  228. return false;
  229. }
  230. num = (num << 4) + unichar_xdigit_value(c);
  231. }
  232. *result = num;
  233. return true;
  234. }
  235. STATIC void parse_string_literal(mp_lexer_t *lex, bool is_raw) {
  236. // get first quoting character
  237. char quote_char = '\'';
  238. if (is_char(lex, '\"')) {
  239. quote_char = '\"';
  240. }
  241. next_char(lex);
  242. // work out if it's a single or triple quoted literal
  243. size_t num_quotes;
  244. if (is_char_and(lex, quote_char, quote_char)) {
  245. // triple quotes
  246. next_char(lex);
  247. next_char(lex);
  248. num_quotes = 3;
  249. } else {
  250. // single quotes
  251. num_quotes = 1;
  252. }
  253. size_t n_closing = 0;
  254. while (!is_end(lex) && (num_quotes > 1 || !is_char(lex, '\n')) && n_closing < num_quotes) {
  255. if (is_char(lex, quote_char)) {
  256. n_closing += 1;
  257. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  258. } else {
  259. n_closing = 0;
  260. if (is_char(lex, '\\')) {
  261. next_char(lex);
  262. unichar c = CUR_CHAR(lex);
  263. if (is_raw) {
  264. // raw strings allow escaping of quotes, but the backslash is also emitted
  265. vstr_add_char(&lex->vstr, '\\');
  266. } else {
  267. switch (c) {
  268. // note: "c" can never be MP_LEXER_EOF because next_char
  269. // always inserts a newline at the end of the input stream
  270. case '\n': c = MP_LEXER_EOF; break; // backslash escape the newline, just ignore it
  271. case '\\': break;
  272. case '\'': break;
  273. case '"': break;
  274. case 'a': c = 0x07; break;
  275. case 'b': c = 0x08; break;
  276. case 't': c = 0x09; break;
  277. case 'n': c = 0x0a; break;
  278. case 'v': c = 0x0b; break;
  279. case 'f': c = 0x0c; break;
  280. case 'r': c = 0x0d; break;
  281. case 'u':
  282. case 'U':
  283. if (lex->tok_kind == MP_TOKEN_BYTES) {
  284. // b'\u1234' == b'\\u1234'
  285. vstr_add_char(&lex->vstr, '\\');
  286. break;
  287. }
  288. // Otherwise fall through.
  289. case 'x':
  290. {
  291. mp_uint_t num = 0;
  292. if (!get_hex(lex, (c == 'x' ? 2 : c == 'u' ? 4 : 8), &num)) {
  293. // not enough hex chars for escape sequence
  294. lex->tok_kind = MP_TOKEN_INVALID;
  295. }
  296. c = num;
  297. break;
  298. }
  299. case 'N':
  300. // Supporting '\N{LATIN SMALL LETTER A}' == 'a' would require keeping the
  301. // entire Unicode name table in the core. As of Unicode 6.3.0, that's nearly
  302. // 3MB of text; even gzip-compressed and with minimal structure, it'll take
  303. // roughly half a meg of storage. This form of Unicode escape may be added
  304. // later on, but it's definitely not a priority right now. -- CJA 20140607
  305. mp_raise_NotImplementedError("unicode name escapes");
  306. break;
  307. default:
  308. if (c >= '0' && c <= '7') {
  309. // Octal sequence, 1-3 chars
  310. size_t digits = 3;
  311. mp_uint_t num = c - '0';
  312. while (is_following_odigit(lex) && --digits != 0) {
  313. next_char(lex);
  314. num = num * 8 + (CUR_CHAR(lex) - '0');
  315. }
  316. c = num;
  317. } else {
  318. // unrecognised escape character; CPython lets this through verbatim as '\' and then the character
  319. vstr_add_char(&lex->vstr, '\\');
  320. }
  321. break;
  322. }
  323. }
  324. if (c != MP_LEXER_EOF) {
  325. if (MICROPY_PY_BUILTINS_STR_UNICODE_DYNAMIC) {
  326. if (c < 0x110000 && lex->tok_kind == MP_TOKEN_STRING) {
  327. vstr_add_char(&lex->vstr, c);
  328. } else if (c < 0x100 && lex->tok_kind == MP_TOKEN_BYTES) {
  329. vstr_add_byte(&lex->vstr, c);
  330. } else {
  331. // unicode character out of range
  332. // this raises a generic SyntaxError; could provide more info
  333. lex->tok_kind = MP_TOKEN_INVALID;
  334. }
  335. } else {
  336. // without unicode everything is just added as an 8-bit byte
  337. if (c < 0x100) {
  338. vstr_add_byte(&lex->vstr, c);
  339. } else {
  340. // 8-bit character out of range
  341. // this raises a generic SyntaxError; could provide more info
  342. lex->tok_kind = MP_TOKEN_INVALID;
  343. }
  344. }
  345. }
  346. } else {
  347. // Add the "character" as a byte so that we remain 8-bit clean.
  348. // This way, strings are parsed correctly whether or not they contain utf-8 chars.
  349. vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
  350. }
  351. }
  352. next_char(lex);
  353. }
  354. // check we got the required end quotes
  355. if (n_closing < num_quotes) {
  356. lex->tok_kind = MP_TOKEN_LONELY_STRING_OPEN;
  357. }
  358. // cut off the end quotes from the token text
  359. vstr_cut_tail_bytes(&lex->vstr, n_closing);
  360. }
  361. STATIC bool skip_whitespace(mp_lexer_t *lex, bool stop_at_newline) {
  362. bool had_physical_newline = false;
  363. while (!is_end(lex)) {
  364. if (is_physical_newline(lex)) {
  365. if (stop_at_newline && lex->nested_bracket_level == 0) {
  366. break;
  367. }
  368. had_physical_newline = true;
  369. next_char(lex);
  370. } else if (is_whitespace(lex)) {
  371. next_char(lex);
  372. } else if (is_char(lex, '#')) {
  373. next_char(lex);
  374. while (!is_end(lex) && !is_physical_newline(lex)) {
  375. next_char(lex);
  376. }
  377. // had_physical_newline will be set on next loop
  378. } else if (is_char_and(lex, '\\', '\n')) {
  379. // line-continuation, so don't set had_physical_newline
  380. next_char(lex);
  381. next_char(lex);
  382. } else {
  383. break;
  384. }
  385. }
  386. return had_physical_newline;
  387. }
  388. void mp_lexer_to_next(mp_lexer_t *lex) {
  389. // start new token text
  390. vstr_reset(&lex->vstr);
  391. // skip white space and comments
  392. bool had_physical_newline = skip_whitespace(lex, false);
  393. // set token source information
  394. lex->tok_line = lex->line;
  395. lex->tok_column = lex->column;
  396. if (lex->emit_dent < 0) {
  397. lex->tok_kind = MP_TOKEN_DEDENT;
  398. lex->emit_dent += 1;
  399. } else if (lex->emit_dent > 0) {
  400. lex->tok_kind = MP_TOKEN_INDENT;
  401. lex->emit_dent -= 1;
  402. } else if (had_physical_newline && lex->nested_bracket_level == 0) {
  403. lex->tok_kind = MP_TOKEN_NEWLINE;
  404. size_t num_spaces = lex->column - 1;
  405. if (num_spaces == indent_top(lex)) {
  406. } else if (num_spaces > indent_top(lex)) {
  407. indent_push(lex, num_spaces);
  408. lex->emit_dent += 1;
  409. } else {
  410. while (num_spaces < indent_top(lex)) {
  411. indent_pop(lex);
  412. lex->emit_dent -= 1;
  413. }
  414. if (num_spaces != indent_top(lex)) {
  415. lex->tok_kind = MP_TOKEN_DEDENT_MISMATCH;
  416. }
  417. }
  418. } else if (is_end(lex)) {
  419. lex->tok_kind = MP_TOKEN_END;
  420. } else if (is_string_or_bytes(lex)) {
  421. // a string or bytes literal
  422. // Python requires adjacent string/bytes literals to be automatically
  423. // concatenated. We do it here in the tokeniser to make efficient use of RAM,
  424. // because then the lexer's vstr can be used to accumulate the string literal,
  425. // in contrast to creating a parse tree of strings and then joining them later
  426. // in the compiler. It's also more compact in code size to do it here.
  427. // MP_TOKEN_END is used to indicate that this is the first string token
  428. lex->tok_kind = MP_TOKEN_END;
  429. // Loop to accumulate string/bytes literals
  430. do {
  431. // parse type codes
  432. bool is_raw = false;
  433. mp_token_kind_t kind = MP_TOKEN_STRING;
  434. int n_char = 0;
  435. if (is_char(lex, 'u')) {
  436. n_char = 1;
  437. } else if (is_char(lex, 'b')) {
  438. kind = MP_TOKEN_BYTES;
  439. n_char = 1;
  440. if (is_char_following(lex, 'r')) {
  441. is_raw = true;
  442. n_char = 2;
  443. }
  444. } else if (is_char(lex, 'r')) {
  445. is_raw = true;
  446. n_char = 1;
  447. if (is_char_following(lex, 'b')) {
  448. kind = MP_TOKEN_BYTES;
  449. n_char = 2;
  450. }
  451. }
  452. // Set or check token kind
  453. if (lex->tok_kind == MP_TOKEN_END) {
  454. lex->tok_kind = kind;
  455. } else if (lex->tok_kind != kind) {
  456. // Can't concatenate string with bytes
  457. break;
  458. }
  459. // Skip any type code characters
  460. if (n_char != 0) {
  461. next_char(lex);
  462. if (n_char == 2) {
  463. next_char(lex);
  464. }
  465. }
  466. // Parse the literal
  467. parse_string_literal(lex, is_raw);
  468. // Skip whitespace so we can check if there's another string following
  469. skip_whitespace(lex, true);
  470. } while (is_string_or_bytes(lex));
  471. } else if (is_head_of_identifier(lex)) {
  472. lex->tok_kind = MP_TOKEN_NAME;
  473. // get first char (add as byte to remain 8-bit clean and support utf-8)
  474. vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
  475. next_char(lex);
  476. // get tail chars
  477. while (!is_end(lex) && is_tail_of_identifier(lex)) {
  478. vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
  479. next_char(lex);
  480. }
  481. // Check if the name is a keyword.
  482. // We also check for __debug__ here and convert it to its value. This is
  483. // so the parser gives a syntax error on, eg, x.__debug__. Otherwise, we
  484. // need to check for this special token in many places in the compiler.
  485. const char *s = vstr_null_terminated_str(&lex->vstr);
  486. for (size_t i = 0; i < MP_ARRAY_SIZE(tok_kw); i++) {
  487. int cmp = strcmp(s, tok_kw[i]);
  488. if (cmp == 0) {
  489. lex->tok_kind = MP_TOKEN_KW_FALSE + i;
  490. if (lex->tok_kind == MP_TOKEN_KW___DEBUG__) {
  491. lex->tok_kind = (MP_STATE_VM(mp_optimise_value) == 0 ? MP_TOKEN_KW_TRUE : MP_TOKEN_KW_FALSE);
  492. }
  493. break;
  494. } else if (cmp < 0) {
  495. // Table is sorted and comparison was less-than, so stop searching
  496. break;
  497. }
  498. }
  499. } else if (is_digit(lex) || (is_char(lex, '.') && is_following_digit(lex))) {
  500. bool forced_integer = false;
  501. if (is_char(lex, '.')) {
  502. lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
  503. } else {
  504. lex->tok_kind = MP_TOKEN_INTEGER;
  505. if (is_char(lex, '0') && is_following_base_char(lex)) {
  506. forced_integer = true;
  507. }
  508. }
  509. // get first char
  510. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  511. next_char(lex);
  512. // get tail chars
  513. while (!is_end(lex)) {
  514. if (!forced_integer && is_char_or(lex, 'e', 'E')) {
  515. lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
  516. vstr_add_char(&lex->vstr, 'e');
  517. next_char(lex);
  518. if (is_char(lex, '+') || is_char(lex, '-')) {
  519. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  520. next_char(lex);
  521. }
  522. } else if (is_letter(lex) || is_digit(lex) || is_char(lex, '.')) {
  523. if (is_char_or3(lex, '.', 'j', 'J')) {
  524. lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
  525. }
  526. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  527. next_char(lex);
  528. } else if (is_char(lex, '_')) {
  529. next_char(lex);
  530. } else {
  531. break;
  532. }
  533. }
  534. } else {
  535. // search for encoded delimiter or operator
  536. const char *t = tok_enc;
  537. size_t tok_enc_index = 0;
  538. for (; *t != 0 && !is_char(lex, *t); t += 1) {
  539. if (*t == 'e' || *t == 'c') {
  540. t += 1;
  541. }
  542. tok_enc_index += 1;
  543. }
  544. next_char(lex);
  545. if (*t == 0) {
  546. // didn't match any delimiter or operator characters
  547. lex->tok_kind = MP_TOKEN_INVALID;
  548. } else if (*t == '!') {
  549. // "!=" is a special case because "!" is not a valid operator
  550. if (is_char(lex, '=')) {
  551. next_char(lex);
  552. lex->tok_kind = MP_TOKEN_OP_NOT_EQUAL;
  553. } else {
  554. lex->tok_kind = MP_TOKEN_INVALID;
  555. }
  556. } else if (*t == '.') {
  557. // "." and "..." are special cases because ".." is not a valid operator
  558. if (is_char_and(lex, '.', '.')) {
  559. next_char(lex);
  560. next_char(lex);
  561. lex->tok_kind = MP_TOKEN_ELLIPSIS;
  562. } else {
  563. lex->tok_kind = MP_TOKEN_DEL_PERIOD;
  564. }
  565. } else {
  566. // matched a delimiter or operator character
  567. // get the maximum characters for a valid token
  568. t += 1;
  569. size_t t_index = tok_enc_index;
  570. while (*t == 'c' || *t == 'e') {
  571. t_index += 1;
  572. if (is_char(lex, t[1])) {
  573. next_char(lex);
  574. tok_enc_index = t_index;
  575. if (*t == 'e') {
  576. break;
  577. }
  578. } else if (*t == 'c') {
  579. break;
  580. }
  581. t += 2;
  582. }
  583. // set token kind
  584. lex->tok_kind = tok_enc_kind[tok_enc_index];
  585. // compute bracket level for implicit line joining
  586. 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) {
  587. lex->nested_bracket_level += 1;
  588. } 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) {
  589. lex->nested_bracket_level -= 1;
  590. }
  591. }
  592. }
  593. }
  594. mp_lexer_t *mp_lexer_new(qstr src_name, mp_reader_t reader) {
  595. mp_lexer_t *lex = m_new_obj(mp_lexer_t);
  596. lex->source_name = src_name;
  597. lex->reader = reader;
  598. lex->line = 1;
  599. lex->column = (size_t)-2; // account for 3 dummy bytes
  600. lex->emit_dent = 0;
  601. lex->nested_bracket_level = 0;
  602. lex->alloc_indent_level = MICROPY_ALLOC_LEXER_INDENT_INIT;
  603. lex->num_indent_level = 1;
  604. lex->indent_level = m_new(uint16_t, lex->alloc_indent_level);
  605. vstr_init(&lex->vstr, 32);
  606. // store sentinel for first indentation level
  607. lex->indent_level[0] = 0;
  608. // load lexer with start of file, advancing lex->column to 1
  609. // start with dummy bytes and use next_char() for proper EOL/EOF handling
  610. lex->chr0 = lex->chr1 = lex->chr2 = 0;
  611. next_char(lex);
  612. next_char(lex);
  613. next_char(lex);
  614. // preload first token
  615. mp_lexer_to_next(lex);
  616. // Check that the first token is in the first column. If it's not then we
  617. // convert the token kind to INDENT so that the parser gives a syntax error.
  618. if (lex->tok_column != 1) {
  619. lex->tok_kind = MP_TOKEN_INDENT;
  620. }
  621. return lex;
  622. }
  623. mp_lexer_t *mp_lexer_new_from_str_len(qstr src_name, const char *str, size_t len, size_t free_len) {
  624. mp_reader_t reader;
  625. mp_reader_new_mem(&reader, (const byte*)str, len, free_len);
  626. return mp_lexer_new(src_name, reader);
  627. }
  628. #if MICROPY_READER_POSIX || MICROPY_READER_VFS
  629. mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
  630. mp_reader_t reader;
  631. mp_reader_new_file(&reader, filename);
  632. return mp_lexer_new(qstr_from_str(filename), reader);
  633. }
  634. #if MICROPY_HELPER_LEXER_UNIX
  635. mp_lexer_t *mp_lexer_new_from_fd(qstr filename, int fd, bool close_fd) {
  636. mp_reader_t reader;
  637. mp_reader_new_file_from_fd(&reader, fd, close_fd);
  638. return mp_lexer_new(filename, reader);
  639. }
  640. #endif
  641. #endif
  642. void mp_lexer_free(mp_lexer_t *lex) {
  643. if (lex) {
  644. lex->reader.close(lex->reader.data);
  645. vstr_clear(&lex->vstr);
  646. m_del(uint16_t, lex->indent_level, lex->alloc_indent_level);
  647. m_del_obj(mp_lexer_t, lex);
  648. }
  649. }
  650. #if 0
  651. // This function is used to print the current token and should only be
  652. // needed to debug the lexer, so it's not available via a config option.
  653. void mp_lexer_show_token(const mp_lexer_t *lex) {
  654. 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);
  655. if (lex->vstr.len > 0) {
  656. const byte *i = (const byte *)lex->vstr.buf;
  657. const byte *j = (const byte *)i + lex->vstr.len;
  658. printf(" ");
  659. while (i < j) {
  660. unichar c = utf8_get_char(i);
  661. i = utf8_next_char(i);
  662. if (unichar_isprint(c)) {
  663. printf("%c", (int)c);
  664. } else {
  665. printf("?");
  666. }
  667. }
  668. }
  669. printf("\n");
  670. }
  671. #endif
  672. #endif // MICROPY_ENABLE_COMPILER