Compiler.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. #include <setjmp.h>
  2. #include <stdarg.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include "Check.h"
  7. #include "Compiler.h"
  8. #include "DataType.h"
  9. #include "tokenizer/Tokenizer.h"
  10. #include "utils/Functions.h"
  11. #include "utils/Variables.h"
  12. #include "vm/Operation.h"
  13. static Error* error = NULL;
  14. static ByteCode* code;
  15. static int16 line = 1;
  16. static const char* path = NULL;
  17. static jmp_buf errorJump;
  18. #define RETURN_BUFFER 16
  19. #define BREAK_BUFFER 32
  20. #define DT_OPERATION(op) \
  21. case RDT_INT: cAddOperation(OP_##op##_INT); break; \
  22. case RDT_FLOAT: cAddOperation(OP_##op##_FLOAT); break;
  23. typedef DataType (*Parser)(void);
  24. static bool onLine = false;
  25. static Variables vars;
  26. static Variables globalVars;
  27. static Functions functions;
  28. static Functions functionQueue;
  29. static Structs structs;
  30. static int returns[RETURN_BUFFER];
  31. static int returnIndex = 0;
  32. static int hasReturn = 0;
  33. static DataType returnType;
  34. static int breaks[BREAK_BUFFER];
  35. static int breakIndex = 0;
  36. static int forWhileStack = 0;
  37. static int continueAt = 0;
  38. typedef struct {
  39. const char* name;
  40. Operation intOp;
  41. Operation floatOp;
  42. Operation pointerOp;
  43. char padding[sizeof(Operation)];
  44. } TypedOp;
  45. #define TYPE_OP(NAME, FLOAT, POINTER, text) \
  46. static const TypedOp TYPED_##NAME = { \
  47. text, OP_##NAME##_INT, OP_##FLOAT, OP_##POINTER, {0}};
  48. TYPE_OP(MUL, MUL_FLOAT, NOTHING, "*")
  49. TYPE_OP(DIV, DIV_FLOAT, NOTHING, "/")
  50. TYPE_OP(MOD, NOTHING, NOTHING, "%")
  51. TYPE_OP(ADD, ADD_FLOAT, NOTHING, "+")
  52. TYPE_OP(SUB, SUB_FLOAT, NOTHING, "-")
  53. TYPE_OP(LESS, LESS_FLOAT, NOTHING, "<")
  54. TYPE_OP(LESS_EQUAL, LESS_EQUAL_FLOAT, NOTHING, "<=")
  55. TYPE_OP(GREATER, GREATER_FLOAT, NOTHING, ">")
  56. TYPE_OP(GREATER_EQUAL, GREATER_EQUAL_FLOAT, NOTHING, ">=")
  57. TYPE_OP(EQUAL, EQUAL_FLOAT, EQUAL_POINTER, "==")
  58. TYPE_OP(NOT_EQUAL, NOT_EQUAL_FLOAT, NOT_EQUAL_POINTER, "!=")
  59. TYPE_OP(BIT_OR, NOTHING, NOTHING, "|")
  60. TYPE_OP(BIT_XOR, NOTHING, NOTHING, "^")
  61. TYPE_OP(BIT_AND, NOTHING, NOTHING, "&")
  62. TYPE_OP(LEFT_SHIFT, NOTHING, NOTHING, "<<")
  63. TYPE_OP(RIGHT_SHIFT, NOTHING, NOTHING, ">>")
  64. static check_format(1, 2) void cError(const char* format, ...) {
  65. va_list args;
  66. va_start(args, format);
  67. eInitErrorV(error, path, line, format, args);
  68. va_end(args);
  69. longjmp(errorJump, 0);
  70. }
  71. static const char* cGetName(DataType dt) {
  72. return dtGetName(&structs, dt);
  73. }
  74. static void cInvalidOperation(DataType a, DataType b, const char* op) {
  75. cError("invalid operation: %s %s %s", cGetName(a), op, cGetName(b));
  76. }
  77. static void cNotDeclared(const char* name) {
  78. cError("variable %s has not been declared", name);
  79. }
  80. static void cDeclared(const char* name) {
  81. cError("%s has already been declared", name);
  82. }
  83. static void cTooMuchArguments(void) {
  84. cError("too much function arguments");
  85. }
  86. static void cUnexpectedToken(Token t) {
  87. cError("unexpected token: %s", tGetName(t));
  88. }
  89. #define BUFFER_SIZE 256
  90. static void cUnknownFunction(Function* f) {
  91. int max = 0;
  92. char buffer[BUFFER_SIZE] = {'\0'};
  93. for(int i = 0; i < f->arguments; i++) {
  94. const char* name = dtGetName(&structs, f->argumentTypes[i]);
  95. max += snprintf(buffer + max, (size_t)(BUFFER_SIZE - max),
  96. i > 0 ? ", %s" : "%s", name);
  97. }
  98. cError("unknown function: %s(%s)", f->name, buffer);
  99. }
  100. static void cAddOperation(Operation token) {
  101. unsigned char c = token;
  102. bcAddBytes(code, &c, 1);
  103. }
  104. static int32 cReserveInt32(void) {
  105. return bcReserveBytes(code, sizeof(int32));
  106. }
  107. static void cSetInt32(int p, int32 i) {
  108. bcSetBytes(code, p, &i, sizeof(int32));
  109. }
  110. static void cAddInt32(int32 i) {
  111. bcAddBytes(code, &i, sizeof(int32));
  112. }
  113. static void cAddInt32Operation(Operation token, int32 i) {
  114. cAddOperation(token);
  115. cAddInt32(i);
  116. }
  117. static void cAddByteOperation(Operation token, int8 i) {
  118. cAddOperation(token);
  119. bcAddBytes(code, &i, sizeof(int8));
  120. }
  121. static void cAddLine(int16 l) {
  122. cAddOperation(OP_LINE);
  123. bcAddBytes(code, &l, sizeof(int16));
  124. }
  125. static Token cReadTokenAndLine(void) {
  126. hasReturn--;
  127. Token t;
  128. if(tReadTokenAndLine(&t, &line)) {
  129. return T_END;
  130. }
  131. return t;
  132. }
  133. static void cConsumeToken(Token wanted) {
  134. Token t = cReadTokenAndLine();
  135. if(wanted != t) {
  136. cError("expected '%s' got '%s'", tGetName(wanted), tGetName(t));
  137. }
  138. }
  139. static bool cConsumeTokenIf(Token t) {
  140. return tPeekToken() == t && cReadTokenAndLine() == t;
  141. }
  142. static void cConstantInt32(void) {
  143. int32 value;
  144. if(tReadInt32(&value)) {
  145. cError("int token without an int");
  146. }
  147. cAddInt32Operation(OP_PUSH_INT, value);
  148. }
  149. static void cConstantFloat(void) {
  150. float value;
  151. if(tReadFloat(&value)) {
  152. cError("float token without a float");
  153. }
  154. cAddOperation(OP_PUSH_FLOAT);
  155. bcAddBytes(code, &value, sizeof(float));
  156. }
  157. static const char* cReadString(void) {
  158. const char* literal = tReadString();
  159. if(literal == NULL) {
  160. cError("literal without string on line %d", line);
  161. }
  162. return literal;
  163. }
  164. static int cGetSize(DataType dt) {
  165. return dtGetSize(dt, &structs);
  166. }
  167. static DataType cExtendType(DataType dt) {
  168. if(cConsumeTokenIf(T_OPEN_SQUARE_BRACKET)) {
  169. cConsumeToken(T_CLOSE_SQUARE_BRACKET);
  170. dt = dtToArray(dt);
  171. }
  172. return dt;
  173. }
  174. static DataType cReadType(Token t, bool force) {
  175. switch(t) {
  176. case T_INT: return dtInt();
  177. case T_FLOAT: return dtFloat();
  178. case T_LITERAL: {
  179. const char* name = cReadString();
  180. Struct* st = stsSearch(&structs, name);
  181. if(st == NULL) {
  182. if(force) {
  183. cError("struct %s does not exist", name);
  184. } else {
  185. return dtVoid();
  186. }
  187. }
  188. return dtStruct(st);
  189. }
  190. default:
  191. if(force) {
  192. cUnexpectedToken(t);
  193. }
  194. return dtVoid();
  195. }
  196. }
  197. static DataType cReadExtendedType(Token t, bool force) {
  198. DataType dt = cReadType(t, force);
  199. if(!dtIsVoid(dt)) {
  200. dt = cExtendType(dt);
  201. }
  202. return dt;
  203. }
  204. static DataType cExpression(void);
  205. static void cLoadRef(DataType type) {
  206. if(dtIsArray(type)) {
  207. cAddOperation(OP_LOAD_ARRAY);
  208. return;
  209. }
  210. switch(dtGetType(type)) {
  211. DT_OPERATION(LOAD);
  212. default: cError("cannot load type %s", cGetName(type));
  213. }
  214. }
  215. static DataType cUnpack(DataType dt) {
  216. if(!dtIsStruct(dt) && dtRemovePointer(&dt)) {
  217. cLoadRef(dt);
  218. }
  219. return dt;
  220. }
  221. static DataType cUnpackedExpression(void) {
  222. return cUnpack(cExpression());
  223. }
  224. static void cCallFunctionArguments(Function* f) {
  225. if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  226. return;
  227. }
  228. while(true) {
  229. DataType dt = cUnpackedExpression();
  230. if(fAddArgument(f, dt, &structs)) {
  231. cTooMuchArguments();
  232. } else if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  233. return;
  234. }
  235. cConsumeToken(T_COMMA);
  236. }
  237. }
  238. static DataType cCallFunction(const char* name) {
  239. int returnAddress = bcGetAddress(code);
  240. Function f;
  241. fInit(&f, name, line);
  242. int oldOnLine = onLine;
  243. onLine = false;
  244. cCallFunctionArguments(&f);
  245. onLine = oldOnLine;
  246. Function* found = fsSearch(&functions, &f);
  247. if(found == NULL) {
  248. cUnknownFunction(&f);
  249. } else if(found->global) {
  250. cAddInt32Operation(OP_CALL, found->line);
  251. return found->returnType;
  252. }
  253. char push[1 + sizeof(int32)] = {OP_PUSH_INT};
  254. bcInsertBytes(code, push, sizeof(push), returnAddress);
  255. cAddOperation(OP_GOSUB);
  256. if(found->address == -1) {
  257. f.returnType = found->returnType;
  258. f.address = cReserveInt32();
  259. fsAdd(&functionQueue, &f);
  260. } else {
  261. cAddInt32(found->address);
  262. }
  263. cAddInt32(found->size);
  264. return found->returnType;
  265. }
  266. static void cStore(DataType left, DataType right, const char* name) {
  267. if(dtIsArray(left)) {
  268. if(!dtCompare(left, right)) {
  269. cInvalidOperation(left, right, name);
  270. }
  271. cAddOperation(OP_STORE_ARRAY);
  272. return;
  273. }
  274. if(!dtCompare(left, right)) {
  275. cInvalidOperation(left, right, name);
  276. }
  277. switch(dtGetType(left)) {
  278. DT_OPERATION(STORE);
  279. default: cError("cannot store type %s", cGetName(left));
  280. }
  281. }
  282. static DataType cLiteral(void) {
  283. const char* literal = cReadString();
  284. if(cConsumeTokenIf(T_OPEN_BRACKET)) {
  285. return cCallFunction(literal);
  286. }
  287. Variable v;
  288. if(!vsSearch(&vars, &v, literal)) {
  289. if(dtIsPointer(v.type)) {
  290. if(!dtIsStruct(v.type)) {
  291. cError("non struct type %s should not be a pointer here",
  292. cGetName(v.type));
  293. }
  294. cAddInt32Operation(OP_PUSH_STRUCT_REFERENCE, v.address);
  295. } else {
  296. cAddInt32Operation(OP_DEREFERENCE_VAR, v.address);
  297. }
  298. return dtToPointer(v.type);
  299. } else if(!vsSearch(&globalVars, &v, literal)) {
  300. cAddInt32Operation(OP_DEREFERENCE_GVAR, v.address);
  301. return dtToPointer(v.type);
  302. }
  303. cNotDeclared(literal);
  304. return dtVoid();
  305. }
  306. static DataType cText(void) {
  307. cAddOperation(OP_PUSH_TEXT);
  308. int32 lengthAddress = cReserveInt32();
  309. int32 length = 0;
  310. int32 c;
  311. while(!tReadInt32(&c) && c != 0) {
  312. cAddInt32(c);
  313. length++;
  314. }
  315. cSetInt32(lengthAddress, length);
  316. return dtText();
  317. }
  318. static DataType cBracketPrimary(void) {
  319. DataType result = cExpression();
  320. cConsumeToken(T_CLOSE_BRACKET);
  321. return result;
  322. }
  323. static void cArrayIndex(void) {
  324. if(!dtIsInt(cUnpackedExpression())) {
  325. cError("array index must be an int");
  326. }
  327. }
  328. static DataType cAllocArray(void) {
  329. DataType dt = cReadType(cReadTokenAndLine(), true);
  330. if(dtIsArray(dt)) {
  331. cError("array type must not be an array");
  332. }
  333. cConsumeToken(T_OPEN_SQUARE_BRACKET);
  334. cArrayIndex();
  335. cConsumeToken(T_CLOSE_SQUARE_BRACKET);
  336. cAddInt32Operation(OP_NEW, cGetSize(dt));
  337. return dtToArray(dt);
  338. }
  339. static DataType cLength(void) {
  340. DataType array = cUnpackedExpression();
  341. if(!dtIsArray(array)) {
  342. cError("length expects an array");
  343. }
  344. cAddOperation(OP_LENGTH);
  345. return dtInt();
  346. }
  347. static DataType cPrimary(void) {
  348. Token t = cReadTokenAndLine();
  349. switch(t) {
  350. case T_INT_VALUE: cConstantInt32(); return dtInt();
  351. case T_FLOAT_VALUE: cConstantFloat(); return dtFloat();
  352. case T_TEXT: return cText();
  353. case T_OPEN_BRACKET: return cBracketPrimary();
  354. case T_LITERAL: return cLiteral();
  355. case T_NEW: return cAllocArray();
  356. case T_LENGTH: return cLength();
  357. default: cUnexpectedToken(t); return dtVoid();
  358. }
  359. }
  360. static void cRemoveReference(DataType* dt, const char* name) {
  361. if(!dtRemovePointer(dt)) {
  362. cError("%s needs a reference not %s", name, cGetName(*dt));
  363. }
  364. }
  365. static void cExpectType(DataType actual, DataType wanted, const char* name) {
  366. if(!dtCompare(actual, wanted)) {
  367. cError("%s needs %s not %s", name, cGetName(wanted), cGetName(actual));
  368. }
  369. }
  370. static void cChangeType(DataType* dt, Operation op, Operation pushOp,
  371. int8 change) {
  372. if(onLine) {
  373. cAddByteOperation(op, change);
  374. *dt = dtVoid();
  375. } else {
  376. cAddByteOperation(pushOp, change);
  377. }
  378. }
  379. static void cPostChange(DataType* dt, int8 change, const char* name) {
  380. cRemoveReference(dt, name);
  381. if(dtIsInt(*dt)) {
  382. cChangeType(dt, OP_CHANGE_INT, OP_PUSH_POST_CHANGE_INT, change);
  383. } else {
  384. cError("%s needs an int not %s", name, cGetName(*dt));
  385. }
  386. }
  387. static DataType cStructAccess(DataType dt) {
  388. Struct* st = dtGetStruct(&structs, dt);
  389. if(st == NULL) {
  390. cError(". expects a struct not %s", cGetName(dt));
  391. }
  392. cConsumeToken(T_LITERAL);
  393. const char* name = cReadString();
  394. Variable inner;
  395. if(vSearchStruct(&inner, &structs, st, name)) {
  396. cError("%s has no member %s", st->name, name);
  397. } else if(inner.address > 0) {
  398. cAddInt32Operation(OP_PUSH_INT, inner.address);
  399. cAddInt32Operation(OP_ADD_REFERENCE, 1);
  400. }
  401. return dtToPointer(inner.type);
  402. }
  403. static DataType cAccess(void) {
  404. DataType dt = cPrimary();
  405. while(true) {
  406. if(cConsumeTokenIf(T_INCREMENT)) {
  407. cPostChange(&dt, 1, "++");
  408. } else if(cConsumeTokenIf(T_DECREMENT)) {
  409. cPostChange(&dt, -1, "--");
  410. } else if(cConsumeTokenIf(T_POINT)) {
  411. cRemoveReference(&dt, ".");
  412. dt = cStructAccess(dt);
  413. } else if(cConsumeTokenIf(T_OPEN_SQUARE_BRACKET)) {
  414. if(!dtIsArray(dt)) {
  415. cError("[] needs an array");
  416. }
  417. cAddOperation(OP_LOAD_ARRAY);
  418. dtRemovePointer(&dt);
  419. cArrayIndex();
  420. cConsumeToken(T_CLOSE_SQUARE_BRACKET);
  421. cAddInt32Operation(OP_ADD_REFERENCE, cGetSize(dt));
  422. dt = dtToPointer(dtRemoveArray(dt));
  423. } else {
  424. return dt;
  425. }
  426. }
  427. }
  428. static DataType cPreChange(DataType dt, int8 change, const char* name) {
  429. cRemoveReference(&dt, name);
  430. if(dtIsInt(dt)) {
  431. cChangeType(&dt, OP_CHANGE_INT, OP_PUSH_PRE_CHANGE_INT, change);
  432. } else {
  433. cError("%s needs an int not %s", name, cGetName(dt));
  434. }
  435. return dt;
  436. }
  437. static DataType cInvertSign(DataType dt) {
  438. if(dtIsInt(dt)) {
  439. cAddOperation(OP_INVERT_SIGN_INT);
  440. } else if(dtIsFloat(dt)) {
  441. cAddOperation(OP_INVERT_SIGN_FLOAT);
  442. } else {
  443. cError("cannot invert sign of %s", cGetName(dt));
  444. }
  445. return dt;
  446. }
  447. static DataType cCast(DataType in, DataType a, Operation aOp, DataType out) {
  448. if(dtCompare(in, a)) {
  449. cAddOperation(aOp);
  450. } else {
  451. cError("cannot cast %s to %s", cGetName(in), cGetName(out));
  452. }
  453. return out;
  454. }
  455. static DataType cUnaryNot(DataType dt) {
  456. cExpectType(dt, dtInt(), "!");
  457. cAddOperation(OP_NOT);
  458. return dt;
  459. }
  460. static DataType cUnaryBitNot(DataType dt) {
  461. if(dtIsInt(dt)) {
  462. cAddOperation(OP_BIT_NOT_INT);
  463. } else {
  464. cError("~ needs an int not %s", cGetName(dt));
  465. }
  466. return dt;
  467. }
  468. static DataType cPreUnary(void) {
  469. int marker = tGetMarker();
  470. if(cConsumeTokenIf(T_OPEN_BRACKET)) {
  471. if(cConsumeTokenIf(T_FLOAT) && cConsumeTokenIf(T_CLOSE_BRACKET)) {
  472. return cCast(cUnpack(cPreUnary()), dtInt(), OP_INT_TO_FLOAT,
  473. dtFloat());
  474. } else if(cConsumeTokenIf(T_INT) && cConsumeTokenIf(T_CLOSE_BRACKET)) {
  475. return cCast(cUnpack(cPreUnary()), dtFloat(), OP_FLOAT_TO_INT,
  476. dtInt());
  477. }
  478. }
  479. tReset(marker);
  480. if(cConsumeTokenIf(T_INCREMENT)) {
  481. return cPreChange(cPreUnary(), 1, "++");
  482. } else if(cConsumeTokenIf(T_DECREMENT)) {
  483. return cPreChange(cPreUnary(), -1, "--");
  484. } else if(cConsumeTokenIf(T_SUB)) {
  485. return cInvertSign(cUnpack(cPreUnary()));
  486. } else if(cConsumeTokenIf(T_NOT)) {
  487. return cUnaryNot(cPreUnary());
  488. } else if(cConsumeTokenIf(T_BIT_NOT)) {
  489. return cUnaryBitNot(cPreUnary());
  490. }
  491. return cAccess();
  492. }
  493. static void cAddTypeOperation(DataType* a, Parser bf, const TypedOp* op) {
  494. *a = cUnpack(*a);
  495. DataType b = cUnpack(bf());
  496. if(!dtCompare(*a, b)) {
  497. cInvalidOperation(*a, b, op->name);
  498. } else if(dtIsInt(*a) && op->intOp != OP_NOTHING) {
  499. cAddOperation(op->intOp);
  500. } else if(dtIsFloat(*a) && op->floatOp != OP_NOTHING) {
  501. cAddOperation(op->floatOp);
  502. } else if(dtIsArray(*a) && op->pointerOp != OP_NOTHING) {
  503. cAddOperation(op->pointerOp);
  504. } else {
  505. cInvalidOperation(*a, b, op->name);
  506. }
  507. }
  508. static DataType cMul(void) {
  509. DataType a = cPreUnary();
  510. while(true) {
  511. if(cConsumeTokenIf(T_MUL)) {
  512. cAddTypeOperation(&a, cPreUnary, &TYPED_MUL);
  513. } else if(cConsumeTokenIf(T_DIV)) {
  514. cAddTypeOperation(&a, cPreUnary, &TYPED_DIV);
  515. } else if(cConsumeTokenIf(T_MOD)) {
  516. cAddTypeOperation(&a, cPreUnary, &TYPED_MOD);
  517. } else {
  518. return a;
  519. }
  520. }
  521. }
  522. static DataType cAdd(void) {
  523. DataType a = cMul();
  524. while(true) {
  525. if(cConsumeTokenIf(T_ADD)) {
  526. cAddTypeOperation(&a, cMul, &TYPED_ADD);
  527. } else if(cConsumeTokenIf(T_SUB)) {
  528. cAddTypeOperation(&a, cMul, &TYPED_SUB);
  529. } else {
  530. return a;
  531. }
  532. }
  533. }
  534. static DataType cShift(void) {
  535. DataType a = cAdd();
  536. while(true) {
  537. if(cConsumeTokenIf(T_LEFT_SHIFT)) {
  538. cAddTypeOperation(&a, cAdd, &TYPED_LEFT_SHIFT);
  539. } else if(cConsumeTokenIf(T_RIGHT_SHIFT)) {
  540. cAddTypeOperation(&a, cAdd, &TYPED_RIGHT_SHIFT);
  541. } else {
  542. return a;
  543. }
  544. }
  545. }
  546. static DataType cComparison(void) {
  547. DataType a = cShift();
  548. while(true) {
  549. if(cConsumeTokenIf(T_LESS)) {
  550. cAddTypeOperation(&a, cShift, &TYPED_LESS);
  551. a = dtInt();
  552. } else if(cConsumeTokenIf(T_LESS_EQUAL)) {
  553. cAddTypeOperation(&a, cShift, &TYPED_LESS_EQUAL);
  554. a = dtInt();
  555. } else if(cConsumeTokenIf(T_GREATER)) {
  556. cAddTypeOperation(&a, cShift, &TYPED_GREATER);
  557. a = dtInt();
  558. } else if(cConsumeTokenIf(T_GREATER_EQUAL)) {
  559. cAddTypeOperation(&a, cShift, &TYPED_GREATER_EQUAL);
  560. a = dtInt();
  561. } else {
  562. return a;
  563. }
  564. }
  565. }
  566. static DataType cEqual(void) {
  567. DataType a = cComparison();
  568. while(true) {
  569. if(cConsumeTokenIf(T_EQUAL)) {
  570. cAddTypeOperation(&a, cComparison, &TYPED_EQUAL);
  571. a = dtInt();
  572. } else if(cConsumeTokenIf(T_NOT_EQUAL)) {
  573. cAddTypeOperation(&a, cComparison, &TYPED_NOT_EQUAL);
  574. a = dtInt();
  575. } else {
  576. return a;
  577. }
  578. }
  579. }
  580. static DataType cRepeat(Token t, Parser f, const TypedOp* op) {
  581. DataType a = f();
  582. while(cConsumeTokenIf(t)) {
  583. cAddTypeOperation(&a, f, op);
  584. }
  585. return a;
  586. }
  587. static DataType cBitAnd(void) {
  588. return cRepeat(T_BIT_AND, cEqual, &TYPED_BIT_AND);
  589. }
  590. static DataType cBitXor(void) {
  591. return cRepeat(T_BIT_XOR, cBitAnd, &TYPED_BIT_XOR);
  592. }
  593. static DataType cBitOr(void) {
  594. return cRepeat(T_BIT_OR, cBitXor, &TYPED_BIT_OR);
  595. }
  596. static DataType cLogical(Parser f, Token t, Operation jump, Operation op) {
  597. DataType a = f();
  598. while(cConsumeTokenIf(t)) {
  599. cAddOperation(jump);
  600. int32 p = cReserveInt32();
  601. DataType b = f();
  602. if(!dtIsInt(a) || !dtIsInt(b)) {
  603. cInvalidOperation(a, b, tGetName(t));
  604. }
  605. cAddOperation(op);
  606. cSetInt32(p, code->length);
  607. }
  608. return a;
  609. }
  610. static DataType cAnd(void) {
  611. return cLogical(cBitOr, T_AND, OP_PEEK_FALSE_GOTO, OP_AND);
  612. }
  613. static DataType cExpression(void) {
  614. return cLogical(cAnd, T_OR, OP_PEEK_TRUE_GOTO, OP_OR);
  615. }
  616. static void cLine(void);
  617. static void cConsumeBody(void) {
  618. int16 oldLine = line;
  619. while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) {
  620. if(tPeekToken() == T_END) {
  621. line = oldLine;
  622. cError("non closed curved bracket");
  623. }
  624. cLine();
  625. }
  626. }
  627. static void cConsumeScope(void) {
  628. Scope scope;
  629. vsEnterScope(&vars, &scope);
  630. cConsumeBody();
  631. vsLeaveScope(&vars, &scope);
  632. }
  633. static void cAddReturn(Operation op) {
  634. if(returnIndex >= RETURN_BUFFER) {
  635. cError("too much returns in function");
  636. }
  637. cAddOperation(op);
  638. returns[returnIndex++] = cReserveInt32();
  639. }
  640. static void cReturn(void) {
  641. if(dtIsVoid(returnType)) {
  642. cConsumeToken(T_SEMICOLON);
  643. cAddReturn(OP_RETURN);
  644. hasReturn = 2;
  645. return;
  646. }
  647. DataType dt = cUnpackedExpression();
  648. if(!dtCompare(returnType, dt)) {
  649. cError("wrong return type, should be %s", cGetName(returnType));
  650. } else if(dtIsInt(dt)) {
  651. cAddReturn(OP_RETURN_INT);
  652. } else if(dtIsFloat(dt)) {
  653. cAddReturn(OP_RETURN_FLOAT);
  654. } else if(dtIsArray(dt)) {
  655. cAddReturn(OP_RETURN_POINTER);
  656. } else {
  657. cError("cannot return %s", cGetName(dt));
  658. }
  659. cConsumeToken(T_SEMICOLON);
  660. hasReturn = 2;
  661. }
  662. static void cIf(void) {
  663. cConsumeToken(T_OPEN_BRACKET);
  664. cExpectType(cExpression(), dtInt(), "if");
  665. cConsumeToken(T_CLOSE_BRACKET);
  666. cAddOperation(OP_IF_GOTO);
  667. int32 ifP = cReserveInt32();
  668. cConsumeToken(T_OPEN_CURVED_BRACKET);
  669. cConsumeScope();
  670. cSetInt32(ifP, code->length);
  671. if(cConsumeTokenIf(T_ELSE)) {
  672. cAddOperation(OP_GOTO);
  673. int32 elseP = cReserveInt32();
  674. cSetInt32(ifP, code->length);
  675. if(cConsumeTokenIf(T_IF)) {
  676. cIf();
  677. } else {
  678. cConsumeToken(T_OPEN_CURVED_BRACKET);
  679. cConsumeScope();
  680. }
  681. cSetInt32(elseP, code->length);
  682. }
  683. }
  684. static void cConsumeBreaks(int start, int address) {
  685. for(int i = start; i < breakIndex; i++) {
  686. cSetInt32(breaks[i], address);
  687. }
  688. breakIndex = start;
  689. }
  690. static void cWhile(void) {
  691. int start = code->length;
  692. cConsumeToken(T_OPEN_BRACKET);
  693. cExpectType(cExpression(), dtInt(), "while");
  694. cConsumeToken(T_CLOSE_BRACKET);
  695. cAddOperation(OP_IF_GOTO);
  696. int32 ifP = cReserveInt32();
  697. int breakStart = breakIndex;
  698. forWhileStack++;
  699. int oldContinue = continueAt;
  700. continueAt = start;
  701. cConsumeToken(T_OPEN_CURVED_BRACKET);
  702. cConsumeScope();
  703. continueAt = oldContinue;
  704. forWhileStack--;
  705. cAddInt32Operation(OP_GOTO, start);
  706. cSetInt32(ifP, code->length);
  707. cConsumeBreaks(breakStart, code->length);
  708. }
  709. static void cOperationSet(DataType left, const TypedOp* op) {
  710. cAddOperation(OP_DUPLICATE_REFERENCE);
  711. cLoadRef(left);
  712. cAddTypeOperation(&left, cUnpackedExpression, op);
  713. cStore(left, left, "=");
  714. }
  715. static void cSetVariable(void) {
  716. onLine = true;
  717. DataType dt = cPreUnary();
  718. onLine = false;
  719. if(dtIsVoid(dt)) {
  720. return;
  721. }
  722. cRemoveReference(&dt, "setter");
  723. Token t = cReadTokenAndLine();
  724. switch(t) {
  725. case T_SET: cStore(dt, cUnpackedExpression(), "="); break;
  726. case T_ADD_SET: cOperationSet(dt, &TYPED_ADD); break;
  727. case T_SUB_SET: cOperationSet(dt, &TYPED_SUB); break;
  728. case T_MUL_SET: cOperationSet(dt, &TYPED_MUL); break;
  729. case T_DIV_SET: cOperationSet(dt, &TYPED_DIV); break;
  730. case T_MOD_SET: cOperationSet(dt, &TYPED_MOD); break;
  731. case T_BIT_AND_SET: cOperationSet(dt, &TYPED_BIT_AND); break;
  732. case T_BIT_OR_SET: cOperationSet(dt, &TYPED_BIT_OR); break;
  733. case T_BIT_XOR_SET: cOperationSet(dt, &TYPED_BIT_XOR); break;
  734. case T_LEFT_SHIFT_SET: cOperationSet(dt, &TYPED_LEFT_SHIFT); break;
  735. case T_RIGHT_SHIFT_SET: cOperationSet(dt, &TYPED_RIGHT_SHIFT); break;
  736. default: cUnexpectedToken(t);
  737. }
  738. }
  739. static void cDeclareSet(Variables* vs, DataType dt, const char* var,
  740. Operation op) {
  741. if(vsInScope(vs, var)) {
  742. cDeclared(var);
  743. }
  744. Variable* v = vsAdd(vs, var, dt, &structs);
  745. if(!dtIsStruct(dt) || dtIsArray(dt)) {
  746. cConsumeToken(T_SET);
  747. cAddInt32Operation(op, v->address);
  748. DataType right = cUnpackedExpression();
  749. cStore(dt, right, "=");
  750. }
  751. }
  752. static bool cDeclaration(Token t) {
  753. DataType dt = cReadExtendedType(t, false);
  754. if(dtIsVoid(dt)) {
  755. return false;
  756. }
  757. cConsumeToken(T_LITERAL);
  758. const char* var = cReadString();
  759. cDeclareSet(&vars, dt, var, OP_DEREFERENCE_VAR);
  760. return true;
  761. }
  762. static void cLineExpression(void) {
  763. int marker = tGetMarker();
  764. Token t = cReadTokenAndLine();
  765. if(cDeclaration(t)) {
  766. return;
  767. }
  768. tReset(marker);
  769. cSetVariable();
  770. }
  771. static void cFor(void) {
  772. Scope scope;
  773. vsEnterScope(&vars, &scope);
  774. cConsumeToken(T_OPEN_BRACKET);
  775. cLineExpression();
  776. cConsumeToken(T_SEMICOLON);
  777. int startCheck = code->length;
  778. cExpectType(cExpression(), dtInt(), "for");
  779. cConsumeToken(T_SEMICOLON);
  780. cAddOperation(OP_IF_GOTO);
  781. int32 end = cReserveInt32();
  782. cAddOperation(OP_GOTO);
  783. int32 beginBody = cReserveInt32();
  784. int startPerLoop = code->length;
  785. cLineExpression();
  786. cAddInt32Operation(OP_GOTO, startCheck);
  787. cConsumeToken(T_CLOSE_BRACKET);
  788. cSetInt32(beginBody, code->length);
  789. int breakStart = breakIndex;
  790. forWhileStack++;
  791. int oldContinue = continueAt;
  792. continueAt = startPerLoop;
  793. cConsumeToken(T_OPEN_CURVED_BRACKET);
  794. cConsumeBody();
  795. continueAt = oldContinue;
  796. forWhileStack--;
  797. cAddInt32Operation(OP_GOTO, startPerLoop);
  798. cSetInt32(end, code->length);
  799. cConsumeBreaks(breakStart, code->length);
  800. vsLeaveScope(&vars, &scope);
  801. }
  802. static void cBreak(void) {
  803. if(forWhileStack == 0) {
  804. cError("break without for or while");
  805. } else if(breakIndex >= BREAK_BUFFER) {
  806. cError("too much breaks");
  807. }
  808. cAddOperation(OP_GOTO);
  809. breaks[breakIndex++] = cReserveInt32();
  810. cConsumeToken(T_SEMICOLON);
  811. }
  812. static void cContinue(void) {
  813. if(forWhileStack == 0) {
  814. cError("continue without for or while");
  815. }
  816. cAddInt32Operation(OP_GOTO, continueAt);
  817. cConsumeToken(T_SEMICOLON);
  818. }
  819. static void cLine(void) {
  820. int marker = tGetMarker();
  821. Token t = cReadTokenAndLine();
  822. cAddLine(line);
  823. switch(t) {
  824. case T_OPEN_CURVED_BRACKET: cConsumeScope(); break;
  825. case T_RETURN: cReturn(); break;
  826. case T_IF: cIf(); break;
  827. case T_WHILE: cWhile(); break;
  828. case T_FOR: cFor(); break;
  829. case T_BREAK: cBreak(); break;
  830. case T_CONTINUE: cContinue(); break;
  831. default:
  832. tReset(marker);
  833. cLineExpression();
  834. cConsumeToken(T_SEMICOLON);
  835. }
  836. }
  837. static void cBuildFunction(Function* f, DataType rType, const char* fName) {
  838. if(dtIsStruct(rType) && !dtIsArray(rType)) {
  839. cError("structs cannot be returned");
  840. }
  841. fInit(f, fName, line);
  842. f->returnType = rType;
  843. vsReset(&vars);
  844. cConsumeToken(T_OPEN_BRACKET);
  845. if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  846. return;
  847. }
  848. while(true) {
  849. DataType dt = cReadExtendedType(cReadTokenAndLine(), true);
  850. cConsumeToken(T_LITERAL);
  851. const char* name = cReadString();
  852. if(vsInScope(&vars, name)) {
  853. cDeclared(name);
  854. }
  855. if(dtIsStruct(dt)) {
  856. dt = dtToPointer(dt);
  857. }
  858. vsAdd(&vars, name, dt, &structs);
  859. if(fAddArgument(f, dt, &structs)) {
  860. cTooMuchArguments();
  861. } else if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  862. return;
  863. }
  864. cConsumeToken(T_COMMA);
  865. }
  866. }
  867. static void cAddFunction(Function* found, Function* f) {
  868. if(found == NULL) {
  869. fsAdd(&functions, f);
  870. } else if(found->global) {
  871. cError("system functions cannot be overwritten");
  872. } else if(found->address != -1 || f->address == -1 || found->global) {
  873. cError("function registered twice");
  874. } else if(!dtCompare(found->returnType, f->returnType)) {
  875. cError("function redeclared with different return type");
  876. } else {
  877. found->address = f->address;
  878. }
  879. }
  880. static void cInnerFunction(Function* f) {
  881. cConsumeToken(T_OPEN_CURVED_BRACKET);
  882. cAddOperation(OP_RESERVE);
  883. int32 p = cReserveInt32();
  884. cAddInt32(f->size);
  885. returnIndex = 0;
  886. cConsumeScope();
  887. if(!dtIsVoid(returnType) && hasReturn <= 0) {
  888. cError("missing return");
  889. }
  890. cAddInt32Operation(OP_RETURN, vars.maxAddress);
  891. cSetInt32(p, vars.maxAddress);
  892. for(int i = 0; i < returnIndex; i++) {
  893. cSetInt32(returns[i], vars.maxAddress);
  894. }
  895. returnIndex = 0;
  896. }
  897. static void cFunction(DataType rType, const char* name) {
  898. Function f;
  899. cBuildFunction(&f, rType, name);
  900. Function* found = fsSearch(&functions, &f);
  901. if(cConsumeTokenIf(T_SEMICOLON)) {
  902. cAddFunction(found, &f);
  903. return;
  904. }
  905. cAddLine(line);
  906. cAddOperation(OP_GOTO);
  907. int32 end = cReserveInt32();
  908. f.address = code->length;
  909. cAddFunction(found, &f);
  910. returnType = rType;
  911. cInnerFunction(&f);
  912. cSetInt32(end, code->length);
  913. }
  914. static void cStruct(void) {
  915. cConsumeToken(T_LITERAL);
  916. const char* name = cReadString();
  917. if(stsSearch(&structs, name) != NULL) {
  918. cError("struct '%s' registered twice", name);
  919. }
  920. Struct* st = stsAdd(&structs, name);
  921. DataType self = dtStruct(st);
  922. cConsumeToken(T_OPEN_CURVED_BRACKET);
  923. while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) {
  924. DataType dt = cReadExtendedType(cReadTokenAndLine(), true);
  925. if(dtCompare(dt, self)) {
  926. cError("struct %s contains itself", name);
  927. }
  928. cConsumeToken(T_LITERAL);
  929. stAddVariable(st, cReadString(), dt);
  930. cConsumeToken(T_SEMICOLON);
  931. }
  932. cConsumeToken(T_SEMICOLON);
  933. }
  934. static void cGlobalScope(Token t) {
  935. if(t == T_OPEN_PATH) {
  936. path = cReadString();
  937. // printf("OPEN PATH %s\n", path);
  938. return;
  939. } else if(t == T_CLOSE_PATH) {
  940. path = cReadString();
  941. // printf("CLOSE OLD PATH - OPEN PATH %s\n", path);
  942. return;
  943. } else if(t == T_STRUCT) {
  944. cStruct();
  945. return;
  946. }
  947. DataType dt = dtVoid();
  948. if(t != T_VOID) {
  949. dt = cReadExtendedType(t, true);
  950. }
  951. cConsumeToken(T_LITERAL);
  952. const char* name = cReadString();
  953. if(tPeekToken() == T_OPEN_BRACKET) {
  954. cFunction(dt, name);
  955. return;
  956. }
  957. cDeclareSet(&globalVars, dt, name, OP_DEREFERENCE_GVAR);
  958. cConsumeToken(T_SEMICOLON);
  959. }
  960. static void cCallMain(void) {
  961. Function f;
  962. fInit(&f, "main", line);
  963. Function* found = fsSearch(&functions, &f);
  964. if(found != NULL && dtIsVoid(found->returnType)) {
  965. cAddInt32Operation(OP_PUSH_INT, 0);
  966. cAddInt32Operation(OP_GOSUB, found->address);
  967. cAddInt32(found->size);
  968. }
  969. }
  970. static void cForEachLine(void) {
  971. cAddOperation(OP_GRESERVE);
  972. int p = cReserveInt32();
  973. while(true) {
  974. Token t = cReadTokenAndLine();
  975. if(t == T_END) {
  976. break;
  977. }
  978. cGlobalScope(t);
  979. }
  980. cCallMain();
  981. cSetInt32(p, globalVars.maxAddress);
  982. cAddInt32Operation(OP_GRESERVE, -globalVars.maxAddress);
  983. }
  984. static void cLinkQueuedFunctions(void) {
  985. for(int i = 0; i < functionQueue.entries; i++) {
  986. Function* f = functionQueue.data + i;
  987. Function* found = fsSearch(&functions, f);
  988. if(found == NULL || found->address == -1) {
  989. line = f->line;
  990. cUnknownFunction(f);
  991. }
  992. cSetInt32(f->address, found->address);
  993. }
  994. }
  995. static void cAllocAndCompile(void) {
  996. forWhileStack = 0;
  997. breakIndex = 0;
  998. returnType = dtVoid();
  999. onLine = false;
  1000. vsInit(&vars);
  1001. vsInit(&globalVars);
  1002. fsInit(&functions);
  1003. fsInit(&functionQueue);
  1004. stsInit(&structs);
  1005. if(!setjmp(errorJump)) {
  1006. cForEachLine();
  1007. cLinkQueuedFunctions();
  1008. }
  1009. stsDelete(&structs);
  1010. fsDelete(&functionQueue);
  1011. fsDelete(&functions);
  1012. vsDelete(&globalVars);
  1013. vsDelete(&vars);
  1014. }
  1015. ByteCode* cCompile(Error* e) {
  1016. error = e;
  1017. eInitSuccess(e);
  1018. code = bcInit();
  1019. cAllocAndCompile();
  1020. if(eHasError(e)) {
  1021. bcDelete(code);
  1022. return NULL;
  1023. }
  1024. return code;
  1025. }