gravity_codegen.c 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918
  1. //
  2. // gravity_codegen.c
  3. // gravity
  4. //
  5. // Created by Marco Bambini on 09/10/14.
  6. // Copyright (c) 2014 CreoLabs. All rights reserved.
  7. //
  8. #include "gravity_codegen.h"
  9. #include "gravity_symboltable.h"
  10. #include "gravity_optimizer.h"
  11. #include "gravity_visitor.h"
  12. #include "gravity_ircode.h"
  13. #include "gravity_utils.h"
  14. #include "gravity_array.h"
  15. #include "gravity_hash.h"
  16. typedef marray_t(gnode_class_decl_t *) gnode_class_r;
  17. struct codegen_t {
  18. gravity_object_r context;
  19. gnode_class_r superfix;
  20. gravity_vm *vm;
  21. };
  22. typedef struct codegen_t codegen_t;
  23. #define CONTEXT_PUSH(x) marray_push(gravity_object_t*, ((codegen_t *)self->data)->context, (gravity_object_t*)x)
  24. #define CONTEXT_POP() marray_pop(((codegen_t *)self->data)->context)
  25. #define CONTEXT_GET() marray_last(((codegen_t *)self->data)->context)
  26. #define CONTEXT_IS_MODULE(x) ((OBJECT_ISA_FUNCTION(x)) && (string_cmp(((gravity_function_t *)x)->identifier, INITMODULE_NAME) == 0))
  27. #define DECLARE_CONTEXT() gravity_object_t *context_object = CONTEXT_GET();
  28. #define DECLARE_FUNCTION_CONTEXT() DECLARE_CONTEXT(); \
  29. if (!context_object || !(OBJECT_ISA_FUNCTION(context_object))) { \
  30. report_error(self, (gnode_t *)node, "Invalid code context."); return;} \
  31. gravity_function_t *context_function = (gravity_function_t *)context_object;
  32. #define DECLARE_CLASS_CONTEXT() DECLARE_CONTEXT(); \
  33. assert(OBJECT_ISA_CLASS(context_object)); \
  34. gravity_class_t *context_class = (gravity_class_t *)context_object;
  35. #define DECLARE_CODE() DECLARE_FUNCTION_CONTEXT(); \
  36. ircode_t *code = (ircode_t *)context_function->bytecode;
  37. #define IS_IMPLICIT_SELF(_expr) (NODE_ISA(_expr, NODE_IDENTIFIER_EXPR) && \
  38. (((gnode_identifier_expr_t *)_expr)->location.type == LOCATION_CLASS_IVAR_SAME) && \
  39. (((gnode_identifier_expr_t *)_expr)->location.nup == 0) && \
  40. (((gnode_identifier_expr_t *)_expr)->location.index == UINT16_MAX))
  41. #define IS_SUPER(_expr) (NODE_ISA(_expr, NODE_KEYWORD_EXPR) && (((gnode_keyword_expr_t *)_expr)->base.token.type == TOK_KEY_SUPER))
  42. #define GET_VM() ((codegen_t *)self->data)->vm
  43. #define IS_LAST_LOOP(n1,n2) (n1+1==n2)
  44. #if 0
  45. #define CODEGEN_COUNT_REGISTERS(_n) uint32_t _n = ircode_register_count(code)
  46. #define CODEGEN_ASSERT_REGISTERS(_n1,_n2,_v) assert(_n2 -_n1 == (_v))
  47. #else
  48. #define CODEGEN_COUNT_REGISTERS(_n)
  49. #define CODEGEN_ASSERT_REGISTERS(_n1,_n2,_v)
  50. #endif
  51. // MARK: -
  52. static void report_error (gvisitor_t *self, gnode_t *node, const char *format, ...) {
  53. // increment internal error counter
  54. ++self->nerr;
  55. // get error callback (if any)
  56. void *data = (self->delegate) ? ((gravity_delegate_t *)self->delegate)->xdata : NULL;
  57. gravity_error_callback error_fn = (self->delegate) ? ((gravity_delegate_t *)self->delegate)->error_callback : NULL;
  58. // build error message
  59. char buffer[1024];
  60. va_list arg;
  61. if (format) {
  62. va_start (arg, format);
  63. vsnprintf(buffer, sizeof(buffer), format, arg);
  64. va_end (arg);
  65. }
  66. // setup error struct
  67. error_desc_t error_desc = {
  68. .lineno = (node) ? node->token.lineno : 0,
  69. .colno = (node) ? node->token.colno : 0,
  70. .fileid = (node) ? node->token.fileid : 0,
  71. .offset = (node) ? node->token.position : 0,
  72. .meta = meta_from_node(node)
  73. };
  74. // finally call error callback
  75. if (error_fn) error_fn(GRAVITY_ERROR_SEMANTIC, buffer, error_desc, data);
  76. else printf("%s\n", buffer);
  77. }
  78. // MARK: -
  79. static opcode_t token2opcode (gtoken_t op) {
  80. switch (op) {
  81. // BIT
  82. case TOK_OP_SHIFT_LEFT: return LSHIFT;
  83. case TOK_OP_SHIFT_RIGHT: return RSHIFT;
  84. case TOK_OP_BIT_NOT: return BNOT;
  85. case TOK_OP_BIT_AND: return BAND;
  86. case TOK_OP_BIT_OR: return BOR;
  87. case TOK_OP_BIT_XOR: return BXOR;
  88. // MATH
  89. case TOK_OP_ADD: return ADD;
  90. case TOK_OP_SUB: return SUB;
  91. case TOK_OP_DIV: return DIV;
  92. case TOK_OP_MUL: return MUL;
  93. case TOK_OP_REM: return REM;
  94. // NEG not handled here
  95. // COMPARISON
  96. case TOK_KEY_ISA: return ISA;
  97. case TOK_OP_LESS: return LT;
  98. case TOK_OP_GREATER: return GT;
  99. case TOK_OP_LESS_EQUAL: return LEQ;
  100. case TOK_OP_GREATER_EQUAL: return GEQ;
  101. case TOK_OP_ISEQUAL: return EQ;
  102. case TOK_OP_ISNOTEQUAL: return NEQ;
  103. case TOK_OP_ISIDENTICAL: return EQQ;
  104. case TOK_OP_ISNOTIDENTICAL: return NEQQ;
  105. case TOK_OP_PATTERN_MATCH: return MATCH;
  106. // LOGICAL
  107. case TOK_OP_AND: return AND;
  108. case TOK_OP_NOT: return NOT;
  109. case TOK_OP_OR: return OR;
  110. default: assert(0); break; // should never reach this point
  111. }
  112. // should never reach this point
  113. assert(0);
  114. return NOT;
  115. }
  116. #if 0
  117. static gravity_value_t literal2value (gnode_literal_expr_t *node) {
  118. if (node->type == LITERAL_STRING) return VALUE_FROM_STRING(NULL, node->value.str, node->len);
  119. if (node->type == LITERAL_FLOAT) return VALUE_FROM_FLOAT(node->value.d);
  120. if (node->type == LITERAL_INT) return VALUE_FROM_INT(node->value.n64);
  121. return VALUE_FROM_INT(node->value.n64); // default BOOLEAN case
  122. }
  123. static gravity_list_t *literals2list (gvisitor_t *self, gnode_r *r, uint32_t start, uint32_t stop) {
  124. gravity_list_t *list = gravity_list_new(GET_VM(), stop-start);
  125. for (uint32_t i=start; i<stop; ++i) {
  126. gnode_literal_expr_t *node = (gnode_literal_expr_t *)marray_get(*r, i);
  127. gravity_value_t value = literal2value(node);
  128. marray_push(gravity_value_t, list->array, value);
  129. }
  130. return list;
  131. }
  132. static gravity_map_t *literals2map (gvisitor_t *self, gnode_r *r1, gnode_r *r2, uint32_t start, uint32_t stop) {
  133. gravity_map_t *map = gravity_map_new(GET_VM(), stop-start);
  134. for (uint32_t i=start; i<stop; ++i) {
  135. gnode_literal_expr_t *_key = (gnode_literal_expr_t *)marray_get(*r1, i);
  136. gnode_literal_expr_t *_value = (gnode_literal_expr_t *)marray_get(*r2, i);
  137. // when here I am sure that both key and value are literals
  138. // so they can be LITERAL_STRING, LITERAL_FLOAT, LITERAL_INT, LITERAL_BOOL
  139. gravity_value_t key = literal2value(_key);
  140. gravity_value_t value = literal2value(_value);
  141. gravity_map_insert(NULL, map, key, value);
  142. }
  143. return map;
  144. }
  145. static gravity_map_t *enum2map (gvisitor_t *self, gnode_enum_decl_t *node) {
  146. uint32_t count = symboltable_count(node->symtable, 0);
  147. gravity_map_t *map = gravity_map_new(GET_VM(), count);
  148. // FixMe
  149. return map;
  150. }
  151. static bool check_literals_list (gvisitor_t *self, gnode_list_expr_t *node, bool ismap, size_t idxstart, size_t idxend, uint32_t dest) {
  152. DEBUG_CODEGEN("check_literal_list_expr");
  153. DECLARE_CODE();
  154. // first check if all nodes inside this chuck are all literals
  155. // and in this case apply a more efficient SETLIST variant
  156. for (size_t j=idxstart; j < idxend; ++j) {
  157. gnode_t *e = gnode_array_get(node->list1, j);
  158. if (!gnode_is_literal(e)) return false;
  159. if (ismap) {
  160. // additional check on key that must be a string literal in case of a map
  161. if (!gnode_is_literal_string(e)) return false;
  162. e = gnode_array_get(node->list2, j);
  163. if (!gnode_is_literal(e)) return false;
  164. }
  165. }
  166. // emit optimized (cpoll based) version
  167. gravity_value_t v;
  168. if (ismap) {
  169. gravity_map_t *map = literals2map(self, node->list1, node->list2, (uint32_t)idxstart, (uint32_t)idxend);
  170. v = VALUE_FROM_OBJECT(map);
  171. } else {
  172. gravity_list_t *list = literals2list(self, node->list1, (uint32_t)idxstart, (uint32_t)idxend);
  173. v = VALUE_FROM_OBJECT(list);
  174. }
  175. uint16_t index = gravity_function_cpool_add(GET_VM(), context_function, v);
  176. ircode_add(code, SETLIST, dest, 0, index);
  177. return true;
  178. }
  179. #endif
  180. static uint32_t node2index (gnode_t * node) {
  181. // node can be a VARIABLE declaration or a local IDENTIFIER
  182. if (NODE_ISA(node, NODE_VARIABLE_DECL)) {
  183. gnode_variable_decl_t *expr = (gnode_variable_decl_t *)node;
  184. assert(gnode_array_size(expr->decls) == 1);
  185. gnode_var_t *var = (gnode_var_t *)gnode_array_get(expr->decls, 0);
  186. return var->index;
  187. }
  188. if (NODE_ISA(node, NODE_IDENTIFIER_EXPR)) {
  189. gnode_identifier_expr_t *expr = (gnode_identifier_expr_t *)node;
  190. assert(expr->location.type == LOCATION_LOCAL);
  191. return expr->location.index;
  192. }
  193. // should never reach this point because semacheck2 should take care of the check
  194. assert(0);
  195. return UINT32_MAX;
  196. }
  197. static void fix_superclasses (gvisitor_t *self) {
  198. // this function cannot fail because superclasses was already checked in samecheck2 so I am sure that they exist somewhere
  199. codegen_t *data = (codegen_t *)self->data;
  200. gnode_class_r *superfix = &data->superfix;
  201. size_t count = gnode_array_size(superfix);
  202. for (size_t i=0; i<count; ++i) {
  203. gnode_class_decl_t *node = (gnode_class_decl_t *)gnode_array_get(superfix, i);
  204. gnode_class_decl_t *super = (gnode_class_decl_t *)node->superclass;
  205. gravity_class_t *c = (gravity_class_t *)node->data;
  206. gravity_class_setsuper(c, (gravity_class_t *)super->data);
  207. }
  208. }
  209. // this function can be called ONLY from visit_postfix_expr where a context has been pushed
  210. static uint32_t compute_self_register (gvisitor_t *self, ircode_t *code, gnode_t *node, uint32_t target_register, gnode_r *list) {
  211. DEBUG_CODEGEN("compute_self_register");
  212. // check for special implicit self slot
  213. if (IS_IMPLICIT_SELF(node)) return 0;
  214. // check for super keyword
  215. if (IS_SUPER(node)) return 0;
  216. // examine next node in list
  217. gnode_postfix_subexpr_t *next = (gnode_array_size(list) > 0) ? (gnode_postfix_subexpr_t *)gnode_array_get(list, 0) : NULL;
  218. bool next_is_access = (next && next->base.tag == NODE_ACCESS_EXPR);
  219. // if node refers to an outer class then load outer class from hidden _outer ivar and return its register
  220. if ((NODE_ISA(node, NODE_IDENTIFIER_EXPR) && ((gnode_identifier_expr_t *)node)->location.type == LOCATION_CLASS_IVAR_OUTER) && !next_is_access) {
  221. gnode_identifier_expr_t *expr = (gnode_identifier_expr_t *)node;
  222. uint32_t dest = ircode_register_push_temp(code);
  223. uint32_t target = 0;
  224. for (uint16_t i=0; i<expr->location.nup; ++i) {
  225. ircode_add(code, LOAD, dest, target, 0 + MAX_REGISTERS);
  226. target = dest;
  227. }
  228. uint32_t reg = ircode_register_pop_context_protect(code, true);
  229. if (reg == REGISTER_ERROR) {
  230. report_error(self, node, "Unexpected register error.");
  231. return UINT32_MAX;
  232. }
  233. return reg;
  234. }
  235. // no special register found, so just return the target
  236. return target_register;
  237. }
  238. // MARK: - Statements -
  239. static void visit_list_stmt (gvisitor_t *self, gnode_compound_stmt_t *node) {
  240. DEBUG_CODEGEN("visit_list_stmt");
  241. gnode_array_each(node->stmts, {visit(val);});
  242. }
  243. static void visit_compound_stmt (gvisitor_t *self, gnode_compound_stmt_t *node) {
  244. DEBUG_CODEGEN("visit_compound_stmt");
  245. gnode_array_each(node->stmts, {
  246. visit(val);
  247. // check if context is a function
  248. DECLARE_CONTEXT();
  249. bool is_func_ctx = OBJECT_ISA_FUNCTION(context_object);
  250. if (!is_func_ctx) continue;
  251. // in case of function context cleanup temporary registers
  252. gravity_function_t *f = (gravity_function_t*)context_object;
  253. ircode_t *code = (ircode_t *)f->bytecode;
  254. ircode_register_clear_temps(code);
  255. });
  256. if (node->nclose != UINT32_MAX) {
  257. DECLARE_CODE();
  258. ircode_add(code, CLOSE, node->nclose, 0, 0);
  259. }
  260. }
  261. static void visit_label_stmt (gvisitor_t *self, gnode_label_stmt_t *node) {
  262. DEBUG_CODEGEN("visit_label_stmt");
  263. gtoken_t type = NODE_TOKEN_TYPE(node);
  264. assert((type == TOK_KEY_DEFAULT) || (type == TOK_KEY_CASE));
  265. if (type == TOK_KEY_DEFAULT) {visit(node->stmt);}
  266. else if (type == TOK_KEY_CASE) {visit(node->expr); visit(node->stmt);}
  267. }
  268. static void visit_flow_if_stmt (gvisitor_t *self, gnode_flow_stmt_t *node) {
  269. DEBUG_CODEGEN("visit_flow_if_stmt");
  270. DECLARE_CODE();
  271. /*
  272. <condition>
  273. if-false: goto $end
  274. <then-part>
  275. goto $true
  276. $end:
  277. <else-part>
  278. $true:
  279. TRUE := getLabel
  280. FALSE := getLabel
  281. compile condition
  282. emit ifeq FALSE
  283. compile stm1
  284. emit goto TRUE
  285. emit FALSE
  286. compile stm2
  287. emit TRUE
  288. */
  289. uint32_t labelTrue = ircode_newlabel(code);
  290. uint32_t labelFalse = ircode_newlabel(code);
  291. visit(node->cond);
  292. uint32_t reg = ircode_register_pop(code);
  293. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid if condition expression.");
  294. ircode_add(code, JUMPF, reg, labelFalse, 0);
  295. visit(node->stmt);
  296. if (node->elsestmt) ircode_add(code, JUMP, labelTrue, 0, 0);
  297. ircode_marklabel(code, labelFalse);
  298. if (node->elsestmt) {
  299. visit(node->elsestmt);
  300. ircode_marklabel(code, labelTrue);
  301. }
  302. }
  303. static void visit_flow_switch_stmt (gvisitor_t *self, gnode_flow_stmt_t *node) {
  304. DEBUG_CODEGEN("visit_flow_switch_stmt");
  305. return;
  306. visit(node->cond);
  307. visit(node->stmt);
  308. }
  309. static void visit_flow_stmt (gvisitor_t *self, gnode_flow_stmt_t *node) {
  310. DEBUG_CODEGEN("visit_flow_stmt");
  311. gtoken_t type = NODE_TOKEN_TYPE(node);
  312. assert((type == TOK_KEY_IF) || (type == TOK_KEY_SWITCH) || (type == TOK_OP_TERNARY));
  313. if (type == TOK_KEY_IF) {
  314. visit_flow_if_stmt(self, node);
  315. } else if (type == TOK_KEY_SWITCH) {
  316. visit_flow_switch_stmt(self, node);
  317. } else if (type == TOK_OP_TERNARY) {
  318. report_error(self, (gnode_t *)node, "Ternary operator not yet supported.");
  319. }
  320. }
  321. static void visit_loop_while_stmt (gvisitor_t *self, gnode_loop_stmt_t *node) {
  322. DEBUG_CODEGEN("visit_loop_while_stmt");
  323. DECLARE_CODE();
  324. /*
  325. $start: <condition>
  326. if-false: goto $end
  327. <body>
  328. goto $start
  329. $end:
  330. START := getLabel
  331. END := getLabel
  332. emit START
  333. compile exp
  334. emit ifeq END
  335. compile stm
  336. emit goto START
  337. emit END
  338. */
  339. uint32_t labelTrue = ircode_newlabel(code);
  340. uint32_t labelFalse = ircode_newlabel(code);
  341. ircode_setlabel_true(code, labelTrue);
  342. ircode_setlabel_false(code, labelFalse);
  343. ircode_marklabel(code, labelTrue);
  344. visit(node->cond);
  345. uint32_t reg = ircode_register_pop(code);
  346. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid while condition expression.");
  347. ircode_add(code, JUMPF, reg, labelFalse, 0);
  348. visit(node->stmt);
  349. ircode_add(code, JUMP, labelTrue, 0, 0);
  350. ircode_marklabel(code, labelFalse);
  351. ircode_unsetlabel_true(code);
  352. ircode_unsetlabel_false(code);
  353. }
  354. static void visit_loop_repeat_stmt (gvisitor_t *self, gnode_loop_stmt_t *node) {
  355. DEBUG_CODEGEN("visit_loop_repeat_stmt");
  356. DECLARE_CODE();
  357. /*
  358. $start: <body>
  359. <expression>
  360. if-false: goto $start
  361. $end:
  362. */
  363. uint32_t labelTrue = ircode_newlabel(code);
  364. uint32_t labelFalse = ircode_newlabel(code); // end label is necessary to handle optional break statement
  365. ircode_setlabel_true(code, labelTrue);
  366. ircode_setlabel_false(code, labelFalse);
  367. ircode_marklabel(code, labelTrue);
  368. visit(node->stmt);
  369. visit(node->expr);
  370. uint32_t reg = ircode_register_pop(code);
  371. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid repeat condition expression.");
  372. ircode_add(code, JUMPF, reg, labelFalse, 0);
  373. ircode_add(code, JUMP, labelTrue, 0, 0);
  374. ircode_marklabel(code, labelFalse);
  375. ircode_unsetlabel_true(code);
  376. ircode_unsetlabel_false(code);
  377. }
  378. static void visit_loop_for_stmt (gvisitor_t *self, gnode_loop_stmt_t *node) {
  379. // https://www.natashatherobot.com/swift-alternatives-to-c-style-for-loops/
  380. DEBUG_CODEGEN("visit_loop_for_stmt");
  381. DECLARE_CODE();
  382. // FOR loop is transformed to a WHILE loop
  383. //
  384. // from:
  385. // for (cond in expr) {
  386. // stmp;
  387. // }
  388. //
  389. // to:
  390. // {
  391. // var $expr = expr;
  392. // var $value = $expr.iterate(null);
  393. // while ($value) {
  394. // cond = $expr.next($value);
  395. // stmp;
  396. // $value = $expr.iterate($value);
  397. // }
  398. // }
  399. uint32_t $expr = ircode_register_push_temp(code); // ++TEMP => 1
  400. uint32_t $value = ircode_register_push_temp(code); // ++TEMP => 2
  401. // $expr and $value are temporary registers that must not be cleared by ircode_register_clear_temps
  402. // in visit_compound_statement, so mark them to skip clear
  403. ircode_register_set_skip_clear(code, $expr);
  404. ircode_register_set_skip_clear(code, $value);
  405. uint16_t iterate_idx = gravity_function_cpool_add(GET_VM(), context_function, VALUE_FROM_CSTRING(NULL, ITERATOR_INIT_FUNCTION));
  406. uint16_t next_idx = gravity_function_cpool_add(GET_VM(), context_function, VALUE_FROM_CSTRING(NULL, ITERATOR_NEXT_FUNCTION));
  407. uint32_t cond_idx = node2index(node->cond);
  408. // generate code for $expr = expr (so expr is only evaluated once)
  409. visit(node->expr);
  410. uint32_t once_expr = ircode_register_pop(code);
  411. if (once_expr == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid for expression.");
  412. ircode_add(code, MOVE, $expr, once_expr, 0);
  413. // generate code for $value = $expr.iterate(null);
  414. uint32_t iterate_fn = ircode_register_push_temp(code); // ++TEMP => 3
  415. ircode_add(code, LOADK, iterate_fn, iterate_idx, 0);
  416. ircode_add(code, LOAD, iterate_fn, $expr, iterate_fn);
  417. ircode_register_set_skip_clear(code, iterate_fn);
  418. uint32_t next_fn = ircode_register_push_temp(code); // ++TEMP => 4
  419. ircode_add(code, LOADK, next_fn, next_idx, 0);
  420. ircode_add(code, LOAD, next_fn, $expr, next_fn);
  421. ircode_register_set_skip_clear(code, next_fn);
  422. uint32_t temp1 = ircode_register_push_temp(code); // ++TEMP => 5
  423. ircode_add(code, MOVE, temp1, iterate_fn, 0);
  424. uint32_t temp2 = ircode_register_push_temp(code); // ++TEMP => 6
  425. ircode_add(code, MOVE, temp2, $expr, 0);
  426. temp2 = ircode_register_push_temp(code); // ++TEMP => 7
  427. ircode_add(code, LOADK, temp2, CPOOL_VALUE_NULL, 0);
  428. ircode_add(code, CALL, $value, temp1, 2);
  429. uint32_t temp = ircode_register_pop(code); // --TEMP => 6
  430. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  431. temp = ircode_register_pop(code); // --TEMP => 5
  432. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  433. temp = ircode_register_pop(code); // --TEMP => 4
  434. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  435. // while code
  436. uint32_t labelTrue = ircode_newlabel(code);
  437. uint32_t labelFalse = ircode_newlabel(code);
  438. ircode_setlabel_true(code, labelTrue);
  439. ircode_setlabel_false(code, labelFalse);
  440. ircode_marklabel(code, labelTrue);
  441. ircode_add(code, JUMPF, $value, labelFalse, 1); // flag JUMPF instruction to check ONLY BOOL values
  442. // cond = $expr.next($value);
  443. // cond is a local variable
  444. temp1 = ircode_register_push_temp(code); // ++TEMP => 5
  445. ircode_add(code, MOVE, temp1, next_fn, 0);
  446. temp2 = ircode_register_push_temp(code); // ++TEMP => 6
  447. ircode_add(code, MOVE, temp2, $expr, 0);
  448. temp2 = ircode_register_push_temp(code); // ++TEMP => 7
  449. ircode_add(code, MOVE, temp2, $value, 0);
  450. ircode_add(code, CALL, cond_idx, temp1, 2);
  451. // process statement
  452. visit(node->stmt);
  453. // pop next_fn temp register AFTER user code because function ptr must be protected inside loop
  454. temp = ircode_register_pop(code); // --TEMP => 6
  455. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  456. temp = ircode_register_pop(code); // --TEMP => 5
  457. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  458. temp = ircode_register_pop(code); // --TEMP => 4
  459. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  460. // update $value for the next check
  461. // $value = $expr.iterate($value);
  462. temp1 = ircode_register_push_temp(code); // ++TEMP => 5
  463. ircode_add(code, MOVE, temp1, iterate_fn, 0);
  464. temp2 = ircode_register_push_temp(code); // ++TEMP => 6
  465. ircode_add(code, MOVE, temp2, $expr, 0);
  466. temp2 = ircode_register_push_temp(code); // ++TEMP => 7
  467. ircode_add(code, MOVE, temp2, $value, 0);
  468. ircode_add(code, CALL, $value, temp1, 2);
  469. temp = ircode_register_pop(code); // --TEMP => 6
  470. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  471. temp = ircode_register_pop(code); // --TEMP => 5
  472. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  473. temp = ircode_register_pop(code); // --TEMP => 4
  474. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  475. ircode_add(code, JUMP, labelTrue, 0, 0);
  476. ircode_marklabel(code, labelFalse);
  477. ircode_unsetlabel_true(code);
  478. ircode_unsetlabel_false(code);
  479. temp = ircode_register_pop(code); // --TEMP => 3
  480. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  481. temp = ircode_register_pop(code); // --TEMP => 2
  482. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  483. temp = ircode_register_pop(code); // --TEMP => 1
  484. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  485. temp = ircode_register_pop(code); // --TEMP => 0
  486. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  487. ircode_register_unset_skip_clear(code, $expr);
  488. ircode_register_unset_skip_clear(code, $value);
  489. ircode_register_unset_skip_clear(code, iterate_fn);
  490. ircode_register_unset_skip_clear(code, next_fn);
  491. if (node->nclose != UINT32_MAX) {
  492. ircode_add(code, CLOSE, node->nclose, 0, 0);
  493. }
  494. }
  495. static void visit_loop_stmt (gvisitor_t *self, gnode_loop_stmt_t *node) {
  496. DEBUG_CODEGEN("visit_loop_stmt");
  497. gtoken_t type = NODE_TOKEN_TYPE(node);
  498. assert((type == TOK_KEY_WHILE) || (type == TOK_KEY_REPEAT) || (type == TOK_KEY_FOR));
  499. if (type == TOK_KEY_WHILE) {
  500. visit_loop_while_stmt(self, node);
  501. } else if (type == TOK_KEY_REPEAT) {
  502. visit_loop_repeat_stmt(self, node);
  503. } else if (type == TOK_KEY_FOR) {
  504. visit_loop_for_stmt(self, node);
  505. }
  506. }
  507. static void visit_jump_stmt (gvisitor_t *self, gnode_jump_stmt_t *node) {
  508. DEBUG_CODEGEN("visit_jump_stmt");
  509. DECLARE_CODE();
  510. gtoken_t type = NODE_TOKEN_TYPE(node);
  511. assert((type == TOK_KEY_BREAK) || (type == TOK_KEY_CONTINUE) || (type == TOK_KEY_RETURN));
  512. if (type == TOK_KEY_BREAK) {
  513. uint32_t label = ircode_getlabel_false(code);
  514. ircode_add(code, JUMP, label, 0, 0); // goto $end;
  515. } else if (type == TOK_KEY_CONTINUE) {
  516. uint32_t label = ircode_getlabel_true(code);
  517. ircode_add(code, JUMP, label, 0, 0); // goto $start;
  518. } else if (type == TOK_KEY_RETURN) {
  519. if (node->expr) {
  520. visit(node->expr);
  521. uint32_t reg = ircode_register_pop(code);
  522. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid return expression.");
  523. ircode_add(code, RET, reg, 0, 0);
  524. } else {
  525. ircode_add(code, RET0, 0, 0, 0);
  526. }
  527. }
  528. }
  529. static void visit_empty_stmt (gvisitor_t *self, gnode_empty_stmt_t *node) {
  530. #pragma unused(self, node)
  531. DEBUG_CODEGEN("visit_empty_stmt");
  532. DECLARE_CODE();
  533. ircode_add(code, NOP, 0, 0, 0);
  534. }
  535. // MARK: - Declarations -
  536. static void store_declaration (gvisitor_t *self, gravity_object_t *obj, bool is_static, gnode_function_decl_t *node) {
  537. DEBUG_CODEGEN("store_object_declaration");
  538. assert(obj);
  539. DECLARE_CONTEXT();
  540. bool is_module = CONTEXT_IS_MODULE(context_object);
  541. bool is_class = OBJECT_ISA_CLASS(context_object);
  542. bool is_local = ((is_module == false) && (is_class == false));
  543. if (is_static && !is_class){
  544. // static makes sense only for class objects
  545. report_error(self, (gnode_t *)node, "Static storage specifier does not make sense in non class context.");
  546. return;
  547. }
  548. if (is_local || is_module) {
  549. gravity_function_t *context_function = (gravity_function_t *)context_object;
  550. ircode_t *code = (ircode_t *)context_function->bytecode;
  551. // add object to cpool and get its index
  552. uint16_t index = gravity_function_cpool_add(NULL, context_function, VALUE_FROM_OBJECT(obj));
  553. // if it is a function then generate a CLOSURE opcode instead of LOADK
  554. if (OBJECT_ISA_FUNCTION(obj)) {
  555. assert(node);
  556. gravity_function_t *f = (gravity_function_t *)obj;
  557. uint32_t regnum = ircode_register_push_temp(code);
  558. ircode_add(code, CLOSURE, regnum, index, 0);
  559. uint32_t upindex = 0;
  560. for (uint16_t i=0; i<f->nupvalues; ++i) {
  561. gupvalue_t *upvalue = (gupvalue_t *)gnode_array_get(node->uplist, i);
  562. uint32_t opindex = (upvalue->is_direct) ? upvalue->index : upindex++;
  563. ircode_add(code, MOVE, opindex, (upvalue->is_direct) ? 1 : 0, 0);
  564. }
  565. } else {
  566. ircode_add_constant(code, index);
  567. }
  568. if (is_module && obj->identifier) {
  569. index = gravity_function_cpool_add(GET_VM(), context_function, VALUE_FROM_CSTRING(NULL, obj->identifier));
  570. uint32_t reg = ircode_register_pop(code);
  571. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid declaration expression.");
  572. ircode_add(code, STOREG, reg, index, 0);
  573. }
  574. return;
  575. }
  576. if (is_class) {
  577. gravity_class_t *context_class = (gravity_class_t *)context_object;
  578. context_class = (is_static) ? context_class->objclass : context_class;
  579. gravity_class_bind(context_class, obj->identifier, VALUE_FROM_OBJECT(obj));
  580. return;
  581. }
  582. // should never reach this point
  583. assert(0);
  584. }
  585. // used ONLY by CODEGEN
  586. static gravity_function_t *class_lookup_nosuper (gravity_class_t *c, const char *name) {
  587. STATICVALUE_FROM_STRING(key, name, strlen(name));
  588. gravity_value_t *v = gravity_hash_lookup(c->htable, key);
  589. return (v) ? (gravity_function_t*)v->p : NULL;
  590. }
  591. static void process_constructor (gvisitor_t *self, gravity_class_t *c, gnode_t *node) {
  592. DEBUG_CODEGEN("process_constructor");
  593. // $init is an internal function used to initialize instance variables to a default value
  594. // in case of subclasses USER is RESPONSIBLE to call super.init();
  595. // in case of subclasses COMPILER is RESPONSIBLE to create the appropriate $init call chain
  596. // check internal $init function
  597. gravity_function_t *internal_init_function = class_lookup_nosuper(c, CLASS_INTERNAL_INIT_NAME);
  598. // check for user constructor function
  599. gravity_function_t *constructor_function = class_lookup_nosuper(c, CLASS_CONSTRUCTOR_NAME);
  600. // build appropriate $init function
  601. gravity_class_t *super = c->superclass;
  602. uint32_t ninit = 2;
  603. while (super) {
  604. gravity_function_t *super_init = class_lookup_nosuper(super, CLASS_INTERNAL_INIT_NAME);
  605. if (super_init) {
  606. // copy super init code to internal_init code
  607. if (!internal_init_function) internal_init_function = gravity_function_new(NULL, CLASS_INTERNAL_INIT_NAME, 1, 0, 0, ircode_create(1));
  608. // build unique internal init name ($init2, $init3 and so on)
  609. char name[256];
  610. snprintf(name, sizeof(name), "%s%d", CLASS_INTERNAL_INIT_NAME, ninit++);
  611. // add new internal init to class and call it from main $init function
  612. // super_init should not be duplicated here because class hash table values are not freed (only keys are freed)
  613. gravity_class_bind(c, name, VALUE_FROM_OBJECT(super_init));
  614. uint16_t index = gravity_function_cpool_add(NULL, internal_init_function, VALUE_FROM_CSTRING(GET_VM(), name));
  615. ircode_patch_init((ircode_t *)internal_init_function->bytecode, index);
  616. }
  617. super = super->superclass;
  618. }
  619. // 4 cases to handle:
  620. // 1. internal_init and constuctor are not present, so nothing to do here
  621. if ((!internal_init_function) && (!constructor_function)) goto check_meta;
  622. // // 2. internal init is present and constructor is not used
  623. // if ((internal_init_function) && (!constructor_function)) {
  624. // // add a RET0 command
  625. // ircode_t *code = (ircode_t *)internal_init_function->bytecode;
  626. // ircode_add(code, RET0, 0, 0, 0);
  627. //
  628. // // bind internal init as constructor
  629. // gravity_class_bind(c, CLASS_CONSTRUCTOR_NAME, VALUE_FROM_OBJECT(internal_init_function));
  630. // gravity_object_setenclosing((gravity_object_t *)internal_init_function, (gravity_object_t *)c);
  631. // goto process_funcs;
  632. // }
  633. // 3. internal init is present so constructor is mandatory
  634. if (internal_init_function) {
  635. // convert ircode to bytecode for $init special function and add a RET0 command
  636. ircode_t *code = (ircode_t *)internal_init_function->bytecode;
  637. if (!code) {report_error(self, node, "Invalid code context."); return;}
  638. ircode_add(code, RET0, 0, 0, 0);
  639. if (constructor_function == NULL) {
  640. constructor_function = gravity_function_new(NULL, CLASS_CONSTRUCTOR_NAME, 1, 0, 2, ircode_create(1));
  641. ircode_t *code2 = (ircode_t *)constructor_function->bytecode;
  642. ircode_add_skip(code2); // LOADK
  643. ircode_add_skip(code2); // LOAD
  644. ircode_add_skip(code2); // MOVE
  645. ircode_add_skip(code2); // CALL
  646. gravity_class_bind(c, CLASS_CONSTRUCTOR_NAME, VALUE_FROM_OBJECT(constructor_function));
  647. }
  648. }
  649. // 4. constructor is present so internal init is optional
  650. if (constructor_function) {
  651. // add an implicit RET 0 (RET self) to the end of the constructor
  652. ircode_t *code = (ircode_t *)constructor_function->bytecode;
  653. if (!code) {report_error(self, node, "Invalid code context."); return;}
  654. ircode_add(code, RET, 0, 0, 0);
  655. if (internal_init_function) {
  656. // if an internal init function is present ($init) then add a call to it as a first instruction
  657. uint16_t index = gravity_function_cpool_add(GET_VM(), constructor_function, VALUE_FROM_CSTRING(NULL, CLASS_INTERNAL_INIT_NAME));
  658. // load constant
  659. uint32_t dest = ircode_register_push_temp(code);
  660. ircode_set_index(0, code, LOADK, dest, index, 0);
  661. // load from lookup
  662. ircode_set_index(1, code, LOAD, dest, 0, dest);
  663. // prepare parameters
  664. uint32_t dest2 = ircode_register_push_temp(code);
  665. ircode_set_index(2, code, MOVE, dest2, 0, 0);
  666. uint32_t temp = ircode_register_pop(code);
  667. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  668. // execute call
  669. ircode_set_index(3, code, CALL, dest, dest, 1);
  670. }
  671. }
  672. if (internal_init_function) gravity_optimizer(internal_init_function);
  673. if (constructor_function) gravity_optimizer(constructor_function);
  674. check_meta:
  675. // recursively process constructor but stop when object or class class is found, otherwise an infinite loop is triggered
  676. if ((c->objclass) && (c->objclass->isa) && (c->objclass->isa != c->objclass->objclass)) process_constructor(self, c->objclass, node);
  677. }
  678. static void process_getter_setter (gvisitor_t *self, gnode_var_t *p, gravity_class_t *c) {
  679. gnode_compound_stmt_t *expr = (gnode_compound_stmt_t *)p->expr;
  680. gnode_function_decl_t *getter = (gnode_function_decl_t *)gnode_array_get(expr->stmts, 0);
  681. gnode_function_decl_t *setter = (gnode_function_decl_t *)gnode_array_get(expr->stmts, 1);
  682. gnode_function_decl_t *f1[2] = {getter, setter};
  683. gravity_function_t *f2[2] = {NULL, NULL};
  684. for (uint16_t i=0; i<2; ++i) {
  685. gnode_function_decl_t *node = f1[i];
  686. if (!node) continue;
  687. // create gravity function
  688. uint16_t nparams = (node->params) ? (uint16_t)marray_size(*node->params) : 0;
  689. f2[i] = gravity_function_new(NULL, NULL, nparams, node->nlocals, 0, ircode_create(node->nlocals+nparams));
  690. // process inner block
  691. CONTEXT_PUSH(f2[i]);
  692. gnode_compound_stmt_t *block = node->block;
  693. if (block) {gnode_array_each(block->stmts, {visit(val);});}
  694. CONTEXT_POP();
  695. gravity_optimizer(f2[i]);
  696. }
  697. // getter and setter NULL means default
  698. // since getter and setter are methods and not simple functions, do not transfer to VM
  699. gravity_function_t *f = gravity_function_new_special(NULL, NULL, GRAVITY_COMPUTED_INDEX, f2[0], f2[1]);
  700. gravity_class_bind(c, p->identifier, VALUE_FROM_OBJECT(f));
  701. }
  702. static void visit_function_decl (gvisitor_t *self, gnode_function_decl_t *node) {
  703. DEBUG_CODEGEN("visit_function_decl %s", node->identifier);
  704. // extern means it will be provided at runtime by the delegate
  705. if (node->storage == TOK_KEY_EXTERN) return;
  706. DECLARE_CONTEXT();
  707. bool is_class_ctx = OBJECT_ISA_CLASS(context_object);
  708. // create new function object
  709. uint16_t nparams = (node->params) ? (uint16_t)marray_size(*node->params) : 0;
  710. gravity_function_t *f = gravity_function_new((is_class_ctx) ? NULL : GET_VM(), node->identifier,
  711. nparams, node->nlocals, 0, (void *)ircode_create(node->nlocals+nparams));
  712. // check if f is a special constructor function (init)
  713. // name must be CLASS_CONSTRUCTOR_NAME and context_object must be a class
  714. bool is_constructor = (string_cmp(node->identifier, CLASS_CONSTRUCTOR_NAME) == 0) && (is_class_ctx);
  715. CONTEXT_PUSH(f);
  716. if (is_constructor) {
  717. // reserve first four instructions that could be later filled with a CALL to $init
  718. // see process_constructor for more information
  719. ircode_t *code = (ircode_t *)f->bytecode;
  720. if (!code) {report_error(self, (gnode_t *)node, "Invalid code context."); return;}
  721. ircode_add_skip(code);
  722. ircode_add_skip(code);
  723. ircode_add_skip(code);
  724. ircode_add_skip(code);
  725. }
  726. // process inner block
  727. ircode_t *code = (ircode_t *)f->bytecode;
  728. if (node->block) {
  729. gnode_array_each(node->block->stmts, {
  730. // process node
  731. visit(val);
  732. // reset temp registers after each node
  733. ircode_register_clear_temps(code);
  734. });
  735. }
  736. // check for upvalues
  737. if (node->uplist) f->nupvalues = (uint16_t)gnode_array_size(node->uplist);
  738. // remove current function
  739. CONTEXT_POP();
  740. // check for ircode errors
  741. if (ircode_iserror((ircode_t *)f->bytecode))
  742. report_error(self, (gnode_t *)node, "Maximum number of available registers used in function %s.", f->identifier);
  743. // store function in current context
  744. store_declaration(self, (gravity_object_t *)f, (node->storage == TOK_KEY_STATIC), node);
  745. // convert ircode to bytecode (postpone optimization of the constructor)
  746. if (!is_constructor) gravity_optimizer(f);
  747. }
  748. static void visit_variable_decl (gvisitor_t *self, gnode_variable_decl_t *node) {
  749. DEBUG_CODEGEN("visit_variable_decl");
  750. DECLARE_CONTEXT();
  751. // no initialization for extern variables since the real value will be provided at runtime
  752. if (node->storage == TOK_KEY_EXTERN) return;
  753. bool is_module = CONTEXT_IS_MODULE(context_object);
  754. bool is_class = OBJECT_ISA_CLASS(context_object);
  755. bool is_local = ((is_module == false) && (is_class == false));
  756. // loop through declarations
  757. size_t count = gnode_array_size(node->decls);
  758. for (size_t i=0; i<count; ++i) {
  759. gnode_var_t *p = (gnode_var_t *)gnode_array_get(node->decls, i);
  760. DEBUG_CODEGEN("visit_variable_decl %s", p->identifier);
  761. // variable declarations can be specified in:
  762. // FUNCTION (local variable)
  763. // MODULE (module variable)
  764. // CLASS (property)
  765. if (is_local) {
  766. // it is a local variable declaration (default initialized to NULL)
  767. // code is generate ONLY if an init expression is specified
  768. //
  769. // example:
  770. //
  771. // func foo () {
  772. // var a = 10;
  773. // }
  774. //
  775. // LOADI 1 10 ; move 10 into register 1
  776. // MOVE 0 1 ; move register 1 into register 0
  777. //
  778. // generate expression code
  779. if (p->expr) visit(p->expr); // context is a function
  780. gravity_function_t *context_function = (gravity_function_t *)context_object;
  781. ircode_t *code = (ircode_t *)context_function->bytecode;
  782. if (p->expr) {
  783. // assign to variable result of the expression
  784. uint32_t reg = ircode_register_pop(code);
  785. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid var expression.");
  786. ircode_add(code, MOVE, p->index, reg, 0);
  787. } else {
  788. // no default assignment expression found so initialize to NULL
  789. ircode_add(code, LOADK, p->index, CPOOL_VALUE_NULL, 0);
  790. }
  791. continue;
  792. }
  793. if (is_module) {
  794. // it is a module variable (default initialized to null)
  795. // code must ALWAYS be generated
  796. //
  797. // example 1:
  798. // var a;
  799. //
  800. // LOADK 0 NULL ; move null into register 0
  801. // STOREG 0 0 ; move register 0 into hash(constant_pool(0))
  802. //
  803. // example 2:
  804. // var a = 10;
  805. //
  806. // LOADI 0 10 ; move 10 into register 0
  807. // STOREG 0 0 ; move register 0 into hash(constant_pool(0))
  808. //
  809. gravity_function_t *context_function = (gravity_function_t *)context_object;
  810. ircode_t *code = (ircode_t *)context_function->bytecode;
  811. uint16_t index = gravity_function_cpool_add(GET_VM(), context_function, VALUE_FROM_CSTRING(NULL, p->identifier));
  812. if (p->expr) {
  813. visit(p->expr); // context is a function
  814. } else {
  815. ircode_add_constant(code, CPOOL_VALUE_NULL);
  816. }
  817. uint32_t reg = ircode_register_pop(code);
  818. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid var expression.");
  819. ircode_add(code, STOREG, reg, index, 0);
  820. continue;
  821. }
  822. if (is_class) {
  823. bool is_static = (node->storage == TOK_KEY_STATIC);
  824. gravity_class_t *context_class = (is_static) ? ((gravity_class_t *)context_object)->objclass : (gravity_class_t *)context_object;
  825. // check computed property case first
  826. if ((p->expr) && (p->expr->tag == NODE_COMPOUND_STAT)) {
  827. process_getter_setter(self, p, context_class);
  828. continue;
  829. }
  830. // create ivar first
  831. uint16_t ivar_index = (p->index >= 0) ? p->index : gravity_class_add_ivar(context_class, NULL);
  832. // add default getter and setter ONLY if property is public
  833. if (node->access == TOK_KEY_PUBLIC) {
  834. // since getter and setter are methods and not simple functions, do not transfer to VM
  835. gravity_function_t *f = gravity_function_new_special(NULL, NULL, ivar_index, NULL, NULL); // getter and setter NULL means default
  836. gravity_class_bind(context_class, p->identifier, VALUE_FROM_OBJECT(f));
  837. }
  838. DEBUG_CODEGEN("Class: %s (static: %d) property: %s index: %d", context_class->identifier, is_static, p->identifier, ivar_index);
  839. // it is a property (default initialized to null)
  840. // code must be generated ONLY if an init expression is specified
  841. //
  842. // example:
  843. // class foo {
  844. // var a = 10;
  845. // }
  846. //
  847. // get $init function
  848. // depending if variable has been created static
  849. // and push it as current declaration then:
  850. //
  851. // LOADI 0 10 ; move 10 into register 0
  852. // STOREF 0 0 ; move register 0 into property 0
  853. if (p->expr) {
  854. // was gravity_class_lookup but that means than $init or init will be recursively searched also in super classes
  855. gravity_function_t *init_function = class_lookup_nosuper(context_class, CLASS_INTERNAL_INIT_NAME);
  856. if (init_function == NULL) {
  857. // no $init method found so create a new one
  858. init_function = gravity_function_new (NULL, CLASS_INTERNAL_INIT_NAME, 1, 0, 0, ircode_create(1));
  859. gravity_class_bind(context_class, CLASS_INTERNAL_INIT_NAME, VALUE_FROM_OBJECT(init_function));
  860. }
  861. CONTEXT_PUSH(init_function);
  862. ircode_t *code = (ircode_t *)init_function->bytecode;
  863. visit(p->expr);
  864. uint32_t reg = ircode_register_pop(code);
  865. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid var expression.");
  866. ircode_add(code, STORE, reg, 0, p->index + MAX_REGISTERS);
  867. CONTEXT_POP();
  868. }
  869. continue;
  870. }
  871. // should never reach this point
  872. assert(0);
  873. }
  874. }
  875. static void visit_enum_decl (gvisitor_t *self, gnode_enum_decl_t *node) {
  876. #pragma unused(self,node)
  877. DEBUG_CODEGEN("visit_enum_decl %s", node->identifier);
  878. // enum is a map at runtime
  879. // enum foo {a=1,b=2,...}
  880. // is translated to
  881. // var foo = [a:1,b:2,...]
  882. }
  883. static void visit_class_decl (gvisitor_t *self, gnode_class_decl_t *node) {
  884. DEBUG_CODEGEN("visit_class_decl %s", node->identifier);
  885. // extern means it will be provided at runtime by the delegate
  886. if (node->storage == TOK_KEY_EXTERN) return;
  887. // create a new pair of classes (class itself and its meta)
  888. gravity_class_t *c = gravity_class_new_pair(GET_VM(), node->identifier, NULL, node->nivar, node->nsvar);
  889. // mark the class as a struct
  890. c->is_struct = node->is_struct;
  891. // check if class has a declared superclass
  892. if (node->superclass) {
  893. // node->superclass should be a gnode_class_decl_t at this point
  894. assert(NODE_ISA_CLASS(node->superclass));
  895. gnode_class_decl_t *super = (gnode_class_decl_t *)node->superclass;
  896. if (super->data) {
  897. // means that superclass has already been processed and its runtime representation is available
  898. gravity_class_setsuper(c, (gravity_class_t *)super->data);
  899. } else {
  900. // superclass has not yet processed so we need recheck the node at the end of the visit
  901. // add node to superfix for later processing
  902. codegen_t *data = (codegen_t *)self->data;
  903. marray_push(gnode_class_decl_t *, data->superfix, node);
  904. }
  905. }
  906. CONTEXT_PUSH(c);
  907. // process inner declarations
  908. gnode_array_each(node->decls, {visit(val);});
  909. // adjust declaration stack
  910. CONTEXT_POP();
  911. // fix constructor chain
  912. process_constructor(self, c, (gnode_t *)node);
  913. // store class declaration in current context
  914. store_declaration(self, (gravity_object_t *)c, (node->storage == TOK_KEY_STATIC), NULL);
  915. // save runtime representation
  916. // since this class could be a superclass of another class
  917. // then save opaque gravity_class_t pointer to node->data
  918. node->data = (void *)c;
  919. }
  920. static void visit_module_decl (gvisitor_t *self, gnode_module_decl_t *node) {
  921. #pragma unused(self, node)
  922. DEBUG_CODEGEN("visit_module_decl %s", node->identifier);
  923. // a module should be like a class with static entries
  924. // instantiated with import
  925. // gravity_module_t *module = gravity_module_new(GET_VM(), node->identifier);
  926. // CONTEXT_PUSH(module);
  927. //
  928. // // process inner declarations
  929. // gnode_array_each(node->decls, {visit(val);});
  930. //
  931. // // adjust declaration stack
  932. // CONTEXT_POP();
  933. }
  934. // MARK: - Expressions -
  935. //static void process_special_enum (gvisitor_t *self, gnode_enum_decl_t *node, gnode_identifier_expr_t *identifier) {
  936. // symboltable_t *symtable = node->symtable;
  937. // gnode_t *v = symboltable_lookup(symtable, identifier->value);
  938. // assert(v);
  939. // assert(NODE_ISA(v, NODE_LITERAL_EXPR));
  940. // visit(v);
  941. //}
  942. static void visit_binary_expr (gvisitor_t *self, gnode_binary_expr_t *node) {
  943. DEBUG_CODEGEN("visit_binary_expr %s", token_name(node->op));
  944. DECLARE_CODE();
  945. // assignment is right associative
  946. if (node->op == TOK_OP_ASSIGN) {
  947. CODEGEN_COUNT_REGISTERS(n1);
  948. visit(node->right);
  949. visit(node->left); // left expression can be: IDENTIFIER, FILE, POSTIFIX (not a call)
  950. CODEGEN_COUNT_REGISTERS(n2);
  951. CODEGEN_ASSERT_REGISTERS(n1, n2, 0);
  952. return;
  953. }
  954. CODEGEN_COUNT_REGISTERS(n1);
  955. // visiting binary operation from left to right
  956. visit(node->left);
  957. visit(node->right);
  958. uint32_t r3 = ircode_register_pop(code);
  959. if (r3 == REGISTER_ERROR) report_error(self, (gnode_t *)node->right, "Invalid right expression.");
  960. uint32_t r2 = ircode_register_pop(code);
  961. if (r2 == REGISTER_ERROR) report_error(self, (gnode_t *)node->left, "Invalid left expression.");
  962. uint32_t r1 = ircode_register_push_temp(code);
  963. // a special instruction needs to be generated for a binary expression of type RANGE
  964. if ((node->op == TOK_OP_RANGE_INCLUDED) || (node->op == TOK_OP_RANGE_EXCLUDED)) {
  965. ircode_add_tag(code, RANGENEW, r1, r2, r3, (node->op == TOK_OP_RANGE_INCLUDED) ? RANGE_INCLUDE_TAG : RANGE_EXCLUDE_TAG);
  966. return;
  967. }
  968. // generate code for binary OP
  969. opcode_t op = token2opcode(node->op);
  970. ircode_add(code, op, r1, r2, r3);
  971. CODEGEN_COUNT_REGISTERS(n2);
  972. CODEGEN_ASSERT_REGISTERS(n1, n2, 1);
  973. }
  974. static void visit_unary_expr (gvisitor_t *self, gnode_unary_expr_t *node) {
  975. DEBUG_CODEGEN("visit_unary_expr %s", token_name(node->op));
  976. DECLARE_CODE();
  977. CODEGEN_COUNT_REGISTERS(n1);
  978. // unary expression can be:
  979. // + Unary PLUS
  980. // - Unary MINUS
  981. // ! Logical NOT
  982. // ~ Bitwise NOT
  983. visit(node->expr);
  984. if (node->op == TOK_OP_ADD) {
  985. // +1 is just 1 and more generally +expr is just expr so ignore + and proceed
  986. return;
  987. }
  988. uint32_t r2 = ircode_register_pop(code);
  989. if (r2 == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid unary expression.");
  990. uint32_t r1 = ircode_register_push_temp(code);
  991. opcode_t op = (node->op == TOK_OP_SUB) ? NEG : token2opcode(node->op);
  992. ircode_add(code, op, r1, r2, 0);
  993. CODEGEN_COUNT_REGISTERS(n2);
  994. CODEGEN_ASSERT_REGISTERS(n1, n2, 1);
  995. }
  996. static void visit_postfix_expr (gvisitor_t *self, gnode_postfix_expr_t *node) {
  997. DEBUG_CODEGEN("visit_postfix_expr");
  998. // node->list usually cannot be NULL, it is NULL only as a result of a static enum transformation (see semacheck2.c)
  999. if (node->list == NULL) {
  1000. visit(node->id);
  1001. return;
  1002. }
  1003. DECLARE_CODE();
  1004. CODEGEN_COUNT_REGISTERS(n1);
  1005. ircode_push_context(code);
  1006. // disable MOVE optimization
  1007. ircode_pragma(code, PRAGMA_MOVE_OPTIMIZATION, 0);
  1008. // generate code for the common id node
  1009. visit(node->id);
  1010. bool is_super = IS_SUPER(node->id);
  1011. // register that contains callable object
  1012. uint32_t target_register = ircode_register_pop_context_protect(code, true);
  1013. if (target_register == REGISTER_ERROR) {
  1014. report_error(self, (gnode_t *)node->id, "Invalid postfix expression.");
  1015. return;
  1016. }
  1017. // register where to store final result
  1018. uint32_t dest_register = target_register;
  1019. // mandatory self register (initialized to 0 in case of implicit self or explicit super)
  1020. uint32_r self_list; marray_init(self_list);
  1021. uint32_t first_self_register = compute_self_register(self, code, node->id, target_register, node->list);
  1022. if (first_self_register == UINT32_MAX) return;
  1023. marray_push(uint32_t, self_list, first_self_register);
  1024. // process each subnode and set is_assignment flag
  1025. bool is_assignment = node->base.is_assignment;
  1026. size_t count = gnode_array_size(node->list);
  1027. for (size_t i=0; i<count; ++i) {
  1028. // a subnode can be a CALL_EXPR => id.()
  1029. // a NODE_ACCESS_EXPR => id.id2
  1030. // a NODE_SUBSCRIPT_EXPR => id[]
  1031. // or ANY combination of the them! => id.id2.id3()[24]().id5()
  1032. gnode_postfix_subexpr_t *subnode = (gnode_postfix_subexpr_t *)gnode_array_get(node->list, i);
  1033. // identify postfix type: NODE_CALL_EXPR, NODE_ACCESS_EXPR, NODE_SUBSCRIPT_EXPR
  1034. gnode_n tag = subnode->base.tag;
  1035. // check assignment flag
  1036. bool is_real_assigment = (is_assignment && IS_LAST_LOOP(i, count));
  1037. if (tag == NODE_CALL_EXPR) {
  1038. // a CALL instruction needs to properly prepare stack before execution
  1039. // format is CALL A B C
  1040. // where A is the destination register
  1041. // B is the callable object
  1042. // and C is the number of arguments passed to the CALL
  1043. // arguments must be on the stack (so gravity VM can use a register window in order to speed up instruction)
  1044. // and are expected to be starting from B+1
  1045. // check dest register
  1046. bool dest_is_temp = ircode_register_istemp(code, dest_register);
  1047. if (!dest_is_temp) {
  1048. dest_register = ircode_register_push_temp(code);
  1049. dest_is_temp = true;
  1050. }
  1051. // add target register (must be temp)
  1052. uint32_t temp_target_register = ircode_register_push_temp(code);
  1053. ircode_add(code, MOVE, temp_target_register, target_register, 0);
  1054. uint32_t treg = ircode_register_pop_context_protect(code, true);
  1055. if (treg == REGISTER_ERROR) {
  1056. report_error(self, (gnode_t *)subnode, "Unexpected register error.");
  1057. return;
  1058. }
  1059. // always add SELF parameter (must be temp+1)
  1060. uint32_t self_register = marray_pop(self_list);
  1061. uint32_t temp_self_register = ircode_register_push_temp(code);
  1062. ircode_add(code, MOVE, temp_self_register, self_register, 0);
  1063. treg = ircode_register_pop_context_protect(code, true);
  1064. if (treg == REGISTER_ERROR) {
  1065. report_error(self, (gnode_t *)subnode, "Unexpected register error.");
  1066. return;
  1067. }
  1068. // process each parameter (each must be temp+2 ... temp+n)
  1069. marray_decl_init(uint32_r, args);
  1070. size_t n = gnode_array_size(subnode->args);
  1071. for (size_t j=0; j<n; ++j) {
  1072. // process each argument
  1073. gnode_t *arg = (gnode_t *)gnode_array_get(subnode->args, j);
  1074. ircode_pragma(code, PRAGMA_MOVE_OPTIMIZATION, 1);
  1075. visit(arg);
  1076. ircode_pragma(code, PRAGMA_MOVE_OPTIMIZATION, 0);
  1077. uint32_t nreg = ircode_register_pop_context_protect(code, true);
  1078. if (nreg == REGISTER_ERROR) {
  1079. report_error(self, (gnode_t *)arg, "Invalid argument expression at index %d.", j+1);
  1080. return;
  1081. }
  1082. // make sure args are in consecutive register locations (from temp_target_register + 1 to temp_target_register + n)
  1083. if (nreg != temp_target_register + j + 2) {
  1084. uint32_t temp = ircode_register_push_temp(code);
  1085. if (temp == 0) return; // temp value == 0 means codegen error (error will be automatically reported later in visit_function_decl
  1086. ircode_add(code, MOVE, temp, nreg, 0);
  1087. ircode_register_clear(code, nreg);
  1088. nreg = ircode_register_pop_context_protect(code, true);
  1089. if (nreg == REGISTER_ERROR) {
  1090. report_error(self, (gnode_t *)arg, "Invalid argument expression");
  1091. return;
  1092. }
  1093. }
  1094. if (nreg != temp_target_register + j + 2) {
  1095. report_error(self, (gnode_t *)arg, "Invalid register computation in call expression.");
  1096. return;
  1097. }
  1098. marray_push(uint32_t, args, nreg);
  1099. }
  1100. // generate instruction CALL with count parameters (taking in account self)
  1101. ircode_add(code, CALL, dest_register, temp_target_register, (uint32_t)n+1);
  1102. // cleanup temp registers
  1103. ircode_register_clear(code, temp_target_register);
  1104. ircode_register_clear(code, temp_self_register);
  1105. n = gnode_array_size(subnode->args);
  1106. for (size_t j=0; j<n; ++j) {
  1107. uint32_t reg = marray_get(args, j);
  1108. ircode_register_clear(code, reg);
  1109. }
  1110. // update self list
  1111. marray_push(uint32_t, self_list, dest_register);
  1112. // a call returns a value
  1113. if (IS_LAST_LOOP(i, count)) {
  1114. if (ircode_register_count(code)) {
  1115. // code added in order to protect the extra register pushed in case
  1116. // of code like: f(20)(30)
  1117. uint32_t last_register = ircode_register_last(code);
  1118. if (last_register == REGISTER_ERROR) {
  1119. report_error(self, (gnode_t *)subnode, "Invalid call expression.");
  1120. return;
  1121. }
  1122. if (dest_is_temp && last_register == dest_register) dest_is_temp = false;
  1123. }
  1124. if (dest_is_temp) ircode_register_push(code, dest_register);
  1125. if (!ircode_register_protect_outside_context(code, dest_register)) {
  1126. report_error(self, (gnode_t *)subnode, "Invalid register access.");
  1127. return;
  1128. }
  1129. }
  1130. // free temp args array
  1131. marray_destroy(args);
  1132. } else if (tag == NODE_ACCESS_EXPR) {
  1133. // process identifier node (semantic check assures that each node is an identifier)
  1134. gnode_identifier_expr_t *expr = (gnode_identifier_expr_t *)subnode->expr;
  1135. uint32_t index = gravity_function_cpool_add(GET_VM(), context_function, VALUE_FROM_CSTRING(NULL, expr->value));
  1136. uint32_t index_register = ircode_register_push_temp(code);
  1137. ircode_add(code, LOADK, index_register, index, 0);
  1138. uint32_t temp = ircode_register_pop(code);
  1139. if (temp == REGISTER_ERROR) {
  1140. report_error(self, (gnode_t *)expr, "Invalid access expression.");
  1141. return;
  1142. }
  1143. // generate LOAD/STORE instruction
  1144. dest_register = (is_real_assigment) ? ircode_register_pop(code) : ircode_register_push_temp(code);
  1145. if (dest_register == REGISTER_ERROR) {
  1146. report_error(self, (gnode_t *)expr, "Invalid access expression.");
  1147. return;
  1148. }
  1149. if (is_super) ircode_add(code, LOADS, dest_register, target_register, index_register);
  1150. else ircode_add(code, (is_real_assigment) ? STORE : LOAD, dest_register, target_register, index_register);
  1151. if (!is_real_assigment) {
  1152. if (i+1<count) {
  1153. uint32_t rtemp = ircode_register_pop_context_protect(code, true);
  1154. if (rtemp == REGISTER_ERROR) {
  1155. report_error(self, (gnode_t *)expr, "Unexpected register error.");
  1156. return;
  1157. }
  1158. } else {
  1159. // last loop
  1160. if (ircode_register_istemp(code, dest_register))
  1161. ircode_register_protect_outside_context(code, dest_register);
  1162. }
  1163. }
  1164. // update self list (if latest instruction)
  1165. // this was added in order to properly emit instructions for nested_class.gravity unit test
  1166. if (!IS_LAST_LOOP(i, count)) {
  1167. gnode_postfix_subexpr_t *nextnode = (gnode_postfix_subexpr_t *)gnode_array_get(node->list, i+1);
  1168. if (nextnode->base.tag != NODE_CALL_EXPR) marray_push(uint32_t, self_list, dest_register);
  1169. }
  1170. } else if (tag == NODE_SUBSCRIPT_EXPR) {
  1171. // process index
  1172. ircode_pragma(code, PRAGMA_MOVE_OPTIMIZATION, 1);
  1173. visit(subnode->expr);
  1174. ircode_pragma(code, PRAGMA_MOVE_OPTIMIZATION, 0);
  1175. uint32_t index = ircode_register_pop(code);
  1176. if (index == REGISTER_ERROR) {
  1177. report_error(self, (gnode_t *)subnode->expr, "Invalid subscript expression.");
  1178. return;
  1179. }
  1180. // generate LOADAT/STOREAT instruction
  1181. dest_register = (is_real_assigment) ? ircode_register_pop(code) : ircode_register_push_temp(code);
  1182. if (dest_register == REGISTER_ERROR) {
  1183. report_error(self, (gnode_t *)subnode->expr, "Invalid subscript expression.");
  1184. return;
  1185. }
  1186. ircode_add(code, (is_assignment) ? STOREAT : LOADAT, dest_register, target_register, index);
  1187. if ((!is_real_assigment) && (i+1<count)) {
  1188. uint32_t rtemp = ircode_register_pop_context_protect(code, true);
  1189. if (rtemp == REGISTER_ERROR) {
  1190. report_error(self, (gnode_t *)subnode->expr, "Unexpected register error.");
  1191. return;
  1192. }
  1193. }
  1194. }
  1195. // reset is_super flag
  1196. is_super = false;
  1197. // update target
  1198. target_register = dest_register;
  1199. }
  1200. marray_destroy(self_list);
  1201. ircode_pop_context(code);
  1202. // temp fix for not optimal register allocation algorithm generated code
  1203. uint32_t temp_register = ircode_register_first_temp_available(code);
  1204. if (temp_register < dest_register) {
  1205. // free dest register
  1206. ircode_register_pop(code);
  1207. // allocate a new register (that I am now sure does not have holes)
  1208. temp_register = ircode_register_push_temp(code);
  1209. ircode_add(code, MOVE, temp_register, dest_register, 0);
  1210. ircode_register_clear(code, dest_register);
  1211. }
  1212. CODEGEN_COUNT_REGISTERS(n2);
  1213. CODEGEN_ASSERT_REGISTERS(n1, n2, (is_assignment) ? -1 : 1);
  1214. // re-enable MOVE optimization
  1215. ircode_pragma(code, PRAGMA_MOVE_OPTIMIZATION, 1);
  1216. }
  1217. static void visit_file_expr (gvisitor_t *self, gnode_file_expr_t *node) {
  1218. DEBUG_CODEGEN("visit_file_expr");
  1219. DECLARE_CODE();
  1220. CODEGEN_COUNT_REGISTERS(n1);
  1221. // check if the node is a left expression of an assignment
  1222. bool is_assignment = node->base.is_assignment;
  1223. size_t count = gnode_array_size(node->identifiers);
  1224. for (size_t i=0; i<count; ++i) {
  1225. const char *identifier = gnode_array_get(node->identifiers, i);
  1226. uint16_t kindex = gravity_function_cpool_add(GET_VM(), context_function, VALUE_FROM_CSTRING(NULL, identifier));
  1227. if ((is_assignment) && (IS_LAST_LOOP(i, count))) {
  1228. uint32_t reg = ircode_register_pop(code);
  1229. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid file expression.");
  1230. ircode_add(code, STOREG, reg, kindex, 0);
  1231. } else {
  1232. ircode_add(code, LOADG, ircode_register_push_temp(code), kindex, 0);
  1233. }
  1234. }
  1235. CODEGEN_COUNT_REGISTERS(n2);
  1236. CODEGEN_ASSERT_REGISTERS(n1, n2, (is_assignment) ? -1 : 1);
  1237. }
  1238. static void visit_literal_expr (gvisitor_t *self, gnode_literal_expr_t *node) {
  1239. /*
  1240. NOTE:
  1241. doubles and int64 should be added to the constant pool but I avoid
  1242. adding them here so the optimizer has a way to perform better constant folding:
  1243. http://en.wikipedia.org/wiki/Constant_folding
  1244. http://www.compileroptimizations.com/category/constant_folding.htm
  1245. */
  1246. DEBUG_CODEGEN("visit_literal_expr");
  1247. DECLARE_CODE();
  1248. CODEGEN_COUNT_REGISTERS(n1);
  1249. switch (node->type) {
  1250. case LITERAL_STRING: {
  1251. // LOADK temp, s
  1252. uint16_t index = gravity_function_cpool_add(GET_VM(), context_function, VALUE_FROM_STRING(NULL, node->value.str, node->len));
  1253. ircode_add_constant(code, index);
  1254. DEBUG_CODEGEN("visit_literal_expr (string) %s", node->value.str);
  1255. } break;
  1256. case LITERAL_FLOAT:
  1257. // LOADI temp, d
  1258. ircode_add_double(code, node->value.d);
  1259. DEBUG_CODEGEN("visit_literal_expr (float) %.2f", node->value.d);
  1260. break;
  1261. case LITERAL_INT:
  1262. // LOADI temp, n
  1263. ircode_add_int(code, node->value.n64);
  1264. DEBUG_CODEGEN("visit_literal_expr (int) %lld", node->value.n64);
  1265. break;
  1266. case LITERAL_BOOL: {
  1267. uint32_t value = (node->value.n64 == 0) ? CPOOL_VALUE_FALSE : CPOOL_VALUE_TRUE;
  1268. ircode_add_constant(code, value);
  1269. DEBUG_CODEGEN("visit_literal_expr (bool) %lld", node->value.n64);
  1270. } break;
  1271. case LITERAL_STRING_INTERPOLATED: {
  1272. // codegen for string interpolation is like a list.join()
  1273. gnode_list_expr_t *list = (gnode_list_expr_t *)gnode_list_expr_create(node->base.token, node->value.r, NULL, false, node->base.decl);
  1274. visit((gnode_t *)list);
  1275. // list
  1276. uint32_t listreg = ircode_register_last(code);
  1277. if (listreg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid string interpolated expression.");
  1278. // LOADK
  1279. uint16_t index = gravity_function_cpool_add(GET_VM(), context_function, VALUE_FROM_CSTRING(NULL, "join"));
  1280. ircode_add_constant(code, index);
  1281. uint32_t temp1 = ircode_register_last(code);
  1282. DEBUG_ASSERT(temp1 != REGISTER_ERROR, "Unexpected register error.");
  1283. // LOAD
  1284. ircode_add(code, LOAD, temp1, listreg, temp1);
  1285. // temp1+1 register used for parameter passing
  1286. uint32_t temp2 = ircode_register_push_temp(code);
  1287. // MOVE
  1288. ircode_add(code, MOVE, temp2, listreg, 0);
  1289. // CALL
  1290. ircode_add(code, CALL, listreg, temp1, 1);
  1291. // cleanup
  1292. mem_free(list);
  1293. uint32_t temp = ircode_register_pop(code); // temp2
  1294. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  1295. temp = ircode_register_pop(code); // temp1
  1296. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  1297. /*
  1298. 00012 LOADK 6 4
  1299. 00013 LOAD 6 4 6
  1300. 00014 MOVE 7 6
  1301. 00015 MOVE 8 4
  1302. 00016 CALL 6 7 1
  1303. */
  1304. break;
  1305. }
  1306. default: assert(0);
  1307. }
  1308. CODEGEN_COUNT_REGISTERS(n2);
  1309. CODEGEN_ASSERT_REGISTERS(n1, n2, 1);
  1310. }
  1311. static void visit_identifier_expr (gvisitor_t *self, gnode_identifier_expr_t *node) {
  1312. DEBUG_CODEGEN("visit_identifier_expr %s", node->value);
  1313. DECLARE_CODE();
  1314. CODEGEN_COUNT_REGISTERS(n1);
  1315. // check if the node is a left expression of an assignment
  1316. bool is_assignment = node->base.is_assignment;
  1317. const char *identifier = node->value; // identifier as c string
  1318. gnode_location_type type = node->location.type; // location type
  1319. uint16_t index = node->location.index; // symbol index
  1320. uint16_t nup = node->location.nup; // upvalue index or outer index
  1321. switch (type) {
  1322. // local variable
  1323. case LOCATION_LOCAL: {
  1324. if (is_assignment) {
  1325. uint32_t reg = ircode_register_pop(code);
  1326. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid identifier expression.");
  1327. ircode_add(code, MOVE, index, reg, 0);
  1328. } else {
  1329. ircode_register_push(code, index);
  1330. }
  1331. } break;
  1332. // module (global) variable
  1333. case LOCATION_GLOBAL: {
  1334. uint16_t kindex = gravity_function_cpool_add(GET_VM(), context_function, VALUE_FROM_CSTRING(NULL, identifier));
  1335. if (is_assignment) {
  1336. uint32_t reg = ircode_register_pop(code);
  1337. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid identifier expression.");
  1338. ircode_add(code, STOREG, reg, kindex, 0);
  1339. } else {
  1340. ircode_add(code, LOADG, ircode_register_push_temp(code), kindex, 0);
  1341. }
  1342. } break;
  1343. // upvalue access
  1344. case LOCATION_UPVALUE: {
  1345. gupvalue_t *upvalue = node->upvalue;
  1346. if (is_assignment) {
  1347. uint32_t reg = ircode_register_pop(code);
  1348. if (reg == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid identifier expression.");
  1349. ircode_add(code, STOREU, reg, upvalue->selfindex, 0);
  1350. } else {
  1351. ircode_add(code, LOADU, ircode_register_push_temp(code), upvalue->selfindex, 0);
  1352. }
  1353. } break;
  1354. // class ivar case (outer case just need a loop lookup before)
  1355. case LOCATION_CLASS_IVAR_OUTER:
  1356. case LOCATION_CLASS_IVAR_SAME: {
  1357. // needs to differentiate ivar (indexed by an integer) from other cases (indexed by a string)
  1358. bool is_ivar = (index != UINT16_MAX);
  1359. uint32_t dest = 0;
  1360. uint32_t target = 0;
  1361. if (type == LOCATION_CLASS_IVAR_OUTER) {
  1362. dest = ircode_register_push_temp(code);
  1363. for (uint16_t i=0; i<nup; ++i) {
  1364. ircode_add(code, LOAD, dest, target, 0 + MAX_REGISTERS);
  1365. target = dest;
  1366. }
  1367. if (is_assignment) {
  1368. uint32_t temp = ircode_register_pop(code);
  1369. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  1370. }
  1371. }
  1372. uint32_t index_register;
  1373. if (is_ivar) {
  1374. // ivar case, use an index to load/retrieve it
  1375. index_register = index + MAX_REGISTERS;
  1376. } else {
  1377. // not an ivar so it could be another class declaration like a func, a class or an enum
  1378. // use lookup in order to retrieve it (assignment is handled here so you can change a
  1379. // first class citizen at runtime too)
  1380. uint16_t kindex = gravity_function_cpool_add(GET_VM(), context_function, VALUE_FROM_CSTRING(NULL, identifier));
  1381. index_register = ircode_register_push_temp(code);
  1382. ircode_add(code, LOADK, index_register, kindex, 0);
  1383. uint32_t temp = ircode_register_pop(code);
  1384. DEBUG_ASSERT(temp != REGISTER_ERROR, "Unexpected register error.");
  1385. }
  1386. if (is_assignment) {
  1387. // should be prohibited by semantic to store something into a non ivar slot?
  1388. dest = ircode_register_pop(code); // consume temp register
  1389. if (dest == REGISTER_ERROR) report_error(self, (gnode_t *)node, "Invalid identifier expression.");
  1390. ircode_add(code, STORE, dest, target, index_register);
  1391. } else {
  1392. dest = (type == LOCATION_CLASS_IVAR_OUTER) ? target : ircode_register_push_temp(code);
  1393. ircode_add(code, LOAD, dest , target, index_register);
  1394. }
  1395. } break;
  1396. }
  1397. CODEGEN_COUNT_REGISTERS(n2);
  1398. CODEGEN_ASSERT_REGISTERS(n1, n2, (is_assignment) ? -1 : 1);
  1399. }
  1400. static void visit_keyword_expr (gvisitor_t *self, gnode_keyword_expr_t *node) {
  1401. DEBUG_CODEGEN("visit_keyword_expr %s", token_name(node->base.token.type));
  1402. DECLARE_CODE();
  1403. CODEGEN_COUNT_REGISTERS(n1);
  1404. gtoken_t type = NODE_TOKEN_TYPE(node);
  1405. switch (type) {
  1406. case TOK_KEY_CURRFUNC:
  1407. ircode_add_constant(code, CPOOL_VALUE_FUNC);
  1408. break;
  1409. case TOK_KEY_NULL:
  1410. ircode_add_constant(code, CPOOL_VALUE_NULL);
  1411. break;
  1412. case TOK_KEY_SUPER:
  1413. ircode_add_constant(code, CPOOL_VALUE_SUPER);
  1414. break;
  1415. case TOK_KEY_CURRARGS:
  1416. // compiler can know in advance if arguments special array is used
  1417. context_function->useargs = true;
  1418. ircode_add_constant(code, CPOOL_VALUE_ARGUMENTS);
  1419. break;
  1420. case TOK_KEY_UNDEFINED:
  1421. ircode_add_constant(code, CPOOL_VALUE_UNDEFINED);
  1422. break;
  1423. case TOK_KEY_TRUE:
  1424. ircode_add_constant(code, CPOOL_VALUE_TRUE);
  1425. break;
  1426. case TOK_KEY_FALSE:
  1427. ircode_add_constant(code, CPOOL_VALUE_FALSE);
  1428. break;
  1429. default:
  1430. // should never reach this point
  1431. assert(0);
  1432. break;
  1433. }
  1434. CODEGEN_COUNT_REGISTERS(n2);
  1435. CODEGEN_ASSERT_REGISTERS(n1, n2, 1);
  1436. }
  1437. static void visit_list_expr (gvisitor_t *self, gnode_list_expr_t *node) {
  1438. DEBUG_CODEGEN("visit_list_expr");
  1439. DECLARE_CODE();
  1440. CODEGEN_COUNT_REGISTERS(n1);
  1441. bool ismap = node->ismap;
  1442. uint32_t n = (uint32_t)gnode_array_size(node->list1);
  1443. // a map requires twice registers than a list
  1444. uint32_t max_fields = (ismap) ? MAX_FIELDSxFLUSH : MAX_FIELDSxFLUSH*2;
  1445. // destination register of a new instruction is ALWAYS a temp register
  1446. // then the optimizer could decide to optimize and merge the step
  1447. uint32_t dest = ircode_register_push_temp(code);
  1448. ircode_add(code, (ismap) ? MAPNEW : LISTNEW, dest, n, 0);
  1449. if (n == 0) return;
  1450. // this is just like Lua "fields per flush"
  1451. // basically nodes are processed in a finite chunk
  1452. // and then added to the list/map
  1453. uint32_t nloops = n / max_fields;
  1454. if (n % max_fields != 0) ++nloops;
  1455. uint32_t nprocessed = 0;
  1456. ircode_pragma(code, PRAGMA_MOVE_OPTIMIZATION, 0);
  1457. while (nprocessed < n) {
  1458. size_t k = (n - nprocessed > max_fields) ? max_fields : (n - nprocessed);
  1459. size_t idxstart = nprocessed;
  1460. size_t idxend = nprocessed + k;
  1461. nprocessed += k;
  1462. // check if this chunk can be optimized
  1463. // if (check_literals_list(self, node, ismap, idxstart, idxend, dest)) continue;
  1464. // save register context
  1465. ircode_push_context(code);
  1466. // process each node
  1467. for (size_t i=1, j=idxstart; j<idxend; ++j) {
  1468. gnode_t *e = gnode_array_get(node->list1, j);
  1469. visit(e);
  1470. uint32_t nreg = ircode_register_pop_context_protect(code, true);
  1471. if ((nreg == REGISTER_ERROR) || ((nreg <= dest) && (ircode_register_istemp(code, nreg)))) {
  1472. report_error(self, (gnode_t *)e, "Invalid list expression.");
  1473. continue;
  1474. }
  1475. if (nreg != dest + i) {
  1476. uint32_t temp_register = ircode_register_push_temp(code);
  1477. ircode_add(code, MOVE, temp_register, nreg, 0);
  1478. ircode_register_clear(code, nreg);
  1479. uint32_t temp = ircode_register_pop_context_protect(code, true);
  1480. if (temp == REGISTER_ERROR) {report_error(self, (gnode_t *)e, "Unexpected register error."); continue;}
  1481. if (temp_register != dest + i) {report_error(self, (gnode_t *)e, "Unexpected register computation."); continue;}
  1482. }
  1483. if (ismap) {
  1484. e = gnode_array_get(node->list2, j);
  1485. ircode_pragma(code, PRAGMA_MOVE_OPTIMIZATION, 1);
  1486. visit(e);
  1487. ircode_pragma(code, PRAGMA_MOVE_OPTIMIZATION, 0);
  1488. nreg = ircode_register_pop_context_protect(code, true);
  1489. if ((nreg == REGISTER_ERROR) || ((nreg <= dest) && (ircode_register_istemp(code, nreg)))) {
  1490. report_error(self, (gnode_t *)e, "Invalid map expression.");
  1491. continue;
  1492. }
  1493. if (nreg != dest + i + 1) {
  1494. uint32_t temp_register = ircode_register_push_temp(code);
  1495. ircode_add(code, MOVE, temp_register, nreg, 0);
  1496. ircode_register_clear(code, nreg);
  1497. uint32_t temp = ircode_register_pop_context_protect(code, true);
  1498. if (temp == REGISTER_ERROR) {report_error(self, (gnode_t *)e, "Unexpected register error."); continue;}
  1499. if (temp_register != dest + i + 1) {report_error(self, (gnode_t *)e, "Unexpected register computation."); continue;}
  1500. }
  1501. }
  1502. i += (ismap) ? 2 : 1;
  1503. }
  1504. // emit proper SETLIST instruction
  1505. // since in a map registers are always used in pairs (key, value) it is
  1506. // extremely easier to just set reg1 to be always 0 and use r in a loop
  1507. ircode_add(code, SETLIST, dest, (uint32_t)(idxend-idxstart), 0);
  1508. // restore register context
  1509. ircode_pop_context(code);
  1510. }
  1511. ircode_pragma(code, PRAGMA_MOVE_OPTIMIZATION, 1);
  1512. CODEGEN_COUNT_REGISTERS(n2);
  1513. CODEGEN_ASSERT_REGISTERS(n1, n2, 1);
  1514. }
  1515. // MARK: -
  1516. gravity_function_t *gravity_codegen(gnode_t *node, gravity_delegate_t *delegate, gravity_vm *vm) {
  1517. codegen_t data;
  1518. data.vm = vm;
  1519. marray_init(data.context);
  1520. marray_init(data.superfix);
  1521. ircode_t *code = ircode_create(0);
  1522. gravity_function_t *f = gravity_function_new(vm, INITMODULE_NAME, 0, 0, 0, code);
  1523. marray_push(gravity_object_t*, data.context, (gravity_object_t *)f);
  1524. gvisitor_t visitor = {
  1525. .nerr = 0, // used for internal codegen errors
  1526. .data = &data, // used to store a pointer to codegen struct
  1527. .delegate = (void *)delegate, // compiler delegate to report errors
  1528. // COMMON
  1529. .visit_pre = NULL,
  1530. .visit_post = NULL,
  1531. // STATEMENTS: 7
  1532. .visit_list_stmt = visit_list_stmt,
  1533. .visit_compound_stmt = visit_compound_stmt,
  1534. .visit_label_stmt = visit_label_stmt,
  1535. .visit_flow_stmt = visit_flow_stmt,
  1536. .visit_loop_stmt = visit_loop_stmt,
  1537. .visit_jump_stmt = visit_jump_stmt,
  1538. .visit_empty_stmt = visit_empty_stmt,
  1539. // DECLARATIONS: 5
  1540. .visit_function_decl = visit_function_decl,
  1541. .visit_variable_decl = visit_variable_decl,
  1542. .visit_enum_decl = visit_enum_decl,
  1543. .visit_class_decl = visit_class_decl,
  1544. .visit_module_decl = visit_module_decl,
  1545. // EXPRESSIONS: 8
  1546. .visit_binary_expr = visit_binary_expr,
  1547. .visit_unary_expr = visit_unary_expr,
  1548. .visit_file_expr = visit_file_expr,
  1549. .visit_literal_expr = visit_literal_expr,
  1550. .visit_identifier_expr = visit_identifier_expr,
  1551. .visit_keyword_expr = visit_keyword_expr,
  1552. .visit_list_expr = visit_list_expr,
  1553. .visit_postfix_expr = visit_postfix_expr,
  1554. };
  1555. DEBUG_CODEGEN("=== BEGIN CODEGEN ===");
  1556. gvisit(&visitor, node);
  1557. DEBUG_CODEGEN("\n");
  1558. // check for special superfix
  1559. if (marray_size(data.superfix)) {
  1560. fix_superclasses(&visitor);
  1561. }
  1562. // pop globals instance init special function
  1563. marray_pop(data.context);
  1564. assert(marray_size(data.context) == 0);
  1565. marray_destroy(data.context);
  1566. // in case of codegen errors explicity free code and return NULL
  1567. if (visitor.nerr != 0) {ircode_free(code); f->bytecode = NULL;}
  1568. return (visitor.nerr == 0) ? f : NULL;
  1569. }