compiler.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. #include "pocketpy/compiler.h"
  2. namespace pkpy{
  3. NameScope Compiler::name_scope() const {
  4. auto s = contexts.size()>1 ? NAME_LOCAL : NAME_GLOBAL;
  5. if(unknown_global_scope && s == NAME_GLOBAL) s = NAME_GLOBAL_UNKNOWN;
  6. return s;
  7. }
  8. CodeObject_ Compiler::push_global_context(){
  9. CodeObject_ co = std::make_shared<CodeObject>(lexer->src, lexer->src->filename);
  10. contexts.push(CodeEmitContext(vm, co, contexts.size()));
  11. return co;
  12. }
  13. FuncDecl_ Compiler::push_f_context(Str name){
  14. FuncDecl_ decl = std::make_shared<FuncDecl>();
  15. decl->code = std::make_shared<CodeObject>(lexer->src, name);
  16. decl->nested = name_scope() == NAME_LOCAL;
  17. contexts.push(CodeEmitContext(vm, decl->code, contexts.size()));
  18. return decl;
  19. }
  20. void Compiler::pop_context(){
  21. if(!ctx()->s_expr.empty()){
  22. throw std::runtime_error("!ctx()->s_expr.empty()\n" + ctx()->_log_s_expr());
  23. }
  24. // add a `return None` in the end as a guard
  25. // previously, we only do this if the last opcode is not a return
  26. // however, this is buggy...since there may be a jump to the end (out of bound) even if the last opcode is a return
  27. ctx()->emit(OP_LOAD_NONE, BC_NOARG, BC_KEEPLINE);
  28. ctx()->emit(OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  29. // ctx()->co->optimize(vm);
  30. if(ctx()->co->varnames.size() > PK_MAX_CO_VARNAMES){
  31. SyntaxError("maximum number of local variables exceeded");
  32. }
  33. contexts.pop();
  34. }
  35. void Compiler::init_pratt_rules(){
  36. if(rules[TK(".")].precedence != PREC_NONE) return;
  37. // http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
  38. #define METHOD(name) &Compiler::name
  39. #define NO_INFIX nullptr, PREC_NONE
  40. for(TokenIndex i=0; i<kTokenCount; i++) rules[i] = { nullptr, NO_INFIX };
  41. rules[TK(".")] = { nullptr, METHOD(exprAttrib), PREC_ATTRIB };
  42. rules[TK("(")] = { METHOD(exprGroup), METHOD(exprCall), PREC_CALL };
  43. rules[TK("[")] = { METHOD(exprList), METHOD(exprSubscr), PREC_SUBSCRIPT };
  44. rules[TK("{")] = { METHOD(exprMap), NO_INFIX };
  45. rules[TK("%")] = { nullptr, METHOD(exprBinaryOp), PREC_FACTOR };
  46. rules[TK("+")] = { nullptr, METHOD(exprBinaryOp), PREC_TERM };
  47. rules[TK("-")] = { METHOD(exprUnaryOp), METHOD(exprBinaryOp), PREC_TERM };
  48. rules[TK("*")] = { METHOD(exprUnaryOp), METHOD(exprBinaryOp), PREC_FACTOR };
  49. rules[TK("~")] = { METHOD(exprUnaryOp), nullptr, PREC_UNARY };
  50. rules[TK("/")] = { nullptr, METHOD(exprBinaryOp), PREC_FACTOR };
  51. rules[TK("//")] = { nullptr, METHOD(exprBinaryOp), PREC_FACTOR };
  52. rules[TK("**")] = { METHOD(exprUnaryOp), METHOD(exprBinaryOp), PREC_EXPONENT };
  53. rules[TK(">")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  54. rules[TK("<")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  55. rules[TK("==")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  56. rules[TK("!=")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  57. rules[TK(">=")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  58. rules[TK("<=")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  59. rules[TK("in")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  60. rules[TK("is")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  61. rules[TK("<<")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_SHIFT };
  62. rules[TK(">>")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_SHIFT };
  63. rules[TK("&")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_AND };
  64. rules[TK("|")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_OR };
  65. rules[TK("^")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_XOR };
  66. rules[TK("@")] = { nullptr, METHOD(exprBinaryOp), PREC_FACTOR };
  67. rules[TK("if")] = { nullptr, METHOD(exprTernary), PREC_TERNARY };
  68. rules[TK(",")] = { nullptr, METHOD(exprTuple), PREC_TUPLE };
  69. rules[TK("not in")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  70. rules[TK("is not")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  71. rules[TK("and") ] = { nullptr, METHOD(exprAnd), PREC_LOGICAL_AND };
  72. rules[TK("or")] = { nullptr, METHOD(exprOr), PREC_LOGICAL_OR };
  73. rules[TK("not")] = { METHOD(exprNot), nullptr, PREC_LOGICAL_NOT };
  74. rules[TK("True")] = { METHOD(exprLiteral0), NO_INFIX };
  75. rules[TK("False")] = { METHOD(exprLiteral0), NO_INFIX };
  76. rules[TK("None")] = { METHOD(exprLiteral0), NO_INFIX };
  77. rules[TK("...")] = { METHOD(exprLiteral0), NO_INFIX };
  78. rules[TK("lambda")] = { METHOD(exprLambda), NO_INFIX };
  79. rules[TK("@id")] = { METHOD(exprName), NO_INFIX };
  80. rules[TK("@num")] = { METHOD(exprLiteral), NO_INFIX };
  81. rules[TK("@str")] = { METHOD(exprLiteral), NO_INFIX };
  82. rules[TK("@fstr")] = { METHOD(exprFString), NO_INFIX };
  83. rules[TK("@long")] = { METHOD(exprLong), NO_INFIX };
  84. rules[TK("@bytes")] = { METHOD(exprBytes), NO_INFIX };
  85. #undef METHOD
  86. #undef NO_INFIX
  87. }
  88. bool Compiler::match(TokenIndex expected) {
  89. if (curr().type != expected) return false;
  90. advance();
  91. return true;
  92. }
  93. void Compiler::consume(TokenIndex expected) {
  94. if (!match(expected)){
  95. SyntaxError(
  96. fmt("expected '", TK_STR(expected), "', got '", TK_STR(curr().type), "'")
  97. );
  98. }
  99. }
  100. bool Compiler::match_newlines_repl(){
  101. return match_newlines(mode()==REPL_MODE);
  102. }
  103. bool Compiler::match_newlines(bool repl_throw) {
  104. bool consumed = false;
  105. if (curr().type == TK("@eol")) {
  106. while (curr().type == TK("@eol")) advance();
  107. consumed = true;
  108. }
  109. if (repl_throw && curr().type == TK("@eof")){
  110. throw NeedMoreLines(ctx()->is_compiling_class);
  111. }
  112. return consumed;
  113. }
  114. bool Compiler::match_end_stmt() {
  115. if (match(TK(";"))) { match_newlines(); return true; }
  116. if (match_newlines() || curr().type == TK("@eof")) return true;
  117. if (curr().type == TK("@dedent")) return true;
  118. return false;
  119. }
  120. void Compiler::consume_end_stmt() {
  121. if (!match_end_stmt()) SyntaxError("expected statement end");
  122. }
  123. void Compiler::EXPR(bool push_stack) {
  124. parse_expression(PREC_TUPLE+1, push_stack);
  125. }
  126. void Compiler::EXPR_TUPLE(bool push_stack) {
  127. parse_expression(PREC_TUPLE, push_stack);
  128. }
  129. // special case for `for loop` and `comp`
  130. Expr_ Compiler::EXPR_VARS(){
  131. std::vector<Expr_> items;
  132. do {
  133. consume(TK("@id"));
  134. items.push_back(make_expr<NameExpr>(prev().str(), name_scope()));
  135. } while(match(TK(",")));
  136. if(items.size()==1) return std::move(items[0]);
  137. return make_expr<TupleExpr>(std::move(items));
  138. }
  139. void Compiler::exprLiteral(){
  140. ctx()->s_expr.push(make_expr<LiteralExpr>(prev().value));
  141. }
  142. void Compiler::exprLong(){
  143. ctx()->s_expr.push(make_expr<LongExpr>(prev().str()));
  144. }
  145. void Compiler::exprBytes(){
  146. ctx()->s_expr.push(make_expr<BytesExpr>(std::get<Str>(prev().value)));
  147. }
  148. void Compiler::exprFString(){
  149. ctx()->s_expr.push(make_expr<FStringExpr>(std::get<Str>(prev().value)));
  150. }
  151. void Compiler::exprLambda(){
  152. FuncDecl_ decl = push_f_context("<lambda>");
  153. auto e = make_expr<LambdaExpr>(decl);
  154. if(!match(TK(":"))){
  155. _compile_f_args(e->decl, false);
  156. consume(TK(":"));
  157. }
  158. // https://github.com/blueloveTH/pocketpy/issues/37
  159. parse_expression(PREC_LAMBDA + 1, false);
  160. ctx()->emit(OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  161. pop_context();
  162. ctx()->s_expr.push(std::move(e));
  163. }
  164. void Compiler::exprTuple(){
  165. std::vector<Expr_> items;
  166. items.push_back(ctx()->s_expr.popx());
  167. do {
  168. if(curr().brackets_level) match_newlines_repl();
  169. if(!is_expression()) break;
  170. EXPR();
  171. items.push_back(ctx()->s_expr.popx());
  172. if(curr().brackets_level) match_newlines_repl();
  173. } while(match(TK(",")));
  174. ctx()->s_expr.push(make_expr<TupleExpr>(
  175. std::move(items)
  176. ));
  177. }
  178. void Compiler::exprOr(){
  179. auto e = make_expr<OrExpr>();
  180. e->lhs = ctx()->s_expr.popx();
  181. parse_expression(PREC_LOGICAL_OR + 1);
  182. e->rhs = ctx()->s_expr.popx();
  183. ctx()->s_expr.push(std::move(e));
  184. }
  185. void Compiler::exprAnd(){
  186. auto e = make_expr<AndExpr>();
  187. e->lhs = ctx()->s_expr.popx();
  188. parse_expression(PREC_LOGICAL_AND + 1);
  189. e->rhs = ctx()->s_expr.popx();
  190. ctx()->s_expr.push(std::move(e));
  191. }
  192. void Compiler::exprTernary(){
  193. auto e = make_expr<TernaryExpr>();
  194. e->true_expr = ctx()->s_expr.popx();
  195. // cond
  196. parse_expression(PREC_TERNARY + 1);
  197. e->cond = ctx()->s_expr.popx();
  198. consume(TK("else"));
  199. // if false
  200. parse_expression(PREC_TERNARY + 1);
  201. e->false_expr = ctx()->s_expr.popx();
  202. ctx()->s_expr.push(std::move(e));
  203. }
  204. void Compiler::exprBinaryOp(){
  205. auto e = make_expr<BinaryExpr>();
  206. e->op = prev().type;
  207. e->lhs = ctx()->s_expr.popx();
  208. parse_expression(rules[e->op].precedence + 1);
  209. e->rhs = ctx()->s_expr.popx();
  210. ctx()->s_expr.push(std::move(e));
  211. }
  212. void Compiler::exprNot() {
  213. parse_expression(PREC_LOGICAL_NOT + 1);
  214. ctx()->s_expr.push(make_expr<NotExpr>(ctx()->s_expr.popx()));
  215. }
  216. void Compiler::exprUnaryOp(){
  217. TokenIndex op = prev().type;
  218. parse_expression(PREC_UNARY + 1);
  219. switch(op){
  220. case TK("-"):
  221. ctx()->s_expr.push(make_expr<NegatedExpr>(ctx()->s_expr.popx()));
  222. break;
  223. case TK("~"):
  224. ctx()->s_expr.push(make_expr<InvertExpr>(ctx()->s_expr.popx()));
  225. break;
  226. case TK("*"):
  227. ctx()->s_expr.push(make_expr<StarredExpr>(1, ctx()->s_expr.popx()));
  228. break;
  229. case TK("**"):
  230. ctx()->s_expr.push(make_expr<StarredExpr>(2, ctx()->s_expr.popx()));
  231. break;
  232. default: FATAL_ERROR();
  233. }
  234. }
  235. void Compiler::exprGroup(){
  236. match_newlines_repl();
  237. EXPR_TUPLE(); // () is just for change precedence
  238. match_newlines_repl();
  239. consume(TK(")"));
  240. if(ctx()->s_expr.top()->is_tuple()) return;
  241. Expr_ g = make_expr<GroupedExpr>(ctx()->s_expr.popx());
  242. ctx()->s_expr.push(std::move(g));
  243. }
  244. void Compiler::exprList() {
  245. int line = prev().line;
  246. std::vector<Expr_> items;
  247. do {
  248. match_newlines_repl();
  249. if (curr().type == TK("]")) break;
  250. EXPR();
  251. items.push_back(ctx()->s_expr.popx());
  252. match_newlines_repl();
  253. if(items.size()==1 && match(TK("for"))){
  254. _consume_comp<ListCompExpr>(std::move(items[0]));
  255. consume(TK("]"));
  256. return;
  257. }
  258. match_newlines_repl();
  259. } while (match(TK(",")));
  260. consume(TK("]"));
  261. auto e = make_expr<ListExpr>(std::move(items));
  262. e->line = line; // override line
  263. ctx()->s_expr.push(std::move(e));
  264. }
  265. void Compiler::exprMap() {
  266. bool parsing_dict = false; // {...} may be dict or set
  267. std::vector<Expr_> items;
  268. do {
  269. match_newlines_repl();
  270. if (curr().type == TK("}")) break;
  271. EXPR();
  272. int star_level = ctx()->s_expr.top()->star_level();
  273. if(star_level==2 || curr().type == TK(":")){
  274. parsing_dict = true;
  275. }
  276. if(parsing_dict){
  277. auto dict_item = make_expr<DictItemExpr>();
  278. if(star_level == 2){
  279. dict_item->key = nullptr;
  280. dict_item->value = ctx()->s_expr.popx();
  281. }else{
  282. consume(TK(":"));
  283. EXPR();
  284. dict_item->key = ctx()->s_expr.popx();
  285. dict_item->value = ctx()->s_expr.popx();
  286. }
  287. items.push_back(std::move(dict_item));
  288. }else{
  289. items.push_back(ctx()->s_expr.popx());
  290. }
  291. match_newlines_repl();
  292. if(items.size()==1 && match(TK("for"))){
  293. if(parsing_dict) _consume_comp<DictCompExpr>(std::move(items[0]));
  294. else _consume_comp<SetCompExpr>(std::move(items[0]));
  295. consume(TK("}"));
  296. return;
  297. }
  298. match_newlines_repl();
  299. } while (match(TK(",")));
  300. consume(TK("}"));
  301. if(items.size()==0 || parsing_dict){
  302. auto e = make_expr<DictExpr>(std::move(items));
  303. ctx()->s_expr.push(std::move(e));
  304. }else{
  305. auto e = make_expr<SetExpr>(std::move(items));
  306. ctx()->s_expr.push(std::move(e));
  307. }
  308. }
  309. void Compiler::exprCall() {
  310. auto e = make_expr<CallExpr>();
  311. e->callable = ctx()->s_expr.popx();
  312. do {
  313. match_newlines_repl();
  314. if (curr().type==TK(")")) break;
  315. if(curr().type==TK("@id") && next().type==TK("=")) {
  316. consume(TK("@id"));
  317. Str key = prev().str();
  318. consume(TK("="));
  319. EXPR();
  320. e->kwargs.push_back({key, ctx()->s_expr.popx()});
  321. } else{
  322. EXPR();
  323. if(ctx()->s_expr.top()->star_level() == 2){
  324. // **kwargs
  325. e->kwargs.push_back({"**", ctx()->s_expr.popx()});
  326. }else{
  327. // positional argument
  328. if(!e->kwargs.empty()) SyntaxError("positional argument follows keyword argument");
  329. e->args.push_back(ctx()->s_expr.popx());
  330. }
  331. }
  332. match_newlines_repl();
  333. } while (match(TK(",")));
  334. consume(TK(")"));
  335. if(e->args.size() > 32767) SyntaxError("too many positional arguments");
  336. if(e->kwargs.size() > 32767) SyntaxError("too many keyword arguments");
  337. ctx()->s_expr.push(std::move(e));
  338. }
  339. void Compiler::exprName(){
  340. Str name = prev().str();
  341. NameScope scope = name_scope();
  342. if(ctx()->global_names.count(name)){
  343. scope = NAME_GLOBAL;
  344. }
  345. ctx()->s_expr.push(make_expr<NameExpr>(name, scope));
  346. }
  347. void Compiler::exprAttrib() {
  348. consume(TK("@id"));
  349. ctx()->s_expr.push(
  350. make_expr<AttribExpr>(ctx()->s_expr.popx(), prev().str())
  351. );
  352. }
  353. void Compiler::exprSubscr() {
  354. auto e = make_expr<SubscrExpr>();
  355. e->a = ctx()->s_expr.popx();
  356. auto slice = make_expr<SliceExpr>();
  357. bool is_slice = false;
  358. // a[<0> <state:1> : state<3> : state<5>]
  359. int state = 0;
  360. do{
  361. match_newlines_repl();
  362. switch(state){
  363. case 0:
  364. if(match(TK(":"))){
  365. is_slice=true;
  366. state=2;
  367. break;
  368. }
  369. if(match(TK("]"))) SyntaxError();
  370. EXPR_TUPLE();
  371. slice->start = ctx()->s_expr.popx();
  372. state=1;
  373. break;
  374. case 1:
  375. if(match(TK(":"))){
  376. is_slice=true;
  377. state=2;
  378. break;
  379. }
  380. if(match(TK("]"))) goto __SUBSCR_END;
  381. SyntaxError("expected ':' or ']'");
  382. break;
  383. case 2:
  384. if(match(TK(":"))){
  385. state=4;
  386. break;
  387. }
  388. if(match(TK("]"))) goto __SUBSCR_END;
  389. EXPR_TUPLE();
  390. slice->stop = ctx()->s_expr.popx();
  391. state=3;
  392. break;
  393. case 3:
  394. if(match(TK(":"))){
  395. state=4;
  396. break;
  397. }
  398. if(match(TK("]"))) goto __SUBSCR_END;
  399. SyntaxError("expected ':' or ']'");
  400. break;
  401. case 4:
  402. if(match(TK("]"))) goto __SUBSCR_END;
  403. EXPR_TUPLE();
  404. slice->step = ctx()->s_expr.popx();
  405. state=5;
  406. break;
  407. case 5: consume(TK("]")); goto __SUBSCR_END;
  408. }
  409. match_newlines_repl();
  410. }while(true);
  411. __SUBSCR_END:
  412. if(is_slice){
  413. e->b = std::move(slice);
  414. }else{
  415. if(state != 1) FATAL_ERROR();
  416. e->b = std::move(slice->start);
  417. }
  418. ctx()->s_expr.push(std::move(e));
  419. }
  420. void Compiler::exprLiteral0() {
  421. ctx()->s_expr.push(make_expr<Literal0Expr>(prev().type));
  422. }
  423. void Compiler::compile_block_body() {
  424. consume(TK(":"));
  425. if(curr().type!=TK("@eol") && curr().type!=TK("@eof")){
  426. compile_stmt(); // inline block
  427. return;
  428. }
  429. if(!match_newlines(mode()==REPL_MODE)){
  430. SyntaxError("expected a new line after ':'");
  431. }
  432. consume(TK("@indent"));
  433. while (curr().type != TK("@dedent")) {
  434. match_newlines();
  435. compile_stmt();
  436. match_newlines();
  437. }
  438. consume(TK("@dedent"));
  439. }
  440. // import a [as b]
  441. // import a [as b], c [as d]
  442. void Compiler::compile_normal_import() {
  443. if(name_scope() != NAME_GLOBAL) SyntaxError("import statement should be used in global scope");
  444. do {
  445. consume(TK("@id"));
  446. Str name = prev().str();
  447. ctx()->emit(OP_IMPORT_PATH, ctx()->add_const(VAR(name)), prev().line);
  448. if (match(TK("as"))) {
  449. consume(TK("@id"));
  450. name = prev().str();
  451. }
  452. ctx()->emit(OP_STORE_GLOBAL, StrName(name).index, prev().line);
  453. } while (match(TK(",")));
  454. consume_end_stmt();
  455. }
  456. // from a import b [as c], d [as e]
  457. // from a.b import c [as d]
  458. // from . import a [as b]
  459. // from .a import b [as c]
  460. // from ..a import b [as c]
  461. // from .a.b import c [as d]
  462. // from xxx import *
  463. void Compiler::compile_from_import() {
  464. if(name_scope() != NAME_GLOBAL) SyntaxError("import statement should be used in global scope");
  465. int dots = 0;
  466. while(true){
  467. switch(curr().type){
  468. case TK("."): dots+=1; break;
  469. case TK(".."): dots+=2; break;
  470. case TK("..."): dots+=3; break;
  471. default: goto __EAT_DOTS_END;
  472. }
  473. advance();
  474. }
  475. __EAT_DOTS_END:
  476. std::stringstream ss;
  477. for(int i=0; i<dots; i++) ss << '.';
  478. if(dots > 0){
  479. // @id is optional if dots > 0
  480. if(match(TK("@id"))){
  481. ss << prev().str();
  482. while (match(TK("."))) {
  483. consume(TK("@id"));
  484. ss << "." << prev().str();
  485. }
  486. }
  487. }else{
  488. // @id is required if dots == 0
  489. consume(TK("@id"));
  490. ss << prev().str();
  491. while (match(TK("."))) {
  492. consume(TK("@id"));
  493. ss << "." << prev().str();
  494. }
  495. }
  496. ctx()->emit(OP_IMPORT_PATH, ctx()->add_const(VAR(ss.str())), prev().line);
  497. consume(TK("import"));
  498. if (match(TK("*"))) {
  499. // pop the module and import __all__
  500. ctx()->emit(OP_POP_IMPORT_STAR, BC_NOARG, prev().line);
  501. consume_end_stmt();
  502. return;
  503. }
  504. do {
  505. ctx()->emit(OP_DUP_TOP, BC_NOARG, BC_KEEPLINE);
  506. consume(TK("@id"));
  507. Str name = prev().str();
  508. ctx()->emit(OP_LOAD_ATTR, StrName(name).index, prev().line);
  509. if (match(TK("as"))) {
  510. consume(TK("@id"));
  511. name = prev().str();
  512. }
  513. ctx()->emit(OP_STORE_GLOBAL, StrName(name).index, prev().line);
  514. } while (match(TK(",")));
  515. ctx()->emit(OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  516. consume_end_stmt();
  517. }
  518. bool Compiler::is_expression(){
  519. PrattCallback prefix = rules[curr().type].prefix;
  520. return prefix != nullptr;
  521. }
  522. void Compiler::parse_expression(int precedence, bool push_stack) {
  523. PrattCallback prefix = rules[curr().type].prefix;
  524. if (prefix == nullptr) SyntaxError(Str("expected an expression, got ") + TK_STR(curr().type));
  525. advance();
  526. (this->*prefix)();
  527. while (rules[curr().type].precedence >= precedence) {
  528. TokenIndex op = curr().type;
  529. advance();
  530. PrattCallback infix = rules[op].infix;
  531. PK_ASSERT(infix != nullptr);
  532. (this->*infix)();
  533. }
  534. if(!push_stack) ctx()->emit_expr();
  535. }
  536. void Compiler::compile_if_stmt() {
  537. EXPR(false); // condition
  538. int patch = ctx()->emit(OP_POP_JUMP_IF_FALSE, BC_NOARG, prev().line);
  539. compile_block_body();
  540. if (match(TK("elif"))) {
  541. int exit_patch = ctx()->emit(OP_JUMP_ABSOLUTE, BC_NOARG, prev().line);
  542. ctx()->patch_jump(patch);
  543. compile_if_stmt();
  544. ctx()->patch_jump(exit_patch);
  545. } else if (match(TK("else"))) {
  546. int exit_patch = ctx()->emit(OP_JUMP_ABSOLUTE, BC_NOARG, prev().line);
  547. ctx()->patch_jump(patch);
  548. compile_block_body();
  549. ctx()->patch_jump(exit_patch);
  550. } else {
  551. ctx()->patch_jump(patch);
  552. }
  553. }
  554. void Compiler::compile_while_loop() {
  555. CodeBlock* block = ctx()->enter_block(WHILE_LOOP);
  556. EXPR(false); // condition
  557. int patch = ctx()->emit(OP_POP_JUMP_IF_FALSE, BC_NOARG, prev().line);
  558. compile_block_body();
  559. ctx()->emit(OP_LOOP_CONTINUE, ctx()->get_loop(), BC_KEEPLINE);
  560. ctx()->patch_jump(patch);
  561. ctx()->exit_block();
  562. // optional else clause
  563. if (match(TK("else"))) {
  564. compile_block_body();
  565. block->end2 = ctx()->co->codes.size();
  566. }
  567. }
  568. void Compiler::compile_for_loop() {
  569. Expr_ vars = EXPR_VARS();
  570. consume(TK("in"));
  571. EXPR_TUPLE(false);
  572. ctx()->emit(OP_GET_ITER, BC_NOARG, BC_KEEPLINE);
  573. CodeBlock* block = ctx()->enter_block(FOR_LOOP);
  574. ctx()->emit(OP_FOR_ITER, BC_NOARG, BC_KEEPLINE);
  575. bool ok = vars->emit_store(ctx());
  576. if(!ok) SyntaxError(); // this error occurs in `vars` instead of this line, but...nevermind
  577. compile_block_body();
  578. ctx()->emit(OP_LOOP_CONTINUE, ctx()->get_loop(), BC_KEEPLINE);
  579. ctx()->exit_block();
  580. // optional else clause
  581. if (match(TK("else"))) {
  582. compile_block_body();
  583. block->end2 = ctx()->co->codes.size();
  584. }
  585. }
  586. void Compiler::compile_try_except() {
  587. ctx()->enter_block(TRY_EXCEPT);
  588. compile_block_body();
  589. std::vector<int> patches = {
  590. ctx()->emit(OP_JUMP_ABSOLUTE, BC_NOARG, BC_KEEPLINE)
  591. };
  592. ctx()->exit_block();
  593. do {
  594. consume(TK("except"));
  595. if(match(TK("@id"))){
  596. ctx()->emit(OP_EXCEPTION_MATCH, StrName(prev().str()).index, prev().line);
  597. }else{
  598. ctx()->emit(OP_LOAD_TRUE, BC_NOARG, BC_KEEPLINE);
  599. }
  600. int patch = ctx()->emit(OP_POP_JUMP_IF_FALSE, BC_NOARG, BC_KEEPLINE);
  601. // pop the exception on match
  602. ctx()->emit(OP_POP_EXCEPTION, BC_NOARG, BC_KEEPLINE);
  603. compile_block_body();
  604. patches.push_back(ctx()->emit(OP_JUMP_ABSOLUTE, BC_NOARG, BC_KEEPLINE));
  605. ctx()->patch_jump(patch);
  606. }while(curr().type == TK("except"));
  607. // no match, re-raise
  608. ctx()->emit(OP_RE_RAISE, BC_NOARG, BC_KEEPLINE);
  609. for (int patch : patches) ctx()->patch_jump(patch);
  610. }
  611. void Compiler::compile_decorated(){
  612. std::vector<Expr_> decorators;
  613. do{
  614. EXPR();
  615. decorators.push_back(ctx()->s_expr.popx());
  616. if(!match_newlines_repl()) SyntaxError();
  617. }while(match(TK("@")));
  618. consume(TK("def"));
  619. compile_function(decorators);
  620. }
  621. bool Compiler::try_compile_assignment(){
  622. switch (curr().type) {
  623. case TK("+="): case TK("-="): case TK("*="): case TK("/="): case TK("//="): case TK("%="):
  624. case TK("<<="): case TK(">>="): case TK("&="): case TK("|="): case TK("^="): {
  625. Expr* lhs_p = ctx()->s_expr.top().get();
  626. if(lhs_p->is_starred()) SyntaxError();
  627. if(ctx()->is_compiling_class) SyntaxError("can't use inplace operator in class definition");
  628. advance();
  629. auto e = make_expr<BinaryExpr>();
  630. e->op = prev().type - 1; // -1 to remove =
  631. e->lhs = ctx()->s_expr.popx();
  632. EXPR_TUPLE();
  633. e->rhs = ctx()->s_expr.popx();
  634. if(e->is_starred()) SyntaxError();
  635. e->emit(ctx());
  636. bool ok = lhs_p->emit_store(ctx());
  637. if(!ok) SyntaxError();
  638. } return true;
  639. case TK("="): {
  640. int n = 0;
  641. while(match(TK("="))){
  642. EXPR_TUPLE();
  643. Expr* _tp = ctx()->s_expr.top().get();
  644. if(ctx()->is_compiling_class && _tp->is_tuple()){
  645. SyntaxError("can't use unpack tuple in class definition");
  646. }
  647. n += 1;
  648. }
  649. if(ctx()->is_compiling_class && n>1){
  650. SyntaxError("can't assign to multiple targets in class definition");
  651. }
  652. // stack size is n+1
  653. Expr_ val = ctx()->s_expr.popx();
  654. val->emit(ctx());
  655. for(int j=1; j<n; j++) ctx()->emit(OP_DUP_TOP, BC_NOARG, BC_KEEPLINE);
  656. for(int j=0; j<n; j++){
  657. auto e = ctx()->s_expr.popx();
  658. if(e->is_starred()) SyntaxError();
  659. bool ok = e->emit_store(ctx());
  660. if(!ok) SyntaxError();
  661. }
  662. } return true;
  663. default: return false;
  664. }
  665. }
  666. void Compiler::compile_stmt() {
  667. advance();
  668. int kw_line = prev().line; // backup line number
  669. int curr_loop_block = ctx()->get_loop();
  670. switch(prev().type){
  671. case TK("break"):
  672. if (curr_loop_block < 0) SyntaxError("'break' outside loop");
  673. ctx()->emit(OP_LOOP_BREAK, curr_loop_block, kw_line);
  674. consume_end_stmt();
  675. break;
  676. case TK("continue"):
  677. if (curr_loop_block < 0) SyntaxError("'continue' not properly in loop");
  678. ctx()->emit(OP_LOOP_CONTINUE, curr_loop_block, kw_line);
  679. consume_end_stmt();
  680. break;
  681. case TK("yield"):
  682. if (contexts.size() <= 1) SyntaxError("'yield' outside function");
  683. EXPR_TUPLE(false);
  684. // if yield present, mark the function as generator
  685. ctx()->co->is_generator = true;
  686. ctx()->emit(OP_YIELD_VALUE, BC_NOARG, kw_line);
  687. consume_end_stmt();
  688. break;
  689. case TK("yield from"):
  690. if (contexts.size() <= 1) SyntaxError("'yield from' outside function");
  691. EXPR_TUPLE(false);
  692. // if yield from present, mark the function as generator
  693. ctx()->co->is_generator = true;
  694. ctx()->emit(OP_GET_ITER, BC_NOARG, kw_line);
  695. ctx()->enter_block(FOR_LOOP);
  696. ctx()->emit(OP_FOR_ITER, BC_NOARG, BC_KEEPLINE);
  697. ctx()->emit(OP_YIELD_VALUE, BC_NOARG, BC_KEEPLINE);
  698. ctx()->emit(OP_LOOP_CONTINUE, ctx()->get_loop(), BC_KEEPLINE);
  699. ctx()->exit_block();
  700. consume_end_stmt();
  701. break;
  702. case TK("return"):
  703. if (contexts.size() <= 1) SyntaxError("'return' outside function");
  704. if(match_end_stmt()){
  705. ctx()->emit(OP_LOAD_NONE, BC_NOARG, kw_line);
  706. }else{
  707. EXPR_TUPLE(false);
  708. consume_end_stmt();
  709. }
  710. ctx()->emit(OP_RETURN_VALUE, BC_NOARG, kw_line);
  711. break;
  712. /*************************************************/
  713. case TK("if"): compile_if_stmt(); break;
  714. case TK("while"): compile_while_loop(); break;
  715. case TK("for"): compile_for_loop(); break;
  716. case TK("import"): compile_normal_import(); break;
  717. case TK("from"): compile_from_import(); break;
  718. case TK("def"): compile_function(); break;
  719. case TK("@"): compile_decorated(); break;
  720. case TK("try"): compile_try_except(); break;
  721. case TK("pass"): consume_end_stmt(); break;
  722. /*************************************************/
  723. case TK("++"):{
  724. consume(TK("@id"));
  725. StrName name(prev().sv());
  726. switch(name_scope()){
  727. case NAME_LOCAL:
  728. ctx()->emit(OP_INC_FAST, ctx()->add_varname(name), prev().line);
  729. break;
  730. case NAME_GLOBAL:
  731. ctx()->emit(OP_INC_GLOBAL, name.index, prev().line);
  732. break;
  733. default: SyntaxError(); break;
  734. }
  735. consume_end_stmt();
  736. break;
  737. }
  738. case TK("--"):{
  739. consume(TK("@id"));
  740. StrName name(prev().sv());
  741. switch(name_scope()){
  742. case NAME_LOCAL:
  743. ctx()->emit(OP_DEC_FAST, ctx()->add_varname(name), prev().line);
  744. break;
  745. case NAME_GLOBAL:
  746. ctx()->emit(OP_DEC_GLOBAL, name.index, prev().line);
  747. break;
  748. default: SyntaxError(); break;
  749. }
  750. consume_end_stmt();
  751. break;
  752. }
  753. case TK("assert"):
  754. EXPR_TUPLE(false);
  755. ctx()->emit(OP_ASSERT, BC_NOARG, kw_line);
  756. consume_end_stmt();
  757. break;
  758. case TK("global"):
  759. do {
  760. consume(TK("@id"));
  761. ctx()->global_names.insert(prev().str());
  762. } while (match(TK(",")));
  763. consume_end_stmt();
  764. break;
  765. case TK("raise"): {
  766. consume(TK("@id"));
  767. int dummy_t = StrName(prev().str()).index;
  768. if(match(TK("(")) && !match(TK(")"))){
  769. EXPR(false); consume(TK(")"));
  770. }else{
  771. ctx()->emit(OP_LOAD_NONE, BC_NOARG, kw_line);
  772. }
  773. ctx()->emit(OP_RAISE, dummy_t, kw_line);
  774. consume_end_stmt();
  775. } break;
  776. case TK("del"): {
  777. EXPR_TUPLE();
  778. Expr_ e = ctx()->s_expr.popx();
  779. bool ok = e->emit_del(ctx());
  780. if(!ok) SyntaxError();
  781. consume_end_stmt();
  782. } break;
  783. case TK("with"): {
  784. EXPR(false);
  785. consume(TK("as"));
  786. consume(TK("@id"));
  787. Expr_ e = make_expr<NameExpr>(prev().str(), name_scope());
  788. bool ok = e->emit_store(ctx());
  789. if(!ok) SyntaxError();
  790. e->emit(ctx());
  791. ctx()->emit(OP_WITH_ENTER, BC_NOARG, prev().line);
  792. compile_block_body();
  793. e->emit(ctx());
  794. ctx()->emit(OP_WITH_EXIT, BC_NOARG, prev().line);
  795. } break;
  796. /*************************************************/
  797. case TK("=="): {
  798. consume(TK("@id"));
  799. if(mode()!=EXEC_MODE) SyntaxError("'label' is only available in EXEC_MODE");
  800. bool ok = ctx()->add_label(prev().str());
  801. consume(TK("=="));
  802. if(!ok) SyntaxError("label " + prev().str().escape() + " already exists");
  803. consume_end_stmt();
  804. } break;
  805. case TK("->"):
  806. consume(TK("@id"));
  807. if(mode()!=EXEC_MODE) SyntaxError("'goto' is only available in EXEC_MODE");
  808. ctx()->emit(OP_GOTO, StrName(prev().str()).index, prev().line);
  809. consume_end_stmt();
  810. break;
  811. /*************************************************/
  812. // handle dangling expression or assignment
  813. default: {
  814. advance(-1); // do revert since we have pre-called advance() at the beginning
  815. EXPR_TUPLE();
  816. bool is_typed_name = false; // e.g. x: int
  817. // eat variable's type hint if it is a single name
  818. if(ctx()->s_expr.top()->is_name()){
  819. if(match(TK(":"))){
  820. consume_type_hints();
  821. is_typed_name = true;
  822. }
  823. }
  824. if(!try_compile_assignment()){
  825. if(!ctx()->s_expr.empty() && ctx()->s_expr.top()->is_starred()){
  826. SyntaxError();
  827. }
  828. if(!is_typed_name){
  829. ctx()->emit_expr();
  830. if((mode()==CELL_MODE || mode()==REPL_MODE) && name_scope()==NAME_GLOBAL){
  831. ctx()->emit(OP_PRINT_EXPR, BC_NOARG, BC_KEEPLINE);
  832. }else{
  833. ctx()->emit(OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  834. }
  835. }else{
  836. PK_ASSERT(ctx()->s_expr.size() == 1)
  837. ctx()->s_expr.pop();
  838. }
  839. }
  840. consume_end_stmt();
  841. }
  842. }
  843. }
  844. void Compiler::consume_type_hints(){
  845. EXPR();
  846. ctx()->s_expr.pop();
  847. }
  848. void Compiler::compile_class(){
  849. consume(TK("@id"));
  850. int namei = StrName(prev().str()).index;
  851. Expr_ base = nullptr;
  852. if(match(TK("("))){
  853. if(is_expression()){
  854. EXPR();
  855. base = ctx()->s_expr.popx();
  856. }
  857. consume(TK(")"));
  858. }
  859. if(base == nullptr){
  860. ctx()->emit(OP_LOAD_NONE, BC_NOARG, prev().line);
  861. }else {
  862. base->emit(ctx());
  863. }
  864. ctx()->emit(OP_BEGIN_CLASS, namei, BC_KEEPLINE);
  865. ctx()->is_compiling_class = true;
  866. compile_block_body();
  867. ctx()->is_compiling_class = false;
  868. ctx()->emit(OP_END_CLASS, BC_NOARG, BC_KEEPLINE);
  869. }
  870. void Compiler::_compile_f_args(FuncDecl_ decl, bool enable_type_hints){
  871. int state = 0; // 0 for args, 1 for *args, 2 for k=v, 3 for **kwargs
  872. do {
  873. if(state > 3) SyntaxError();
  874. if(state == 3) SyntaxError("**kwargs should be the last argument");
  875. match_newlines();
  876. if(match(TK("*"))){
  877. if(state < 1) state = 1;
  878. else SyntaxError("*args should be placed before **kwargs");
  879. }
  880. else if(match(TK("**"))){
  881. state = 3;
  882. }
  883. consume(TK("@id"));
  884. StrName name = prev().str();
  885. // check duplicate argument name
  886. for(int j: decl->args){
  887. if(decl->code->varnames[j] == name) {
  888. SyntaxError("duplicate argument name");
  889. }
  890. }
  891. for(auto& kv: decl->kwargs){
  892. if(decl->code->varnames[kv.key] == name){
  893. SyntaxError("duplicate argument name");
  894. }
  895. }
  896. if(decl->starred_arg!=-1 && decl->code->varnames[decl->starred_arg] == name){
  897. SyntaxError("duplicate argument name");
  898. }
  899. if(decl->starred_kwarg!=-1 && decl->code->varnames[decl->starred_kwarg] == name){
  900. SyntaxError("duplicate argument name");
  901. }
  902. // eat type hints
  903. if(enable_type_hints && match(TK(":"))) consume_type_hints();
  904. if(state == 0 && curr().type == TK("=")) state = 2;
  905. int index = ctx()->add_varname(name);
  906. switch (state)
  907. {
  908. case 0:
  909. decl->args.push_back(index);
  910. break;
  911. case 1:
  912. decl->starred_arg = index;
  913. state+=1;
  914. break;
  915. case 2: {
  916. consume(TK("="));
  917. PyObject* value = read_literal();
  918. if(value == nullptr){
  919. SyntaxError(Str("default argument must be a literal"));
  920. }
  921. decl->kwargs.push_back(FuncDecl::KwArg{index, value});
  922. } break;
  923. case 3:
  924. decl->starred_kwarg = index;
  925. state+=1;
  926. break;
  927. }
  928. } while (match(TK(",")));
  929. }
  930. void Compiler::compile_function(const std::vector<Expr_>& decorators){
  931. const char* _start = curr().start;
  932. consume(TK("@id"));
  933. Str decl_name = prev().str();
  934. FuncDecl_ decl = push_f_context(decl_name);
  935. consume(TK("("));
  936. if (!match(TK(")"))) {
  937. _compile_f_args(decl, true);
  938. consume(TK(")"));
  939. }
  940. if(match(TK("->"))) consume_type_hints();
  941. const char* _end = curr().start;
  942. decl->signature = Str(_start, _end-_start);
  943. compile_block_body();
  944. pop_context();
  945. PyObject* docstring = nullptr;
  946. if(decl->code->codes.size()>=2 && decl->code->codes[0].op == OP_LOAD_CONST && decl->code->codes[1].op == OP_POP_TOP){
  947. PyObject* c = decl->code->consts[decl->code->codes[0].arg];
  948. if(is_type(c, vm->tp_str)){
  949. decl->code->codes[0].op = OP_NO_OP;
  950. decl->code->codes[1].op = OP_NO_OP;
  951. docstring = c;
  952. }
  953. }
  954. if(docstring != nullptr){
  955. decl->docstring = PK_OBJ_GET(Str, docstring);
  956. }
  957. ctx()->emit(OP_LOAD_FUNCTION, ctx()->add_func_decl(decl), prev().line);
  958. // add decorators
  959. for(auto it=decorators.rbegin(); it!=decorators.rend(); ++it){
  960. (*it)->emit(ctx());
  961. ctx()->emit(OP_ROT_TWO, BC_NOARG, (*it)->line);
  962. ctx()->emit(OP_LOAD_NULL, BC_NOARG, BC_KEEPLINE);
  963. ctx()->emit(OP_ROT_TWO, BC_NOARG, BC_KEEPLINE);
  964. ctx()->emit(OP_CALL, 1, (*it)->line);
  965. }
  966. if(!ctx()->is_compiling_class){
  967. auto e = make_expr<NameExpr>(decl_name, name_scope());
  968. e->emit_store(ctx());
  969. }else{
  970. int index = StrName(decl_name).index;
  971. ctx()->emit(OP_STORE_CLASS_ATTR, index, prev().line);
  972. }
  973. }
  974. PyObject* Compiler::to_object(const TokenValue& value){
  975. PyObject* obj = nullptr;
  976. if(std::holds_alternative<i64>(value)){
  977. obj = VAR(std::get<i64>(value));
  978. }
  979. if(std::holds_alternative<f64>(value)){
  980. obj = VAR(std::get<f64>(value));
  981. }
  982. if(std::holds_alternative<Str>(value)){
  983. obj = VAR(std::get<Str>(value));
  984. }
  985. if(obj == nullptr) FATAL_ERROR();
  986. return obj;
  987. }
  988. PyObject* Compiler::read_literal(){
  989. advance();
  990. switch(prev().type){
  991. case TK("-"): {
  992. consume(TK("@num"));
  993. PyObject* val = to_object(prev().value);
  994. return vm->py_negate(val);
  995. }
  996. case TK("@num"): return to_object(prev().value);
  997. case TK("@str"): return to_object(prev().value);
  998. case TK("True"): return VAR(true);
  999. case TK("False"): return VAR(false);
  1000. case TK("None"): return vm->None;
  1001. case TK("..."): return vm->Ellipsis;
  1002. default: break;
  1003. }
  1004. return nullptr;
  1005. }
  1006. Compiler::Compiler(VM* vm, const Str& source, const Str& filename, CompileMode mode, bool unknown_global_scope){
  1007. this->vm = vm;
  1008. this->used = false;
  1009. this->unknown_global_scope = unknown_global_scope;
  1010. this->lexer = std::make_unique<Lexer>(
  1011. std::make_shared<SourceData>(source, filename, mode)
  1012. );
  1013. init_pratt_rules();
  1014. }
  1015. CodeObject_ Compiler::compile(){
  1016. if(used) FATAL_ERROR();
  1017. used = true;
  1018. tokens = lexer->run();
  1019. // if(lexer->src->filename == "<stdin>"){
  1020. // for(auto& t: tokens) std::cout << t.info() << std::endl;
  1021. // }
  1022. CodeObject_ code = push_global_context();
  1023. advance(); // skip @sof, so prev() is always valid
  1024. match_newlines(); // skip possible leading '\n'
  1025. if(mode()==EVAL_MODE) {
  1026. EXPR_TUPLE(false);
  1027. consume(TK("@eof"));
  1028. ctx()->emit(OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  1029. pop_context();
  1030. return code;
  1031. }else if(mode()==JSON_MODE){
  1032. EXPR();
  1033. Expr_ e = ctx()->s_expr.popx();
  1034. if(!e->is_json_object()) SyntaxError("expect a JSON object, literal or array");
  1035. consume(TK("@eof"));
  1036. e->emit(ctx());
  1037. ctx()->emit(OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  1038. pop_context();
  1039. return code;
  1040. }
  1041. while (!match(TK("@eof"))) {
  1042. if (match(TK("class"))) {
  1043. compile_class();
  1044. } else {
  1045. compile_stmt();
  1046. }
  1047. match_newlines();
  1048. }
  1049. pop_context();
  1050. return code;
  1051. }
  1052. } // namespace pkpy