lexer.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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. #if MICROPY_PY_FSTRINGS
  54. static bool is_char_or4(mp_lexer_t *lex, byte c1, byte c2, byte c3, byte c4) {
  55. return lex->chr0 == c1 || lex->chr0 == c2 || lex->chr0 == c3 || lex->chr0 == c4;
  56. }
  57. #endif
  58. static bool is_char_following(mp_lexer_t *lex, byte c) {
  59. return lex->chr1 == c;
  60. }
  61. static bool is_char_following_or(mp_lexer_t *lex, byte c1, byte c2) {
  62. return lex->chr1 == c1 || lex->chr1 == c2;
  63. }
  64. static bool is_char_following_following_or(mp_lexer_t *lex, byte c1, byte c2) {
  65. return lex->chr2 == c1 || lex->chr2 == c2;
  66. }
  67. static bool is_char_and(mp_lexer_t *lex, byte c1, byte c2) {
  68. return lex->chr0 == c1 && lex->chr1 == c2;
  69. }
  70. static bool is_whitespace(mp_lexer_t *lex) {
  71. return unichar_isspace(lex->chr0);
  72. }
  73. static bool is_letter(mp_lexer_t *lex) {
  74. return unichar_isalpha(lex->chr0);
  75. }
  76. static bool is_digit(mp_lexer_t *lex) {
  77. return unichar_isdigit(lex->chr0);
  78. }
  79. static bool is_following_digit(mp_lexer_t *lex) {
  80. return unichar_isdigit(lex->chr1);
  81. }
  82. static bool is_following_base_char(mp_lexer_t *lex) {
  83. const unichar chr1 = lex->chr1 | 0x20;
  84. return chr1 == 'b' || chr1 == 'o' || chr1 == 'x';
  85. }
  86. static bool is_following_odigit(mp_lexer_t *lex) {
  87. return lex->chr1 >= '0' && lex->chr1 <= '7';
  88. }
  89. static bool is_string_or_bytes(mp_lexer_t *lex) {
  90. return is_char_or(lex, '\'', '\"')
  91. #if MICROPY_PY_FSTRINGS
  92. || (is_char_or4(lex, 'r', 'u', 'b', 'f') && is_char_following_or(lex, '\'', '\"'))
  93. || (((is_char_and(lex, 'r', 'f') || is_char_and(lex, 'f', 'r'))
  94. && is_char_following_following_or(lex, '\'', '\"')))
  95. #else
  96. || (is_char_or3(lex, 'r', 'u', 'b') && is_char_following_or(lex, '\'', '\"'))
  97. #endif
  98. || ((is_char_and(lex, 'r', 'b') || is_char_and(lex, 'b', 'r'))
  99. && is_char_following_following_or(lex, '\'', '\"'));
  100. }
  101. // to easily parse utf-8 identifiers we allow any raw byte with high bit set
  102. static bool is_head_of_identifier(mp_lexer_t *lex) {
  103. return is_letter(lex) || lex->chr0 == '_' || lex->chr0 >= 0x80;
  104. }
  105. static bool is_tail_of_identifier(mp_lexer_t *lex) {
  106. return is_head_of_identifier(lex) || is_digit(lex);
  107. }
  108. static void next_char(mp_lexer_t *lex) {
  109. if (lex->chr0 == '\n') {
  110. // a new line
  111. ++lex->line;
  112. lex->column = 1;
  113. } else if (lex->chr0 == '\t') {
  114. // a tab
  115. lex->column = (((lex->column - 1 + TAB_SIZE) / TAB_SIZE) * TAB_SIZE) + 1;
  116. } else {
  117. // a character worth one column
  118. ++lex->column;
  119. }
  120. // shift the input queue forward
  121. lex->chr0 = lex->chr1;
  122. lex->chr1 = lex->chr2;
  123. // and add the next byte from either the fstring args or the reader
  124. #if MICROPY_PY_FSTRINGS
  125. if (lex->fstring_args_idx) {
  126. // if there are saved chars, then we're currently injecting fstring args
  127. if (lex->fstring_args_idx < lex->fstring_args.len) {
  128. lex->chr2 = lex->fstring_args.buf[lex->fstring_args_idx++];
  129. } else {
  130. // no more fstring arg bytes
  131. lex->chr2 = '\0';
  132. }
  133. if (lex->chr0 == '\0') {
  134. // consumed all fstring data, restore saved input queue
  135. lex->chr0 = lex->chr0_saved;
  136. lex->chr1 = lex->chr1_saved;
  137. lex->chr2 = lex->chr2_saved;
  138. // stop consuming fstring arg data
  139. vstr_reset(&lex->fstring_args);
  140. lex->fstring_args_idx = 0;
  141. }
  142. } else
  143. #endif
  144. {
  145. lex->chr2 = lex->reader.readbyte(lex->reader.data);
  146. }
  147. if (lex->chr1 == '\r') {
  148. // CR is a new line, converted to LF
  149. lex->chr1 = '\n';
  150. if (lex->chr2 == '\n') {
  151. // CR LF is a single new line, throw out the extra LF
  152. lex->chr2 = lex->reader.readbyte(lex->reader.data);
  153. }
  154. }
  155. // check if we need to insert a newline at end of file
  156. if (lex->chr2 == MP_LEXER_EOF && lex->chr1 != MP_LEXER_EOF && lex->chr1 != '\n') {
  157. lex->chr2 = '\n';
  158. }
  159. }
  160. static void indent_push(mp_lexer_t *lex, size_t indent) {
  161. if (lex->num_indent_level >= lex->alloc_indent_level) {
  162. lex->indent_level = m_renew(uint16_t, lex->indent_level, lex->alloc_indent_level, lex->alloc_indent_level + MICROPY_ALLOC_LEXEL_INDENT_INC);
  163. lex->alloc_indent_level += MICROPY_ALLOC_LEXEL_INDENT_INC;
  164. }
  165. lex->indent_level[lex->num_indent_level++] = indent;
  166. }
  167. static size_t indent_top(mp_lexer_t *lex) {
  168. return lex->indent_level[lex->num_indent_level - 1];
  169. }
  170. static void indent_pop(mp_lexer_t *lex) {
  171. lex->num_indent_level -= 1;
  172. }
  173. // some tricky operator encoding:
  174. // <op> = begin with <op>, if this opchar matches then begin here
  175. // e<op> = end with <op>, if this opchar matches then end
  176. // c<op> = continue with <op>, if this opchar matches then continue matching
  177. // this means if the start of two ops are the same then they are equal til the last char
  178. static const char *const tok_enc =
  179. "()[]{},;~" // singles
  180. ":e=" // : :=
  181. "<e=c<e=" // < <= << <<=
  182. ">e=c>e=" // > >= >> >>=
  183. "*e=c*e=" // * *= ** **=
  184. "+e=" // + +=
  185. "-e=e>" // - -= ->
  186. "&e=" // & &=
  187. "|e=" // | |=
  188. "/e=c/e=" // / /= // //=
  189. "%e=" // % %=
  190. "^e=" // ^ ^=
  191. "@e=" // @ @=
  192. "=e=" // = ==
  193. "!."; // start of special cases: != . ...
  194. // TODO static assert that number of tokens is less than 256 so we can safely make this table with byte sized entries
  195. static const uint8_t tok_enc_kind[] = {
  196. MP_TOKEN_DEL_PAREN_OPEN, MP_TOKEN_DEL_PAREN_CLOSE,
  197. MP_TOKEN_DEL_BRACKET_OPEN, MP_TOKEN_DEL_BRACKET_CLOSE,
  198. MP_TOKEN_DEL_BRACE_OPEN, MP_TOKEN_DEL_BRACE_CLOSE,
  199. MP_TOKEN_DEL_COMMA, MP_TOKEN_DEL_SEMICOLON, MP_TOKEN_OP_TILDE,
  200. MP_TOKEN_DEL_COLON, MP_TOKEN_OP_ASSIGN,
  201. MP_TOKEN_OP_LESS, MP_TOKEN_OP_LESS_EQUAL, MP_TOKEN_OP_DBL_LESS, MP_TOKEN_DEL_DBL_LESS_EQUAL,
  202. MP_TOKEN_OP_MORE, MP_TOKEN_OP_MORE_EQUAL, MP_TOKEN_OP_DBL_MORE, MP_TOKEN_DEL_DBL_MORE_EQUAL,
  203. MP_TOKEN_OP_STAR, MP_TOKEN_DEL_STAR_EQUAL, MP_TOKEN_OP_DBL_STAR, MP_TOKEN_DEL_DBL_STAR_EQUAL,
  204. MP_TOKEN_OP_PLUS, MP_TOKEN_DEL_PLUS_EQUAL,
  205. MP_TOKEN_OP_MINUS, MP_TOKEN_DEL_MINUS_EQUAL, MP_TOKEN_DEL_MINUS_MORE,
  206. MP_TOKEN_OP_AMPERSAND, MP_TOKEN_DEL_AMPERSAND_EQUAL,
  207. MP_TOKEN_OP_PIPE, MP_TOKEN_DEL_PIPE_EQUAL,
  208. MP_TOKEN_OP_SLASH, MP_TOKEN_DEL_SLASH_EQUAL, MP_TOKEN_OP_DBL_SLASH, MP_TOKEN_DEL_DBL_SLASH_EQUAL,
  209. MP_TOKEN_OP_PERCENT, MP_TOKEN_DEL_PERCENT_EQUAL,
  210. MP_TOKEN_OP_CARET, MP_TOKEN_DEL_CARET_EQUAL,
  211. MP_TOKEN_OP_AT, MP_TOKEN_DEL_AT_EQUAL,
  212. MP_TOKEN_DEL_EQUAL, MP_TOKEN_OP_DBL_EQUAL,
  213. };
  214. // must have the same order as enum in lexer.h
  215. // must be sorted according to strcmp
  216. static const char *const tok_kw[] = {
  217. "False",
  218. "None",
  219. "True",
  220. "__debug__",
  221. "and",
  222. "as",
  223. "assert",
  224. #if MICROPY_PY_ASYNC_AWAIT
  225. "async",
  226. "await",
  227. #endif
  228. "break",
  229. "class",
  230. "continue",
  231. "def",
  232. "del",
  233. "elif",
  234. "else",
  235. "except",
  236. "finally",
  237. "for",
  238. "from",
  239. "global",
  240. "if",
  241. "import",
  242. "in",
  243. "is",
  244. "lambda",
  245. "nonlocal",
  246. "not",
  247. "or",
  248. "pass",
  249. "raise",
  250. "return",
  251. "try",
  252. "while",
  253. "with",
  254. "yield",
  255. };
  256. // This is called with CUR_CHAR() before first hex digit, and should return with
  257. // it pointing to last hex digit
  258. // num_digits must be greater than zero
  259. static bool get_hex(mp_lexer_t *lex, size_t num_digits, mp_uint_t *result) {
  260. mp_uint_t num = 0;
  261. while (num_digits-- != 0) {
  262. next_char(lex);
  263. unichar c = CUR_CHAR(lex);
  264. if (!unichar_isxdigit(c)) {
  265. return false;
  266. }
  267. num = (num << 4) + unichar_xdigit_value(c);
  268. }
  269. *result = num;
  270. return true;
  271. }
  272. static void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) {
  273. // get first quoting character
  274. char quote_char = '\'';
  275. if (is_char(lex, '\"')) {
  276. quote_char = '\"';
  277. }
  278. next_char(lex);
  279. // work out if it's a single or triple quoted literal
  280. size_t num_quotes;
  281. if (is_char_and(lex, quote_char, quote_char)) {
  282. // triple quotes
  283. next_char(lex);
  284. next_char(lex);
  285. num_quotes = 3;
  286. } else {
  287. // single quotes
  288. num_quotes = 1;
  289. }
  290. size_t n_closing = 0;
  291. #if MICROPY_PY_FSTRINGS
  292. if (is_fstring) {
  293. // assume there's going to be interpolation, so prep the injection data
  294. // fstring_args_idx==0 && len(fstring_args)>0 means we're extracting the args.
  295. // only when fstring_args_idx>0 will we consume the arg data
  296. // note: lex->fstring_args will be empty already (it's reset when finished)
  297. vstr_add_str(&lex->fstring_args, ".format(");
  298. }
  299. #endif
  300. while (!is_end(lex) && (num_quotes > 1 || !is_char(lex, '\n')) && n_closing < num_quotes) {
  301. if (is_char(lex, quote_char)) {
  302. n_closing += 1;
  303. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  304. } else {
  305. n_closing = 0;
  306. #if MICROPY_PY_FSTRINGS
  307. while (is_fstring && is_char(lex, '{')) {
  308. next_char(lex);
  309. if (is_char(lex, '{')) {
  310. // "{{" is passed through unchanged to be handled by str.format
  311. vstr_add_byte(&lex->vstr, '{');
  312. next_char(lex);
  313. } else {
  314. // wrap each argument in (), e.g.
  315. // f"{a,b,}, {c}" --> "{}".format((a,b), (c),)
  316. vstr_add_byte(&lex->fstring_args, '(');
  317. // remember the start of this argument (if we need it for f'{a=}').
  318. size_t i = lex->fstring_args.len;
  319. // Extract characters inside the { until the bracket level
  320. // is zero and we reach the conversion specifier '!',
  321. // format specifier ':', or closing '}'. The conversion
  322. // and format specifiers are left unchanged in the format
  323. // string to be handled by str.format.
  324. // (MicroPython limitation) note: this is completely
  325. // unaware of Python syntax and will not handle any
  326. // expression containing '}' or ':'. e.g. f'{"}"}' or f'
  327. // {foo({})}'. However, detection of the '!' will
  328. // specifically ensure that it's followed by [rs] and
  329. // then either the format specifier or the closing
  330. // brace. This allows the use of e.g. != in expressions.
  331. unsigned int nested_bracket_level = 0;
  332. while (!is_end(lex) && (nested_bracket_level != 0
  333. || !(is_char_or(lex, ':', '}')
  334. || (is_char(lex, '!')
  335. && is_char_following_or(lex, 'r', 's')
  336. && is_char_following_following_or(lex, ':', '}'))))
  337. ) {
  338. unichar c = CUR_CHAR(lex);
  339. if (c == '[' || c == '{') {
  340. nested_bracket_level += 1;
  341. } else if (c == ']' || c == '}') {
  342. nested_bracket_level -= 1;
  343. }
  344. // like the default case at the end of this function, stay 8-bit clean
  345. vstr_add_byte(&lex->fstring_args, c);
  346. next_char(lex);
  347. }
  348. if (lex->fstring_args.buf[lex->fstring_args.len - 1] == '=') {
  349. // if the last character of the arg was '=', then inject "arg=" before the '{'.
  350. // f'{a=}' --> 'a={}'.format(a)
  351. vstr_add_strn(&lex->vstr, lex->fstring_args.buf + i, lex->fstring_args.len - i);
  352. // remove the trailing '='
  353. lex->fstring_args.len--;
  354. }
  355. // close the paren-wrapped arg to .format().
  356. vstr_add_byte(&lex->fstring_args, ')');
  357. // comma-separate args to .format().
  358. vstr_add_byte(&lex->fstring_args, ',');
  359. }
  360. vstr_add_byte(&lex->vstr, '{');
  361. }
  362. #endif
  363. if (is_char(lex, '\\')) {
  364. next_char(lex);
  365. unichar c = CUR_CHAR(lex);
  366. if (is_raw) {
  367. // raw strings allow escaping of quotes, but the backslash is also emitted
  368. vstr_add_char(&lex->vstr, '\\');
  369. } else {
  370. switch (c) {
  371. // note: "c" can never be MP_LEXER_EOF because next_char
  372. // always inserts a newline at the end of the input stream
  373. case '\n':
  374. c = MP_LEXER_EOF;
  375. break; // backslash escape the newline, just ignore it
  376. case '\\':
  377. break;
  378. case '\'':
  379. break;
  380. case '"':
  381. break;
  382. case 'a':
  383. c = 0x07;
  384. break;
  385. case 'b':
  386. c = 0x08;
  387. break;
  388. case 't':
  389. c = 0x09;
  390. break;
  391. case 'n':
  392. c = 0x0a;
  393. break;
  394. case 'v':
  395. c = 0x0b;
  396. break;
  397. case 'f':
  398. c = 0x0c;
  399. break;
  400. case 'r':
  401. c = 0x0d;
  402. break;
  403. case 'u':
  404. case 'U':
  405. if (lex->tok_kind == MP_TOKEN_BYTES) {
  406. // b'\u1234' == b'\\u1234'
  407. vstr_add_char(&lex->vstr, '\\');
  408. break;
  409. }
  410. // Otherwise fall through.
  411. MP_FALLTHROUGH
  412. case 'x': {
  413. mp_uint_t num = 0;
  414. if (!get_hex(lex, (c == 'x' ? 2 : c == 'u' ? 4 : 8), &num)) {
  415. // not enough hex chars for escape sequence
  416. lex->tok_kind = MP_TOKEN_INVALID;
  417. }
  418. c = num;
  419. break;
  420. }
  421. case 'N':
  422. // Supporting '\N{LATIN SMALL LETTER A}' == 'a' would require keeping the
  423. // entire Unicode name table in the core. As of Unicode 6.3.0, that's nearly
  424. // 3MB of text; even gzip-compressed and with minimal structure, it'll take
  425. // roughly half a meg of storage. This form of Unicode escape may be added
  426. // later on, but it's definitely not a priority right now. -- CJA 20140607
  427. mp_raise_NotImplementedError(MP_ERROR_TEXT("unicode name escapes"));
  428. break;
  429. default:
  430. if (c >= '0' && c <= '7') {
  431. // Octal sequence, 1-3 chars
  432. size_t digits = 3;
  433. mp_uint_t num = c - '0';
  434. while (is_following_odigit(lex) && --digits != 0) {
  435. next_char(lex);
  436. num = num * 8 + (CUR_CHAR(lex) - '0');
  437. }
  438. c = num;
  439. } else {
  440. // unrecognised escape character; CPython lets this through verbatim as '\' and then the character
  441. vstr_add_char(&lex->vstr, '\\');
  442. }
  443. break;
  444. }
  445. }
  446. if (c != MP_LEXER_EOF) {
  447. #if MICROPY_PY_BUILTINS_STR_UNICODE
  448. if (c < 0x110000 && lex->tok_kind == MP_TOKEN_STRING) {
  449. // Valid unicode character in a str object.
  450. vstr_add_char(&lex->vstr, c);
  451. } else if (c < 0x100 && lex->tok_kind == MP_TOKEN_BYTES) {
  452. // Valid byte in a bytes object.
  453. vstr_add_byte(&lex->vstr, c);
  454. }
  455. #else
  456. if (c < 0x100) {
  457. // Without unicode everything is just added as an 8-bit byte.
  458. vstr_add_byte(&lex->vstr, c);
  459. }
  460. #endif
  461. else {
  462. // Character out of range; this raises a generic SyntaxError.
  463. lex->tok_kind = MP_TOKEN_INVALID;
  464. }
  465. }
  466. } else {
  467. // Add the "character" as a byte so that we remain 8-bit clean.
  468. // This way, strings are parsed correctly whether or not they contain utf-8 chars.
  469. vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
  470. }
  471. }
  472. next_char(lex);
  473. }
  474. // check we got the required end quotes
  475. if (n_closing < num_quotes) {
  476. lex->tok_kind = MP_TOKEN_LONELY_STRING_OPEN;
  477. }
  478. // cut off the end quotes from the token text
  479. vstr_cut_tail_bytes(&lex->vstr, n_closing);
  480. }
  481. // This function returns whether it has crossed a newline or not.
  482. // It therefore always return true if stop_at_newline is true
  483. static bool skip_whitespace(mp_lexer_t *lex, bool stop_at_newline) {
  484. while (!is_end(lex)) {
  485. if (is_physical_newline(lex)) {
  486. if (stop_at_newline && lex->nested_bracket_level == 0) {
  487. return true;
  488. }
  489. next_char(lex);
  490. } else if (is_whitespace(lex)) {
  491. next_char(lex);
  492. } else if (is_char(lex, '#')) {
  493. next_char(lex);
  494. while (!is_end(lex) && !is_physical_newline(lex)) {
  495. next_char(lex);
  496. }
  497. // will return true on next loop
  498. } else if (is_char_and(lex, '\\', '\n')) {
  499. // line-continuation, so don't return true
  500. next_char(lex);
  501. next_char(lex);
  502. } else {
  503. break;
  504. }
  505. }
  506. return false;
  507. }
  508. void mp_lexer_to_next(mp_lexer_t *lex) {
  509. #if MICROPY_PY_FSTRINGS
  510. if (lex->fstring_args.len && lex->fstring_args_idx == 0) {
  511. // moving onto the next token means the literal string is complete.
  512. // switch into injecting the format args.
  513. vstr_add_byte(&lex->fstring_args, ')');
  514. lex->chr0_saved = lex->chr0;
  515. lex->chr1_saved = lex->chr1;
  516. lex->chr2_saved = lex->chr2;
  517. lex->chr0 = lex->fstring_args.buf[0];
  518. lex->chr1 = lex->fstring_args.buf[1];
  519. lex->chr2 = lex->fstring_args.buf[2];
  520. // we've already extracted 3 chars, but setting this non-zero also
  521. // means we'll start consuming the fstring data
  522. lex->fstring_args_idx = 3;
  523. }
  524. #endif
  525. // start new token text
  526. vstr_reset(&lex->vstr);
  527. // skip white space and comments
  528. // set the newline tokens at the line and column of the preceding line:
  529. // only advance on the pointer until a new line is crossed, save the
  530. // line and column, and then readvance it
  531. bool had_physical_newline = skip_whitespace(lex, true);
  532. // set token source information
  533. lex->tok_line = lex->line;
  534. lex->tok_column = lex->column;
  535. if (lex->emit_dent < 0) {
  536. lex->tok_kind = MP_TOKEN_DEDENT;
  537. lex->emit_dent += 1;
  538. } else if (lex->emit_dent > 0) {
  539. lex->tok_kind = MP_TOKEN_INDENT;
  540. lex->emit_dent -= 1;
  541. } else if (had_physical_newline) {
  542. // The cursor is at the end of the previous line, pointing to a
  543. // physical newline. Skip any remaining whitespace, comments, and
  544. // newlines.
  545. skip_whitespace(lex, false);
  546. lex->tok_kind = MP_TOKEN_NEWLINE;
  547. size_t num_spaces = lex->column - 1;
  548. if (num_spaces == indent_top(lex)) {
  549. } else if (num_spaces > indent_top(lex)) {
  550. indent_push(lex, num_spaces);
  551. lex->emit_dent += 1;
  552. } else {
  553. while (num_spaces < indent_top(lex)) {
  554. indent_pop(lex);
  555. lex->emit_dent -= 1;
  556. }
  557. if (num_spaces != indent_top(lex)) {
  558. lex->tok_kind = MP_TOKEN_DEDENT_MISMATCH;
  559. }
  560. }
  561. } else if (is_end(lex)) {
  562. lex->tok_kind = MP_TOKEN_END;
  563. } else if (is_string_or_bytes(lex)) {
  564. // a string or bytes literal
  565. // Python requires adjacent string/bytes literals to be automatically
  566. // concatenated. We do it here in the tokeniser to make efficient use of RAM,
  567. // because then the lexer's vstr can be used to accumulate the string literal,
  568. // in contrast to creating a parse tree of strings and then joining them later
  569. // in the compiler. It's also more compact in code size to do it here.
  570. // MP_TOKEN_END is used to indicate that this is the first string token
  571. lex->tok_kind = MP_TOKEN_END;
  572. // Loop to accumulate string/bytes literals
  573. do {
  574. // parse type codes
  575. bool is_raw = false;
  576. bool is_fstring = false;
  577. mp_token_kind_t kind = MP_TOKEN_STRING;
  578. int n_char = 0;
  579. if (is_char(lex, 'u')) {
  580. n_char = 1;
  581. } else if (is_char(lex, 'b')) {
  582. kind = MP_TOKEN_BYTES;
  583. n_char = 1;
  584. if (is_char_following(lex, 'r')) {
  585. is_raw = true;
  586. n_char = 2;
  587. }
  588. } else if (is_char(lex, 'r')) {
  589. is_raw = true;
  590. n_char = 1;
  591. if (is_char_following(lex, 'b')) {
  592. kind = MP_TOKEN_BYTES;
  593. n_char = 2;
  594. }
  595. #if MICROPY_PY_FSTRINGS
  596. if (is_char_following(lex, 'f')) {
  597. // raw-f-strings unsupported, immediately return (invalid) token.
  598. lex->tok_kind = MP_TOKEN_FSTRING_RAW;
  599. break;
  600. }
  601. #endif
  602. }
  603. #if MICROPY_PY_FSTRINGS
  604. else if (is_char(lex, 'f')) {
  605. if (is_char_following(lex, 'r')) {
  606. // raw-f-strings unsupported, immediately return (invalid) token.
  607. lex->tok_kind = MP_TOKEN_FSTRING_RAW;
  608. break;
  609. }
  610. n_char = 1;
  611. is_fstring = true;
  612. }
  613. #endif
  614. // Set or check token kind
  615. if (lex->tok_kind == MP_TOKEN_END) {
  616. lex->tok_kind = kind;
  617. } else if (lex->tok_kind != kind) {
  618. // Can't concatenate string with bytes
  619. break;
  620. }
  621. // Skip any type code characters
  622. if (n_char != 0) {
  623. next_char(lex);
  624. if (n_char == 2) {
  625. next_char(lex);
  626. }
  627. }
  628. // Parse the literal
  629. parse_string_literal(lex, is_raw, is_fstring);
  630. // Skip whitespace so we can check if there's another string following
  631. skip_whitespace(lex, true);
  632. } while (is_string_or_bytes(lex));
  633. } else if (is_head_of_identifier(lex)) {
  634. lex->tok_kind = MP_TOKEN_NAME;
  635. // get first char (add as byte to remain 8-bit clean and support utf-8)
  636. vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
  637. next_char(lex);
  638. // get tail chars
  639. while (!is_end(lex) && is_tail_of_identifier(lex)) {
  640. vstr_add_byte(&lex->vstr, CUR_CHAR(lex));
  641. next_char(lex);
  642. }
  643. // Check if the name is a keyword.
  644. // We also check for __debug__ here and convert it to its value. This is
  645. // so the parser gives a syntax error on, eg, x.__debug__. Otherwise, we
  646. // need to check for this special token in many places in the compiler.
  647. const char *s = vstr_null_terminated_str(&lex->vstr);
  648. for (size_t i = 0; i < MP_ARRAY_SIZE(tok_kw); i++) {
  649. int cmp = strcmp(s, tok_kw[i]);
  650. if (cmp == 0) {
  651. lex->tok_kind = MP_TOKEN_KW_FALSE + i;
  652. if (lex->tok_kind == MP_TOKEN_KW___DEBUG__) {
  653. lex->tok_kind = (MP_STATE_VM(mp_optimise_value) == 0 ? MP_TOKEN_KW_TRUE : MP_TOKEN_KW_FALSE);
  654. }
  655. break;
  656. } else if (cmp < 0) {
  657. // Table is sorted and comparison was less-than, so stop searching
  658. break;
  659. }
  660. }
  661. } else if (is_digit(lex) || (is_char(lex, '.') && is_following_digit(lex))) {
  662. bool forced_integer = false;
  663. if (is_char(lex, '.')) {
  664. lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
  665. } else {
  666. lex->tok_kind = MP_TOKEN_INTEGER;
  667. if (is_char(lex, '0') && is_following_base_char(lex)) {
  668. forced_integer = true;
  669. }
  670. }
  671. // get first char
  672. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  673. next_char(lex);
  674. // get tail chars
  675. while (!is_end(lex)) {
  676. if (!forced_integer && is_char_or(lex, 'e', 'E')) {
  677. lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
  678. vstr_add_char(&lex->vstr, 'e');
  679. next_char(lex);
  680. if (is_char(lex, '+') || is_char(lex, '-')) {
  681. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  682. next_char(lex);
  683. }
  684. } else if (is_letter(lex) || is_digit(lex) || is_char(lex, '.')) {
  685. if (is_char_or3(lex, '.', 'j', 'J')) {
  686. lex->tok_kind = MP_TOKEN_FLOAT_OR_IMAG;
  687. }
  688. vstr_add_char(&lex->vstr, CUR_CHAR(lex));
  689. next_char(lex);
  690. } else if (is_char(lex, '_')) {
  691. next_char(lex);
  692. } else {
  693. break;
  694. }
  695. }
  696. } else {
  697. // search for encoded delimiter or operator
  698. const char *t = tok_enc;
  699. size_t tok_enc_index = 0;
  700. for (; *t != 0 && !is_char(lex, *t); t += 1) {
  701. if (*t == 'e' || *t == 'c') {
  702. t += 1;
  703. }
  704. tok_enc_index += 1;
  705. }
  706. next_char(lex);
  707. if (*t == 0) {
  708. // didn't match any delimiter or operator characters
  709. lex->tok_kind = MP_TOKEN_INVALID;
  710. } else if (*t == '!') {
  711. // "!=" is a special case because "!" is not a valid operator
  712. if (is_char(lex, '=')) {
  713. next_char(lex);
  714. lex->tok_kind = MP_TOKEN_OP_NOT_EQUAL;
  715. } else {
  716. lex->tok_kind = MP_TOKEN_INVALID;
  717. }
  718. } else if (*t == '.') {
  719. // "." and "..." are special cases because ".." is not a valid operator
  720. if (is_char_and(lex, '.', '.')) {
  721. next_char(lex);
  722. next_char(lex);
  723. lex->tok_kind = MP_TOKEN_ELLIPSIS;
  724. } else {
  725. lex->tok_kind = MP_TOKEN_DEL_PERIOD;
  726. }
  727. } else {
  728. // matched a delimiter or operator character
  729. // get the maximum characters for a valid token
  730. t += 1;
  731. size_t t_index = tok_enc_index;
  732. while (*t == 'c' || *t == 'e') {
  733. t_index += 1;
  734. if (is_char(lex, t[1])) {
  735. next_char(lex);
  736. tok_enc_index = t_index;
  737. if (*t == 'e') {
  738. break;
  739. }
  740. } else if (*t == 'c') {
  741. break;
  742. }
  743. t += 2;
  744. }
  745. // set token kind
  746. lex->tok_kind = tok_enc_kind[tok_enc_index];
  747. // compute bracket level for implicit line joining
  748. 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) {
  749. lex->nested_bracket_level += 1;
  750. } 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) {
  751. lex->nested_bracket_level -= 1;
  752. }
  753. }
  754. }
  755. }
  756. mp_lexer_t *mp_lexer_new(qstr src_name, mp_reader_t reader) {
  757. mp_lexer_t *lex = m_new_obj(mp_lexer_t);
  758. lex->source_name = src_name;
  759. lex->reader = reader;
  760. lex->line = 1;
  761. lex->column = (size_t)-2; // account for 3 dummy bytes
  762. lex->emit_dent = 0;
  763. lex->nested_bracket_level = 0;
  764. lex->alloc_indent_level = MICROPY_ALLOC_LEXER_INDENT_INIT;
  765. lex->num_indent_level = 1;
  766. lex->indent_level = m_new(uint16_t, lex->alloc_indent_level);
  767. vstr_init(&lex->vstr, 32);
  768. #if MICROPY_PY_FSTRINGS
  769. vstr_init(&lex->fstring_args, 0);
  770. lex->fstring_args_idx = 0;
  771. #endif
  772. // store sentinel for first indentation level
  773. lex->indent_level[0] = 0;
  774. // load lexer with start of file, advancing lex->column to 1
  775. // start with dummy bytes and use next_char() for proper EOL/EOF handling
  776. lex->chr0 = lex->chr1 = lex->chr2 = 0;
  777. next_char(lex);
  778. next_char(lex);
  779. next_char(lex);
  780. // preload first token
  781. mp_lexer_to_next(lex);
  782. // Check that the first token is in the first column unless it is a
  783. // newline. Otherwise we convert the token kind to INDENT so that
  784. // the parser gives a syntax error.
  785. if (lex->tok_column != 1 && lex->tok_kind != MP_TOKEN_NEWLINE) {
  786. lex->tok_kind = MP_TOKEN_INDENT;
  787. }
  788. return lex;
  789. }
  790. mp_lexer_t *mp_lexer_new_from_str_len(qstr src_name, const char *str, size_t len, size_t free_len) {
  791. mp_reader_t reader;
  792. mp_reader_new_mem(&reader, (const byte *)str, len, free_len);
  793. return mp_lexer_new(src_name, reader);
  794. }
  795. #if MICROPY_READER_POSIX || MICROPY_READER_VFS
  796. mp_lexer_t *mp_lexer_new_from_file(qstr filename) {
  797. mp_reader_t reader;
  798. mp_reader_new_file(&reader, filename);
  799. return mp_lexer_new(filename, reader);
  800. }
  801. #if MICROPY_HELPER_LEXER_UNIX
  802. mp_lexer_t *mp_lexer_new_from_fd(qstr filename, int fd, bool close_fd) {
  803. mp_reader_t reader;
  804. mp_reader_new_file_from_fd(&reader, fd, close_fd);
  805. return mp_lexer_new(filename, reader);
  806. }
  807. #endif
  808. #endif
  809. void mp_lexer_free(mp_lexer_t *lex) {
  810. if (lex) {
  811. lex->reader.close(lex->reader.data);
  812. vstr_clear(&lex->vstr);
  813. #if MICROPY_PY_FSTRINGS
  814. vstr_clear(&lex->fstring_args);
  815. #endif
  816. m_del(uint16_t, lex->indent_level, lex->alloc_indent_level);
  817. m_del_obj(mp_lexer_t, lex);
  818. }
  819. }
  820. #if 0
  821. // This function is used to print the current token and should only be
  822. // needed to debug the lexer, so it's not available via a config option.
  823. void mp_lexer_show_token(const mp_lexer_t *lex) {
  824. 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);
  825. if (lex->vstr.len > 0) {
  826. const byte *i = (const byte *)lex->vstr.buf;
  827. const byte *j = (const byte *)i + lex->vstr.len;
  828. printf(" ");
  829. while (i < j) {
  830. unichar c = utf8_get_char(i);
  831. i = utf8_next_char(i);
  832. if (unichar_isprint(c)) {
  833. printf("%c", (int)c);
  834. } else {
  835. printf("?");
  836. }
  837. }
  838. }
  839. printf("\n");
  840. }
  841. #endif
  842. #endif // MICROPY_ENABLE_COMPILER