lexer.c 27 KB

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