lexer.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. #pragma once
  2. #include "common.h"
  3. #include "error.h"
  4. #include "str.h"
  5. namespace pkpy{
  6. typedef uint8_t TokenIndex;
  7. constexpr const char* kTokens[] = {
  8. "is not", "not in",
  9. "@eof", "@eol", "@sof",
  10. "@id", "@num", "@str", "@fstr",
  11. "@indent", "@dedent",
  12. /*****************************************/
  13. "+", "+=", "-", "-=", // (INPLACE_OP - 1) can get '=' removed
  14. "*", "*=", "/", "/=", "//", "//=", "%", "%=",
  15. "&", "&=", "|", "|=", "^", "^=",
  16. "<<", "<<=", ">>", ">>=",
  17. /*****************************************/
  18. ".", ",", ":", ";", "#", "(", ")", "[", "]", "{", "}", "::",
  19. "**", "=", ">", "<", "...", "->", "?", "@", "==", "!=", ">=", "<=",
  20. /** KW_BEGIN **/
  21. "class", "import", "as", "def", "lambda", "pass", "del", "from", "with", "yield",
  22. "None", "in", "is", "and", "or", "not", "True", "False", "global", "try", "except", "finally",
  23. "goto", "label", // extended keywords, not available in cpython
  24. "while", "for", "if", "elif", "else", "break", "continue", "return", "assert", "raise"
  25. };
  26. using TokenValue = std::variant<std::monostate, i64, f64, Str>;
  27. const TokenIndex kTokenCount = sizeof(kTokens) / sizeof(kTokens[0]);
  28. constexpr TokenIndex TK(const char token[]) {
  29. for(int k=0; k<kTokenCount; k++){
  30. const char* i = kTokens[k];
  31. const char* j = token;
  32. while(*i && *j && *i == *j) { i++; j++;}
  33. if(*i == *j) return k;
  34. }
  35. UNREACHABLE();
  36. }
  37. #define TK_STR(t) kTokens[t]
  38. const std::map<std::string_view, TokenIndex> kTokenKwMap = [](){
  39. std::map<std::string_view, TokenIndex> map;
  40. for(int k=TK("class"); k<kTokenCount; k++) map[kTokens[k]] = k;
  41. return map;
  42. }();
  43. struct Token{
  44. TokenIndex type;
  45. const char* start;
  46. int length;
  47. int line;
  48. TokenValue value;
  49. Str str() const { return Str(start, length);}
  50. std::string_view sv() const { return std::string_view(start, length);}
  51. std::string info() const {
  52. std::stringstream ss;
  53. ss << line << ": " << TK_STR(type) << " '" << (
  54. sv()=="\n" ? "\\n" : sv()
  55. ) << "'";
  56. return ss.str();
  57. }
  58. };
  59. // https://docs.python.org/3/reference/expressions.html#operator-precedence
  60. enum Precedence {
  61. PREC_NONE,
  62. PREC_TUPLE, // ,
  63. PREC_TERNARY, // ?:
  64. PREC_LOGICAL_OR, // or
  65. PREC_LOGICAL_AND, // and
  66. PREC_LOGICAL_NOT, // not
  67. PREC_EQUALITY, // == !=
  68. PREC_TEST, // in / is / is not / not in
  69. PREC_COMPARISION, // < > <= >=
  70. PREC_BITWISE_OR, // |
  71. PREC_BITWISE_XOR, // ^
  72. PREC_BITWISE_AND, // &
  73. PREC_BITWISE_SHIFT, // << >>
  74. PREC_TERM, // + -
  75. PREC_FACTOR, // * / % //
  76. PREC_UNARY, // - not
  77. PREC_EXPONENT, // **
  78. PREC_CALL, // ()
  79. PREC_SUBSCRIPT, // []
  80. PREC_ATTRIB, // .index
  81. PREC_PRIMARY,
  82. };
  83. enum StringType { NORMAL_STRING, RAW_STRING, F_STRING };
  84. struct Lexer {
  85. shared_ptr<SourceData> src;
  86. const char* token_start;
  87. const char* curr_char;
  88. int current_line = 1;
  89. std::vector<Token> nexts;
  90. stack<int> indents;
  91. int brackets_level = 0;
  92. bool used = false;
  93. char peekchar() const{ return *curr_char; }
  94. bool match_n_chars(int n, char c0){
  95. const char* c = curr_char;
  96. for(int i=0; i<n; i++){
  97. if(*c == '\0') return false;
  98. if(*c != c0) return false;
  99. c++;
  100. }
  101. for(int i=0; i<n; i++) eatchar_include_newline();
  102. return true;
  103. }
  104. int eat_spaces(){
  105. int count = 0;
  106. while (true) {
  107. switch (peekchar()) {
  108. case ' ' : count+=1; break;
  109. case '\t': count+=4; break;
  110. default: return count;
  111. }
  112. eatchar();
  113. }
  114. }
  115. bool eat_indentation(){
  116. if(brackets_level > 0) return true;
  117. int spaces = eat_spaces();
  118. if(peekchar() == '#') skip_line_comment();
  119. if(peekchar() == '\0' || peekchar() == '\n') return true;
  120. // https://docs.python.org/3/reference/lexical_analysis.html#indentation
  121. if(spaces > indents.top()){
  122. indents.push(spaces);
  123. nexts.push_back(Token{TK("@indent"), token_start, 0, current_line});
  124. } else if(spaces < indents.top()){
  125. while(spaces < indents.top()){
  126. indents.pop();
  127. nexts.push_back(Token{TK("@dedent"), token_start, 0, current_line});
  128. }
  129. if(spaces != indents.top()){
  130. return false;
  131. }
  132. }
  133. return true;
  134. }
  135. char eatchar() {
  136. char c = peekchar();
  137. if(c == '\n') throw std::runtime_error("eatchar() cannot consume a newline");
  138. curr_char++;
  139. return c;
  140. }
  141. char eatchar_include_newline() {
  142. char c = peekchar();
  143. curr_char++;
  144. if (c == '\n'){
  145. current_line++;
  146. src->line_starts.push_back(curr_char);
  147. }
  148. return c;
  149. }
  150. int eat_name() {
  151. curr_char--;
  152. while(true){
  153. unsigned char c = peekchar();
  154. int u8bytes = utf8len(c, true);
  155. if(u8bytes == 0) return 1;
  156. if(u8bytes == 1){
  157. if(isalpha(c) || c=='_' || isdigit(c)) {
  158. curr_char++;
  159. continue;
  160. }else{
  161. break;
  162. }
  163. }
  164. // handle multibyte char
  165. std::string u8str(curr_char, u8bytes);
  166. if(u8str.size() != u8bytes) return 2;
  167. uint32_t value = 0;
  168. for(int k=0; k < u8bytes; k++){
  169. uint8_t b = u8str[k];
  170. if(k==0){
  171. if(u8bytes == 2) value = (b & 0b00011111) << 6;
  172. else if(u8bytes == 3) value = (b & 0b00001111) << 12;
  173. else if(u8bytes == 4) value = (b & 0b00000111) << 18;
  174. }else{
  175. value |= (b & 0b00111111) << (6*(u8bytes-k-1));
  176. }
  177. }
  178. if(is_unicode_Lo_char(value)) curr_char += u8bytes;
  179. else break;
  180. }
  181. int length = (int)(curr_char - token_start);
  182. if(length == 0) return 3;
  183. std::string_view name(token_start, length);
  184. if(src->mode == JSON_MODE){
  185. if(name == "true"){
  186. add_token(TK("True"));
  187. } else if(name == "false"){
  188. add_token(TK("False"));
  189. } else if(name == "null"){
  190. add_token(TK("None"));
  191. } else {
  192. return 4;
  193. }
  194. return 0;
  195. }
  196. if(kTokenKwMap.count(name)){
  197. if(name == "not"){
  198. if(strncmp(curr_char, " in", 3) == 0){
  199. curr_char += 3;
  200. add_token(TK("not in"));
  201. return 0;
  202. }
  203. }else if(name == "is"){
  204. if(strncmp(curr_char, " not", 4) == 0){
  205. curr_char += 4;
  206. add_token(TK("is not"));
  207. return 0;
  208. }
  209. }
  210. add_token(kTokenKwMap.at(name));
  211. } else {
  212. add_token(TK("@id"));
  213. }
  214. return 0;
  215. }
  216. void skip_line_comment() {
  217. char c;
  218. while ((c = peekchar()) != '\0') {
  219. if (c == '\n') return;
  220. eatchar();
  221. }
  222. }
  223. bool matchchar(char c) {
  224. if (peekchar() != c) return false;
  225. eatchar_include_newline();
  226. return true;
  227. }
  228. void add_token(TokenIndex type, TokenValue value={}) {
  229. switch(type){
  230. case TK("{"): case TK("["): case TK("("): brackets_level++; break;
  231. case TK(")"): case TK("]"): case TK("}"): brackets_level--; break;
  232. }
  233. nexts.push_back( Token{
  234. type,
  235. token_start,
  236. (int)(curr_char - token_start),
  237. current_line - ((type == TK("@eol")) ? 1 : 0),
  238. value
  239. });
  240. }
  241. void add_token_2(char c, TokenIndex one, TokenIndex two) {
  242. if (matchchar(c)) add_token(two);
  243. else add_token(one);
  244. }
  245. Str eat_string_until(char quote, bool raw) {
  246. bool quote3 = match_n_chars(2, quote);
  247. std::vector<char> buff;
  248. while (true) {
  249. char c = eatchar_include_newline();
  250. if (c == quote){
  251. if(quote3 && !match_n_chars(2, quote)){
  252. buff.push_back(c);
  253. continue;
  254. }
  255. break;
  256. }
  257. if (c == '\0'){
  258. if(quote3 && src->mode == REPL_MODE){
  259. throw NeedMoreLines(false);
  260. }
  261. SyntaxError("EOL while scanning string literal");
  262. }
  263. if (c == '\n'){
  264. if(!quote3) SyntaxError("EOL while scanning string literal");
  265. else{
  266. buff.push_back(c);
  267. continue;
  268. }
  269. }
  270. if (!raw && c == '\\') {
  271. switch (eatchar_include_newline()) {
  272. case '"': buff.push_back('"'); break;
  273. case '\'': buff.push_back('\''); break;
  274. case '\\': buff.push_back('\\'); break;
  275. case 'n': buff.push_back('\n'); break;
  276. case 'r': buff.push_back('\r'); break;
  277. case 't': buff.push_back('\t'); break;
  278. default: SyntaxError("invalid escape char");
  279. }
  280. } else {
  281. buff.push_back(c);
  282. }
  283. }
  284. return Str(buff.data(), buff.size());
  285. }
  286. void eat_string(char quote, StringType type) {
  287. Str s = eat_string_until(quote, type == RAW_STRING);
  288. if(type == F_STRING){
  289. add_token(TK("@fstr"), s);
  290. }else{
  291. add_token(TK("@str"), s);
  292. }
  293. }
  294. void eat_number() {
  295. static const std::regex pattern("^(0x)?[0-9a-fA-F]+(\\.[0-9]+)?");
  296. std::smatch m;
  297. const char* i = token_start;
  298. while(*i != '\n' && *i != '\0') i++;
  299. std::string s = std::string(token_start, i);
  300. try{
  301. if (std::regex_search(s, m, pattern)) {
  302. // here is m.length()-1, since the first char was eaten by lex_token()
  303. for(int j=0; j<m.length()-1; j++) eatchar();
  304. int base = 10;
  305. size_t size;
  306. if (m[1].matched) base = 16;
  307. if (m[2].matched) {
  308. if(base == 16) SyntaxError("hex literal should not contain a dot");
  309. add_token(TK("@num"), S_TO_FLOAT(m[0], &size));
  310. } else {
  311. add_token(TK("@num"), S_TO_INT(m[0], &size, base));
  312. }
  313. if (size != m.length()) UNREACHABLE();
  314. }
  315. }catch(std::exception& _){
  316. SyntaxError("invalid number literal");
  317. }
  318. }
  319. bool lex_one_token() {
  320. while (peekchar() != '\0') {
  321. token_start = curr_char;
  322. char c = eatchar_include_newline();
  323. switch (c) {
  324. case '\'': case '"': eat_string(c, NORMAL_STRING); return true;
  325. case '#': skip_line_comment(); break;
  326. case '{': add_token(TK("{")); return true;
  327. case '}': add_token(TK("}")); return true;
  328. case ',': add_token(TK(",")); return true;
  329. case ':': add_token_2(':', TK(":"), TK("::")); return true;
  330. case ';': add_token(TK(";")); return true;
  331. case '(': add_token(TK("(")); return true;
  332. case ')': add_token(TK(")")); return true;
  333. case '[': add_token(TK("[")); return true;
  334. case ']': add_token(TK("]")); return true;
  335. case '@': add_token(TK("@")); return true;
  336. case '%': add_token_2('=', TK("%"), TK("%=")); return true;
  337. case '&': add_token_2('=', TK("&"), TK("&=")); return true;
  338. case '|': add_token_2('=', TK("|"), TK("|=")); return true;
  339. case '^': add_token_2('=', TK("^"), TK("^=")); return true;
  340. case '?': add_token(TK("?")); return true;
  341. case '.': {
  342. if(matchchar('.')) {
  343. if(matchchar('.')) {
  344. add_token(TK("..."));
  345. } else {
  346. SyntaxError("invalid token '..'");
  347. }
  348. } else {
  349. add_token(TK("."));
  350. }
  351. return true;
  352. }
  353. case '=': add_token_2('=', TK("="), TK("==")); return true;
  354. case '+': add_token_2('=', TK("+"), TK("+=")); return true;
  355. case '>': {
  356. if(matchchar('=')) add_token(TK(">="));
  357. else if(matchchar('>')) add_token_2('=', TK(">>"), TK(">>="));
  358. else add_token(TK(">"));
  359. return true;
  360. }
  361. case '<': {
  362. if(matchchar('=')) add_token(TK("<="));
  363. else if(matchchar('<')) add_token_2('=', TK("<<"), TK("<<="));
  364. else add_token(TK("<"));
  365. return true;
  366. }
  367. case '-': {
  368. if(matchchar('=')) add_token(TK("-="));
  369. else if(matchchar('>')) add_token(TK("->"));
  370. else add_token(TK("-"));
  371. return true;
  372. }
  373. case '!':
  374. if(matchchar('=')) add_token(TK("!="));
  375. else SyntaxError("expected '=' after '!'");
  376. break;
  377. case '*':
  378. if (matchchar('*')) {
  379. add_token(TK("**")); // '**'
  380. } else {
  381. add_token_2('=', TK("*"), TK("*="));
  382. }
  383. return true;
  384. case '/':
  385. if(matchchar('/')) {
  386. add_token_2('=', TK("//"), TK("//="));
  387. } else {
  388. add_token_2('=', TK("/"), TK("/="));
  389. }
  390. return true;
  391. case ' ': case '\t': eat_spaces(); break;
  392. case '\n': {
  393. add_token(TK("@eol"));
  394. if(!eat_indentation()) IndentationError("unindent does not match any outer indentation level");
  395. return true;
  396. }
  397. default: {
  398. if(c == 'f'){
  399. if(matchchar('\'')) {eat_string('\'', F_STRING); return true;}
  400. if(matchchar('"')) {eat_string('"', F_STRING); return true;}
  401. }else if(c == 'r'){
  402. if(matchchar('\'')) {eat_string('\'', RAW_STRING); return true;}
  403. if(matchchar('"')) {eat_string('"', RAW_STRING); return true;}
  404. }
  405. if (c >= '0' && c <= '9') {
  406. eat_number();
  407. return true;
  408. }
  409. switch (eat_name())
  410. {
  411. case 0: break;
  412. case 1: SyntaxError("invalid char: " + std::string(1, c));
  413. case 2: SyntaxError("invalid utf8 sequence: " + std::string(1, c));
  414. case 3: SyntaxError("@id contains invalid char"); break;
  415. case 4: SyntaxError("invalid JSON token"); break;
  416. default: UNREACHABLE();
  417. }
  418. return true;
  419. }
  420. }
  421. }
  422. token_start = curr_char;
  423. while(indents.size() > 1){
  424. indents.pop();
  425. add_token(TK("@dedent"));
  426. return true;
  427. }
  428. add_token(TK("@eof"));
  429. return false;
  430. }
  431. /***** Error Reporter *****/
  432. void throw_err(Str type, Str msg){
  433. int lineno = current_line;
  434. const char* cursor = curr_char;
  435. if(peekchar() == '\n'){
  436. lineno--;
  437. cursor--;
  438. }
  439. throw_err(type, msg, lineno, cursor);
  440. }
  441. void throw_err(Str type, Str msg, int lineno, const char* cursor){
  442. auto e = Exception("SyntaxError", msg);
  443. e.st_push(src->snapshot(lineno, cursor));
  444. throw e;
  445. }
  446. void SyntaxError(Str msg){ throw_err("SyntaxError", msg); }
  447. void SyntaxError(){ throw_err("SyntaxError", "invalid syntax"); }
  448. void IndentationError(Str msg){ throw_err("IndentationError", msg); }
  449. Lexer(shared_ptr<SourceData> src) {
  450. this->src = src;
  451. this->token_start = src->source.c_str();
  452. this->curr_char = src->source.c_str();
  453. this->nexts.push_back(Token{TK("@sof"), token_start, 0, current_line});
  454. this->indents.push(0);
  455. }
  456. std::vector<Token> run() {
  457. if(used) UNREACHABLE();
  458. used = true;
  459. while (lex_one_token());
  460. return std::move(nexts);
  461. }
  462. };
  463. } // namespace pkpy