compiler.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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. NameScope scope = name_scope();
  727. bool is_global = ctx()->global_names.count(name.sv());
  728. if(is_global) scope = NAME_GLOBAL;
  729. switch(scope){
  730. case NAME_LOCAL:
  731. ctx()->emit(OP_INC_FAST, ctx()->add_varname(name), prev().line);
  732. break;
  733. case NAME_GLOBAL:
  734. ctx()->emit(OP_INC_GLOBAL, name.index, prev().line);
  735. break;
  736. default: SyntaxError(); break;
  737. }
  738. consume_end_stmt();
  739. break;
  740. }
  741. case TK("--"):{
  742. consume(TK("@id"));
  743. StrName name(prev().sv());
  744. switch(name_scope()){
  745. case NAME_LOCAL:
  746. ctx()->emit(OP_DEC_FAST, ctx()->add_varname(name), prev().line);
  747. break;
  748. case NAME_GLOBAL:
  749. ctx()->emit(OP_DEC_GLOBAL, name.index, prev().line);
  750. break;
  751. default: SyntaxError(); break;
  752. }
  753. consume_end_stmt();
  754. break;
  755. }
  756. case TK("assert"):{
  757. EXPR(false); // condition
  758. int index = ctx()->emit(OP_POP_JUMP_IF_TRUE, BC_NOARG, kw_line);
  759. int has_msg = 0;
  760. if(match(TK(","))){
  761. EXPR(false); // message
  762. has_msg = 1;
  763. }
  764. ctx()->emit(OP_RAISE_ASSERT, has_msg, kw_line);
  765. ctx()->patch_jump(index);
  766. consume_end_stmt();
  767. break;
  768. }
  769. case TK("global"):
  770. do {
  771. consume(TK("@id"));
  772. ctx()->global_names.insert(prev().str());
  773. } while (match(TK(",")));
  774. consume_end_stmt();
  775. break;
  776. case TK("raise"): {
  777. consume(TK("@id"));
  778. int dummy_t = StrName(prev().str()).index;
  779. if(match(TK("(")) && !match(TK(")"))){
  780. EXPR(false); consume(TK(")"));
  781. }else{
  782. ctx()->emit(OP_LOAD_NONE, BC_NOARG, kw_line);
  783. }
  784. ctx()->emit(OP_RAISE, dummy_t, kw_line);
  785. consume_end_stmt();
  786. } break;
  787. case TK("del"): {
  788. EXPR_TUPLE();
  789. Expr_ e = ctx()->s_expr.popx();
  790. bool ok = e->emit_del(ctx());
  791. if(!ok) SyntaxError();
  792. consume_end_stmt();
  793. } break;
  794. case TK("with"): {
  795. EXPR(false);
  796. consume(TK("as"));
  797. consume(TK("@id"));
  798. Expr_ e = make_expr<NameExpr>(prev().str(), name_scope());
  799. bool ok = e->emit_store(ctx());
  800. if(!ok) SyntaxError();
  801. e->emit(ctx());
  802. ctx()->emit(OP_WITH_ENTER, BC_NOARG, prev().line);
  803. compile_block_body();
  804. e->emit(ctx());
  805. ctx()->emit(OP_WITH_EXIT, BC_NOARG, prev().line);
  806. } break;
  807. /*************************************************/
  808. case TK("=="): {
  809. consume(TK("@id"));
  810. if(mode()!=EXEC_MODE) SyntaxError("'label' is only available in EXEC_MODE");
  811. bool ok = ctx()->add_label(prev().str());
  812. consume(TK("=="));
  813. if(!ok) SyntaxError("label " + prev().str().escape() + " already exists");
  814. consume_end_stmt();
  815. } break;
  816. case TK("->"):
  817. consume(TK("@id"));
  818. if(mode()!=EXEC_MODE) SyntaxError("'goto' is only available in EXEC_MODE");
  819. ctx()->emit(OP_GOTO, StrName(prev().str()).index, prev().line);
  820. consume_end_stmt();
  821. break;
  822. /*************************************************/
  823. // handle dangling expression or assignment
  824. default: {
  825. advance(-1); // do revert since we have pre-called advance() at the beginning
  826. EXPR_TUPLE();
  827. bool is_typed_name = false; // e.g. x: int
  828. // eat variable's type hint if it is a single name
  829. if(ctx()->s_expr.top()->is_name()){
  830. if(match(TK(":"))){
  831. consume_type_hints();
  832. is_typed_name = true;
  833. }
  834. }
  835. if(!try_compile_assignment()){
  836. if(!ctx()->s_expr.empty() && ctx()->s_expr.top()->is_starred()){
  837. SyntaxError();
  838. }
  839. if(!is_typed_name){
  840. ctx()->emit_expr();
  841. if((mode()==CELL_MODE || mode()==REPL_MODE) && name_scope()==NAME_GLOBAL){
  842. ctx()->emit(OP_PRINT_EXPR, BC_NOARG, BC_KEEPLINE);
  843. }else{
  844. ctx()->emit(OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  845. }
  846. }else{
  847. PK_ASSERT(ctx()->s_expr.size() == 1)
  848. ctx()->s_expr.pop();
  849. }
  850. }
  851. consume_end_stmt();
  852. }
  853. }
  854. }
  855. void Compiler::consume_type_hints(){
  856. EXPR();
  857. ctx()->s_expr.pop();
  858. }
  859. void Compiler::compile_class(){
  860. consume(TK("@id"));
  861. int namei = StrName(prev().str()).index;
  862. Expr_ base = nullptr;
  863. if(match(TK("("))){
  864. if(is_expression()){
  865. EXPR();
  866. base = ctx()->s_expr.popx();
  867. }
  868. consume(TK(")"));
  869. }
  870. if(base == nullptr){
  871. ctx()->emit(OP_LOAD_NONE, BC_NOARG, prev().line);
  872. }else {
  873. base->emit(ctx());
  874. }
  875. ctx()->emit(OP_BEGIN_CLASS, namei, BC_KEEPLINE);
  876. ctx()->is_compiling_class = true;
  877. compile_block_body();
  878. ctx()->is_compiling_class = false;
  879. ctx()->emit(OP_END_CLASS, BC_NOARG, BC_KEEPLINE);
  880. }
  881. void Compiler::_compile_f_args(FuncDecl_ decl, bool enable_type_hints){
  882. int state = 0; // 0 for args, 1 for *args, 2 for k=v, 3 for **kwargs
  883. do {
  884. if(state > 3) SyntaxError();
  885. if(state == 3) SyntaxError("**kwargs should be the last argument");
  886. match_newlines();
  887. if(match(TK("*"))){
  888. if(state < 1) state = 1;
  889. else SyntaxError("*args should be placed before **kwargs");
  890. }
  891. else if(match(TK("**"))){
  892. state = 3;
  893. }
  894. consume(TK("@id"));
  895. StrName name = prev().str();
  896. // check duplicate argument name
  897. for(int j: decl->args){
  898. if(decl->code->varnames[j] == name) {
  899. SyntaxError("duplicate argument name");
  900. }
  901. }
  902. for(auto& kv: decl->kwargs){
  903. if(decl->code->varnames[kv.key] == name){
  904. SyntaxError("duplicate argument name");
  905. }
  906. }
  907. if(decl->starred_arg!=-1 && decl->code->varnames[decl->starred_arg] == name){
  908. SyntaxError("duplicate argument name");
  909. }
  910. if(decl->starred_kwarg!=-1 && decl->code->varnames[decl->starred_kwarg] == name){
  911. SyntaxError("duplicate argument name");
  912. }
  913. // eat type hints
  914. if(enable_type_hints && match(TK(":"))) consume_type_hints();
  915. if(state == 0 && curr().type == TK("=")) state = 2;
  916. int index = ctx()->add_varname(name);
  917. switch (state)
  918. {
  919. case 0:
  920. decl->args.push_back(index);
  921. break;
  922. case 1:
  923. decl->starred_arg = index;
  924. state+=1;
  925. break;
  926. case 2: {
  927. consume(TK("="));
  928. PyObject* value = read_literal();
  929. if(value == nullptr){
  930. SyntaxError(Str("default argument must be a literal"));
  931. }
  932. decl->kwargs.push_back(FuncDecl::KwArg{index, value});
  933. } break;
  934. case 3:
  935. decl->starred_kwarg = index;
  936. state+=1;
  937. break;
  938. }
  939. } while (match(TK(",")));
  940. }
  941. void Compiler::compile_function(const std::vector<Expr_>& decorators){
  942. const char* _start = curr().start;
  943. consume(TK("@id"));
  944. Str decl_name = prev().str();
  945. FuncDecl_ decl = push_f_context(decl_name);
  946. consume(TK("("));
  947. if (!match(TK(")"))) {
  948. _compile_f_args(decl, true);
  949. consume(TK(")"));
  950. }
  951. if(match(TK("->"))) consume_type_hints();
  952. const char* _end = curr().start;
  953. decl->signature = Str(_start, _end-_start);
  954. compile_block_body();
  955. pop_context();
  956. PyObject* docstring = nullptr;
  957. if(decl->code->codes.size()>=2 && decl->code->codes[0].op == OP_LOAD_CONST && decl->code->codes[1].op == OP_POP_TOP){
  958. PyObject* c = decl->code->consts[decl->code->codes[0].arg];
  959. if(is_type(c, vm->tp_str)){
  960. decl->code->codes[0].op = OP_NO_OP;
  961. decl->code->codes[1].op = OP_NO_OP;
  962. docstring = c;
  963. }
  964. }
  965. if(docstring != nullptr){
  966. decl->docstring = PK_OBJ_GET(Str, docstring);
  967. }
  968. ctx()->emit(OP_LOAD_FUNCTION, ctx()->add_func_decl(decl), prev().line);
  969. // add decorators
  970. for(auto it=decorators.rbegin(); it!=decorators.rend(); ++it){
  971. (*it)->emit(ctx());
  972. ctx()->emit(OP_ROT_TWO, BC_NOARG, (*it)->line);
  973. ctx()->emit(OP_LOAD_NULL, BC_NOARG, BC_KEEPLINE);
  974. ctx()->emit(OP_ROT_TWO, BC_NOARG, BC_KEEPLINE);
  975. ctx()->emit(OP_CALL, 1, (*it)->line);
  976. }
  977. if(!ctx()->is_compiling_class){
  978. auto e = make_expr<NameExpr>(decl_name, name_scope());
  979. e->emit_store(ctx());
  980. }else{
  981. int index = StrName(decl_name).index;
  982. ctx()->emit(OP_STORE_CLASS_ATTR, index, prev().line);
  983. }
  984. }
  985. PyObject* Compiler::to_object(const TokenValue& value){
  986. PyObject* obj = nullptr;
  987. if(std::holds_alternative<i64>(value)){
  988. obj = VAR(std::get<i64>(value));
  989. }
  990. if(std::holds_alternative<f64>(value)){
  991. obj = VAR(std::get<f64>(value));
  992. }
  993. if(std::holds_alternative<Str>(value)){
  994. obj = VAR(std::get<Str>(value));
  995. }
  996. if(obj == nullptr) FATAL_ERROR();
  997. return obj;
  998. }
  999. PyObject* Compiler::read_literal(){
  1000. advance();
  1001. switch(prev().type){
  1002. case TK("-"): {
  1003. consume(TK("@num"));
  1004. PyObject* val = to_object(prev().value);
  1005. return vm->py_negate(val);
  1006. }
  1007. case TK("@num"): return to_object(prev().value);
  1008. case TK("@str"): return to_object(prev().value);
  1009. case TK("True"): return VAR(true);
  1010. case TK("False"): return VAR(false);
  1011. case TK("None"): return vm->None;
  1012. case TK("..."): return vm->Ellipsis;
  1013. default: break;
  1014. }
  1015. return nullptr;
  1016. }
  1017. Compiler::Compiler(VM* vm, const Str& source, const Str& filename, CompileMode mode, bool unknown_global_scope){
  1018. this->vm = vm;
  1019. this->used = false;
  1020. this->unknown_global_scope = unknown_global_scope;
  1021. this->lexer = std::make_unique<Lexer>(
  1022. std::make_shared<SourceData>(source, filename, mode)
  1023. );
  1024. init_pratt_rules();
  1025. }
  1026. CodeObject_ Compiler::compile(){
  1027. if(used) FATAL_ERROR();
  1028. used = true;
  1029. tokens = lexer->run();
  1030. // if(lexer->src->filename == "<stdin>"){
  1031. // for(auto& t: tokens) std::cout << t.info() << std::endl;
  1032. // }
  1033. CodeObject_ code = push_global_context();
  1034. advance(); // skip @sof, so prev() is always valid
  1035. match_newlines(); // skip possible leading '\n'
  1036. if(mode()==EVAL_MODE) {
  1037. EXPR_TUPLE(false);
  1038. consume(TK("@eof"));
  1039. ctx()->emit(OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  1040. pop_context();
  1041. return code;
  1042. }else if(mode()==JSON_MODE){
  1043. EXPR();
  1044. Expr_ e = ctx()->s_expr.popx();
  1045. if(!e->is_json_object()) SyntaxError("expect a JSON object, literal or array");
  1046. consume(TK("@eof"));
  1047. e->emit(ctx());
  1048. ctx()->emit(OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  1049. pop_context();
  1050. return code;
  1051. }
  1052. while (!match(TK("@eof"))) {
  1053. if (match(TK("class"))) {
  1054. compile_class();
  1055. } else {
  1056. compile_stmt();
  1057. }
  1058. match_newlines();
  1059. }
  1060. pop_context();
  1061. return code;
  1062. }
  1063. } // namespace pkpy