parser.h 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #pragma once
  2. #include "error.h"
  3. #include "obj.h"
  4. namespace pkpy{
  5. typedef uint8_t TokenIndex;
  6. constexpr const char* kTokens[] = {
  7. "@error", "@eof", "@eol", "@sof",
  8. ".", ",", ":", ";", "#", "(", ")", "[", "]", "{", "}", "%", "::",
  9. "+", "-", "*", "/", "//", "**", "=", ">", "<", "...", "->",
  10. "<<", ">>", "&", "|", "^", "?", "@",
  11. "==", "!=", ">=", "<=",
  12. "+=", "-=", "*=", "/=", "//=", "%=", "&=", "|=", "^=", ">>=", "<<=",
  13. /** KW_BEGIN **/
  14. "class", "import", "as", "def", "lambda", "pass", "del", "from", "with", "yield",
  15. "None", "in", "is", "and", "or", "not", "True", "False", "global", "try", "except", "finally",
  16. "goto", "label", // extended keywords, not available in cpython
  17. "while", "for", "if", "elif", "else", "break", "continue", "return", "assert", "raise",
  18. /** KW_END **/
  19. "is not", "not in",
  20. "@id", "@num", "@str", "@fstr",
  21. "@indent", "@dedent"
  22. };
  23. const TokenIndex kTokenCount = sizeof(kTokens) / sizeof(kTokens[0]);
  24. constexpr TokenIndex TK(const char token[]) {
  25. for(int k=0; k<kTokenCount; k++){
  26. const char* i = kTokens[k];
  27. const char* j = token;
  28. while(*i && *j && *i == *j) { i++; j++;}
  29. if(*i == *j) return k;
  30. }
  31. UNREACHABLE();
  32. }
  33. #define TK_STR(t) kTokens[t]
  34. const TokenIndex kTokenKwBegin = TK("class");
  35. const TokenIndex kTokenKwEnd = TK("raise");
  36. const std::map<std::string_view, TokenIndex> kTokenKwMap = [](){
  37. std::map<std::string_view, TokenIndex> map;
  38. for(int k=kTokenKwBegin; k<=kTokenKwEnd; k++) map[kTokens[k]] = k;
  39. return map;
  40. }();
  41. struct Token{
  42. TokenIndex type;
  43. const char* start;
  44. int length;
  45. int line;
  46. PyVar value;
  47. Str str() const { return Str(start, length);}
  48. Str info() const {
  49. StrStream ss;
  50. Str raw = str();
  51. if (raw == Str("\n")) raw = "\\n";
  52. ss << line << ": " << TK_STR(type) << " '" << raw << "'";
  53. return ss.str();
  54. }
  55. };
  56. enum Precedence {
  57. PREC_NONE,
  58. PREC_ASSIGNMENT, // =
  59. PREC_COMMA, // ,
  60. PREC_TERNARY, // ?:
  61. PREC_LOGICAL_OR, // or
  62. PREC_LOGICAL_AND, // and
  63. PREC_EQUALITY, // == !=
  64. PREC_TEST, // in is
  65. PREC_COMPARISION, // < > <= >=
  66. PREC_BITWISE_OR, // |
  67. PREC_BITWISE_XOR, // ^
  68. PREC_BITWISE_AND, // &
  69. PREC_BITWISE_SHIFT, // << >>
  70. PREC_TERM, // + -
  71. PREC_FACTOR, // * / % //
  72. PREC_UNARY, // - not
  73. PREC_EXPONENT, // **
  74. PREC_CALL, // ()
  75. PREC_SUBSCRIPT, // []
  76. PREC_ATTRIB, // .index
  77. PREC_PRIMARY,
  78. };
  79. // The context of the parsing phase for the compiler.
  80. struct Parser {
  81. shared_ptr<SourceData> src;
  82. const char* token_start;
  83. const char* curr_char;
  84. int current_line = 1;
  85. Token prev, curr;
  86. std::queue<Token> nexts;
  87. std::stack<int> indents;
  88. int brackets_level = 0;
  89. Token next_token(){
  90. if(nexts.empty()){
  91. return Token{TK("@error"), token_start, (int)(curr_char - token_start), current_line};
  92. }
  93. Token t = nexts.front();
  94. if(t.type == TK("@eof") && indents.size()>1){
  95. nexts.pop();
  96. indents.pop();
  97. return Token{TK("@dedent"), token_start, 0, current_line};
  98. }
  99. nexts.pop();
  100. return t;
  101. }
  102. inline char peekchar() const{ return *curr_char; }
  103. bool match_n_chars(int n, char c0){
  104. const char* c = curr_char;
  105. for(int i=0; i<n; i++){
  106. if(*c == '\0') return false;
  107. if(*c != c0) return false;
  108. c++;
  109. }
  110. for(int i=0; i<n; i++) eatchar_include_newline();
  111. return true;
  112. }
  113. int eat_spaces(){
  114. int count = 0;
  115. while (true) {
  116. switch (peekchar()) {
  117. case ' ' : count+=1; break;
  118. case '\t': count+=4; break;
  119. default: return count;
  120. }
  121. eatchar();
  122. }
  123. }
  124. bool eat_indentation(){
  125. if(brackets_level > 0) return true;
  126. int spaces = eat_spaces();
  127. if(peekchar() == '#') skip_line_comment();
  128. if(peekchar() == '\0' || peekchar() == '\n' || peekchar() == '\r') return true;
  129. // https://docs.python.org/3/reference/lexical_analysis.html#indentation
  130. if(spaces > indents.top()){
  131. indents.push(spaces);
  132. nexts.push(Token{TK("@indent"), token_start, 0, current_line});
  133. } else if(spaces < indents.top()){
  134. while(spaces < indents.top()){
  135. indents.pop();
  136. nexts.push(Token{TK("@dedent"), token_start, 0, current_line});
  137. }
  138. if(spaces != indents.top()){
  139. return false;
  140. }
  141. }
  142. return true;
  143. }
  144. char eatchar() {
  145. char c = peekchar();
  146. if(c == '\n') throw std::runtime_error("eatchar() cannot consume a newline");
  147. curr_char++;
  148. return c;
  149. }
  150. char eatchar_include_newline() {
  151. char c = peekchar();
  152. curr_char++;
  153. if (c == '\n'){
  154. current_line++;
  155. src->line_starts.push_back(curr_char);
  156. }
  157. return c;
  158. }
  159. int eat_name() {
  160. curr_char--;
  161. while(true){
  162. uint8_t c = peekchar();
  163. int u8bytes = 0;
  164. if((c & 0b10000000) == 0b00000000) u8bytes = 1;
  165. else if((c & 0b11100000) == 0b11000000) u8bytes = 2;
  166. else if((c & 0b11110000) == 0b11100000) u8bytes = 3;
  167. else if((c & 0b11111000) == 0b11110000) u8bytes = 4;
  168. else return 1;
  169. if(u8bytes == 1){
  170. if(isalpha(c) || c=='_' || isdigit(c)) {
  171. curr_char++;
  172. continue;
  173. }else{
  174. break;
  175. }
  176. }
  177. // handle multibyte char
  178. std::string u8str(curr_char, u8bytes);
  179. if(u8str.size() != u8bytes) return 2;
  180. uint32_t value = 0;
  181. for(int k=0; k < u8bytes; k++){
  182. uint8_t b = u8str[k];
  183. if(k==0){
  184. if(u8bytes == 2) value = (b & 0b00011111) << 6;
  185. else if(u8bytes == 3) value = (b & 0b00001111) << 12;
  186. else if(u8bytes == 4) value = (b & 0b00000111) << 18;
  187. }else{
  188. value |= (b & 0b00111111) << (6*(u8bytes-k-1));
  189. }
  190. }
  191. if(is_unicode_Lo_char(value)) curr_char += u8bytes;
  192. else break;
  193. }
  194. int length = (int)(curr_char - token_start);
  195. if(length == 0) return 3;
  196. std::string_view name(token_start, length);
  197. if(src->mode == JSON_MODE){
  198. if(name == "true"){
  199. set_next_token(TK("True"));
  200. } else if(name == "false"){
  201. set_next_token(TK("False"));
  202. } else if(name == "null"){
  203. set_next_token(TK("None"));
  204. } else {
  205. return 4;
  206. }
  207. return 0;
  208. }
  209. if(kTokenKwMap.count(name)){
  210. if(name == "not"){
  211. if(strncmp(curr_char, " in", 3) == 0){
  212. curr_char += 3;
  213. set_next_token(TK("not in"));
  214. return 0;
  215. }
  216. }else if(name == "is"){
  217. if(strncmp(curr_char, " not", 4) == 0){
  218. curr_char += 4;
  219. set_next_token(TK("is not"));
  220. return 0;
  221. }
  222. }
  223. set_next_token(kTokenKwMap.at(name));
  224. } else {
  225. set_next_token(TK("@id"));
  226. }
  227. return 0;
  228. }
  229. void skip_line_comment() {
  230. char c;
  231. while ((c = peekchar()) != '\0') {
  232. if (c == '\n') return;
  233. eatchar();
  234. }
  235. }
  236. bool matchchar(char c) {
  237. if (peekchar() != c) return false;
  238. eatchar_include_newline();
  239. return true;
  240. }
  241. void set_next_token(TokenIndex type, PyVar value=nullptr) {
  242. switch(type){
  243. case TK("{"): case TK("["): case TK("("): brackets_level++; break;
  244. case TK(")"): case TK("]"): case TK("}"): brackets_level--; break;
  245. }
  246. nexts.push( Token{
  247. type,
  248. token_start,
  249. (int)(curr_char - token_start),
  250. current_line - ((type == TK("@eol")) ? 1 : 0),
  251. value
  252. });
  253. }
  254. void set_next_token_2(char c, TokenIndex one, TokenIndex two) {
  255. if (matchchar(c)) set_next_token(two);
  256. else set_next_token(one);
  257. }
  258. Parser(shared_ptr<SourceData> src) {
  259. this->src = src;
  260. this->token_start = src->source;
  261. this->curr_char = src->source;
  262. this->nexts.push(Token{TK("@sof"), token_start, 0, current_line});
  263. this->indents.push(0);
  264. }
  265. };
  266. } // namespace pkpy