Compiler.c 33 KB

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