Compiler.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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:
  193. if(dtIsArray(v->type)) {
  194. cAddOperation(OP_STORE_ARRAY);
  195. } else {
  196. cError("cannot store type %s", dtGetName(v->type));
  197. }
  198. }
  199. cAddInt(v->address);
  200. }
  201. static DataType cPostChange(Variable* v, int change, const char* name) {
  202. if(v->type != DT_INT) {
  203. cError("%s needs an int", name);
  204. }
  205. cAddOperation(OP_LOAD_INT);
  206. cAddInt(v->address);
  207. cAddOperation(OP_LOAD_INT);
  208. cAddInt(v->address);
  209. cAddOperation(OP_PUSH_INT);
  210. cAddInt(change);
  211. cAddOperation(OP_ADD_INT);
  212. cAddOperation(OP_STORE_INT);
  213. cAddInt(v->address);
  214. return DT_INT;
  215. }
  216. static DataType cLiteral() {
  217. const char* literal = cReadString();
  218. if(cConsumeTokenIf(T_OPEN_BRACKET)) {
  219. DataType dt = cCallFunction(literal);
  220. if(dt == DT_VOID) {
  221. cError("function returns void");
  222. }
  223. return dt;
  224. }
  225. Variable* v = vSearch(&vars, literal);
  226. if(v == NULL) {
  227. cNotDeclared(literal);
  228. }
  229. if(cConsumeTokenIf(T_INCREMENT)) {
  230. return cPostChange(v, 1, "++");
  231. } else if(cConsumeTokenIf(T_DECREMENT)) {
  232. return cPostChange(v, -1, "--");
  233. }
  234. return cLoadVariable(v);
  235. }
  236. static DataType cBracketPrimary() {
  237. DataType result = cExpression();
  238. cConsumeToken(T_CLOSE_BRACKET);
  239. return result;
  240. }
  241. static DataType cAllocArray(DataType dt, Operation op) {
  242. cConsumeToken(T_OPEN_SQUARE_BRACKET);
  243. DataType index = cExpression();
  244. if(index != DT_INT) {
  245. cError("array size must be an int");
  246. }
  247. cConsumeToken(T_CLOSE_SQUARE_BRACKET);
  248. cAddOperation(op);
  249. return dtArray(dt, 1);
  250. }
  251. static DataType cPrimary() {
  252. Token t = cReadTokenAndLine();
  253. switch(t) {
  254. case T_CONST_INT: cConstantInt(); return DT_INT;
  255. case T_CONST_FLOAT: cConstantFloat(); return DT_FLOAT;
  256. case T_TRUE: cAddOperation(OP_PUSH_TRUE); return DT_BOOL;
  257. case T_FALSE: cAddOperation(OP_PUSH_FALSE); return DT_BOOL;
  258. case T_OPEN_BRACKET: return cBracketPrimary();
  259. case T_LITERAL: return cLiteral();
  260. case T_INT: return cAllocArray(DT_INT, OP_INT_ARRAY);
  261. default: cUnexpectedToken(t); return DT_VOID;
  262. }
  263. }
  264. static DataType cPreChange(int change, const char* name) {
  265. cConsumeToken(T_LITERAL);
  266. const char* literal = cReadString();
  267. Variable* v = vSearch(&vars, literal);
  268. if(v == NULL) {
  269. cNotDeclared(literal);
  270. } else if(v->type != DT_INT) {
  271. cError("%s needs an int", name);
  272. }
  273. cAddOperation(OP_LOAD_INT);
  274. cAddInt(v->address);
  275. cAddOperation(OP_PUSH_INT);
  276. cAddInt(change);
  277. cAddOperation(OP_ADD_INT);
  278. cAddOperation(OP_STORE_INT);
  279. cAddInt(v->address);
  280. cAddOperation(OP_LOAD_INT);
  281. cAddInt(v->address);
  282. return DT_INT;
  283. }
  284. static DataType cPreUnary() {
  285. if(cConsumeTokenIf(T_SUB)) {
  286. DataType result = cPrimary();
  287. switch(result) {
  288. case DT_INT: cAddOperation(OP_INVERT_SIGN_INT); break;
  289. case DT_FLOAT: cAddOperation(OP_INVERT_SIGN_FLOAT); break;
  290. default: cError("cannot invert sign of %s", dtGetName(result));
  291. }
  292. return result;
  293. } else if(cConsumeTokenIf(T_INCREMENT)) {
  294. return cPreChange(1, "++");
  295. } else if(cConsumeTokenIf(T_DECREMENT)) {
  296. return cPreChange(-1, "--");
  297. } else if(cConsumeTokenIf(T_NOT)) {
  298. int counter = 1;
  299. while(cConsumeTokenIf(T_NOT)) {
  300. counter++;
  301. }
  302. DataType result = cPrimary();
  303. if(result != DT_BOOL) {
  304. cError("! needs a bool not %s", dtGetName(result));
  305. }
  306. cAddOperation(OP_NOT);
  307. if((counter & 1) == 0) {
  308. cAddOperation(OP_NOT);
  309. }
  310. return DT_BOOL;
  311. } else if(cConsumeTokenIf(T_BIT_NOT)) {
  312. DataType result = cPrimary();
  313. if(result == DT_INT) {
  314. cAddOperation(OP_BIT_NOT);
  315. } else {
  316. cError("~ needs an int not %s", dtGetName(result));
  317. }
  318. return result;
  319. }
  320. return cPrimary();
  321. }
  322. static void cAddTypeOperation(DataType a, DataType b, const TypedOp* op) {
  323. if(a == DT_INT && b == DT_INT && op->intOp != OP_NOTHING) {
  324. cAddOperation(op->intOp);
  325. } else if(a == DT_FLOAT && b == DT_FLOAT && op->floatOp != OP_NOTHING) {
  326. cAddOperation(op->floatOp);
  327. } else if(a == DT_BOOL && b == DT_BOOL && op->boolOp != OP_NOTHING) {
  328. cAddOperation(op->boolOp);
  329. } else {
  330. cInvalidOperation(a, b, op->name);
  331. }
  332. }
  333. static DataType cMul() {
  334. DataType a = cPreUnary();
  335. while(true) {
  336. if(cConsumeTokenIf(T_MUL)) {
  337. cAddTypeOperation(a, cPreUnary(), &TYPED_MUL);
  338. } else if(cConsumeTokenIf(T_DIV)) {
  339. cAddTypeOperation(a, cPreUnary(), &TYPED_DIV);
  340. } else if(cConsumeTokenIf(T_MOD)) {
  341. cAddTypeOperation(a, cPreUnary(), &TYPED_MOD);
  342. } else {
  343. break;
  344. }
  345. }
  346. return a;
  347. }
  348. static DataType cAdd() {
  349. DataType a = cMul();
  350. while(true) {
  351. if(cConsumeTokenIf(T_ADD)) {
  352. cAddTypeOperation(a, cMul(), &TYPED_ADD);
  353. } else if(cConsumeTokenIf(T_SUB)) {
  354. cAddTypeOperation(a, cMul(), &TYPED_SUB);
  355. } else {
  356. break;
  357. }
  358. }
  359. return a;
  360. }
  361. static DataType cShift() {
  362. DataType a = cAdd();
  363. while(true) {
  364. if(cConsumeTokenIf(T_LEFT_SHIFT)) {
  365. cAddTypeOperation(a, cAdd(), &TYPED_LEFT_SHIFT);
  366. } else if(cConsumeTokenIf(T_RIGHT_SHIFT)) {
  367. cAddTypeOperation(a, cAdd(), &TYPED_RIGHT_SHIFT);
  368. } else {
  369. break;
  370. }
  371. }
  372. return a;
  373. }
  374. static DataType cComparison() {
  375. DataType a = cShift();
  376. while(true) {
  377. if(cConsumeTokenIf(T_LESS)) {
  378. cAddTypeOperation(a, cShift(), &TYPED_LESS);
  379. a = DT_BOOL;
  380. } else if(cConsumeTokenIf(T_LESS_EQUAL)) {
  381. cAddTypeOperation(a, cShift(), &TYPED_LESS_EQUAL);
  382. cAddOperation(OP_NOT);
  383. a = DT_BOOL;
  384. } else if(cConsumeTokenIf(T_GREATER)) {
  385. cAddTypeOperation(a, cShift(), &TYPED_GREATER);
  386. a = DT_BOOL;
  387. } else if(cConsumeTokenIf(T_GREATER_EQUAL)) {
  388. cAddTypeOperation(a, cShift(), &TYPED_GREATER_EQUAL);
  389. cAddOperation(OP_NOT);
  390. a = DT_BOOL;
  391. } else {
  392. break;
  393. }
  394. }
  395. return a;
  396. }
  397. static DataType cEqual() {
  398. DataType a = cComparison();
  399. while(true) {
  400. if(cConsumeTokenIf(T_EQUAL)) {
  401. cAddTypeOperation(a, cComparison(), &TYPED_EQUAL);
  402. a = DT_BOOL;
  403. } else if(cConsumeTokenIf(T_NOT_EQUAL)) {
  404. cAddTypeOperation(a, cComparison(), &TYPED_NOT_EQUAL);
  405. cAddOperation(OP_NOT);
  406. a = DT_BOOL;
  407. } else {
  408. break;
  409. }
  410. }
  411. return a;
  412. }
  413. static DataType cBitAnd() {
  414. DataType a = cEqual();
  415. while(cConsumeTokenIf(T_BIT_AND)) {
  416. DataType b = cEqual();
  417. cAddTypeOperation(a, b, &TYPED_BIT_AND);
  418. }
  419. return a;
  420. }
  421. static DataType cBitXor() {
  422. DataType a = cBitAnd();
  423. while(cConsumeTokenIf(T_BIT_XOR)) {
  424. DataType b = cBitAnd();
  425. cAddTypeOperation(a, b, &TYPED_BIT_XOR);
  426. }
  427. return a;
  428. }
  429. static DataType cBitOr() {
  430. DataType a = cBitXor();
  431. while(cConsumeTokenIf(T_BIT_OR)) {
  432. DataType b = cBitXor();
  433. cAddTypeOperation(a, b, &TYPED_BIT_OR);
  434. }
  435. return a;
  436. }
  437. static DataType cAnd() {
  438. DataType a = cBitOr();
  439. while(cConsumeTokenIf(T_AND)) {
  440. cAddOperation(OP_PEEK_FALSE_GOTO);
  441. int p = cReserveInt();
  442. DataType b = cBitOr();
  443. if(a != DT_BOOL || b != DT_BOOL) {
  444. cInvalidOperation(a, b, "&&");
  445. }
  446. cAddOperation(OP_AND);
  447. cSetInt(p, code->length);
  448. }
  449. return a;
  450. }
  451. static DataType cOr() {
  452. DataType a = cAnd();
  453. while(cConsumeTokenIf(T_OR)) {
  454. cAddOperation(OP_PEEK_TRUE_GOTO);
  455. int p = cReserveInt();
  456. DataType b = cAnd();
  457. if(a != DT_BOOL || b != DT_BOOL) {
  458. cInvalidOperation(a, b, "||");
  459. }
  460. cAddOperation(OP_OR);
  461. cSetInt(p, code->length);
  462. }
  463. return a;
  464. }
  465. static DataType cExpression() {
  466. return cOr();
  467. }
  468. static void cOperationSet(Variable* v, const TypedOp* op) {
  469. DataType a = cLoadVariable(v);
  470. DataType b = cExpression();
  471. cAddTypeOperation(a, b, op);
  472. cStoreVariable(v, b, "=");
  473. }
  474. static void cAddPostLineChange(Variable* v, int change, const char* name) {
  475. if(v->type != DT_INT) {
  476. cError("%s needs an int", name);
  477. }
  478. cAddOperation(OP_LOAD_INT);
  479. cAddInt(v->address);
  480. cAddOperation(OP_PUSH_INT);
  481. cAddInt(change);
  482. cAddOperation(OP_ADD_INT);
  483. cAddOperation(OP_STORE_INT);
  484. cAddInt(v->address);
  485. }
  486. static void cLineLiteral() {
  487. const char* literal = cReadString();
  488. if(cConsumeTokenIf(T_OPEN_BRACKET)) {
  489. DataType dt = cCallFunction(literal);
  490. if(dt != DT_VOID) {
  491. cError("function returns %s not void", dtGetName(dt));
  492. }
  493. return;
  494. }
  495. Variable* v = vSearch(&vars, literal);
  496. if(v == NULL) {
  497. cNotDeclared(literal);
  498. }
  499. Token t = cReadTokenAndLine();
  500. switch(t) {
  501. case T_SET: cStoreVariable(v, cExpression(), "="); break;
  502. case T_ADD_SET: cOperationSet(v, &TYPED_ADD); break;
  503. case T_SUB_SET: cOperationSet(v, &TYPED_SUB); break;
  504. case T_MUL_SET: cOperationSet(v, &TYPED_MUL); break;
  505. case T_DIV_SET: cOperationSet(v, &TYPED_DIV); break;
  506. case T_MOD_SET: cOperationSet(v, &TYPED_MOD); break;
  507. case T_BIT_AND_SET: cOperationSet(v, &TYPED_BIT_AND); break;
  508. case T_BIT_OR_SET: cOperationSet(v, &TYPED_BIT_OR); break;
  509. case T_BIT_XOR_SET: cOperationSet(v, &TYPED_BIT_XOR); break;
  510. case T_LEFT_SHIFT_SET: cOperationSet(v, &TYPED_LEFT_SHIFT); break;
  511. case T_RIGHT_SHIFT_SET: cOperationSet(v, &TYPED_RIGHT_SHIFT); break;
  512. case T_INCREMENT: cAddPostLineChange(v, 1, "++"); break;
  513. case T_DECREMENT: cAddPostLineChange(v, -1, "--"); break;
  514. default: cUnexpectedToken(t);
  515. }
  516. }
  517. static void cLine(Token t);
  518. static void cConsumeBody() {
  519. int oldLine = line;
  520. while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) {
  521. Token t = cReadTokenAndLine();
  522. if(t == T_END) {
  523. line = oldLine;
  524. cError("unexpected end of file: non closed curved bracket");
  525. }
  526. cLine(t);
  527. }
  528. }
  529. static void cConsumeScope() {
  530. Scope scope;
  531. vEnterScope(&vars, &scope);
  532. cConsumeBody();
  533. vLeaveScope(&vars, &scope);
  534. }
  535. static void cAddReturn(Operation op) {
  536. cAddOperation(op);
  537. returns[returnIndex++] = cReserveInt();
  538. }
  539. static void cReturn() {
  540. if(returnIndex >= RETURN_BUFFER) {
  541. cError("too much returns in function");
  542. }
  543. hasReturn = true;
  544. if(returnType == DT_VOID) {
  545. cConsumeToken(T_SEMICOLON);
  546. cAddReturn(OP_RETURN);
  547. return;
  548. }
  549. DataType dt = cExpression();
  550. if(dt != returnType) {
  551. cError("wrong return type, should be %s", dtGetName(returnType));
  552. }
  553. switch(dt) {
  554. case DT_INT: cAddReturn(OP_RETURN_INT); break;
  555. case DT_BOOL: cAddReturn(OP_RETURN_BOOL); break;
  556. case DT_FLOAT: cAddReturn(OP_RETURN_FLOAT); break;
  557. default: cError("cannot return %s", dtGetName(dt));
  558. }
  559. cConsumeToken(T_SEMICOLON);
  560. }
  561. static void cPrint() {
  562. DataType dt = cExpression();
  563. switch(dt) {
  564. case DT_INT: cAddOperation(OP_PRINT_INT); break;
  565. case DT_FLOAT: cAddOperation(OP_PRINT_FLOAT); break;
  566. case DT_BOOL: cAddOperation(OP_PRINT_BOOL); break;
  567. default: cError("cannot print type %s", dtGetName(dt));
  568. }
  569. cConsumeToken(T_SEMICOLON);
  570. }
  571. static void cIf() {
  572. cConsumeToken(T_OPEN_BRACKET);
  573. DataType dt = cExpression();
  574. if(dt != DT_BOOL) {
  575. cError("if expects a bool not %s", dtGetName(dt));
  576. }
  577. cConsumeToken(T_CLOSE_BRACKET);
  578. cAddOperation(OP_IF_GOTO);
  579. int ifP = cReserveInt();
  580. cConsumeToken(T_OPEN_CURVED_BRACKET);
  581. cConsumeScope();
  582. cSetInt(ifP, code->length);
  583. if(cConsumeTokenIf(T_ELSE)) {
  584. cAddOperation(OP_GOTO);
  585. int elseP = cReserveInt();
  586. cSetInt(ifP, code->length);
  587. if(cConsumeTokenIf(T_IF)) {
  588. cIf();
  589. } else {
  590. cConsumeToken(T_OPEN_CURVED_BRACKET);
  591. cConsumeScope();
  592. }
  593. cSetInt(elseP, code->length);
  594. }
  595. }
  596. static void cConsumeBreaks(int start, int address) {
  597. for(int i = start; i < breakIndex; i++) {
  598. cSetInt(breaks[i], address);
  599. }
  600. breakIndex = start;
  601. }
  602. static void cWhile() {
  603. int start = code->length;
  604. cConsumeToken(T_OPEN_BRACKET);
  605. DataType dt = cExpression();
  606. if(dt != DT_BOOL) {
  607. cError("while expects a bool not %s", dtGetName(dt));
  608. }
  609. cConsumeToken(T_CLOSE_BRACKET);
  610. cAddOperation(OP_IF_GOTO);
  611. int ifP = cReserveInt();
  612. int breakStart = breakIndex;
  613. forWhileStack++;
  614. int oldContinue = continueAt;
  615. continueAt = start;
  616. cConsumeToken(T_OPEN_CURVED_BRACKET);
  617. cConsumeScope();
  618. continueAt = oldContinue;
  619. forWhileStack--;
  620. cAddOperation(OP_GOTO);
  621. cAddInt(start);
  622. cSetInt(ifP, code->length);
  623. cConsumeBreaks(breakStart, code->length);
  624. }
  625. static DataType cDimension(DataType dt) {
  626. int dimension = 0;
  627. while(cConsumeTokenIf(T_MUL)) {
  628. dimension++;
  629. }
  630. if(dimension > 0) {
  631. dt = dtArray(dt, dimension);
  632. }
  633. return dt;
  634. }
  635. static void cDeclare(DataType dt) {
  636. dt = cDimension(dt);
  637. cConsumeToken(T_LITERAL);
  638. const char* var = cReadString();
  639. Variable* v = vSearchScope(&vars, var);
  640. if(v != NULL) {
  641. cDeclared(var);
  642. }
  643. v = vAdd(&vars, var, dt);
  644. cConsumeToken(T_SET);
  645. cStoreVariable(v, cExpression(), "=");
  646. }
  647. static void cAddPreLineChange(int change, const char* name) {
  648. cConsumeToken(T_LITERAL);
  649. const char* literal = cReadString();
  650. Variable* v = vSearch(&vars, literal);
  651. if(v == NULL) {
  652. cNotDeclared(literal);
  653. }
  654. cAddPostLineChange(v, change, name);
  655. }
  656. static void cLineExpression(Token t) {
  657. switch(t) {
  658. case T_LITERAL: cLineLiteral(); break;
  659. case T_INT: cDeclare(DT_INT); break;
  660. case T_BOOL: cDeclare(DT_BOOL); break;
  661. case T_FLOAT: cDeclare(DT_FLOAT); break;
  662. case T_INCREMENT: cAddPreLineChange(1, "++"); break;
  663. case T_DECREMENT: cAddPreLineChange(-1, "--"); break;
  664. default: cUnexpectedToken(t);
  665. }
  666. }
  667. static void cFor() {
  668. Scope scope;
  669. vEnterScope(&vars, &scope);
  670. cConsumeToken(T_OPEN_BRACKET);
  671. cLineExpression(cReadTokenAndLine());
  672. cConsumeToken(T_SEMICOLON);
  673. int startCheck = code->length;
  674. DataType dt = cExpression();
  675. if(dt != DT_BOOL) {
  676. cError("for expects a bool not %s", dtGetName(dt));
  677. }
  678. cConsumeToken(T_SEMICOLON);
  679. cAddOperation(OP_IF_GOTO);
  680. int end = cReserveInt();
  681. cAddOperation(OP_GOTO);
  682. int beginBody = cReserveInt();
  683. int startPerLoop = code->length;
  684. cLineExpression(cReadTokenAndLine());
  685. cAddOperation(OP_GOTO);
  686. cAddInt(startCheck);
  687. cConsumeToken(T_CLOSE_BRACKET);
  688. cSetInt(beginBody, code->length);
  689. int breakStart = breakIndex;
  690. forWhileStack++;
  691. int oldContinue = continueAt;
  692. continueAt = startPerLoop;
  693. cConsumeToken(T_OPEN_CURVED_BRACKET);
  694. cConsumeBody();
  695. continueAt = oldContinue;
  696. forWhileStack--;
  697. cAddOperation(OP_GOTO);
  698. cAddInt(startPerLoop);
  699. cSetInt(end, code->length);
  700. cConsumeBreaks(breakStart, code->length);
  701. vLeaveScope(&vars, &scope);
  702. }
  703. static void cBreak() {
  704. if(forWhileStack == 0) {
  705. cError("break without for or while on line %d", line);
  706. } else if(breakIndex >= BREAK_BUFFER) {
  707. cError("too much breaks around line %d", line);
  708. }
  709. cAddOperation(OP_GOTO);
  710. breaks[breakIndex++] = cReserveInt();
  711. cConsumeToken(T_SEMICOLON);
  712. }
  713. static void cContinue() {
  714. if(forWhileStack == 0) {
  715. cError("continue without for or while on line %d", line);
  716. }
  717. cAddOperation(OP_GOTO);
  718. cAddInt(continueAt);
  719. cConsumeToken(T_SEMICOLON);
  720. }
  721. static void cLine(Token t) {
  722. hasReturn = false;
  723. cAddOperation(OP_LINE);
  724. cAddInt16(line);
  725. switch(t) {
  726. case T_OPEN_CURVED_BRACKET: cConsumeScope(); break;
  727. case T_PRINT: cPrint(); break;
  728. case T_RETURN: cReturn(); break;
  729. case T_IF: cIf(); break;
  730. case T_WHILE: cWhile(); break;
  731. case T_FOR: cFor(); break;
  732. case T_BREAK: cBreak(); break;
  733. case T_CONTINUE: cContinue(); break;
  734. default: cLineExpression(t); cConsumeToken(T_SEMICOLON);
  735. }
  736. }
  737. static void cFunctionArgument(Function* f);
  738. static void cFunctionCommaOrEnd(Function* f) {
  739. if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  740. return;
  741. }
  742. cConsumeToken(T_COMMA);
  743. cFunctionArgument(f);
  744. }
  745. static void cFunctionAddArgument(Function* f, DataType dt) {
  746. cConsumeToken(T_LITERAL);
  747. const char* name = cReadString();
  748. Variable* v = vSearchScope(&vars, name);
  749. if(v != NULL) {
  750. cDeclared(name);
  751. }
  752. vAdd(&vars, name, dt);
  753. if(fAddArgument(f, dt)) {
  754. cTooMuchArguments();
  755. }
  756. cFunctionCommaOrEnd(f);
  757. }
  758. static void cFunctionArgument(Function* f) {
  759. Token t = cReadTokenAndLine();
  760. switch(t) {
  761. case T_INT: cFunctionAddArgument(f, DT_INT); break;
  762. default: cUnexpectedToken(t);
  763. }
  764. }
  765. static void cFunctionArguments(Function* f) {
  766. cConsumeToken(T_OPEN_BRACKET);
  767. if(!cConsumeTokenIf(T_CLOSE_BRACKET)) {
  768. cFunctionArgument(f);
  769. }
  770. }
  771. static int cReserve(int offset) {
  772. cAddOperation(OP_RESERVE);
  773. int p = cReserveInt();
  774. cAddInt(offset);
  775. return p;
  776. }
  777. static void cFree(int p, int bytes) {
  778. cAddOperation(OP_RETURN);
  779. cAddInt(bytes);
  780. cSetInt(p, bytes);
  781. }
  782. static void cLinkReturns(int bytes) {
  783. for(int i = 0; i < returnIndex; i++) {
  784. cSetInt(returns[i], bytes);
  785. }
  786. returnIndex = 0;
  787. }
  788. static void cInnerFunction(Function* f) {
  789. cConsumeToken(T_OPEN_CURVED_BRACKET);
  790. int p = cReserve(f->size);
  791. returnIndex = 0;
  792. hasReturn = false;
  793. cConsumeScope();
  794. if(returnType != DT_VOID && !hasReturn) {
  795. cError("missing return");
  796. }
  797. cFree(p, vars.maxAddress);
  798. cLinkReturns(vars.maxAddress);
  799. }
  800. static bool cForwardFunction(Function* found, Function* f) {
  801. if(!cConsumeTokenIf(T_SEMICOLON)) {
  802. return false;
  803. } else if(found != NULL) {
  804. cError("function registered twice");
  805. }
  806. f->address = -1;
  807. fsAdd(&functions, f);
  808. return true;
  809. }
  810. static void cBuildFunction(Function* f, DataType rType) {
  811. cConsumeToken(T_LITERAL);
  812. fInit(f, cReadString(), line);
  813. f->returnType = rType;
  814. vReset(&vars);
  815. cFunctionArguments(f);
  816. }
  817. static void cFunction(DataType rType) {
  818. Function f;
  819. cBuildFunction(&f, rType);
  820. Function* found = fsSearch(&functions, &f);
  821. if(cForwardFunction(found, &f)) {
  822. return;
  823. }
  824. cAddOperation(OP_LINE);
  825. cAddInt16(line);
  826. cAddOperation(OP_GOTO);
  827. int end = cReserveInt();
  828. f.address = code->length;
  829. if(found != NULL) {
  830. if(found->address == -1) {
  831. found->address = f.address;
  832. } else {
  833. cError("function registered twice");
  834. }
  835. } else {
  836. fsAdd(&functions, &f);
  837. }
  838. returnType = rType;
  839. cInnerFunction(&f);
  840. cSetInt(end, code->length);
  841. }
  842. static void cGlobalScope(Token t) {
  843. switch(t) {
  844. case T_VOID: cFunction(DT_VOID); break;
  845. case T_INT: cFunction(DT_INT); break;
  846. case T_BOOL: cFunction(DT_BOOL); break;
  847. case T_FLOAT: cFunction(DT_FLOAT); break;
  848. default: cUnexpectedToken(t);
  849. }
  850. }
  851. static void cCallMain() {
  852. Function f;
  853. fInit(&f, "main", line);
  854. Function* found = fsSearch(&functions, &f);
  855. if(found != NULL && found->returnType == DT_VOID) {
  856. cAddOperation(OP_PUSH_INT);
  857. cAddInt(0);
  858. cAddOperation(OP_GOSUB);
  859. cAddInt(found->address);
  860. cAddInt(found->size);
  861. }
  862. }
  863. static void cForEachLine() {
  864. Token t = cReadTokenAndLine();
  865. while(t != T_END) {
  866. cGlobalScope(t);
  867. t = cReadTokenAndLine();
  868. }
  869. cCallMain();
  870. }
  871. static void cLinkQueuedFunctions() {
  872. for(int i = 0; i < functionQueue.entries; i++) {
  873. Function* f = functionQueue.data + i;
  874. Function* found = fsSearch(&functions, f);
  875. if(found == NULL) {
  876. line = f->line;
  877. cError("unknown function");
  878. } else if(f->returnType != found->returnType) {
  879. line = f->line;
  880. cError("function return type is not %s", dtGetName(f->returnType));
  881. }
  882. cSetInt(f->address, found->address);
  883. }
  884. }
  885. static void cAllocAndCompile() {
  886. forWhileStack = 0;
  887. breakIndex = 0;
  888. vInit(&vars);
  889. fsInit(&functions);
  890. fsInit(&functionQueue);
  891. if(!setjmp(errorJump)) {
  892. cForEachLine();
  893. cLinkQueuedFunctions();
  894. }
  895. fsDelete(&functionQueue);
  896. fsDelete(&functions);
  897. vDelete(&vars);
  898. }
  899. ByteCode* cCompile() {
  900. error[0] = '\0';
  901. code = bcInit();
  902. cAllocAndCompile();
  903. if(error[0] != '\0') {
  904. bcDelete(code);
  905. return NULL;
  906. }
  907. return code;
  908. }
  909. const char* cGetError() {
  910. return error;
  911. }
  912. int cGetLine() {
  913. return line;
  914. }