Compiler.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  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. if(cConsumeTokenIf(T_INCREMENT)) {
  389. return cPreChange(cPreUnary(), 1, "++");
  390. } else if(cConsumeTokenIf(T_DECREMENT)) {
  391. return cPreChange(cPreUnary(), -1, "--");
  392. } else if(cConsumeTokenIf(T_SUB)) {
  393. return cInvertSign(cUnpack(cPreUnary()));
  394. } else if(cConsumeTokenIf(T_NOT)) {
  395. DataType dt = cPreUnary();
  396. cExpectType(dt, dtBool(), "!");
  397. cAddOperation(OP_NOT);
  398. return dt;
  399. } else if(cConsumeTokenIf(T_BIT_NOT)) {
  400. DataType dt = cPreUnary();
  401. cExpectType(dt, dtInt(), "!");
  402. cAddOperation(OP_BIT_NOT);
  403. return dt;
  404. } else if(cConsumeTokenIf(T_BIT_AND)) {
  405. DataType dt = cPreUnary();
  406. cRemoveReference(&dt, "&");
  407. return cDereference(dt);
  408. } else if(cConsumeTokenIf(T_MUL)) {
  409. DataType dt = cPreUnary();
  410. if(!dtIsPointer(dt)) {
  411. cError("* expects a pointer");
  412. }
  413. dt = dtReference(dt);
  414. if(!dtIsPointer(dt) && !dtIsVariable(dt)) {
  415. dt = dtToVariable(dt);
  416. } else {
  417. cAddOperation(OP_REFERENCE);
  418. }
  419. return dt;
  420. }
  421. return cAccess();
  422. }
  423. static void cAddTypeOperation(DataType* a, Parser bf, const TypedOp* op) {
  424. *a = cUnpack(*a);
  425. DataType b = cUnpack(bf());
  426. if(!dtCompare(*a, b)) {
  427. cInvalidOperation(*a, b, op->name);
  428. } else if(dtIsInt(*a) && op->intOp != OP_NOTHING) {
  429. cAddOperation(op->intOp);
  430. } else if(dtIsFloat(*a) && op->floatOp != OP_NOTHING) {
  431. cAddOperation(op->floatOp);
  432. } else if(dtIsBool(*a) && op->boolOp != OP_NOTHING) {
  433. cAddOperation(op->boolOp);
  434. } else if(dtIsPointer(*a) && op->pointerOp != OP_NOTHING) {
  435. cAddOperation(op->pointerOp);
  436. } else {
  437. cInvalidOperation(*a, b, op->name);
  438. }
  439. }
  440. static DataType cMul() {
  441. DataType a = cPreUnary();
  442. while(true) {
  443. if(cConsumeTokenIf(T_MUL)) {
  444. cAddTypeOperation(&a, cPreUnary, &TYPED_MUL);
  445. } else if(cConsumeTokenIf(T_DIV)) {
  446. cAddTypeOperation(&a, cPreUnary, &TYPED_DIV);
  447. } else if(cConsumeTokenIf(T_MOD)) {
  448. cAddTypeOperation(&a, cPreUnary, &TYPED_MOD);
  449. } else {
  450. return a;
  451. }
  452. }
  453. }
  454. static DataType cAdd() {
  455. DataType a = cMul();
  456. while(true) {
  457. if(cConsumeTokenIf(T_ADD)) {
  458. cAddTypeOperation(&a, cMul, &TYPED_ADD);
  459. } else if(cConsumeTokenIf(T_SUB)) {
  460. cAddTypeOperation(&a, cMul, &TYPED_SUB);
  461. } else {
  462. return a;
  463. }
  464. }
  465. }
  466. static DataType cShift() {
  467. DataType a = cAdd();
  468. while(true) {
  469. if(cConsumeTokenIf(T_LEFT_SHIFT)) {
  470. cAddTypeOperation(&a, cAdd, &TYPED_LEFT_SHIFT);
  471. } else if(cConsumeTokenIf(T_RIGHT_SHIFT)) {
  472. cAddTypeOperation(&a, cAdd, &TYPED_RIGHT_SHIFT);
  473. } else {
  474. return a;
  475. }
  476. }
  477. }
  478. static DataType cComparison() {
  479. DataType a = cShift();
  480. while(true) {
  481. if(cConsumeTokenIf(T_LESS)) {
  482. cAddTypeOperation(&a, cShift, &TYPED_LESS);
  483. a = dtBool();
  484. } else if(cConsumeTokenIf(T_LESS_EQUAL)) {
  485. cAddTypeOperation(&a, cShift, &TYPED_LESS_EQUAL);
  486. cAddOperation(OP_NOT);
  487. a = dtBool();
  488. } else if(cConsumeTokenIf(T_GREATER)) {
  489. cAddTypeOperation(&a, cShift, &TYPED_GREATER);
  490. a = dtBool();
  491. } else if(cConsumeTokenIf(T_GREATER_EQUAL)) {
  492. cAddTypeOperation(&a, cShift, &TYPED_GREATER_EQUAL);
  493. cAddOperation(OP_NOT);
  494. a = dtBool();
  495. } else {
  496. return a;
  497. }
  498. }
  499. }
  500. static DataType cEqual() {
  501. DataType a = cComparison();
  502. while(true) {
  503. if(cConsumeTokenIf(T_EQUAL)) {
  504. cAddTypeOperation(&a, cComparison, &TYPED_EQUAL);
  505. a = dtBool();
  506. } else if(cConsumeTokenIf(T_NOT_EQUAL)) {
  507. cAddTypeOperation(&a, cComparison, &TYPED_NOT_EQUAL);
  508. cAddOperation(OP_NOT);
  509. a = dtBool();
  510. } else {
  511. return a;
  512. }
  513. }
  514. }
  515. static DataType cRepeat(Token t, Parser f, const TypedOp* op) {
  516. DataType a = f();
  517. while(cConsumeTokenIf(t)) {
  518. cAddTypeOperation(&a, f, op);
  519. }
  520. return a;
  521. }
  522. static DataType cBitAnd() {
  523. return cRepeat(T_BIT_AND, cEqual, &TYPED_BIT_AND);
  524. }
  525. static DataType cBitXor() {
  526. return cRepeat(T_BIT_XOR, cBitAnd, &TYPED_BIT_XOR);
  527. }
  528. static DataType cBitOr() {
  529. return cRepeat(T_BIT_OR, cBitXor, &TYPED_BIT_OR);
  530. }
  531. static DataType cLogical(Parser f, Token t, Operation jump, Operation op) {
  532. DataType a = f();
  533. while(cConsumeTokenIf(t)) {
  534. a = cUnpack(a);
  535. cAddOperation(jump);
  536. int p = cReserveInt();
  537. DataType b = cUnpack(f());
  538. if(!dtIsBool(a) || !dtIsBool(b)) {
  539. cInvalidOperation(a, b, tGetName(t));
  540. }
  541. cAddOperation(op);
  542. cSetInt(p, code->length);
  543. }
  544. return a;
  545. }
  546. static DataType cAnd() {
  547. return cLogical(cBitOr, T_AND, OP_PEEK_FALSE_GOTO, OP_AND);
  548. }
  549. static DataType cExpression() {
  550. return cLogical(cAnd, T_OR, OP_PEEK_TRUE_GOTO, OP_OR);
  551. }
  552. static void cLine();
  553. static void cConsumeBody() {
  554. int oldLine = line;
  555. while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) {
  556. if(tPeekToken() == T_END) {
  557. line = oldLine;
  558. cError("non closed curved bracket");
  559. }
  560. cLine();
  561. }
  562. }
  563. static void cConsumeScope() {
  564. Scope scope;
  565. vsEnterScope(&vars, &scope);
  566. cConsumeBody();
  567. vsLeaveScope(&vars, &scope);
  568. }
  569. static void cAddReturn(Operation op) {
  570. if(returnIndex >= RETURN_BUFFER) {
  571. cError("too much returns in function");
  572. }
  573. cAddOperation(op);
  574. returns[returnIndex++] = cReserveInt();
  575. }
  576. static void cReturn() {
  577. if(dtIsVoid(returnType)) {
  578. cConsumeToken(T_SEMICOLON);
  579. cAddReturn(OP_RETURN);
  580. hasReturn = 2;
  581. return;
  582. }
  583. DataType dt = cUnpackedExpression();
  584. if(!dtCompare(dt, returnType)) {
  585. cError("wrong return type, should be %s", cGetName(returnType));
  586. } else if(dtIsInt(dt)) {
  587. cAddReturn(OP_RETURN_INT);
  588. } else if(dtIsBool(dt)) {
  589. cAddReturn(OP_RETURN_BOOL);
  590. } else if(dtIsFloat(dt)) {
  591. cAddReturn(OP_RETURN_FLOAT);
  592. } else if(dtIsPointer(dt)) {
  593. cAddReturn(OP_RETURN_POINTER);
  594. } else {
  595. cError("cannot return %s", cGetName(dt));
  596. }
  597. cConsumeToken(T_SEMICOLON);
  598. hasReturn = 2;
  599. }
  600. static void cPrint() {
  601. DataType dt = cUnpackedExpression();
  602. if(dtIsPointer(dt)) {
  603. cAddOperation(OP_PRINT_POINTER);
  604. cConsumeToken(T_SEMICOLON);
  605. return;
  606. }
  607. switch(dt.type) {
  608. DT_OPERATION(PRINT);
  609. default: cError("cannot print type %s", cGetName(dt));
  610. }
  611. cConsumeToken(T_SEMICOLON);
  612. }
  613. static void cIf() {
  614. cConsumeToken(T_OPEN_BRACKET);
  615. cExpectType(cUnpackedExpression(), dtBool(), "if");
  616. cConsumeToken(T_CLOSE_BRACKET);
  617. cAddOperation(OP_IF_GOTO);
  618. int ifP = cReserveInt();
  619. cConsumeToken(T_OPEN_CURVED_BRACKET);
  620. cConsumeScope();
  621. cSetInt(ifP, code->length);
  622. if(cConsumeTokenIf(T_ELSE)) {
  623. cAddOperation(OP_GOTO);
  624. int elseP = cReserveInt();
  625. cSetInt(ifP, code->length);
  626. if(cConsumeTokenIf(T_IF)) {
  627. cIf();
  628. } else {
  629. cConsumeToken(T_OPEN_CURVED_BRACKET);
  630. cConsumeScope();
  631. }
  632. cSetInt(elseP, code->length);
  633. }
  634. }
  635. static void cConsumeBreaks(int start, int address) {
  636. for(int i = start; i < breakIndex; i++) {
  637. cSetInt(breaks[i], address);
  638. }
  639. breakIndex = start;
  640. }
  641. static void cWhile() {
  642. int start = code->length;
  643. cConsumeToken(T_OPEN_BRACKET);
  644. cExpectType(cUnpackedExpression(), dtBool(), "while");
  645. cConsumeToken(T_CLOSE_BRACKET);
  646. cAddOperation(OP_IF_GOTO);
  647. int ifP = cReserveInt();
  648. int breakStart = breakIndex;
  649. forWhileStack++;
  650. int oldContinue = continueAt;
  651. continueAt = start;
  652. cConsumeToken(T_OPEN_CURVED_BRACKET);
  653. cConsumeScope();
  654. continueAt = oldContinue;
  655. forWhileStack--;
  656. cAddIntOperation(OP_GOTO, start);
  657. cSetInt(ifP, code->length);
  658. cConsumeBreaks(breakStart, code->length);
  659. }
  660. static void cDelete() {
  661. DataType pointer = cUnpackedExpression();
  662. if(!dtIsPointer(pointer)) {
  663. cError("delete expects a pointer");
  664. }
  665. cAddOperation(OP_DELETE);
  666. }
  667. static void cOperationSet(DataType left, const TypedOp* op) {
  668. cAddOperation(OP_DUPLICATE_REFERENCE);
  669. cLoadRef(left);
  670. cAddTypeOperation(&left, cUnpackedExpression, op);
  671. cStore(left, left, "=");
  672. }
  673. static void cSetVariable() {
  674. onLine = true;
  675. DataType dt = cPreUnary();
  676. onLine = false;
  677. if(dtIsVoid(dt)) {
  678. return;
  679. }
  680. cRemoveReference(&dt, "setter");
  681. Token t = cReadTokenAndLine();
  682. switch(t) {
  683. case T_SET: cStore(dt, cUnpackedExpression(), "="); break;
  684. case T_ADD_SET: cOperationSet(dt, &TYPED_ADD); break;
  685. case T_SUB_SET: cOperationSet(dt, &TYPED_SUB); break;
  686. case T_MUL_SET: cOperationSet(dt, &TYPED_MUL); break;
  687. case T_DIV_SET: cOperationSet(dt, &TYPED_DIV); break;
  688. case T_MOD_SET: cOperationSet(dt, &TYPED_MOD); break;
  689. case T_BIT_AND_SET: cOperationSet(dt, &TYPED_BIT_AND); break;
  690. case T_BIT_OR_SET: cOperationSet(dt, &TYPED_BIT_OR); break;
  691. case T_BIT_XOR_SET: cOperationSet(dt, &TYPED_BIT_XOR); break;
  692. case T_LEFT_SHIFT_SET: cOperationSet(dt, &TYPED_LEFT_SHIFT); break;
  693. case T_RIGHT_SHIFT_SET: cOperationSet(dt, &TYPED_RIGHT_SHIFT); break;
  694. default: cUnexpectedToken(t);
  695. }
  696. }
  697. static void cDeclare(DataType dt) {
  698. dt = cExtendType(dt);
  699. cConsumeToken(T_LITERAL);
  700. const char* var = cReadString();
  701. if(vsInScope(&vars, var)) {
  702. cDeclared(var);
  703. }
  704. Variable* v = vsAdd(&vars, var, dt, &structs);
  705. if(dt.type != DT_STRUCT || dtIsPointer(dt)) {
  706. cConsumeToken(T_SET);
  707. cAddIntOperation(OP_DEREFERENCE_VAR, v->address);
  708. cStore(v->type, cUnpackedExpression(), "=");
  709. }
  710. }
  711. static void cLineExpression() {
  712. int marker = tGetMarker();
  713. Token t = cReadTokenAndLine();
  714. if(t == T_LITERAL) {
  715. const char* literal = cReadString();
  716. Struct* st = stsSearch(&structs, literal);
  717. if(st != NULL) {
  718. cDeclare(dtStruct(st));
  719. return;
  720. }
  721. }
  722. switch(t) {
  723. case T_INT: cDeclare(dtInt()); break;
  724. case T_BOOL: cDeclare(dtBool()); break;
  725. case T_FLOAT: cDeclare(dtFloat()); break;
  726. case T_DELETE: cDelete(); break;
  727. default: tReset(marker); cSetVariable();
  728. }
  729. }
  730. static void cFor() {
  731. Scope scope;
  732. vsEnterScope(&vars, &scope);
  733. cConsumeToken(T_OPEN_BRACKET);
  734. cLineExpression();
  735. cConsumeToken(T_SEMICOLON);
  736. int startCheck = code->length;
  737. cExpectType(cUnpackedExpression(), dtBool(), "for");
  738. cConsumeToken(T_SEMICOLON);
  739. cAddOperation(OP_IF_GOTO);
  740. int end = cReserveInt();
  741. cAddOperation(OP_GOTO);
  742. int beginBody = cReserveInt();
  743. int startPerLoop = code->length;
  744. cLineExpression();
  745. cAddIntOperation(OP_GOTO, startCheck);
  746. cConsumeToken(T_CLOSE_BRACKET);
  747. cSetInt(beginBody, code->length);
  748. int breakStart = breakIndex;
  749. forWhileStack++;
  750. int oldContinue = continueAt;
  751. continueAt = startPerLoop;
  752. cConsumeToken(T_OPEN_CURVED_BRACKET);
  753. cConsumeBody();
  754. continueAt = oldContinue;
  755. forWhileStack--;
  756. cAddIntOperation(OP_GOTO, startPerLoop);
  757. cSetInt(end, code->length);
  758. cConsumeBreaks(breakStart, code->length);
  759. vsLeaveScope(&vars, &scope);
  760. }
  761. static void cBreak() {
  762. if(forWhileStack == 0) {
  763. cError("break without for or while");
  764. } else if(breakIndex >= BREAK_BUFFER) {
  765. cError("too much breaks");
  766. }
  767. cAddOperation(OP_GOTO);
  768. breaks[breakIndex++] = cReserveInt();
  769. cConsumeToken(T_SEMICOLON);
  770. }
  771. static void cContinue() {
  772. if(forWhileStack == 0) {
  773. cError("continue without for or while");
  774. }
  775. cAddIntOperation(OP_GOTO, continueAt);
  776. cConsumeToken(T_SEMICOLON);
  777. }
  778. static void cLine() {
  779. int marker = tGetMarker();
  780. Token t = cReadTokenAndLine();
  781. cAddLine(line);
  782. switch(t) {
  783. case T_OPEN_CURVED_BRACKET: cConsumeScope(); break;
  784. case T_PRINT: cPrint(); break;
  785. case T_RETURN: cReturn(); break;
  786. case T_IF: cIf(); break;
  787. case T_WHILE: cWhile(); break;
  788. case T_FOR: cFor(); break;
  789. case T_BREAK: cBreak(); break;
  790. case T_CONTINUE: cContinue(); break;
  791. default:
  792. tReset(marker);
  793. cLineExpression();
  794. cConsumeToken(T_SEMICOLON);
  795. }
  796. }
  797. static void cBuildFunction(Function* f, DataType rType) {
  798. cConsumeToken(T_LITERAL);
  799. fInit(f, cReadString(), line);
  800. f->returnType = rType;
  801. vsReset(&vars);
  802. cConsumeToken(T_OPEN_BRACKET);
  803. if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  804. return;
  805. }
  806. while(true) {
  807. DataType dt = cReadType(cReadTokenAndLine());
  808. cConsumeToken(T_LITERAL);
  809. const char* name = cReadString();
  810. if(vsInScope(&vars, name)) {
  811. cDeclared(name);
  812. }
  813. vsAdd(&vars, name, dt, &structs);
  814. if(fAddArgument(f, dt, &structs)) {
  815. cTooMuchArguments();
  816. } else if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  817. return;
  818. }
  819. cConsumeToken(T_COMMA);
  820. }
  821. }
  822. static void cAddFunction(Function* found, Function* f) {
  823. if(found == NULL) {
  824. fsAdd(&functions, f);
  825. } else if(found->address != -1 || f->address == -1) {
  826. cError("function registered twice");
  827. } else if(!dtCompare(found->returnType, f->returnType)) {
  828. cError("function redeclared with different return type");
  829. } else {
  830. found->address = f->address;
  831. }
  832. }
  833. static void cInnerFunction(Function* f) {
  834. cConsumeToken(T_OPEN_CURVED_BRACKET);
  835. cAddOperation(OP_RESERVE);
  836. int p = cReserveInt();
  837. cAddInt(f->size);
  838. returnIndex = 0;
  839. cConsumeScope();
  840. if(!dtIsVoid(returnType) && hasReturn <= 0) {
  841. cError("missing return");
  842. }
  843. cAddIntOperation(OP_RETURN, vars.maxAddress);
  844. cSetInt(p, vars.maxAddress);
  845. for(int i = 0; i < returnIndex; i++) {
  846. cSetInt(returns[i], vars.maxAddress);
  847. }
  848. returnIndex = 0;
  849. }
  850. static void cFunction(DataType rType) {
  851. rType = cExtendType(rType);
  852. Function f;
  853. cBuildFunction(&f, rType);
  854. Function* found = fsSearch(&functions, &f);
  855. if(cConsumeTokenIf(T_SEMICOLON)) {
  856. cAddFunction(found, &f);
  857. return;
  858. }
  859. cAddLine(line);
  860. cAddOperation(OP_GOTO);
  861. int end = cReserveInt();
  862. f.address = code->length;
  863. cAddFunction(found, &f);
  864. returnType = rType;
  865. cInnerFunction(&f);
  866. cSetInt(end, code->length);
  867. }
  868. static void cStruct() {
  869. cConsumeToken(T_LITERAL);
  870. const char* name = cReadString();
  871. if(stsSearch(&structs, name) != NULL) {
  872. cError("struct registered twice");
  873. }
  874. Struct* st = stsAdd(&structs, name);
  875. DataType self = dtStruct(st);
  876. cConsumeToken(T_OPEN_CURVED_BRACKET);
  877. while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) {
  878. DataType dt = cReadType(cReadTokenAndLine());
  879. if(dtCompare(dt, self)) {
  880. cError("struct %s contains itself", name);
  881. }
  882. cConsumeToken(T_LITERAL);
  883. stAddVariable(st, cReadString(), dt);
  884. cConsumeToken(T_SEMICOLON);
  885. }
  886. cConsumeToken(T_SEMICOLON);
  887. }
  888. static void cGlobalScope(Token t) {
  889. switch(t) {
  890. case T_VOID: cFunction(dtVoid()); break;
  891. case T_STRUCT: cStruct(); break;
  892. default: cFunction(cReadType(t));
  893. }
  894. }
  895. static void cCallMain() {
  896. Function f;
  897. fInit(&f, "main", line);
  898. Function* found = fsSearch(&functions, &f);
  899. if(found != NULL && dtIsVoid(found->returnType)) {
  900. cAddIntOperation(OP_PUSH_INT, 0);
  901. cAddIntOperation(OP_GOSUB, found->address);
  902. cAddInt(found->size);
  903. }
  904. }
  905. static void cForEachLine() {
  906. while(true) {
  907. Token t = cReadTokenAndLine();
  908. if(t == T_END) {
  909. break;
  910. }
  911. cGlobalScope(t);
  912. }
  913. cCallMain();
  914. }
  915. static void cLinkQueuedFunctions() {
  916. for(int i = 0; i < functionQueue.entries; i++) {
  917. Function* f = functionQueue.data + i;
  918. Function* found = fsSearch(&functions, f);
  919. if(found == NULL || found->address == -1) {
  920. line = f->line;
  921. cError("unknown function");
  922. }
  923. cSetInt(f->address, found->address);
  924. }
  925. }
  926. static void cAllocAndCompile() {
  927. forWhileStack = 0;
  928. breakIndex = 0;
  929. returnType = dtVoid();
  930. onLine = false;
  931. vsInit(&vars);
  932. fsInit(&functions);
  933. fsInit(&functionQueue);
  934. stsInit(&structs);
  935. if(!setjmp(errorJump)) {
  936. cForEachLine();
  937. cLinkQueuedFunctions();
  938. }
  939. stsDelete(&structs);
  940. fsDelete(&functionQueue);
  941. fsDelete(&functions);
  942. vsDelete(&vars);
  943. }
  944. ByteCode* cCompile() {
  945. error[0] = '\0';
  946. code = bcInit();
  947. cAllocAndCompile();
  948. if(error[0] != '\0') {
  949. bcDelete(code);
  950. return NULL;
  951. }
  952. return code;
  953. }
  954. const char* cGetError() {
  955. return error;
  956. }
  957. int cGetLine() {
  958. return line;
  959. }