Compiler.c 33 KB

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