lexer.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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. "!."; // start of special cases: != . ...
  157. // TODO static assert that number of tokens is less than 256 so we can safely make this table with byte sized entries
  158. STATIC const uint8_t tok_enc_kind[] = {
  159. MP_TOKEN_DEL_PAREN_OPEN, MP_TOKEN_DEL_PAREN_CLOSE,
  160. MP_TOKEN_DEL_BRACKET_OPEN, MP_TOKEN_DEL_BRACKET_CLOSE,
  161. MP_TOKEN_DEL_BRACE_OPEN, MP_TOKEN_DEL_BRACE_CLOSE,
  162. MP_TOKEN_DEL_COMMA, MP_TOKEN_DEL_COLON, MP_TOKEN_DEL_SEMICOLON, MP_TOKEN_DEL_AT, MP_TOKEN_OP_TILDE,
  163. MP_TOKEN_OP_LESS, MP_TOKEN_OP_LESS_EQUAL, MP_TOKEN_OP_DBL_LESS, MP_TOKEN_DEL_DBL_LESS_EQUAL,
  164. MP_TOKEN_OP_MORE, MP_TOKEN_OP_MORE_EQUAL, MP_TOKEN_OP_DBL_MORE, MP_TOKEN_DEL_DBL_MORE_EQUAL,
  165. MP_TOKEN_OP_STAR, MP_TOKEN_DEL_STAR_EQUAL, MP_TOKEN_OP_DBL_STAR, MP_TOKEN_DEL_DBL_STAR_EQUAL,
  166. MP_TOKEN_OP_PLUS, MP_TOKEN_DEL_PLUS_EQUAL,
  167. MP_TOKEN_OP_MINUS, MP_TOKEN_DEL_MINUS_EQUAL, MP_TOKEN_DEL_MINUS_MORE,
  168. MP_TOKEN_OP_AMPERSAND, MP_TOKEN_DEL_AMPERSAND_EQUAL,
  169. MP_TOKEN_OP_PIPE, MP_TOKEN_DEL_PIPE_EQUAL,
  170. MP_TOKEN_OP_SLASH, MP_TOKEN_DEL_SLASH_EQUAL, MP_TOKEN_OP_DBL_SLASH, MP_TOKEN_DEL_DBL_SLASH_EQUAL,
  171. MP_TOKEN_OP_PERCENT, MP_TOKEN_DEL_PERCENT_EQUAL,
  172. MP_TOKEN_OP_CARET, MP_TOKEN_DEL_CARET_EQUAL,
  173. MP_TOKEN_DEL_EQUAL, MP_TOKEN_OP_DBL_EQUAL,
  174. };
  175. // must have the same order as enum in lexer.h
  176. // must be sorted according to strcmp
  177. STATIC const char *const tok_kw[] = {
  178. "False",
  179. "None",
  180. "True",
  181. "__debug__",
  182. "and",
  183. "as",
  184. "assert",
  185. #if MICROPY_PY_ASYNC_AWAIT
  186. "async",
  187. "await",
  188. #endif
  189. "break",
  190. "class",
  191. "continue",
  192. "def",
  193. "del",
  194. "elif",
  195. "else",
  196. "except",
  197. "finally",
  198. "for",
  199. "from",
  200. "global",
  201. "if",
  202. "import",
  203. "in",
  204. "is",
  205. "lambda",
  206. "nonlocal",
  207. "not",
  208. "or",
  209. "pass",
  210. "raise",
  211. "return",
  212. "try",
  213. "while",
  214. "with",
  215. "yield",
  216. };
  217. // This is called with CUR_CHAR() before first hex digit, and should return with
  218. // it pointing to last hex digit
  219. // num_digits must be greater than zero
  220. STATIC bool get_hex(mp_lexer_t *lex, size_t num_digits, mp_uint_t *result) {
  221. mp_uint_t num = 0;
  222. while (num_digits-- != 0) {
  223. next_char(lex);
  224. unichar c = CUR_CHAR(lex);
  225. if (!unichar_isxdigit(c)) {
  226. return false;
  227. }
  228. num = (num << 4) + unichar_xdigit_value(c);
  229. }
  230. *result = num;
  231. return true;
  232. }
  233. STATIC void parse_string_literal(mp_lexer_t *lex, bool is_raw) {
  234. // get first quoting character
  235. char quote_char = '\'';
  236. if (is_char(lex, '\"')) {
  237. quote_char = '\"';
  238. }
  239. next_char(lex);
  240. // work out if it's a single or triple quoted literal
  241. size_t num_quotes;
  242. if (is_char_and(lex, quote_char, quote_char)) {
  243. // triple quotes
  244. next_char(lex);
  245. next_char(lex);
  246. num_quotes = 3;
  247. } else {
  248. // single quotes
  249. num_quotes = 1;
  250. }
  251. size_t n_closing = 0;
  252. while (!is_end(lex) && (num_quotes > 1 || !is_char(lex, '\n')) && n_closing < num_quotes) {
  253. if (is_char(lex, quote_char)) {
  254. n_closing += 1;
  255. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  256. } else {
  257. n_closing = 0;
  258. if (is_char(lex, '\\')) {
  259. next_char(lex);
  260. unichar c = CUR_CHAR(lex);
  261. if (is_raw) {
  262. // raw strings allow escaping of quotes, but the backslash is also emitted
  263. vstr_add_char(&lex->vstr, '\\');
  264. } else {
  265. switch (c) {
  266. // note: "c" can never be MP_LEXER_EOF because next_char
  267. // always inserts a newline at the end of the input stream
  268. case '\n': c = MP_LEXER_EOF; break; // backslash escape the newline, just ignore it
  269. case '\\': break;
  270. case '\'': break;
  271. case '"': break;
  272. case 'a': c = 0x07; break;
  273. case 'b': c = 0x08; break;
  274. case 't': c = 0x09; break;
  275. case 'n': c = 0x0a; break;
  276. case 'v': c = 0x0b; break;
  277. case 'f': c = 0x0c; break;
  278. case 'r': c = 0x0d; break;
  279. case 'u':
  280. case 'U':
  281. if (lex->tok_kind == MP_TOKEN_BYTES) {
  282. // b'\u1234' == b'\\u1234'
  283. vstr_add_char(&lex->vstr, '\\');
  284. break;
  285. }
  286. // Otherwise fall through.
  287. case 'x':
  288. {
  289. mp_uint_t num = 0;
  290. if (!get_hex(lex, (c == 'x' ? 2 : c == 'u' ? 4 : 8), &num)) {
  291. // not enough hex chars for escape sequence
  292. lex->tok_kind = MP_TOKEN_INVALID;
  293. }
  294. c = num;
  295. break;
  296. }
  297. case 'N':
  298. // Supporting '\N{LATIN SMALL LETTER A}' == 'a' would require keeping the
  299. // entire Unicode name table in the core. As of Unicode 6.3.0, that's nearly
  300. // 3MB of text; even gzip-compressed and with minimal structure, it'll take
  301. // roughly half a meg of storage. This form of Unicode escape may be added
  302. // later on, but it's definitely not a priority right now. -- CJA 20140607
  303. mp_raise_NotImplementedError("unicode name escapes");
  304. break;
  305. default:
  306. if (c >= '0' && c <= '7') {
  307. // Octal sequence, 1-3 chars
  308. size_t digits = 3;
  309. mp_uint_t num = c - '0';
  310. while (is_following_odigit(lex) && --digits != 0) {
  311. next_char(lex);
  312. num = num * 8 + (CUR_CHAR(lex) - '0');
  313. }
  314. c = num;
  315. } else {
  316. // unrecognised escape character; CPython lets this through verbatim as '\' and then the character
  317. vstr_add_char(&lex->vstr, '\\');
  318. }
  319. break;
  320. }
  321. }
  322. if (c != MP_LEXER_EOF) {
  323. if (MICROPY_PY_BUILTINS_STR_UNICODE_DYNAMIC) {
  324. if (c < 0x110000 && lex->tok_kind == MP_TOKEN_STRING) {
  325. vstr_add_char(&lex->vstr, c);
  326. } else if (c < 0x100 && lex->tok_kind == MP_TOKEN_BYTES) {
  327. vstr_add_byte(&lex->vstr, c);
  328. } else {
  329. // unicode character out of range
  330. // this raises a generic SyntaxError; could provide more info
  331. lex->tok_kind = MP_TOKEN_INVALID;
  332. }
  333. } else {
  334. // without unicode everything is just added as an 8-bit byte
  335. if (c < 0x100) {
  336. vstr_add_byte(&lex->vstr, c);
  337. } else {
  338. // 8-bit character out of range
  339. // this raises a generic SyntaxError; could provide more info
  340. lex->tok_kind = MP_TOKEN_INVALID;
  341. }
  342. }
  343. }
  344. } else {
  345. // Add the "character" as a byte so that we remain 8-bit clean.
  346. // This way, strings are parsed correctly whether or not they contain utf-8 chars.
  347. vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
  348. }
  349. }
  350. next_char(lex);
  351. }
  352. // check we got the required end quotes
  353. if (n_closing < num_quotes) {
  354. lex->tok_kind = MP_TOKEN_LONELY_STRING_OPEN;
  355. }
  356. // cut off the end quotes from the token text
  357. vstr_cut_tail_bytes(&lex->vstr, n_closing);
  358. }
  359. STATIC bool skip_whitespace(mp_lexer_t *lex, bool stop_at_newline) {
  360. bool had_physical_newline = false;
  361. while (!is_end(lex)) {
  362. if (is_physical_newline(lex)) {
  363. if (stop_at_newline && lex->nested_bracket_level == 0) {
  364. break;
  365. }
  366. had_physical_newline = true;
  367. next_char(lex);
  368. } else if (is_whitespace(lex)) {
  369. next_char(lex);
  370. } else if (is_char(lex, '#')) {
  371. next_char(lex);
  372. while (!is_end(lex) && !is_physical_newline(lex)) {
  373. next_char(lex);
  374. }
  375. // had_physical_newline will be set on next loop
  376. } else if (is_char_and(lex, '\\', '\n')) {
  377. // line-continuation, so don't set had_physical_newline
  378. next_char(lex);
  379. next_char(lex);
  380. } else {
  381. break;
  382. }
  383. }
  384. return had_physical_newline;
  385. }
  386. void mp_lexer_to_next(mp_lexer_t *lex) {
  387. // start new token text
  388. vstr_reset(&lex->vstr);
  389. // skip white space and comments
  390. bool had_physical_newline = skip_whitespace(lex, false);
  391. // set token source information
  392. lex->tok_line = lex->line;
  393. lex->tok_column = lex->column;
  394. if (lex->emit_dent < 0) {
  395. lex->tok_kind = MP_TOKEN_DEDENT;
  396. lex->emit_dent += 1;
  397. } else if (lex->emit_dent > 0) {
  398. lex->tok_kind = MP_TOKEN_INDENT;
  399. lex->emit_dent -= 1;
  400. } else if (had_physical_newline && lex->nested_bracket_level == 0) {
  401. lex->tok_kind = MP_TOKEN_NEWLINE;
  402. size_t num_spaces = lex->column - 1;
  403. if (num_spaces == indent_top(lex)) {
  404. } else if (num_spaces > indent_top(lex)) {
  405. indent_push(lex, num_spaces);
  406. lex->emit_dent += 1;
  407. } else {
  408. while (num_spaces < indent_top(lex)) {
  409. indent_pop(lex);
  410. lex->emit_dent -= 1;
  411. }
  412. if (num_spaces != indent_top(lex)) {
  413. lex->tok_kind = MP_TOKEN_DEDENT_MISMATCH;
  414. }
  415. }
  416. } else if (is_end(lex)) {
  417. lex->tok_kind = MP_TOKEN_END;
  418. } else if (is_string_or_bytes(lex)) {
  419. // a string or bytes literal
  420. // Python requires adjacent string/bytes literals to be automatically
  421. // concatenated. We do it here in the tokeniser to make efficient use of RAM,
  422. // because then the lexer's vstr can be used to accumulate the string literal,
  423. // in contrast to creating a parse tree of strings and then joining them later
  424. // in the compiler. It's also more compact in code size to do it here.
  425. // MP_TOKEN_END is used to indicate that this is the first string token
  426. lex->tok_kind = MP_TOKEN_END;
  427. // Loop to accumulate string/bytes literals
  428. do {
  429. // parse type codes
  430. bool is_raw = false;
  431. mp_token_kind_t kind = MP_TOKEN_STRING;
  432. int n_char = 0;
  433. if (is_char(lex, 'u')) {
  434. n_char = 1;
  435. } else if (is_char(lex, 'b')) {
  436. kind = MP_TOKEN_BYTES;
  437. n_char = 1;
  438. if (is_char_following(lex, 'r')) {
  439. is_raw = true;
  440. n_char = 2;
  441. }
  442. } else if (is_char(lex, 'r')) {
  443. is_raw = true;
  444. n_char = 1;
  445. if (is_char_following(lex, 'b')) {
  446. kind = MP_TOKEN_BYTES;
  447. n_char = 2;
  448. }
  449. }
  450. // Set or check token kind
  451. if (lex->tok_kind == MP_TOKEN_END) {
  452. lex->tok_kind = kind;
  453. } else if (lex->tok_kind != kind) {
  454. // Can't concatenate string with bytes
  455. break;
  456. }
  457. // Skip any type code characters
  458. if (n_char != 0) {
  459. next_char(lex);
  460. if (n_char == 2) {
  461. next_char(lex);
  462. }
  463. }
  464. // Parse the literal
  465. parse_string_literal(lex, is_raw);
  466. // Skip whitespace so we can check if there's another string following
  467. skip_whitespace(lex, true);
  468. } while (is_string_or_bytes(lex));
  469. } else if (is_head_of_identifier(lex)) {
  470. lex->tok_kind = MP_TOKEN_NAME;
  471. // get first char (add as byte to remain 8-bit clean and support utf-8)
  472. vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
  473. next_char(lex);
  474. // get tail chars
  475. while (!is_end(lex) && is_tail_of_identifier(lex)) {
  476. vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
  477. next_char(lex);
  478. }
  479. // Check if the name is a keyword.
  480. // We also check for __debug__ here and convert it to its value. This is
  481. // so the parser gives a syntax error on, eg, x.__debug__. Otherwise, we
  482. // need to check for this special token in many places in the compiler.
  483. const char *s = vstr_null_terminated_str(&lex->vstr);
  484. for (size_t i = 0; i < MP_ARRAY_SIZE(tok_kw); i++) {
  485. int cmp = strcmp(s, tok_kw[i]);
  486. if (cmp == 0) {
  487. lex->tok_kind = MP_TOKEN_KW_FALSE + i;
  488. if (lex->tok_kind == MP_TOKEN_KW___DEBUG__) {
  489. lex->tok_kind = (MP_STATE_VM(mp_optimise_value) == 0 ? MP_TOKEN_KW_TRUE : MP_TOKEN_KW_FALSE);
  490. }
  491. break;
  492. } else if (cmp < 0) {
  493. // Table is sorted and comparison was less-than, so stop searching
  494. break;
  495. }
  496. }
  497. } else if (is_digit(lex) || (is_char(lex, '.') && is_following_digit(lex))) {
  498. bool forced_integer = false;
  499. if (is_char(lex, '.')) {
  500. lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
  501. } else {
  502. lex->tok_kind = MP_TOKEN_INTEGER;
  503. if (is_char(lex, '0') && is_following_base_char(lex)) {
  504. forced_integer = true;
  505. }
  506. }
  507. // get first char
  508. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  509. next_char(lex);
  510. // get tail chars
  511. while (!is_end(lex)) {
  512. if (!forced_integer && is_char_or(lex, 'e', 'E')) {
  513. lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
  514. vstr_add_char(&lex->vstr, 'e');
  515. next_char(lex);
  516. if (is_char(lex, '+') || is_char(lex, '-')) {
  517. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  518. next_char(lex);
  519. }
  520. } else if (is_letter(lex) || is_digit(lex) || is_char(lex, '.')) {
  521. if (is_char_or3(lex, '.', 'j', 'J')) {
  522. lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
  523. }
  524. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  525. next_char(lex);
  526. } else if (is_char(lex, '_')) {
  527. next_char(lex);
  528. } else {
  529. break;
  530. }
  531. }
  532. } else {
  533. // search for encoded delimiter or operator
  534. const char *t = tok_enc;
  535. size_t tok_enc_index = 0;
  536. for (; *t != 0 && !is_char(lex, *t); t += 1) {
  537. if (*t == 'e' || *t == 'c') {
  538. t += 1;
  539. }
  540. tok_enc_index += 1;
  541. }
  542. next_char(lex);
  543. if (*t == 0) {
  544. // didn't match any delimiter or operator characters
  545. lex->tok_kind = MP_TOKEN_INVALID;
  546. } else if (*t == '!') {
  547. // "!=" is a special case because "!" is not a valid operator
  548. if (is_char(lex, '=')) {
  549. next_char(lex);
  550. lex->tok_kind = MP_TOKEN_OP_NOT_EQUAL;
  551. } else {
  552. lex->tok_kind = MP_TOKEN_INVALID;
  553. }
  554. } else if (*t == '.') {
  555. // "." and "..." are special cases because ".." is not a valid operator
  556. if (is_char_and(lex, '.', '.')) {
  557. next_char(lex);
  558. next_char(lex);
  559. lex->tok_kind = MP_TOKEN_ELLIPSIS;
  560. } else {
  561. lex->tok_kind = MP_TOKEN_DEL_PERIOD;
  562. }
  563. } else {
  564. // matched a delimiter or operator character
  565. // get the maximum characters for a valid token
  566. t += 1;
  567. size_t t_index = tok_enc_index;
  568. while (*t == 'c' || *t == 'e') {
  569. t_index += 1;
  570. if (is_char(lex, t[1])) {
  571. next_char(lex);
  572. tok_enc_index = t_index;
  573. if (*t == 'e') {
  574. break;
  575. }
  576. } else if (*t == 'c') {
  577. break;
  578. }
  579. t += 2;
  580. }
  581. // set token kind
  582. lex->tok_kind = tok_enc_kind[tok_enc_index];
  583. // compute bracket level for implicit line joining
  584. 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) {
  585. lex->nested_bracket_level += 1;
  586. } 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) {
  587. lex->nested_bracket_level -= 1;
  588. }
  589. }
  590. }
  591. }
  592. mp_lexer_t *mp_lexer_new(qstr src_name, mp_reader_t reader) {
  593. mp_lexer_t *lex = m_new_obj(mp_lexer_t);
  594. lex->source_name = src_name;
  595. lex->reader = reader;
  596. lex->line = 1;
  597. lex->column = (size_t)-2; // account for 3 dummy bytes
  598. lex->emit_dent = 0;
  599. lex->nested_bracket_level = 0;
  600. lex->alloc_indent_level = MICROPY_ALLOC_LEXER_INDENT_INIT;
  601. lex->num_indent_level = 1;
  602. lex->indent_level = m_new(uint16_t, lex->alloc_indent_level);
  603. vstr_init(&lex->vstr, 32);
  604. // store sentinel for first indentation level
  605. lex->indent_level[0] = 0;
  606. // load lexer with start of file, advancing lex->column to 1
  607. // start with dummy bytes and use next_char() for proper EOL/EOF handling
  608. lex->chr0 = lex->chr1 = lex->chr2 = 0;
  609. next_char(lex);
  610. next_char(lex);
  611. next_char(lex);
  612. // preload first token
  613. mp_lexer_to_next(lex);
  614. // Check that the first token is in the first column. If it's not then we
  615. // convert the token kind to INDENT so that the parser gives a syntax error.
  616. if (lex->tok_column != 1) {
  617. lex->tok_kind = MP_TOKEN_INDENT;
  618. }
  619. return lex;
  620. }
  621. mp_lexer_t *mp_lexer_new_from_str_len(qstr src_name, const char *str, size_t len, size_t free_len) {
  622. mp_reader_t reader;
  623. mp_reader_new_mem(&reader, (const byte*)str, len, free_len);
  624. return mp_lexer_new(src_name, reader);
  625. }
  626. #if MICROPY_READER_POSIX || MICROPY_READER_VFS
  627. mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
  628. mp_reader_t reader;
  629. mp_reader_new_file(&reader, filename);
  630. return mp_lexer_new(qstr_from_str(filename), reader);
  631. }
  632. #if MICROPY_HELPER_LEXER_UNIX
  633. mp_lexer_t *mp_lexer_new_from_fd(qstr filename, int fd, bool close_fd) {
  634. mp_reader_t reader;
  635. mp_reader_new_file_from_fd(&reader, fd, close_fd);
  636. return mp_lexer_new(filename, reader);
  637. }
  638. #endif
  639. #endif
  640. void mp_lexer_free(mp_lexer_t *lex) {
  641. if (lex) {
  642. lex->reader.close(lex->reader.data);
  643. vstr_clear(&lex->vstr);
  644. m_del(uint16_t, lex->indent_level, lex->alloc_indent_level);
  645. m_del_obj(mp_lexer_t, lex);
  646. }
  647. }
  648. #if 0
  649. // This function is used to print the current token and should only be
  650. // needed to debug the lexer, so it's not available via a config option.
  651. void mp_lexer_show_token(const mp_lexer_t *lex) {
  652. 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);
  653. if (lex->vstr.len > 0) {
  654. const byte *i = (const byte *)lex->vstr.buf;
  655. const byte *j = (const byte *)i + lex->vstr.len;
  656. printf(" ");
  657. while (i < j) {
  658. unichar c = utf8_get_char(i);
  659. i = utf8_next_char(i);
  660. if (unichar_isprint(c)) {
  661. printf("%c", (int)c);
  662. } else {
  663. printf("?");
  664. }
  665. }
  666. }
  667. printf("\n");
  668. }
  669. #endif
  670. #endif // MICROPY_ENABLE_COMPILER