Compiler.c 30 KB

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