Compiler.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. #include <setjmp.h>
  2. #include <stdarg.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include "Compiler.h"
  6. #include "DataType.h"
  7. #include "tokenizer/Tokenizer.h"
  8. #include "utils/Functions.h"
  9. #include "utils/Variables.h"
  10. #include "vm/Operation.h"
  11. #define ERROR_LENGTH 256
  12. #define RETURN_BUFFER 16
  13. #define BREAK_BUFFER 32
  14. static jmp_buf errorJump;
  15. static char error[ERROR_LENGTH] = {'\0'};
  16. static ByteCode* code;
  17. static int16 line = 1;
  18. static Variables vars;
  19. static Functions functions;
  20. static Functions functionQueue;
  21. static int returns[RETURN_BUFFER];
  22. static int returnIndex = 0;
  23. static bool hasReturn = false;
  24. static DataType returnType = DT_VOID;
  25. static int breaks[BREAK_BUFFER];
  26. static int breakIndex = 0;
  27. static int forWhileStack = 0;
  28. static int continueAt = 0;
  29. typedef struct {
  30. Operation intOp;
  31. Operation floatOp;
  32. Operation boolOp;
  33. const char* name;
  34. } TypedOp;
  35. static const TypedOp TYPED_MUL = {OP_MUL_INT, OP_MUL_FLOAT, OP_NOTHING, "*"};
  36. static const TypedOp TYPED_DIV = {OP_DIV_INT, OP_DIV_FLOAT, OP_NOTHING, "/"};
  37. static const TypedOp TYPED_MOD = {OP_MOD_INT, OP_NOTHING, OP_NOTHING, "%"};
  38. static const TypedOp TYPED_ADD = {OP_ADD_INT, OP_ADD_FLOAT, OP_NOTHING, "+"};
  39. static const TypedOp TYPED_SUB = {OP_SUB_INT, OP_SUB_FLOAT, OP_NOTHING, "-"};
  40. static const TypedOp TYPED_LESS = {OP_LESS_INT, OP_LESS_FLOAT, OP_NOTHING, "<"};
  41. static const TypedOp TYPED_LESS_EQUAL = {OP_GREATER_INT, OP_GREATER_FLOAT,
  42. OP_NOTHING, "<="};
  43. static const TypedOp TYPED_GREATER = {OP_GREATER_INT, OP_GREATER_FLOAT,
  44. OP_NOTHING, ">"};
  45. static const TypedOp TYPED_GREATER_EQUAL = {OP_LESS_INT, OP_LESS_FLOAT,
  46. OP_NOTHING, ">="};
  47. static const TypedOp TYPED_EQUAL = {OP_EQUAL_INT, OP_EQUAL_FLOAT, OP_EQUAL_BOOL,
  48. "=="};
  49. static const TypedOp TYPED_NOT_EQUAL = {OP_EQUAL_INT, OP_EQUAL_FLOAT,
  50. OP_EQUAL_BOOL, "!="};
  51. static const TypedOp TYPED_BIT_OR = {OP_BIT_OR, OP_NOTHING, OP_NOTHING, "|"};
  52. static const TypedOp TYPED_BIT_XOR = {OP_BIT_XOR, OP_NOTHING, OP_NOTHING, "^"};
  53. static const TypedOp TYPED_BIT_AND = {OP_BIT_AND, OP_NOTHING, OP_NOTHING, "&"};
  54. static const TypedOp TYPED_LEFT_SHIFT = {OP_LEFT_SHIFT, OP_NOTHING, OP_NOTHING,
  55. "<<"};
  56. static const TypedOp TYPED_RIGHT_SHIFT = {OP_RIGHT_SHIFT, OP_NOTHING,
  57. OP_NOTHING, ">>"};
  58. static void cError(const char* format, ...) {
  59. va_list args;
  60. va_start(args, format);
  61. vsnprintf(error, ERROR_LENGTH, format, args);
  62. va_end(args);
  63. longjmp(errorJump, 0);
  64. }
  65. static void cInvalidOperation(DataType a, DataType b, const char* op) {
  66. cError("invalid operation: %s %s %s", dtGetName(a), op, dtGetName(b));
  67. }
  68. static void cNotDeclared(const char* name) {
  69. cError("variable %s has not been declared", name);
  70. }
  71. static void cDeclared(const char* name) {
  72. cError("%s has already been declared", name);
  73. }
  74. static void cTooMuchArguments() {
  75. cError("too much function arguments");
  76. }
  77. static void cUnexpectedToken(Token t) {
  78. cError("unexpected token on line %d: %s", line, tGetName(t));
  79. }
  80. static void cAddOperation(Operation token) {
  81. unsigned char c = token;
  82. bcAddBytes(code, &c, 1);
  83. }
  84. static int cReserveInt() {
  85. return bcReserveBytes(code, sizeof(int));
  86. }
  87. static void cSetInt(int p, int i) {
  88. bcSetBytes(code, p, &i, sizeof(int));
  89. }
  90. static void cAddInt(int i) {
  91. bcAddBytes(code, &i, sizeof(int));
  92. }
  93. static void cAddInt16(int16 i) {
  94. bcAddBytes(code, &i, sizeof(int16));
  95. }
  96. static Token cReadTokenAndLine() {
  97. Token t = tReadToken();
  98. if(tReadInt16(&line)) {
  99. return t;
  100. }
  101. return T_END;
  102. }
  103. static void cConsumeToken(Token wanted) {
  104. Token t = cReadTokenAndLine();
  105. if(wanted != t) {
  106. cError("unexpected token on line %d: expected '%s' got '%s'", line,
  107. tGetName(wanted), tGetName(t));
  108. }
  109. }
  110. static bool cConsumeTokenIf(Token t) {
  111. if(tPeekToken() == t) {
  112. cReadTokenAndLine();
  113. return true;
  114. }
  115. return false;
  116. }
  117. static void cConstantInt() {
  118. int value;
  119. if(!tReadInt(&value)) {
  120. cError("int token without an int on line %d", line);
  121. }
  122. cAddOperation(OP_PUSH_INT);
  123. cAddInt(value);
  124. }
  125. static void cConstantFloat() {
  126. float value;
  127. if(!tReadFloat(&value)) {
  128. cError("float token without a float on line %d", line);
  129. }
  130. cAddOperation(OP_PUSH_FLOAT);
  131. bcAddBytes(code, &value, sizeof(float));
  132. }
  133. static const char* cReadString() {
  134. int length;
  135. const char* literal = tReadString(&length);
  136. if(literal == NULL) {
  137. cError("literal without string on line %d", line);
  138. }
  139. return literal;
  140. }
  141. static DataType cExpression();
  142. static void cCallFunctionArguments(Function* f) {
  143. while(!cConsumeTokenIf(T_CLOSE_BRACKET)) {
  144. DataType dt = cExpression();
  145. if(fAddArgument(f, dt)) {
  146. cTooMuchArguments();
  147. }
  148. if(cConsumeTokenIf(T_COMMA) && tPeekToken() == T_CLOSE_BRACKET) {
  149. cUnexpectedToken(tPeekToken());
  150. }
  151. }
  152. }
  153. static DataType cCallFunction(const char* name) {
  154. cAddOperation(OP_PUSH_INT);
  155. cAddInt(0);
  156. Function f;
  157. fInit(&f, name, line);
  158. cCallFunctionArguments(&f);
  159. cAddOperation(OP_GOSUB);
  160. Function* found = fsSearch(&functions, &f);
  161. if(found == NULL) {
  162. cError("unknown function");
  163. }
  164. if(found->address == -1) {
  165. f.returnType = found->returnType;
  166. f.address = cReserveInt();
  167. fsAdd(&functionQueue, &f);
  168. } else {
  169. cAddInt(found->address);
  170. }
  171. cAddInt(found->size);
  172. return found->returnType;
  173. }
  174. static DataType cLoadVariable(Variable* v) {
  175. switch(v->type) {
  176. case DT_INT: cAddOperation(OP_LOAD_INT); break;
  177. case DT_BOOL: cAddOperation(OP_LOAD_BOOL); break;
  178. case DT_FLOAT: cAddOperation(OP_LOAD_FLOAT); break;
  179. default: cError("cannot load type %s", dtGetName(v->type));
  180. }
  181. cAddInt(v->address);
  182. return v->type;
  183. }
  184. static void cStoreVariable(Variable* v, DataType dt, const char* name) {
  185. if(v->type != dt) {
  186. cInvalidOperation(v->type, dt, name);
  187. }
  188. switch(v->type) {
  189. case DT_INT: cAddOperation(OP_STORE_INT); break;
  190. case DT_BOOL: cAddOperation(OP_STORE_BOOL); break;
  191. case DT_FLOAT: cAddOperation(OP_STORE_FLOAT); break;
  192. default: cError("cannot store type %s", dtGetName(v->type));
  193. }
  194. cAddInt(v->address);
  195. }
  196. static DataType cPostChange(Variable* v, int change, const char* name) {
  197. if(v->type != DT_INT) {
  198. cError("%s needs an int", name);
  199. }
  200. cAddOperation(OP_LOAD_INT);
  201. cAddInt(v->address);
  202. cAddOperation(OP_LOAD_INT);
  203. cAddInt(v->address);
  204. cAddOperation(OP_PUSH_INT);
  205. cAddInt(change);
  206. cAddOperation(OP_ADD_INT);
  207. cAddOperation(OP_STORE_INT);
  208. cAddInt(v->address);
  209. return DT_INT;
  210. }
  211. static DataType cLiteral() {
  212. const char* literal = cReadString();
  213. if(cConsumeTokenIf(T_OPEN_BRACKET)) {
  214. DataType dt = cCallFunction(literal);
  215. if(dt == DT_VOID) {
  216. cError("function returns void");
  217. }
  218. return dt;
  219. }
  220. Variable* v = vSearch(&vars, literal);
  221. if(v == NULL) {
  222. cNotDeclared(literal);
  223. }
  224. if(cConsumeTokenIf(T_INCREMENT)) {
  225. return cPostChange(v, 1, "++");
  226. } else if(cConsumeTokenIf(T_DECREMENT)) {
  227. return cPostChange(v, -1, "--");
  228. }
  229. return cLoadVariable(v);
  230. }
  231. static DataType cBracketPrimary() {
  232. DataType result = cExpression();
  233. cConsumeToken(T_CLOSE_BRACKET);
  234. return result;
  235. }
  236. static DataType cPrimary() {
  237. Token t = cReadTokenAndLine();
  238. switch(t) {
  239. case T_CONST_INT: cConstantInt(); return DT_INT;
  240. case T_CONST_FLOAT: cConstantFloat(); return DT_FLOAT;
  241. case T_TRUE: cAddOperation(OP_PUSH_TRUE); return DT_BOOL;
  242. case T_FALSE: cAddOperation(OP_PUSH_FALSE); return DT_BOOL;
  243. case T_OPEN_BRACKET: return cBracketPrimary();
  244. case T_LITERAL: return cLiteral();
  245. default: cUnexpectedToken(t); return DT_VOID;
  246. }
  247. }
  248. static DataType cPreChange(int change, const char* name) {
  249. cConsumeToken(T_LITERAL);
  250. const char* literal = cReadString();
  251. Variable* v = vSearch(&vars, literal);
  252. if(v == NULL) {
  253. cNotDeclared(literal);
  254. } else if(v->type != DT_INT) {
  255. cError("%s needs an int", name);
  256. }
  257. cAddOperation(OP_LOAD_INT);
  258. cAddInt(v->address);
  259. cAddOperation(OP_PUSH_INT);
  260. cAddInt(change);
  261. cAddOperation(OP_ADD_INT);
  262. cAddOperation(OP_STORE_INT);
  263. cAddInt(v->address);
  264. cAddOperation(OP_LOAD_INT);
  265. cAddInt(v->address);
  266. return DT_INT;
  267. }
  268. static DataType cPreUnary() {
  269. if(cConsumeTokenIf(T_SUB)) {
  270. DataType result = cPrimary();
  271. switch(result) {
  272. case DT_INT: cAddOperation(OP_INVERT_SIGN_INT); break;
  273. case DT_FLOAT: cAddOperation(OP_INVERT_SIGN_FLOAT); break;
  274. default: cError("cannot invert sign of %s", dtGetName(result));
  275. }
  276. return result;
  277. } else if(cConsumeTokenIf(T_INCREMENT)) {
  278. return cPreChange(1, "++");
  279. } else if(cConsumeTokenIf(T_DECREMENT)) {
  280. return cPreChange(-1, "--");
  281. } else if(cConsumeTokenIf(T_NOT)) {
  282. int counter = 1;
  283. while(cConsumeTokenIf(T_NOT)) {
  284. counter++;
  285. }
  286. DataType result = cPrimary();
  287. if(result != DT_BOOL) {
  288. cError("! needs a bool not %s", dtGetName(result));
  289. }
  290. cAddOperation(OP_NOT);
  291. if((counter & 1) == 0) {
  292. cAddOperation(OP_NOT);
  293. }
  294. return DT_BOOL;
  295. } else if(cConsumeTokenIf(T_BIT_NOT)) {
  296. DataType result = cPrimary();
  297. if(result == DT_INT) {
  298. cAddOperation(OP_BIT_NOT);
  299. } else {
  300. cError("~ needs an int not %s", dtGetName(result));
  301. }
  302. return result;
  303. }
  304. return cPrimary();
  305. }
  306. static void cAddTypeOperation(DataType a, DataType b, const TypedOp* op) {
  307. if(a == DT_INT && b == DT_INT && op->intOp != OP_NOTHING) {
  308. cAddOperation(op->intOp);
  309. } else if(a == DT_FLOAT && b == DT_FLOAT && op->floatOp != OP_NOTHING) {
  310. cAddOperation(op->floatOp);
  311. } else if(a == DT_BOOL && b == DT_BOOL && op->boolOp != OP_NOTHING) {
  312. cAddOperation(op->boolOp);
  313. } else {
  314. cInvalidOperation(a, b, op->name);
  315. }
  316. }
  317. static DataType cMul() {
  318. DataType a = cPreUnary();
  319. while(true) {
  320. if(cConsumeTokenIf(T_MUL)) {
  321. cAddTypeOperation(a, cPreUnary(), &TYPED_MUL);
  322. } else if(cConsumeTokenIf(T_DIV)) {
  323. cAddTypeOperation(a, cPreUnary(), &TYPED_DIV);
  324. } else if(cConsumeTokenIf(T_MOD)) {
  325. cAddTypeOperation(a, cPreUnary(), &TYPED_MOD);
  326. } else {
  327. break;
  328. }
  329. }
  330. return a;
  331. }
  332. static DataType cAdd() {
  333. DataType a = cMul();
  334. while(true) {
  335. if(cConsumeTokenIf(T_ADD)) {
  336. cAddTypeOperation(a, cMul(), &TYPED_ADD);
  337. } else if(cConsumeTokenIf(T_SUB)) {
  338. cAddTypeOperation(a, cMul(), &TYPED_SUB);
  339. } else {
  340. break;
  341. }
  342. }
  343. return a;
  344. }
  345. static DataType cShift() {
  346. DataType a = cAdd();
  347. while(true) {
  348. if(cConsumeTokenIf(T_LEFT_SHIFT)) {
  349. cAddTypeOperation(a, cAdd(), &TYPED_LEFT_SHIFT);
  350. } else if(cConsumeTokenIf(T_RIGHT_SHIFT)) {
  351. cAddTypeOperation(a, cAdd(), &TYPED_RIGHT_SHIFT);
  352. } else {
  353. break;
  354. }
  355. }
  356. return a;
  357. }
  358. static DataType cComparison() {
  359. DataType a = cShift();
  360. while(true) {
  361. if(cConsumeTokenIf(T_LESS)) {
  362. cAddTypeOperation(a, cShift(), &TYPED_LESS);
  363. a = DT_BOOL;
  364. } else if(cConsumeTokenIf(T_LESS_EQUAL)) {
  365. cAddTypeOperation(a, cShift(), &TYPED_LESS_EQUAL);
  366. cAddOperation(OP_NOT);
  367. a = DT_BOOL;
  368. } else if(cConsumeTokenIf(T_GREATER)) {
  369. cAddTypeOperation(a, cShift(), &TYPED_GREATER);
  370. a = DT_BOOL;
  371. } else if(cConsumeTokenIf(T_GREATER_EQUAL)) {
  372. cAddTypeOperation(a, cShift(), &TYPED_GREATER_EQUAL);
  373. cAddOperation(OP_NOT);
  374. a = DT_BOOL;
  375. } else {
  376. break;
  377. }
  378. }
  379. return a;
  380. }
  381. static DataType cEqual() {
  382. DataType a = cComparison();
  383. while(true) {
  384. if(cConsumeTokenIf(T_EQUAL)) {
  385. cAddTypeOperation(a, cComparison(), &TYPED_EQUAL);
  386. a = DT_BOOL;
  387. } else if(cConsumeTokenIf(T_NOT_EQUAL)) {
  388. cAddTypeOperation(a, cComparison(), &TYPED_NOT_EQUAL);
  389. cAddOperation(OP_NOT);
  390. a = DT_BOOL;
  391. } else {
  392. break;
  393. }
  394. }
  395. return a;
  396. }
  397. static DataType cBitAnd() {
  398. DataType a = cEqual();
  399. while(cConsumeTokenIf(T_BIT_AND)) {
  400. DataType b = cEqual();
  401. cAddTypeOperation(a, b, &TYPED_BIT_AND);
  402. }
  403. return a;
  404. }
  405. static DataType cBitXor() {
  406. DataType a = cBitAnd();
  407. while(cConsumeTokenIf(T_BIT_XOR)) {
  408. DataType b = cBitAnd();
  409. cAddTypeOperation(a, b, &TYPED_BIT_XOR);
  410. }
  411. return a;
  412. }
  413. static DataType cBitOr() {
  414. DataType a = cBitXor();
  415. while(cConsumeTokenIf(T_BIT_OR)) {
  416. DataType b = cBitXor();
  417. cAddTypeOperation(a, b, &TYPED_BIT_OR);
  418. }
  419. return a;
  420. }
  421. static DataType cAnd() {
  422. DataType a = cBitOr();
  423. while(cConsumeTokenIf(T_AND)) {
  424. cAddOperation(OP_PEEK_FALSE_GOTO);
  425. int p = cReserveInt();
  426. DataType b = cBitOr();
  427. if(a != DT_BOOL || b != DT_BOOL) {
  428. cInvalidOperation(a, b, "&&");
  429. }
  430. cAddOperation(OP_AND);
  431. cSetInt(p, code->length);
  432. }
  433. return a;
  434. }
  435. static DataType cOr() {
  436. DataType a = cAnd();
  437. while(cConsumeTokenIf(T_OR)) {
  438. cAddOperation(OP_PEEK_TRUE_GOTO);
  439. int p = cReserveInt();
  440. DataType b = cAnd();
  441. if(a != DT_BOOL || b != DT_BOOL) {
  442. cInvalidOperation(a, b, "||");
  443. }
  444. cAddOperation(OP_OR);
  445. cSetInt(p, code->length);
  446. }
  447. return a;
  448. }
  449. static DataType cExpression() {
  450. return cOr();
  451. }
  452. static void cOperationSet(Variable* v, const TypedOp* op) {
  453. DataType a = cLoadVariable(v);
  454. DataType b = cExpression();
  455. cAddTypeOperation(a, b, op);
  456. cStoreVariable(v, b, "=");
  457. }
  458. static void cAddPostLineChange(Variable* v, int change, const char* name) {
  459. if(v->type != DT_INT) {
  460. cError("%s needs an int", name);
  461. }
  462. cAddOperation(OP_LOAD_INT);
  463. cAddInt(v->address);
  464. cAddOperation(OP_PUSH_INT);
  465. cAddInt(change);
  466. cAddOperation(OP_ADD_INT);
  467. cAddOperation(OP_STORE_INT);
  468. cAddInt(v->address);
  469. }
  470. static void cLineLiteral() {
  471. const char* literal = cReadString();
  472. if(cConsumeTokenIf(T_OPEN_BRACKET)) {
  473. DataType dt = cCallFunction(literal);
  474. if(dt != DT_VOID) {
  475. cError("function returns %s not void", dtGetName(dt));
  476. }
  477. return;
  478. }
  479. Variable* v = vSearch(&vars, literal);
  480. if(v == NULL) {
  481. cNotDeclared(literal);
  482. }
  483. Token t = cReadTokenAndLine();
  484. switch(t) {
  485. case T_SET: cStoreVariable(v, cExpression(), "="); break;
  486. case T_ADD_SET: cOperationSet(v, &TYPED_ADD); break;
  487. case T_SUB_SET: cOperationSet(v, &TYPED_SUB); break;
  488. case T_MUL_SET: cOperationSet(v, &TYPED_MUL); break;
  489. case T_DIV_SET: cOperationSet(v, &TYPED_DIV); break;
  490. case T_MOD_SET: cOperationSet(v, &TYPED_MOD); break;
  491. case T_BIT_AND_SET: cOperationSet(v, &TYPED_BIT_AND); break;
  492. case T_BIT_OR_SET: cOperationSet(v, &TYPED_BIT_OR); break;
  493. case T_BIT_XOR_SET: cOperationSet(v, &TYPED_BIT_XOR); break;
  494. case T_LEFT_SHIFT_SET: cOperationSet(v, &TYPED_LEFT_SHIFT); break;
  495. case T_RIGHT_SHIFT_SET: cOperationSet(v, &TYPED_RIGHT_SHIFT); break;
  496. case T_INCREMENT: cAddPostLineChange(v, 1, "++"); break;
  497. case T_DECREMENT: cAddPostLineChange(v, -1, "--"); break;
  498. default: cUnexpectedToken(t);
  499. }
  500. }
  501. static void cLine(Token t);
  502. static void cConsumeBody() {
  503. int oldLine = line;
  504. while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) {
  505. Token t = cReadTokenAndLine();
  506. if(t == T_END) {
  507. line = oldLine;
  508. cError("unexpected end of file: non closed curved bracket");
  509. }
  510. cLine(t);
  511. }
  512. }
  513. static void cConsumeScope() {
  514. Scope scope;
  515. vEnterScope(&vars, &scope);
  516. cConsumeBody();
  517. vLeaveScope(&vars, &scope);
  518. }
  519. static void cAddReturn(Operation op) {
  520. cAddOperation(op);
  521. returns[returnIndex++] = cReserveInt();
  522. }
  523. static void cReturn() {
  524. if(returnIndex >= RETURN_BUFFER) {
  525. cError("too much returns in function");
  526. }
  527. hasReturn = true;
  528. if(returnType == DT_VOID) {
  529. cConsumeToken(T_SEMICOLON);
  530. cAddReturn(OP_RETURN);
  531. return;
  532. }
  533. DataType dt = cExpression();
  534. if(dt != returnType) {
  535. cError("wrong return type, should be %s", dtGetName(returnType));
  536. }
  537. switch(dt) {
  538. case DT_INT: cAddReturn(OP_RETURN_INT); break;
  539. case DT_BOOL: cAddReturn(OP_RETURN_BOOL); break;
  540. case DT_FLOAT: cAddReturn(OP_RETURN_FLOAT); break;
  541. default: cError("cannot return %s", dtGetName(dt));
  542. }
  543. cConsumeToken(T_SEMICOLON);
  544. }
  545. static void cPrint() {
  546. DataType dt = cExpression();
  547. switch(dt) {
  548. case DT_INT: cAddOperation(OP_PRINT_INT); break;
  549. case DT_FLOAT: cAddOperation(OP_PRINT_FLOAT); break;
  550. case DT_BOOL: cAddOperation(OP_PRINT_BOOL); break;
  551. default: cError("cannot print type %s", dtGetName(dt));
  552. }
  553. cConsumeToken(T_SEMICOLON);
  554. }
  555. static void cIf() {
  556. cConsumeToken(T_OPEN_BRACKET);
  557. DataType dt = cExpression();
  558. if(dt != DT_BOOL) {
  559. cError("if expects a bool not %s", dtGetName(dt));
  560. }
  561. cConsumeToken(T_CLOSE_BRACKET);
  562. cAddOperation(OP_IF_GOTO);
  563. int ifP = cReserveInt();
  564. cConsumeToken(T_OPEN_CURVED_BRACKET);
  565. cConsumeScope();
  566. cSetInt(ifP, code->length);
  567. if(cConsumeTokenIf(T_ELSE)) {
  568. cAddOperation(OP_GOTO);
  569. int elseP = cReserveInt();
  570. cSetInt(ifP, code->length);
  571. if(cConsumeTokenIf(T_IF)) {
  572. cIf();
  573. } else {
  574. cConsumeToken(T_OPEN_CURVED_BRACKET);
  575. cConsumeScope();
  576. }
  577. cSetInt(elseP, code->length);
  578. }
  579. }
  580. static void cConsumeBreaks(int start, int address) {
  581. for(int i = start; i < breakIndex; i++) {
  582. cSetInt(breaks[i], address);
  583. }
  584. breakIndex = start;
  585. }
  586. static void cWhile() {
  587. int start = code->length;
  588. cConsumeToken(T_OPEN_BRACKET);
  589. DataType dt = cExpression();
  590. if(dt != DT_BOOL) {
  591. cError("while expects a bool not %s", dtGetName(dt));
  592. }
  593. cConsumeToken(T_CLOSE_BRACKET);
  594. cAddOperation(OP_IF_GOTO);
  595. int ifP = cReserveInt();
  596. int breakStart = breakIndex;
  597. forWhileStack++;
  598. int oldContinue = continueAt;
  599. continueAt = start;
  600. cConsumeToken(T_OPEN_CURVED_BRACKET);
  601. cConsumeScope();
  602. continueAt = oldContinue;
  603. forWhileStack--;
  604. cAddOperation(OP_GOTO);
  605. cAddInt(start);
  606. cSetInt(ifP, code->length);
  607. cConsumeBreaks(breakStart, code->length);
  608. }
  609. static void cDeclare(DataType dt) {
  610. cConsumeToken(T_LITERAL);
  611. const char* var = cReadString();
  612. Variable* v = vSearchScope(&vars, var);
  613. if(v != NULL) {
  614. cDeclared(var);
  615. }
  616. v = vAdd(&vars, var, dt);
  617. cConsumeToken(T_SET);
  618. cStoreVariable(v, cExpression(), "=");
  619. }
  620. static void cAddPreLineChange(int change, const char* name) {
  621. cConsumeToken(T_LITERAL);
  622. const char* literal = cReadString();
  623. Variable* v = vSearch(&vars, literal);
  624. if(v == NULL) {
  625. cNotDeclared(literal);
  626. }
  627. cAddPostLineChange(v, change, name);
  628. }
  629. static void cLineExpression(Token t) {
  630. switch(t) {
  631. case T_LITERAL: cLineLiteral(); break;
  632. case T_INT: cDeclare(DT_INT); break;
  633. case T_BOOL: cDeclare(DT_BOOL); break;
  634. case T_FLOAT: cDeclare(DT_FLOAT); break;
  635. case T_INCREMENT: cAddPreLineChange(1, "++"); break;
  636. case T_DECREMENT: cAddPreLineChange(-1, "--"); break;
  637. default: cUnexpectedToken(t);
  638. }
  639. }
  640. static void cFor() {
  641. Scope scope;
  642. vEnterScope(&vars, &scope);
  643. cConsumeToken(T_OPEN_BRACKET);
  644. cLineExpression(cReadTokenAndLine());
  645. cConsumeToken(T_SEMICOLON);
  646. int startCheck = code->length;
  647. DataType dt = cExpression();
  648. if(dt != DT_BOOL) {
  649. cError("for expects a bool not %s", dtGetName(dt));
  650. }
  651. cConsumeToken(T_SEMICOLON);
  652. cAddOperation(OP_IF_GOTO);
  653. int end = cReserveInt();
  654. cAddOperation(OP_GOTO);
  655. int beginBody = cReserveInt();
  656. int startPerLoop = code->length;
  657. cLineExpression(cReadTokenAndLine());
  658. cAddOperation(OP_GOTO);
  659. cAddInt(startCheck);
  660. cConsumeToken(T_CLOSE_BRACKET);
  661. cSetInt(beginBody, code->length);
  662. int breakStart = breakIndex;
  663. forWhileStack++;
  664. int oldContinue = continueAt;
  665. continueAt = startPerLoop;
  666. cConsumeToken(T_OPEN_CURVED_BRACKET);
  667. cConsumeBody();
  668. continueAt = oldContinue;
  669. forWhileStack--;
  670. cAddOperation(OP_GOTO);
  671. cAddInt(startPerLoop);
  672. cSetInt(end, code->length);
  673. cConsumeBreaks(breakStart, code->length);
  674. vLeaveScope(&vars, &scope);
  675. }
  676. static void cBreak() {
  677. if(forWhileStack == 0) {
  678. cError("break without for or while on line %d", line);
  679. } else if(breakIndex >= BREAK_BUFFER) {
  680. cError("too much breaks around line %d", line);
  681. }
  682. cAddOperation(OP_GOTO);
  683. breaks[breakIndex++] = cReserveInt();
  684. cConsumeToken(T_SEMICOLON);
  685. }
  686. static void cContinue() {
  687. if(forWhileStack == 0) {
  688. cError("continue without for or while on line %d", line);
  689. }
  690. cAddOperation(OP_GOTO);
  691. cAddInt(continueAt);
  692. cConsumeToken(T_SEMICOLON);
  693. }
  694. static void cLine(Token t) {
  695. hasReturn = false;
  696. cAddOperation(OP_LINE);
  697. cAddInt16(line);
  698. switch(t) {
  699. case T_OPEN_CURVED_BRACKET: cConsumeScope(); break;
  700. case T_PRINT: cPrint(); break;
  701. case T_RETURN: cReturn(); break;
  702. case T_IF: cIf(); break;
  703. case T_WHILE: cWhile(); break;
  704. case T_FOR: cFor(); break;
  705. case T_BREAK: cBreak(); break;
  706. case T_CONTINUE: cContinue(); break;
  707. default: cLineExpression(t); cConsumeToken(T_SEMICOLON);
  708. }
  709. }
  710. static void cFunctionArgument(Function* f);
  711. static void cFunctionCommaOrEnd(Function* f) {
  712. if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  713. return;
  714. }
  715. cConsumeToken(T_COMMA);
  716. cFunctionArgument(f);
  717. }
  718. static void cFunctionAddArgument(Function* f, DataType dt) {
  719. cConsumeToken(T_LITERAL);
  720. const char* name = cReadString();
  721. Variable* v = vSearchScope(&vars, name);
  722. if(v != NULL) {
  723. cDeclared(name);
  724. }
  725. vAdd(&vars, name, dt);
  726. if(fAddArgument(f, dt)) {
  727. cTooMuchArguments();
  728. }
  729. cFunctionCommaOrEnd(f);
  730. }
  731. static void cFunctionArgument(Function* f) {
  732. Token t = cReadTokenAndLine();
  733. switch(t) {
  734. case T_INT: cFunctionAddArgument(f, DT_INT); break;
  735. default: cUnexpectedToken(t);
  736. }
  737. }
  738. static void cFunctionArguments(Function* f) {
  739. cConsumeToken(T_OPEN_BRACKET);
  740. if(!cConsumeTokenIf(T_CLOSE_BRACKET)) {
  741. cFunctionArgument(f);
  742. }
  743. }
  744. static int cReserve(int offset) {
  745. cAddOperation(OP_RESERVE);
  746. int p = cReserveInt();
  747. cAddInt(offset);
  748. return p;
  749. }
  750. static void cFree(int p, int bytes) {
  751. cAddOperation(OP_RETURN);
  752. cAddInt(bytes);
  753. cSetInt(p, bytes);
  754. }
  755. static void cLinkReturns(int bytes) {
  756. for(int i = 0; i < returnIndex; i++) {
  757. cSetInt(returns[i], bytes);
  758. }
  759. returnIndex = 0;
  760. }
  761. static void cInnerFunction(Function* f) {
  762. cConsumeToken(T_OPEN_CURVED_BRACKET);
  763. int p = cReserve(f->size);
  764. returnIndex = 0;
  765. hasReturn = false;
  766. cConsumeScope();
  767. if(returnType != DT_VOID && !hasReturn) {
  768. cError("missing return");
  769. }
  770. cFree(p, vars.maxAddress);
  771. cLinkReturns(vars.maxAddress);
  772. }
  773. static bool cForwardFunction(Function* found, Function* f) {
  774. if(!cConsumeTokenIf(T_SEMICOLON)) {
  775. return false;
  776. } else if(found != NULL) {
  777. cError("function registered twice");
  778. }
  779. f->address = -1;
  780. fsAdd(&functions, f);
  781. return true;
  782. }
  783. static void cBuildFunction(Function* f, DataType rType) {
  784. cConsumeToken(T_LITERAL);
  785. fInit(f, cReadString(), line);
  786. f->returnType = rType;
  787. vReset(&vars);
  788. cFunctionArguments(f);
  789. }
  790. static void cFunction(DataType rType) {
  791. Function f;
  792. cBuildFunction(&f, rType);
  793. Function* found = fsSearch(&functions, &f);
  794. if(cForwardFunction(found, &f)) {
  795. return;
  796. }
  797. cAddOperation(OP_LINE);
  798. cAddInt16(line);
  799. cAddOperation(OP_GOTO);
  800. int end = cReserveInt();
  801. f.address = code->length;
  802. if(found != NULL) {
  803. if(found->address == -1) {
  804. found->address = f.address;
  805. } else {
  806. cError("function registered twice");
  807. }
  808. } else {
  809. fsAdd(&functions, &f);
  810. }
  811. returnType = rType;
  812. cInnerFunction(&f);
  813. cSetInt(end, code->length);
  814. }
  815. static void cGlobalScope(Token t) {
  816. switch(t) {
  817. case T_VOID: cFunction(DT_VOID); break;
  818. case T_INT: cFunction(DT_INT); break;
  819. case T_BOOL: cFunction(DT_BOOL); break;
  820. case T_FLOAT: cFunction(DT_FLOAT); break;
  821. default: cUnexpectedToken(t);
  822. }
  823. }
  824. static void cCallMain() {
  825. Function f;
  826. fInit(&f, "main", line);
  827. Function* found = fsSearch(&functions, &f);
  828. if(found != NULL && found->returnType == DT_VOID) {
  829. cAddOperation(OP_PUSH_INT);
  830. cAddInt(0);
  831. cAddOperation(OP_GOSUB);
  832. cAddInt(found->address);
  833. cAddInt(found->size);
  834. }
  835. }
  836. static void cForEachLine() {
  837. Token t = cReadTokenAndLine();
  838. while(t != T_END) {
  839. cGlobalScope(t);
  840. t = cReadTokenAndLine();
  841. }
  842. cCallMain();
  843. }
  844. static void cLinkQueuedFunctions() {
  845. for(int i = 0; i < functionQueue.entries; i++) {
  846. Function* f = functionQueue.data + i;
  847. Function* found = fsSearch(&functions, f);
  848. if(found == NULL) {
  849. line = f->line;
  850. cError("unknown function");
  851. } else if(f->returnType != found->returnType) {
  852. line = f->line;
  853. cError("function return type is not %s", dtGetName(f->returnType));
  854. }
  855. cSetInt(f->address, found->address);
  856. }
  857. }
  858. static void cAllocAndCompile() {
  859. forWhileStack = 0;
  860. breakIndex = 0;
  861. vInit(&vars);
  862. fsInit(&functions);
  863. fsInit(&functionQueue);
  864. if(!setjmp(errorJump)) {
  865. cForEachLine();
  866. cLinkQueuedFunctions();
  867. }
  868. fsDelete(&functionQueue);
  869. fsDelete(&functions);
  870. vDelete(&vars);
  871. }
  872. ByteCode* cCompile() {
  873. error[0] = '\0';
  874. code = bcInit();
  875. cAllocAndCompile();
  876. if(error[0] != '\0') {
  877. bcDelete(code);
  878. return NULL;
  879. }
  880. return code;
  881. }
  882. const char* cGetError() {
  883. return error;
  884. }
  885. int cGetLine() {
  886. return line;
  887. }