Compiler.c 30 KB

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