compiler.cpp 43 KB

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