Compiler.c 29 KB

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