lexer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. #include "pocketpy/compiler/lexer.hpp"
  2. namespace pkpy {
  3. // clang-format off
  4. static const uint32_t kLoRangeA[] = {170,186,443,448,660,1488,1519,1568,1601,1646,1649,1749,1774,1786,1791,1808,1810,1869,1969,1994,2048,2112,2144,2208,2230,2308,2365,2384,2392,2418,2437,2447,2451,2474,2482,2486,2493,2510,2524,2527,2544,2556,2565,2575,2579,2602,2610,2613,2616,2649,2654,2674,2693,2703,2707,2730,2738,2741,2749,2768,2784,2809,2821,2831,2835,2858,2866,2869,2877,2908,2911,2929,2947,2949,2958,2962,2969,2972,2974,2979,2984,2990,3024,3077,3086,3090,3114,3133,3160,3168,3200,3205,3214,3218,3242,3253,3261,3294,3296,3313,3333,3342,3346,3389,3406,3412,3423,3450,3461,3482,3507,3517,3520,3585,3634,3648,3713,3716,3718,3724,3749,3751,3762,3773,3776,3804,3840,3904,3913,3976,4096,4159,4176,4186,4193,4197,4206,4213,4238,4352,4682,4688,4696,4698,4704,4746,4752,4786,4792,4800,4802,4808,4824,4882,4888,4992,5121,5743,5761,5792,5873,5888,5902,5920,5952,5984,5998,6016,6108,6176,6212,6272,6279,6314,6320,6400,6480,6512,6528,6576,6656,6688,6917,6981,7043,7086,7098,7168,7245,7258,7401,7406,7413,7418,8501,11568,11648,11680,11688,11696,11704,11712,11720,11728,11736,12294,12348,12353,12447,12449,12543,12549,12593,12704,12784,13312,19968,40960,40982,42192,42240,42512,42538,42606,42656,42895,42999,43003,43011,43015,43020,43072,43138,43250,43259,43261,43274,43312,43360,43396,43488,43495,43514,43520,43584,43588,43616,43633,43642,43646,43697,43701,43705,43712,43714,43739,43744,43762,43777,43785,43793,43808,43816,43968,44032,55216,55243,63744,64112,64285,64287,64298,64312,64318,64320,64323,64326,64467,64848,64914,65008,65136,65142,65382,65393,65440,65474,65482,65490,65498,65536,65549,65576,65596,65599,65616,65664,66176,66208,66304,66349,66370,66384,66432,66464,66504,66640,66816,66864,67072,67392,67424,67584,67592,67594,67639,67644,67647,67680,67712,67808,67828,67840,67872,67968,68030,68096,68112,68117,68121,68192,68224,68288,68297,68352,68416,68448,68480,68608,68864,69376,69415,69424,69600,69635,69763,69840,69891,69956,69968,70006,70019,70081,70106,70108,70144,70163,70272,70280,70282,70287,70303,70320,70405,70415,70419,70442,70450,70453,70461,70480,70493,70656,70727,70751,70784,70852,70855,71040,71128,71168,71236,71296,71352,71424,71680,71935,72096,72106,72161,72163,72192,72203,72250,72272,72284,72349,72384,72704,72714,72768,72818,72960,72968,72971,73030,73056,73063,73066,73112,73440,73728,74880,77824,82944,92160,92736,92880,92928,93027,93053,93952,94032,94208,100352,110592,110928,110948,110960,113664,113776,113792,113808,123136,123214,123584,124928,126464,126469,126497,126500,126503,126505,126516,126521,126523,126530,126535,126537,126539,126541,126545,126548,126551,126553,126555,126557,126559,126561,126564,126567,126572,126580,126585,126590,126592,126603,126625,126629,126635,131072,173824,177984,178208,183984,194560};
  5. static const uint32_t kLoRangeB[] = {170,186,443,451,660,1514,1522,1599,1610,1647,1747,1749,1775,1788,1791,1808,1839,1957,1969,2026,2069,2136,2154,2228,2237,2361,2365,2384,2401,2432,2444,2448,2472,2480,2482,2489,2493,2510,2525,2529,2545,2556,2570,2576,2600,2608,2611,2614,2617,2652,2654,2676,2701,2705,2728,2736,2739,2745,2749,2768,2785,2809,2828,2832,2856,2864,2867,2873,2877,2909,2913,2929,2947,2954,2960,2965,2970,2972,2975,2980,2986,3001,3024,3084,3088,3112,3129,3133,3162,3169,3200,3212,3216,3240,3251,3257,3261,3294,3297,3314,3340,3344,3386,3389,3406,3414,3425,3455,3478,3505,3515,3517,3526,3632,3635,3653,3714,3716,3722,3747,3749,3760,3763,3773,3780,3807,3840,3911,3948,3980,4138,4159,4181,4189,4193,4198,4208,4225,4238,4680,4685,4694,4696,4701,4744,4749,4784,4789,4798,4800,4805,4822,4880,4885,4954,5007,5740,5759,5786,5866,5880,5900,5905,5937,5969,5996,6000,6067,6108,6210,6264,6276,6312,6314,6389,6430,6509,6516,6571,6601,6678,6740,6963,6987,7072,7087,7141,7203,7247,7287,7404,7411,7414,7418,8504,11623,11670,11686,11694,11702,11710,11718,11726,11734,11742,12294,12348,12438,12447,12538,12543,12591,12686,12730,12799,19893,40943,40980,42124,42231,42507,42527,42539,42606,42725,42895,42999,43009,43013,43018,43042,43123,43187,43255,43259,43262,43301,43334,43388,43442,43492,43503,43518,43560,43586,43595,43631,43638,43642,43695,43697,43702,43709,43712,43714,43740,43754,43762,43782,43790,43798,43814,43822,44002,55203,55238,55291,64109,64217,64285,64296,64310,64316,64318,64321,64324,64433,64829,64911,64967,65019,65140,65276,65391,65437,65470,65479,65487,65495,65500,65547,65574,65594,65597,65613,65629,65786,66204,66256,66335,66368,66377,66421,66461,66499,66511,66717,66855,66915,67382,67413,67431,67589,67592,67637,67640,67644,67669,67702,67742,67826,67829,67861,67897,68023,68031,68096,68115,68119,68149,68220,68252,68295,68324,68405,68437,68466,68497,68680,68899,69404,69415,69445,69622,69687,69807,69864,69926,69956,70002,70006,70066,70084,70106,70108,70161,70187,70278,70280,70285,70301,70312,70366,70412,70416,70440,70448,70451,70457,70461,70480,70497,70708,70730,70751,70831,70853,70855,71086,71131,71215,71236,71338,71352,71450,71723,71935,72103,72144,72161,72163,72192,72242,72250,72272,72329,72349,72440,72712,72750,72768,72847,72966,72969,73008,73030,73061,73064,73097,73112,73458,74649,75075,78894,83526,92728,92766,92909,92975,93047,93071,94026,94032,100343,101106,110878,110930,110951,111355,113770,113788,113800,113817,123180,123214,123627,125124,126467,126495,126498,126500,126503,126514,126519,126521,126523,126530,126535,126537,126539,126543,126546,126548,126551,126553,126555,126557,126559,126562,126564,126570,126578,126583,126588,126590,126601,126619,126627,126633,126651,173782,177972,178205,183969,191456,195101};
  6. // clang-format on
  7. static bool is_possible_number_char(char c) {
  8. switch(c) {
  9. // clang-format off
  10. case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  11. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
  12. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
  13. case '.': case 'L': case 'x': case 'o': case 'j':
  14. return true;
  15. default: return false;
  16. // clang-format on
  17. }
  18. }
  19. static bool is_unicode_Lo_char(uint32_t c) {
  20. // open a hole for carrot
  21. if(c == U'🥕') return true;
  22. auto index = std::lower_bound(kLoRangeA, kLoRangeA + 476, c) - kLoRangeA;
  23. if(c == kLoRangeA[index]) return true;
  24. index -= 1;
  25. if(index < 0) return false;
  26. return c >= kLoRangeA[index] && c <= kLoRangeB[index];
  27. }
  28. bool Lexer::match_n_chars(int n, char c0) {
  29. const char* c = curr_char;
  30. for(int i = 0; i < n; i++) {
  31. if(*c == '\0') return false;
  32. if(*c != c0) return false;
  33. c++;
  34. }
  35. for(int i = 0; i < n; i++)
  36. eatchar_include_newline();
  37. return true;
  38. }
  39. bool Lexer::match_string(const char* s) {
  40. int s_len = strlen(s);
  41. bool ok = strncmp(curr_char, s, s_len) == 0;
  42. if(ok)
  43. for(int i = 0; i < s_len; i++)
  44. eatchar_include_newline();
  45. return ok;
  46. }
  47. int Lexer::eat_spaces() {
  48. int count = 0;
  49. while(true) {
  50. switch(peekchar()) {
  51. case ' ': count += 1; break;
  52. case '\t': count += 4; break;
  53. default: return count;
  54. }
  55. eatchar();
  56. }
  57. }
  58. bool Lexer::eat_indentation() {
  59. if(brackets_level > 0) return true;
  60. int spaces = eat_spaces();
  61. if(peekchar() == '#') skip_line_comment();
  62. if(peekchar() == '\0' || peekchar() == '\n') return true;
  63. // https://docs.python.org/3/reference/lexical_analysis.html#indentation
  64. if(spaces > indents.back()) {
  65. indents.push_back(spaces);
  66. nexts.push_back(Token{TK("@indent"), token_start, 0, current_line, brackets_level, {}});
  67. } else if(spaces < indents.back()) {
  68. while(spaces < indents.back()) {
  69. indents.pop_back();
  70. nexts.push_back(Token{TK("@dedent"), token_start, 0, current_line, brackets_level, {}});
  71. }
  72. if(spaces != indents.back()) { return false; }
  73. }
  74. return true;
  75. }
  76. char Lexer::eatchar() {
  77. char c = peekchar();
  78. assert(c != '\n'); // eatchar() cannot consume a newline
  79. curr_char++;
  80. return c;
  81. }
  82. char Lexer::eatchar_include_newline() {
  83. char c = peekchar();
  84. curr_char++;
  85. if(c == '\n') {
  86. current_line++;
  87. src->line_starts.push_back(curr_char);
  88. }
  89. return c;
  90. }
  91. int Lexer::eat_name() {
  92. curr_char--;
  93. while(true) {
  94. unsigned char c = peekchar();
  95. int u8bytes = utf8len(c, true);
  96. if(u8bytes == 0) return 1;
  97. if(u8bytes == 1) {
  98. if(isalpha(c) || c == '_' || isdigit(c)) {
  99. curr_char++;
  100. continue;
  101. } else {
  102. break;
  103. }
  104. }
  105. // handle multibyte char
  106. Str u8str(curr_char, u8bytes);
  107. if(u8str.size != u8bytes) return 2;
  108. uint32_t value = 0;
  109. for(int k = 0; k < u8bytes; k++) {
  110. uint8_t b = u8str[k];
  111. if(k == 0) {
  112. if(u8bytes == 2)
  113. value = (b & 0b00011111) << 6;
  114. else if(u8bytes == 3)
  115. value = (b & 0b00001111) << 12;
  116. else if(u8bytes == 4)
  117. value = (b & 0b00000111) << 18;
  118. } else {
  119. value |= (b & 0b00111111) << (6 * (u8bytes - k - 1));
  120. }
  121. }
  122. if(is_unicode_Lo_char(value))
  123. curr_char += u8bytes;
  124. else
  125. break;
  126. }
  127. int length = (int)(curr_char - token_start);
  128. if(length == 0) return 3;
  129. std::string_view name(token_start, length);
  130. if(src->mode == JSON_MODE) {
  131. if(name == "true") {
  132. add_token(TK("True"));
  133. } else if(name == "false") {
  134. add_token(TK("False"));
  135. } else if(name == "null") {
  136. add_token(TK("None"));
  137. } else {
  138. return 4;
  139. }
  140. return 0;
  141. }
  142. const auto KW_BEGIN = kTokens + TK("False");
  143. const auto KW_END = kTokens + kTokenCount;
  144. auto it = std::lower_bound(KW_BEGIN, KW_END, name);
  145. if(it != KW_END) {
  146. assert(*it == name);
  147. add_token(it - kTokens);
  148. } else {
  149. add_token(TK("@id"));
  150. }
  151. return 0;
  152. }
  153. void Lexer::skip_line_comment() {
  154. char c;
  155. while((c = peekchar()) != '\0') {
  156. if(c == '\n') return;
  157. eatchar();
  158. }
  159. }
  160. bool Lexer::matchchar(char c) {
  161. if(peekchar() != c) return false;
  162. eatchar_include_newline();
  163. return true;
  164. }
  165. void Lexer::add_token(TokenIndex type, TokenValue value) {
  166. switch(type) {
  167. case TK("{"):
  168. case TK("["):
  169. case TK("("): brackets_level++; break;
  170. case TK(")"):
  171. case TK("]"):
  172. case TK("}"): brackets_level--; break;
  173. }
  174. auto token = Token{type,
  175. token_start,
  176. (int)(curr_char - token_start),
  177. current_line - ((type == TK("@eol")) ? 1 : 0),
  178. brackets_level,
  179. value};
  180. // handle "not in", "is not", "yield from"
  181. if(!nexts.empty()) {
  182. auto& back = nexts.back();
  183. if(back.type == TK("not") && type == TK("in")) {
  184. back.type = TK("not in");
  185. return;
  186. }
  187. if(back.type == TK("is") && type == TK("not")) {
  188. back.type = TK("is not");
  189. return;
  190. }
  191. if(back.type == TK("yield") && type == TK("from")) {
  192. back.type = TK("yield from");
  193. return;
  194. }
  195. nexts.push_back(token);
  196. }
  197. }
  198. void Lexer::add_token_2(char c, TokenIndex one, TokenIndex two) {
  199. if(matchchar(c))
  200. add_token(two);
  201. else
  202. add_token(one);
  203. }
  204. Str Lexer::eat_string_until(char quote, bool raw) {
  205. bool quote3 = match_n_chars(2, quote);
  206. small_vector_2<char, 32> buff;
  207. while(true) {
  208. char c = eatchar_include_newline();
  209. if(c == quote) {
  210. if(quote3 && !match_n_chars(2, quote)) {
  211. buff.push_back(c);
  212. continue;
  213. }
  214. break;
  215. }
  216. if(c == '\0') {
  217. if(quote3 && src->mode == REPL_MODE) { throw NeedMoreLines(false); }
  218. SyntaxError("EOL while scanning string literal");
  219. }
  220. if(c == '\n') {
  221. if(!quote3)
  222. SyntaxError("EOL while scanning string literal");
  223. else {
  224. buff.push_back(c);
  225. continue;
  226. }
  227. }
  228. if(!raw && c == '\\') {
  229. switch(eatchar_include_newline()) {
  230. case '"': buff.push_back('"'); break;
  231. case '\'': buff.push_back('\''); break;
  232. case '\\': buff.push_back('\\'); break;
  233. case 'n': buff.push_back('\n'); break;
  234. case 'r': buff.push_back('\r'); break;
  235. case 't': buff.push_back('\t'); break;
  236. case 'b': buff.push_back('\b'); break;
  237. case 'x': {
  238. char hex[3] = {eatchar(), eatchar(), '\0'};
  239. size_t parsed;
  240. char code;
  241. try {
  242. code = (char)std::stoi(hex, &parsed, 16);
  243. } catch(...) { SyntaxError("invalid hex char"); }
  244. if(parsed != 2) SyntaxError("invalid hex char");
  245. buff.push_back(code);
  246. } break;
  247. default: SyntaxError("invalid escape char");
  248. }
  249. } else {
  250. buff.push_back(c);
  251. }
  252. }
  253. return Str(buff.data(), buff.size());
  254. }
  255. void Lexer::eat_string(char quote, StringType type) {
  256. Str s = eat_string_until(quote, type == RAW_STRING);
  257. if(type == F_STRING) {
  258. add_token(TK("@fstr"), s);
  259. return;
  260. }
  261. if(type == NORMAL_BYTES) {
  262. add_token(TK("@bytes"), s);
  263. return;
  264. }
  265. add_token(TK("@str"), s);
  266. }
  267. void Lexer::eat_number() {
  268. const char* i = token_start;
  269. while(is_possible_number_char(*i))
  270. i++;
  271. bool is_scientific_notation = false;
  272. if(*(i - 1) == 'e' && (*i == '+' || *i == '-')) {
  273. i++;
  274. while(isdigit(*i) || *i == 'j')
  275. i++;
  276. is_scientific_notation = true;
  277. }
  278. std::string_view text(token_start, i - token_start);
  279. this->curr_char = i;
  280. if(text[0] != '.' && !is_scientific_notation) {
  281. // try long
  282. if(i[-1] == 'L') {
  283. add_token(TK("@long"));
  284. return;
  285. }
  286. // try integer
  287. i64 int_out;
  288. switch(parse_uint(text, &int_out, -1)) {
  289. case IntParsingResult::Success: add_token(TK("@num"), int_out); return;
  290. case IntParsingResult::Overflow: SyntaxError("int literal is too large"); return;
  291. case IntParsingResult::Failure: break; // do nothing
  292. }
  293. }
  294. // try float
  295. double float_out;
  296. char* p_end;
  297. try {
  298. float_out = std::strtod(text.data(), &p_end);
  299. } catch(...) { SyntaxError("invalid number literal"); }
  300. if(p_end == text.data() + text.size()) {
  301. add_token(TK("@num"), (f64)float_out);
  302. return;
  303. }
  304. if(i[-1] == 'j' && p_end == text.data() + text.size() - 1) {
  305. add_token(TK("@imag"), (f64)float_out);
  306. return;
  307. }
  308. SyntaxError("invalid number literal");
  309. }
  310. bool Lexer::lex_one_token() {
  311. while(peekchar() != '\0') {
  312. token_start = curr_char;
  313. char c = eatchar_include_newline();
  314. switch(c) {
  315. case '\'':
  316. case '"': eat_string(c, NORMAL_STRING); return true;
  317. case '#': skip_line_comment(); break;
  318. case '~': add_token(TK("~")); return true;
  319. case '{': add_token(TK("{")); return true;
  320. case '}': add_token(TK("}")); return true;
  321. case ',': add_token(TK(",")); return true;
  322. case ':': add_token(TK(":")); return true;
  323. case ';': add_token(TK(";")); return true;
  324. case '(': add_token(TK("(")); return true;
  325. case ')': add_token(TK(")")); return true;
  326. case '[': add_token(TK("[")); return true;
  327. case ']': add_token(TK("]")); return true;
  328. case '@': add_token(TK("@")); return true;
  329. case '\\': {
  330. // line continuation character
  331. char c = eatchar_include_newline();
  332. if(c != '\n') {
  333. if(src->mode == REPL_MODE && c == '\0') throw NeedMoreLines(false);
  334. SyntaxError("expected newline after line continuation character");
  335. }
  336. eat_spaces();
  337. return true;
  338. }
  339. case '%': add_token_2('=', TK("%"), TK("%=")); return true;
  340. case '&': add_token_2('=', TK("&"), TK("&=")); return true;
  341. case '|': add_token_2('=', TK("|"), TK("|=")); return true;
  342. case '^': add_token_2('=', TK("^"), TK("^=")); return true;
  343. case '.': {
  344. if(matchchar('.')) {
  345. if(matchchar('.')) {
  346. add_token(TK("..."));
  347. } else {
  348. add_token(TK(".."));
  349. }
  350. } else {
  351. char next_char = peekchar();
  352. if(next_char >= '0' && next_char <= '9') {
  353. eat_number();
  354. } else {
  355. add_token(TK("."));
  356. }
  357. }
  358. return true;
  359. }
  360. case '=': add_token_2('=', TK("="), TK("==")); return true;
  361. case '+':
  362. if(matchchar('+')) {
  363. add_token(TK("++"));
  364. } else {
  365. add_token_2('=', TK("+"), TK("+="));
  366. }
  367. return true;
  368. case '>': {
  369. if(matchchar('='))
  370. add_token(TK(">="));
  371. else if(matchchar('>'))
  372. add_token_2('=', TK(">>"), TK(">>="));
  373. else
  374. add_token(TK(">"));
  375. return true;
  376. }
  377. case '<': {
  378. if(matchchar('='))
  379. add_token(TK("<="));
  380. else if(matchchar('<'))
  381. add_token_2('=', TK("<<"), TK("<<="));
  382. else
  383. add_token(TK("<"));
  384. return true;
  385. }
  386. case '-': {
  387. if(matchchar('-')) {
  388. add_token(TK("--"));
  389. } else {
  390. if(matchchar('='))
  391. add_token(TK("-="));
  392. else if(matchchar('>'))
  393. add_token(TK("->"));
  394. else
  395. add_token(TK("-"));
  396. }
  397. return true;
  398. }
  399. case '!':
  400. if(matchchar('='))
  401. add_token(TK("!="));
  402. else
  403. SyntaxError("expected '=' after '!'");
  404. break;
  405. case '*':
  406. if(matchchar('*')) {
  407. add_token(TK("**")); // '**'
  408. } else {
  409. add_token_2('=', TK("*"), TK("*="));
  410. }
  411. return true;
  412. case '/':
  413. if(matchchar('/')) {
  414. add_token_2('=', TK("//"), TK("//="));
  415. } else {
  416. add_token_2('=', TK("/"), TK("/="));
  417. }
  418. return true;
  419. case ' ':
  420. case '\t': eat_spaces(); break;
  421. case '\n': {
  422. add_token(TK("@eol"));
  423. if(!eat_indentation()) IndentationError("unindent does not match any outer indentation level");
  424. return true;
  425. }
  426. default: {
  427. if(c == 'f') {
  428. if(matchchar('\'')) {
  429. eat_string('\'', F_STRING);
  430. return true;
  431. }
  432. if(matchchar('"')) {
  433. eat_string('"', F_STRING);
  434. return true;
  435. }
  436. } else if(c == 'r') {
  437. if(matchchar('\'')) {
  438. eat_string('\'', RAW_STRING);
  439. return true;
  440. }
  441. if(matchchar('"')) {
  442. eat_string('"', RAW_STRING);
  443. return true;
  444. }
  445. } else if(c == 'b') {
  446. if(matchchar('\'')) {
  447. eat_string('\'', NORMAL_BYTES);
  448. return true;
  449. }
  450. if(matchchar('"')) {
  451. eat_string('"', NORMAL_BYTES);
  452. return true;
  453. }
  454. }
  455. if(c >= '0' && c <= '9') {
  456. eat_number();
  457. return true;
  458. }
  459. switch(eat_name()) {
  460. case 0: break;
  461. case 1: SyntaxError("invalid char: " + std::string(1, c)); break;
  462. case 2: SyntaxError("invalid utf8 sequence: " + std::string(1, c)); break;
  463. case 3: SyntaxError("@id contains invalid char"); break;
  464. case 4: SyntaxError("invalid JSON token"); break;
  465. default: assert(false);
  466. }
  467. return true;
  468. }
  469. }
  470. }
  471. token_start = curr_char;
  472. while(indents.size() > 1) {
  473. indents.pop_back();
  474. add_token(TK("@dedent"));
  475. return true;
  476. }
  477. add_token(TK("@eof"));
  478. return false;
  479. }
  480. void Lexer::throw_err(StrName type, Str msg) {
  481. int lineno = current_line;
  482. const char* cursor = curr_char;
  483. if(peekchar() == '\n') {
  484. lineno--;
  485. cursor--;
  486. }
  487. throw_err(type, msg, lineno, cursor);
  488. }
  489. Lexer::Lexer(VM* vm, std::shared_ptr<SourceData> src) : vm(vm), src(src) {
  490. this->token_start = src->source.c_str();
  491. this->curr_char = src->source.c_str();
  492. this->nexts.push_back(Token{TK("@sof"), token_start, 0, current_line, brackets_level, {}});
  493. this->indents.push_back(0);
  494. }
  495. vector<Token> Lexer::run() {
  496. assert(curr_char == src->source.c_str());
  497. while(lex_one_token())
  498. ;
  499. return std::move(nexts);
  500. }
  501. constexpr inline bool f_startswith_2(std::string_view t, const char* prefix) {
  502. if(t.length() < 2) return false;
  503. return t[0] == prefix[0] && t[1] == prefix[1];
  504. }
  505. IntParsingResult parse_uint(std::string_view text, i64* out, int base) {
  506. *out = 0;
  507. if(base == -1) {
  508. if(f_startswith_2(text, "0b"))
  509. base = 2;
  510. else if(f_startswith_2(text, "0o"))
  511. base = 8;
  512. else if(f_startswith_2(text, "0x"))
  513. base = 16;
  514. else
  515. base = 10;
  516. }
  517. if(base == 10) {
  518. // 10-base 12334
  519. if(text.length() == 0) return IntParsingResult::Failure;
  520. for(char c: text) {
  521. if(c >= '0' && c <= '9') {
  522. i64 prev_out = *out;
  523. *out = (*out * 10) + (c - '0');
  524. if(*out < prev_out) return IntParsingResult::Overflow;
  525. } else {
  526. return IntParsingResult::Failure;
  527. }
  528. }
  529. return IntParsingResult::Success;
  530. } else if(base == 2) {
  531. // 2-base 0b101010
  532. if(f_startswith_2(text, "0b")) text.remove_prefix(2);
  533. if(text.length() == 0) return IntParsingResult::Failure;
  534. for(char c: text) {
  535. if(c == '0' || c == '1') {
  536. i64 prev_out = *out;
  537. *out = (*out << 1) | (c - '0');
  538. if(*out < prev_out) return IntParsingResult::Overflow;
  539. } else {
  540. return IntParsingResult::Failure;
  541. }
  542. }
  543. return IntParsingResult::Success;
  544. } else if(base == 8) {
  545. // 8-base 0o123
  546. if(f_startswith_2(text, "0o")) text.remove_prefix(2);
  547. if(text.length() == 0) return IntParsingResult::Failure;
  548. for(char c: text) {
  549. if(c >= '0' && c <= '7') {
  550. i64 prev_out = *out;
  551. *out = (*out << 3) | (c - '0');
  552. if(*out < prev_out) return IntParsingResult::Overflow;
  553. } else {
  554. return IntParsingResult::Failure;
  555. }
  556. }
  557. return IntParsingResult::Success;
  558. } else if(base == 16) {
  559. // 16-base 0x123
  560. if(f_startswith_2(text, "0x")) text.remove_prefix(2);
  561. if(text.length() == 0) return IntParsingResult::Failure;
  562. for(char c: text) {
  563. i64 prev_out = *out;
  564. if(c >= '0' && c <= '9') {
  565. *out = (*out << 4) | (c - '0');
  566. if(*out < prev_out) return IntParsingResult::Overflow;
  567. } else if(c >= 'a' && c <= 'f') {
  568. *out = (*out << 4) | (c - 'a' + 10);
  569. if(*out < prev_out) return IntParsingResult::Overflow;
  570. } else if(c >= 'A' && c <= 'F') {
  571. *out = (*out << 4) | (c - 'A' + 10);
  572. if(*out < prev_out) return IntParsingResult::Overflow;
  573. } else {
  574. return IntParsingResult::Failure;
  575. }
  576. }
  577. return IntParsingResult::Success;
  578. }
  579. return IntParsingResult::Failure;
  580. }
  581. } // namespace pkpy